From b9c0d5a6c7f40262833f77490ed7e404e7ec6580 Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Sat, 7 Feb 2026 20:31:41 -0500 Subject: [PATCH 01/15] docs: codec --- cmd/lambda/lambda_engine_list.go | 2 +- pkg/codec/codec.go | 12 ++++++++++++ pkg/lambda/{expression.go => lambda.go} | 0 3 files changed, 13 insertions(+), 1 deletion(-) rename pkg/lambda/{expression.go => lambda.go} (100%) diff --git a/cmd/lambda/lambda_engine_list.go b/cmd/lambda/lambda_engine_list.go index 338098d..c69dbd3 100644 --- a/cmd/lambda/lambda_engine_list.go +++ b/cmd/lambda/lambda_engine_list.go @@ -11,7 +11,7 @@ func LambdaEngineList() *cobra.Command { Use: "list", Aliases: []string{"ls"}, Short: "List available engines", - RunE: func(cmd *cobra.Command, args []string) error { + RunE: func(*cobra.Command, []string) error { r := GetRegistry() for engine := range r.ListEngines() { diff --git a/pkg/codec/codec.go b/pkg/codec/codec.go index ecbe258..160547d 100644 --- a/pkg/codec/codec.go +++ b/pkg/codec/codec.go @@ -1,8 +1,20 @@ +// Package codec defines processes to convert between different representations +// of lambda calculus, and serialize the different representations. package codec +// A Conversion is a function that turns one representation into another. +// Returns an error if the input expression cannot be converted. type Conversion[T, U any] = func(T) (U, error) +// A Codec is an object that can serialize/deserialize one type of +// representation. It is assumed that for any x ∋ T, Decode(Encode(x)) = x. type Codec[T any] interface { + // Encode takes an expression, and returns its serialized format, as a + // string. Returns an error if the expression cannot be serialized. Encode(T) (string, error) + + // Decode takes the serialized format of an expression, and returns its true + // value. Returns an error if the string doesn't correctly represent any + // valid expression. Decode(string) (T, error) } diff --git a/pkg/lambda/expression.go b/pkg/lambda/lambda.go similarity index 100% rename from pkg/lambda/expression.go rename to pkg/lambda/lambda.go -- 2.49.1 From b259ab01257ae24523611fff435308bd1ecfc27f Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Sat, 7 Feb 2026 20:46:33 -0500 Subject: [PATCH 02/15] docs: registry --- internal/registry/registry.go | 23 +++++++++++++++++++++++ pkg/convert/saccharine_to_lambda.go | 5 +++++ pkg/engine/engine.go | 10 ++++++++-- 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/internal/registry/registry.go b/internal/registry/registry.go index ecbf28f..d0e33ba 100644 --- a/internal/registry/registry.go +++ b/internal/registry/registry.go @@ -1,3 +1,5 @@ +// Package registry defines a structure to hold all available representations, +// engines, and conversions between them. package registry import ( @@ -6,12 +8,15 @@ import ( "maps" ) +// A Registry holds all representations, conversions, codecs, and engines +// available to the program. type Registry struct { codecs map[string]Codec converter *Converter engines map[string]Engine } +// New makes an empty registry. func New() *Registry { return &Registry{ codecs: map[string]Codec{}, @@ -20,6 +25,8 @@ func New() *Registry { } } +// GetEngine finds an engine based on its name. Returns an error if an engine +// with that name cannot be found. func (r Registry) GetEngine(name string) (Engine, error) { e, ok := r.engines[name] if !ok { @@ -29,10 +36,13 @@ func (r Registry) GetEngine(name string) (Engine, error) { return e, nil } +// ListEngines returns all available engines to the registry. func (r Registry) ListEngines() iter.Seq[Engine] { return maps.Values(r.engines) } +// GetDefaultEngine infers the preferred engine for a representation. Returns an +// error if one cannot be chosen. func (r *Registry) GetDefaultEngine(id string) (Engine, error) { for _, engine := range r.engines { if engine.InType() == id { @@ -45,6 +55,12 @@ func (r *Registry) GetDefaultEngine(id string) (Engine, error) { // return nil, fmt.Errorf("no engine for '%s'", id) } +// ConvertTo attempts to convert an expression of one type of representation to +// another. Returns the converted expression, otherwise an error. +// +// It can convert between any two types of representations, given there is a +// valid conversion path between them. It uses BFS to traverse a graph of +// conversion edges, and converts along the shortest path. func (r *Registry) ConvertTo(expr Expr, outType string) (Expr, error) { path, err := r.ConversionPath(expr.Repr(), outType) if err != nil { @@ -62,6 +78,8 @@ func (r *Registry) ConvertTo(expr Expr, outType string) (Expr, error) { return result, err } +// Marshal serializes an expression, given that representation has a codec. +// Returns an error if the representation is not registered, or it has no codec. func (r *Registry) Marshal(expr Expr) (string, error) { m, ok := r.codecs[expr.Repr()] if !ok { @@ -71,6 +89,8 @@ func (r *Registry) Marshal(expr Expr) (string, error) { return m.Encode(expr) } +// Unmarshal deserializes an expression. Returns an error if the representation +// or a codec for it is not registered. func (r *Registry) Unmarshal(s string, outType string) (Expr, error) { m, ok := r.codecs[outType] if !ok { @@ -94,6 +114,9 @@ func reverse[T any](list []T) []T { return reversed } +// ConversionPath attempts to find a set of valid conversions that (if applied) +// convert one representation to another. Returns an error if no path can be +// found. func (r *Registry) ConversionPath(from, to string) ([]Conversion, error) { backtrack := map[string]Conversion{} iteration := []string{from} diff --git a/pkg/convert/saccharine_to_lambda.go b/pkg/convert/saccharine_to_lambda.go index 73aeb0f..d8caa97 100644 --- a/pkg/convert/saccharine_to_lambda.go +++ b/pkg/convert/saccharine_to_lambda.go @@ -1,3 +1,5 @@ +// Package convert defined some standard conversions between various types of +// representations. package convert import ( @@ -124,10 +126,13 @@ func decodeExression(l lambda.Expression) saccharine.Expression { } } +// Lambda2Saccharine converts a pure lambda calculus expression into its +// Saccharine counterpart. func Lambda2Saccharine(l lambda.Expression) (saccharine.Expression, error) { return decodeExression(l), nil } +// Saccharine2Lambda desugars a saccharine expression into pure lambda calculus. func Saccharine2Lambda(s saccharine.Expression) (lambda.Expression, error) { return encodeExpression(s), nil } diff --git a/pkg/engine/engine.go b/pkg/engine/engine.go index 571b09e..9cbc307 100644 --- a/pkg/engine/engine.go +++ b/pkg/engine/engine.go @@ -2,11 +2,17 @@ // expression. package engine -// A Process handles the reduction of a +// A Process handles the reduction of a single expression. type Process[T any] interface { + // Get the current state of the process. + // Returns an error if the current state cannot be represented. Get() (T, error) + + // Step performs reduction(s) on the representation. If the number of steps + // defined is less than zero, it will perform as many reductions as + // possible. Returns whether a reduction was performed. Step(int) bool } -// An Engine is an object that handles +// An Engine is an function that generates reduction processes. type Engine[T any] = func(T) (Process[T], error) -- 2.49.1 From 375148eae50c890d76ca8a8469c9a0c9ba17411f Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Sat, 7 Feb 2026 20:55:42 -0500 Subject: [PATCH 03/15] feat: removed trace package --- pkg/saccharine/expression.go | 10 +++++----- pkg/saccharine/parse.go | 15 +++++++-------- pkg/saccharine/scan.go | 5 ++--- pkg/trace/trace.go | 25 ------------------------- 4 files changed, 14 insertions(+), 41 deletions(-) delete mode 100644 pkg/trace/trace.go diff --git a/pkg/saccharine/expression.go b/pkg/saccharine/expression.go index 80c8f1b..a0bb7d2 100644 --- a/pkg/saccharine/expression.go +++ b/pkg/saccharine/expression.go @@ -1,7 +1,7 @@ package saccharine type Expression interface { - IsExpression() + isExpression() } /** ------------------------------------------------------------------------- */ @@ -25,10 +25,10 @@ type Clause struct { Returns Expression } -func (Abstraction) IsExpression() {} -func (Application) IsExpression() {} -func (Atom) IsExpression() {} -func (Clause) IsExpression() {} +func (Abstraction) isExpression() {} +func (Application) isExpression() {} +func (Atom) isExpression() {} +func (Clause) isExpression() {} /** ------------------------------------------------------------------------- */ diff --git a/pkg/saccharine/parse.go b/pkg/saccharine/parse.go index 8b73394..88c9e72 100644 --- a/pkg/saccharine/parse.go +++ b/pkg/saccharine/parse.go @@ -5,7 +5,6 @@ import ( "fmt" "git.maximhutz.com/max/lambda/pkg/iterator" - "git.maximhutz.com/max/lambda/pkg/trace" ) type TokenIterator = iterator.Iterator[Token] @@ -42,7 +41,7 @@ func parseToken(i *TokenIterator, expected TokenType, ignoreSoftBreaks bool) (*T func parseString(i *TokenIterator) (string, error) { if tok, err := parseToken(i, TokenAtom, true); err != nil { - return "", trace.Wrap(err, "no variable (col %d)", i.Index()) + return "", fmt.Errorf("no variable (col %d): %w", i.Index(), err) } else { return tok.Value, nil } @@ -64,7 +63,7 @@ func parseList[U any](i *TokenIterator, fn func(*TokenIterator) (U, error), mini for { if u, err := fn(i); err != nil { if len(results) < minimum { - return nil, trace.Wrap(err, "expected at least '%v' items, got only '%v'", minimum, len(results)) + return nil, fmt.Errorf("expected at least '%v' items, got only '%v': %w", minimum, len(results), err) } return results, nil } else { @@ -76,11 +75,11 @@ func parseList[U any](i *TokenIterator, fn func(*TokenIterator) (U, error), mini func parseAbstraction(i *TokenIterator) (*Abstraction, error) { return iterator.Do(i, func(i *TokenIterator) (*Abstraction, error) { if _, err := parseToken(i, TokenSlash, true); err != nil { - return nil, trace.Wrap(err, "no function slash (col %d)", i.MustGet().Column) + return nil, fmt.Errorf("no function slash (col %d): %w", i.MustGet().Column, err) } else if parameters, err := parseList(i, parseString, 0); err != nil { return nil, err } else if _, err = parseToken(i, TokenDot, true); err != nil { - return nil, trace.Wrap(err, "no function dot (col %d)", i.MustGet().Column) + return nil, fmt.Errorf("no function dot (col %d): %w", i.MustGet().Column, err) } else if body, err := parseExpression(i); err != nil { return nil, err } else { @@ -92,11 +91,11 @@ func parseAbstraction(i *TokenIterator) (*Abstraction, error) { func parseApplication(i *TokenIterator) (*Application, error) { return iterator.Do(i, func(i *TokenIterator) (*Application, error) { if _, err := parseToken(i, TokenOpenParen, true); err != nil { - return nil, trace.Wrap(err, "no openning brackets (col %d)", i.MustGet().Column) + return nil, fmt.Errorf("no openning brackets (col %d): %w", i.MustGet().Column, err) } else if expressions, err := parseList(i, parseExpression, 1); err != nil { return nil, err } else if _, err := parseToken(i, TokenCloseParen, true); err != nil { - return nil, trace.Wrap(err, "no closing brackets (col %d)", i.MustGet().Column) + return nil, fmt.Errorf("no closing brackets (col %d): %w", i.MustGet().Column, err) } else { return NewApplication(expressions[0], expressions[1:]), nil } @@ -105,7 +104,7 @@ func parseApplication(i *TokenIterator) (*Application, error) { func parseAtom(i *TokenIterator) (*Atom, error) { if tok, err := parseToken(i, TokenAtom, true); err != nil { - return nil, trace.Wrap(err, "no variable (col %d)", i.Index()) + return nil, fmt.Errorf("no variable (col %d): %w", i.Index(), err) } else { return NewAtom(tok.Value), nil } diff --git a/pkg/saccharine/scan.go b/pkg/saccharine/scan.go index 08e3459..e190b9d 100644 --- a/pkg/saccharine/scan.go +++ b/pkg/saccharine/scan.go @@ -6,7 +6,6 @@ import ( "unicode" "git.maximhutz.com/max/lambda/pkg/iterator" - "git.maximhutz.com/max/lambda/pkg/trace" ) // isVariables determines whether a rune can be a valid variable. @@ -51,7 +50,7 @@ func scanToken(i *iterator.Iterator[rune]) (*Token, error) { letter, err := i.Next() if err != nil { - return nil, trace.Wrap(err, "cannot produce next token") + return nil, fmt.Errorf("cannot produce next token: %w", err) } switch { @@ -82,7 +81,7 @@ func scanToken(i *iterator.Iterator[rune]) (*Token, error) { for !i.Done() { r, err := i.Next() if err != nil { - return nil, trace.Wrap(err, "error while parsing comment") + return nil, fmt.Errorf("error while parsing comment: %w", err) } if r == '\n' { diff --git a/pkg/trace/trace.go b/pkg/trace/trace.go deleted file mode 100644 index 87a0337..0000000 --- a/pkg/trace/trace.go +++ /dev/null @@ -1,25 +0,0 @@ -package trace - -import ( - "errors" - "fmt" - "strings" -) - -func Indent(s string, size int) string { - lines := strings.Lines(s) - indent := strings.Repeat(" ", size) - - indented := "" - for line := range lines { - indented += indent + line - } - - return indented -} - -func Wrap(child error, format string, a ...any) error { - parent := fmt.Errorf(format, a...) - childErrString := Indent(child.Error(), 4) - return errors.New(parent.Error() + "\n" + childErrString) -} -- 2.49.1 From 1fcffb2ea44e0090d74dd0726267a32ab61a6c4b Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Sat, 7 Feb 2026 21:02:13 -0500 Subject: [PATCH 04/15] docs: iterator --- pkg/iterator/iterator.go | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/pkg/iterator/iterator.go b/pkg/iterator/iterator.go index 2db5cd4..bbcde01 100644 --- a/pkg/iterator/iterator.go +++ b/pkg/iterator/iterator.go @@ -1,35 +1,37 @@ -/* -Package "iterator" -*/ +// Package iterator defines a generic way to iterator over a slice of data. package iterator import "fmt" -// An iterator over slices. +// An Iterator traverses over slices. type Iterator[T any] struct { items []T index int } -// Create a new iterator, over a set of items. +// Of creates a new iterator, over a set of defined items. func Of[T any](items []T) *Iterator[T] { return &Iterator[T]{items: items, index: 0} } -// Returns the current position of the iterator. +// Index returns the current position of the iterator. func (i Iterator[T]) Index() int { return i.index } +// Copy returns a identical clone of the iterator. The underlying data structure +// is not cloned. func (i Iterator[T]) Copy() *Iterator[T] { return &Iterator[T]{items: i.items, index: i.index} } +// Sync returns the iterator to the position of another. It is assumed that the +// iterators both operate on the same set of data. func (i *Iterator[T]) Sync(o *Iterator[T]) { i.index = o.index } -// Create a new iterator, over a set of items. +// Get returns the datum at the current position of the iterator. func (i Iterator[T]) Get() (T, error) { var null T if i.Done() { @@ -39,6 +41,7 @@ func (i Iterator[T]) Get() (T, error) { return i.items[i.index], nil } +// MustGet is a version of Get, that panics if the datum cannot be returned. func (i Iterator[T]) MustGet() T { var null T if i.Done() { @@ -48,13 +51,16 @@ func (i Iterator[T]) MustGet() T { return i.items[i.index] } +// Forward increments the iterator if the iterator is not yet at the end of the +// slice. func (i *Iterator[T]) Forward() { if !i.Done() { i.index++ } } -// Create a new iterator, over a set of items. +// Next attempts to increment the iterator. Returns an error if it cannot be +// incremented. func (i *Iterator[T]) Next() (T, error) { item, err := i.Get() if err == nil { @@ -64,16 +70,20 @@ func (i *Iterator[T]) Next() (T, error) { return item, err } -// Create a new iterator, over a set of items. +// Back decrements the iterator. If the iterator is already at the beginning of +// the slice, this is a no-op. func (i *Iterator[T]) Back() { i.index = max(i.index-1, 0) } -// Returns the current position of the iterator. +// Done returns whether the iterator is at the end of the slice or not. func (i Iterator[T]) Done() bool { return i.index == len(i.items) } +// Do attempts to perform an operation using the iterator. If the operation +// succeeds, the iterator is updated. If the operation fails, the iterator is +// rolled back, and an error is returned. func Do[T any, U any](i *Iterator[T], fn func(i *Iterator[T]) (U, error)) (U, error) { i2 := i.Copy() -- 2.49.1 From 4171f0ccb2f784e83b5020cea54aee4a1525f339 Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Sat, 7 Feb 2026 21:05:04 -0500 Subject: [PATCH 05/15] docs: cmd/lambda --- cmd/lambda/lambda.go | 1 + cmd/lambda/lambda_engine.go | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/cmd/lambda/lambda.go b/cmd/lambda/lambda.go index 60070fc..c79df81 100644 --- a/cmd/lambda/lambda.go +++ b/cmd/lambda/lambda.go @@ -1,3 +1,4 @@ +// Package main defines the 'lambda' command-line interface (CLI). package main import ( diff --git a/cmd/lambda/lambda_engine.go b/cmd/lambda/lambda_engine.go index 150e851..8e2f9e9 100644 --- a/cmd/lambda/lambda_engine.go +++ b/cmd/lambda/lambda_engine.go @@ -9,7 +9,7 @@ func LambdaEngine() *cobra.Command { Use: "engine", Aliases: []string{"eng"}, Short: "Information about available engines", - RunE: func(cmd *cobra.Command, args []string) error { + RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }, } -- 2.49.1 From 2a028d95ecd60ae7138329f258f3c51a065e1532 Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Sat, 7 Feb 2026 21:10:27 -0500 Subject: [PATCH 06/15] docs: set --- pkg/set/set.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/pkg/set/set.go b/pkg/set/set.go index c66cf71..2e2ee59 100644 --- a/pkg/set/set.go +++ b/pkg/set/set.go @@ -1,31 +1,41 @@ +// Package set defines a generic, mutable unordered set data structure. package set import "iter" +// A Set is an implementation of an mutable, unordered set. It uses a Golang map +// as its underlying data structure. type Set[T comparable] map[T]bool +// Add appends a list of items into the set. func (s Set[T]) Add(items ...T) { for _, item := range items { s[item] = true } } +// Has returns true an item is present in the set. func (s Set[T]) Has(item T) bool { return s[item] } +// Remove deletes a list of items from the set. func (s Set[T]) Remove(items ...T) { for _, item := range items { delete(s, item) } } +// Merge adds all items in the argument into the set. The argument is not +// mutated. func (s Set[T]) Merge(o Set[T]) { for item := range o { s.Add(item) } } +// ToList returns all items present in the set, as a slice. The order of the +// items is not guaranteed. func (s Set[T]) ToList() []T { list := []T{} @@ -36,6 +46,8 @@ func (s Set[T]) ToList() []T { return list } +// Items returns a sequence of all items present in the set. The order of the +// items is not guaranteed. func (s Set[T]) Items() iter.Seq[T] { return func(yield func(T) bool) { for item := range s { @@ -46,6 +58,7 @@ func (s Set[T]) Items() iter.Seq[T] { } } +// New creates a set of all items as argument. func New[T comparable](items ...T) Set[T] { result := Set[T]{} -- 2.49.1 From 98b327103f276642783d3a08c8669d5f7af49095 Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Mon, 9 Feb 2026 18:26:03 -0500 Subject: [PATCH 07/15] docs: registry --- internal/registry/codec.go | 18 +++++++++++++----- internal/registry/conversion.go | 28 ++++++++++++++++++++++------ internal/registry/converter.go | 7 +++++++ internal/registry/engine.go | 26 +++++++++++++++++++------- internal/registry/expr.go | 12 +++++++----- internal/registry/process.go | 8 ++++---- 6 files changed, 72 insertions(+), 27 deletions(-) diff --git a/internal/registry/codec.go b/internal/registry/codec.go index 302d3d6..e8e9c79 100644 --- a/internal/registry/codec.go +++ b/internal/registry/codec.go @@ -7,18 +7,24 @@ import ( "git.maximhutz.com/max/lambda/pkg/codec" ) +// A Codec is a type-erased codec that serializes and deserializes expressions +// as Expr values, regardless of the underlying representation type. type Codec interface { codec.Codec[Expr] + // InType returns the name of the representation this codec handles. InType() string } -type convertedCodec[T any] struct { +// A registeredCodec adapts a typed codec.Codec[T] into the type-erased Codec +// interface. It wraps decoded values into Expr on decode, and extracts the +// underlying T from an Expr on encode. +type registeredCodec[T any] struct { codec codec.Codec[T] inType string } -func (c convertedCodec[T]) Decode(s string) (Expr, error) { +func (c registeredCodec[T]) Decode(s string) (Expr, error) { t, err := c.codec.Decode(s) if err != nil { return nil, err @@ -27,7 +33,7 @@ func (c convertedCodec[T]) Decode(s string) (Expr, error) { return NewExpr(c.inType, t), nil } -func (c convertedCodec[T]) Encode(r Expr) (string, error) { +func (c registeredCodec[T]) Encode(r Expr) (string, error) { t, ok := r.Data().(T) if !ok { dataType := reflect.TypeOf(r.Data()) @@ -38,13 +44,15 @@ func (c convertedCodec[T]) Encode(r Expr) (string, error) { return c.codec.Encode(t) } -func (c convertedCodec[T]) InType() string { return c.inType } +func (c registeredCodec[T]) InType() string { return c.inType } +// RegisterCodec registers a typed codec under the given representation name. +// Returns an error if a codec for that representation is already registered. func RegisterCodec[T any](registry *Registry, m codec.Codec[T], inType string) error { if _, ok := registry.codecs[inType]; ok { return fmt.Errorf("Codec for '%s' already registered", inType) } - registry.codecs[inType] = convertedCodec[T]{m, inType} + registry.codecs[inType] = registeredCodec[T]{m, inType} return nil } diff --git a/internal/registry/conversion.go b/internal/registry/conversion.go index d5b4d13..75674eb 100644 --- a/internal/registry/conversion.go +++ b/internal/registry/conversion.go @@ -6,19 +6,29 @@ import ( "git.maximhutz.com/max/lambda/pkg/codec" ) +// A Conversion is a type-erased transformation from one representation to +// another. It operates on Expr values, hiding the underlying representation +// types. type Conversion interface { + // InType returns the name of the source representation. InType() string + // OutType returns the name of the target representation. OutType() string + // Run applies the conversion to the given expression. Returns an error if + // the expression's data does not match the expected source type. Run(Expr) (Expr, error) } -type convertedConversion[T, U any] struct { +// A registeredConversion adapts a typed codec.Conversion[T, U] into the +// type-erased Conversion interface. It extracts the underlying T from an Expr, +// applies the conversion, and wraps the result as a new Expr. +type registeredConversion[T, U any] struct { conversion codec.Conversion[T, U] inType, outType string } -func (c convertedConversion[T, U]) Run(expr Expr) (Expr, error) { +func (c registeredConversion[T, U]) Run(expr Expr) (Expr, error) { t, ok := expr.Data().(T) if !ok { return nil, fmt.Errorf("could not parse '%v' as '%s'", t, c.inType) @@ -32,12 +42,18 @@ func (c convertedConversion[T, U]) Run(expr Expr) (Expr, error) { return NewExpr(c.outType, u), nil } -func (c convertedConversion[T, U]) InType() string { return c.inType } +func (c registeredConversion[T, U]) InType() string { return c.inType } -func (c convertedConversion[T, U]) OutType() string { return c.outType } +func (c registeredConversion[T, U]) OutType() string { return c.outType } -func RegisterConversion[T, U any](registry *Registry, conversion func(T) (U, error), inType, outType string) error { - registry.converter.Add(convertedConversion[T, U]{conversion, inType, outType}) +// RegisterConversion registers a typed conversion function between two +// representations. +func RegisterConversion[T, U any]( + registry *Registry, + conversion codec.Conversion[T, U], + inType, outType string, +) error { + registry.converter.Add(registeredConversion[T, U]{conversion, inType, outType}) return nil } diff --git a/internal/registry/converter.go b/internal/registry/converter.go index 5ae74bf..f97de98 100644 --- a/internal/registry/converter.go +++ b/internal/registry/converter.go @@ -1,13 +1,18 @@ package registry +// A Converter is a directed graph of conversions between representations. Each +// node is a representation name, and each edge is a Conversion. type Converter struct { data map[string][]Conversion } +// NewConverter creates an empty Converter with no registered conversions. func NewConverter() *Converter { return &Converter{data: map[string][]Conversion{}} } +// Add registers a conversion, adding an edge from its source representation +// to its target representation. func (g *Converter) Add(c Conversion) { conversionsFromIn, ok := g.data[c.InType()] if !ok { @@ -18,6 +23,8 @@ func (g *Converter) Add(c Conversion) { g.data[c.InType()] = conversionsFromIn } +// ConversionsFrom returns all conversions that have the given representation +// as their source type. func (g *Converter) ConversionsFrom(t string) []Conversion { return g.data[t] } diff --git a/internal/registry/engine.go b/internal/registry/engine.go index 9931916..43ff48c 100644 --- a/internal/registry/engine.go +++ b/internal/registry/engine.go @@ -6,26 +6,36 @@ import ( "git.maximhutz.com/max/lambda/pkg/engine" ) +// An Engine is a type-erased evaluation engine that can load an expression +// into a runnable Process. type Engine interface { + // Load prepares an expression for evaluation, returning a Process. Returns + // an error if the expression's data does not match the engine's expected + // representation type. Load(Expr) (Process, error) + // Name returns the name of this engine. Name() string + // InType returns the name of the representation this engine operates on. InType() string } -type convertedEngine[T any] struct { +// A registeredEngine adapts a typed engine.Engine[T] into the type-erased +// Engine interface. It extracts the underlying T from an Expr before passing it +// to the engine. +type registeredEngine[T any] struct { engine engine.Engine[T] name string inType string } -func (e convertedEngine[T]) InType() string { return e.inType } +func (e registeredEngine[T]) InType() string { return e.inType } -func (e convertedEngine[T]) Name() string { return e.name } +func (e registeredEngine[T]) Name() string { return e.name } -func (e convertedEngine[T]) Load(expr Expr) (Process, error) { +func (e registeredEngine[T]) Load(expr Expr) (Process, error) { t, ok := expr.Data().(T) if !ok { - return nil, fmt.Errorf("'ncorrent format '%s' for engine '%s'", expr.Repr(), e.inType) + return nil, fmt.Errorf("incorrect format '%s' for engine '%s'", expr.Repr(), e.inType) } process, err := e.engine(t) @@ -33,14 +43,16 @@ func (e convertedEngine[T]) Load(expr Expr) (Process, error) { return nil, err } - return convertedProcess[T]{process, e.inType}, nil + return registeredProcess[T]{process, e.inType}, nil } +// RegisterEngine registers a typed engine under the given name. Returns an +// error if an engine with that name is already registered. func RegisterEngine[T any](registry *Registry, e engine.Engine[T], name, inType string) error { if _, ok := registry.engines[name]; ok { return fmt.Errorf("engine '%s' already registered", name) } - registry.engines[name] = &convertedEngine[T]{e, name, inType} + registry.engines[name] = ®isteredEngine[T]{e, name, inType} return nil } diff --git a/internal/registry/expr.go b/internal/registry/expr.go index 49377ae..71db96d 100644 --- a/internal/registry/expr.go +++ b/internal/registry/expr.go @@ -1,17 +1,18 @@ package registry -// A Expr is a lambda calculus expression. It can have any type of -// Expresentation, so long as that class is known to the registry it is handled +// An Expr is a type-erased lambda calculus expression. It can have any type of +// representation, so long as that type is known to the registry it is handled // by. type Expr interface { - // Repr returns the name of the underlying Expresentation. It is assumed if - // two expressions have the same Repr(), they have the same Expresentation. + // Repr returns the name of the underlying representation. Two expressions + // with the same Repr() are assumed to have the same representation type. Repr() string - // The base expression data. + // Data returns the underlying expression data. Data() any } +// A baseExpr is the default implementation of Expr. type baseExpr struct { id string data any @@ -21,4 +22,5 @@ func (r baseExpr) Repr() string { return r.id } func (r baseExpr) Data() any { return r.data } +// NewExpr creates an Expr with the given representation name and data. func NewExpr(id string, data any) Expr { return baseExpr{id, data} } diff --git a/internal/registry/process.go b/internal/registry/process.go index 9e4a0f0..2a83685 100644 --- a/internal/registry/process.go +++ b/internal/registry/process.go @@ -10,14 +10,14 @@ type Process interface { InType() string } -type convertedProcess[T any] struct { +type registeredProcess[T any] struct { process engine.Process[T] inType string } -func (e convertedProcess[T]) InType() string { return e.inType } +func (e registeredProcess[T]) InType() string { return e.inType } -func (b convertedProcess[T]) Get() (Expr, error) { +func (b registeredProcess[T]) Get() (Expr, error) { s, err := b.process.Get() if err != nil { return nil, err @@ -26,6 +26,6 @@ func (b convertedProcess[T]) Get() (Expr, error) { return NewExpr(b.inType, s), nil } -func (b convertedProcess[T]) Step(i int) bool { +func (b registeredProcess[T]) Step(i int) bool { return b.process.Step(i) } -- 2.49.1 From 4201225ce91952a6dcf84c9315c77bde1c6c8487 Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Mon, 9 Feb 2026 18:31:01 -0500 Subject: [PATCH 08/15] docs: process --- internal/registry/expr.go | 4 ++-- internal/registry/process.go | 16 ++++++++++------ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/internal/registry/expr.go b/internal/registry/expr.go index 71db96d..7d4d506 100644 --- a/internal/registry/expr.go +++ b/internal/registry/expr.go @@ -18,9 +18,9 @@ type baseExpr struct { data any } -func (r baseExpr) Repr() string { return r.id } +func (e baseExpr) Repr() string { return e.id } -func (r baseExpr) Data() any { return r.data } +func (e baseExpr) Data() any { return e.data } // NewExpr creates an Expr with the given representation name and data. func NewExpr(id string, data any) Expr { return baseExpr{id, data} } diff --git a/internal/registry/process.go b/internal/registry/process.go index 2a83685..b39227c 100644 --- a/internal/registry/process.go +++ b/internal/registry/process.go @@ -4,28 +4,32 @@ import ( "git.maximhutz.com/max/lambda/pkg/engine" ) +// A Process is a type-erased reduction process that operates on Expr values. type Process interface { engine.Process[Expr] + // InType returns the name of the representation this process operates on. InType() string } +// A registeredProcess adapts a typed engine.Process[T] into the type-erased +// Process interface. It wraps the result of Get into an Expr. type registeredProcess[T any] struct { process engine.Process[T] inType string } -func (e registeredProcess[T]) InType() string { return e.inType } +func (p registeredProcess[T]) InType() string { return p.inType } -func (b registeredProcess[T]) Get() (Expr, error) { - s, err := b.process.Get() +func (p registeredProcess[T]) Get() (Expr, error) { + s, err := p.process.Get() if err != nil { return nil, err } - return NewExpr(b.inType, s), nil + return NewExpr(p.inType, s), nil } -func (b registeredProcess[T]) Step(i int) bool { - return b.process.Step(i) +func (p registeredProcess[T]) Step(i int) bool { + return p.process.Step(i) } -- 2.49.1 From d24cbd9d860084dea6364e44b75490af4d80794b Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Mon, 9 Feb 2026 18:40:35 -0500 Subject: [PATCH 09/15] docs: token --- pkg/saccharine/scan.go | 18 ++++----- pkg/saccharine/token.go | 90 ++++++++++++++++++----------------------- 2 files changed, 49 insertions(+), 59 deletions(-) diff --git a/pkg/saccharine/scan.go b/pkg/saccharine/scan.go index e190b9d..762900b 100644 --- a/pkg/saccharine/scan.go +++ b/pkg/saccharine/scan.go @@ -55,27 +55,27 @@ func scanToken(i *iterator.Iterator[rune]) (*Token, error) { switch { case letter == '(': - return NewTokenOpenParen(index), nil + return NewToken(TokenOpenParen, index), nil case letter == ')': - return NewTokenCloseParen(index), nil + return NewToken(TokenCloseParen, index), nil case letter == '.': - return NewTokenDot(index), nil + return NewToken(TokenDot, index), nil case letter == '\\': - return NewTokenSlash(index), nil + return NewToken(TokenSlash, index), nil case letter == '\n': - return NewTokenSoftBreak(index), nil + return NewToken(TokenSoftBreak, index), nil case letter == '{': - return NewTokenOpenBrace(index), nil + return NewToken(TokenOpenBrace, index), nil case letter == '}': - return NewTokenCloseBrace(index), nil + return NewToken(TokenCloseBrace, index), nil case letter == ':': if _, err := scanCharacter(i, '='); err != nil { return nil, err } else { - return NewTokenAssign(index), nil + return NewToken(TokenAssign, index), nil } case letter == ';': - return NewTokenHardBreak(index), nil + return NewToken(TokenHardBreak, index), nil case letter == '#': // Skip everything until the next newline or EOF. for !i.Done() { diff --git a/pkg/saccharine/token.go b/pkg/saccharine/token.go index ee61dbf..c7a1ac6 100644 --- a/pkg/saccharine/token.go +++ b/pkg/saccharine/token.go @@ -2,90 +2,80 @@ package saccharine import "fmt" -// All tokens in the pseudo-lambda language. +// A TokenType is an identifier for any token in the Saccharine language. type TokenType int +// All official tokens of the Saccharine language. const ( - TokenOpenParen TokenType = iota // Denotes the '(' token. - TokenCloseParen // Denotes the ')' token. - TokenOpenBrace // Denotes the '{' token. - TokenCloseBrace // Denotes the '}' token. - TokenHardBreak // Denotes the ';' token. - TokenAssign // Denotes the ':=' token. - TokenAtom // Denotes an alpha-numeric variable. - TokenSlash // Denotes the '/' token. - TokenDot // Denotes the '.' token. - TokenSoftBreak // Denotes a new-line. + // TokenOpenParen denotes the '(' token. + TokenOpenParen TokenType = iota + // TokenCloseParen denotes the ')' token. + TokenCloseParen + // TokenOpenBrace denotes the '{' token. + TokenOpenBrace + // TokenCloseBrace denotes the '}' token. + TokenCloseBrace + // TokenHardBreak denotes the ';' token. + TokenHardBreak + // TokenAssign denotes the ':=' token. + TokenAssign + // TokenAtom denotes an alpha-numeric variable. + TokenAtom + // TokenSlash denotes the '/' token. + TokenSlash + // TokenDot denotes the '.' token. + TokenDot + // TokenSoftBreak denotes a new-line. + TokenSoftBreak ) -// A representation of a token in source code. +// A Token in the Saccharine language. type Token struct { Column int // Where the token begins in the source text. Type TokenType // What type the token is. Value string // The value of the token. } -func NewTokenOpenParen(column int) *Token { - return &Token{Type: TokenOpenParen, Column: column, Value: "("} -} - -func NewTokenCloseParen(column int) *Token { - return &Token{Type: TokenCloseParen, Column: column, Value: ")"} -} - -func NewTokenOpenBrace(column int) *Token { - return &Token{Type: TokenOpenBrace, Column: column, Value: "{"} -} - -func NewTokenCloseBrace(column int) *Token { - return &Token{Type: TokenCloseBrace, Column: column, Value: "}"} -} - -func NewTokenDot(column int) *Token { - return &Token{Type: TokenDot, Column: column, Value: "."} -} - -func NewTokenHardBreak(column int) *Token { - return &Token{Type: TokenHardBreak, Column: column, Value: ";"} -} - -func NewTokenAssign(column int) *Token { - return &Token{Type: TokenAssign, Column: column, Value: ":="} -} - -func NewTokenSlash(column int) *Token { - return &Token{Type: TokenSlash, Column: column, Value: "\\"} +// NewToken creates a [Token] of the given type at the given column. +// The token's value is derived from its [TokenType]. +func NewToken(typ TokenType, column int) *Token { + return &Token{Type: typ, Column: column, Value: typ.Name()} } +// NewTokenAtom creates a [TokenAtom] with the given name at the given column. func NewTokenAtom(name string, column int) *Token { return &Token{Type: TokenAtom, Column: column, Value: name} } -func NewTokenSoftBreak(column int) *Token { - return &Token{Type: TokenSoftBreak, Column: column, Value: "\\n"} -} - +// Name returns the type of the TokenType, as a string. func (t TokenType) Name() string { switch t { case TokenOpenParen: return "(" case TokenCloseParen: return ")" + case TokenOpenBrace: + return "{" + case TokenCloseBrace: + return "}" + case TokenHardBreak: + return ";" + case TokenAssign: + return ":=" + case TokenAtom: + return "ATOM" case TokenSlash: return "\\" case TokenDot: return "." - case TokenAtom: - return "ATOM" case TokenSoftBreak: return "\\n" - case TokenHardBreak: - return ";" default: panic(fmt.Errorf("unknown token type %v", t)) } } +// Name returns the type of the Token, as a string. func (t Token) Name() string { return t.Type.Name() } -- 2.49.1 From c4ba80924aa2a95671826d1722004e87a305824f Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Mon, 9 Feb 2026 19:37:49 -0500 Subject: [PATCH 10/15] feat: no constructors for expressions and statements for saccharine --- pkg/convert/saccharine_to_lambda.go | 16 ++++++++-------- pkg/saccharine/expression.go | 28 +++++----------------------- pkg/saccharine/parse.go | 12 ++++++------ pkg/saccharine/statement.go | 16 +++------------- 4 files changed, 22 insertions(+), 50 deletions(-) diff --git a/pkg/convert/saccharine_to_lambda.go b/pkg/convert/saccharine_to_lambda.go index d8caa97..c441e8e 100644 --- a/pkg/convert/saccharine_to_lambda.go +++ b/pkg/convert/saccharine_to_lambda.go @@ -55,7 +55,7 @@ func reduceLet(s *saccharine.LetStatement, e lambda.Expression) lambda.Expressio if len(s.Parameters) == 0 { value = encodeExpression(s.Body) } else { - value = encodeAbstraction(saccharine.NewAbstraction(s.Parameters, s.Body)) + value = encodeAbstraction(&saccharine.Abstraction{Parameters: s.Parameters, Body: s.Body}) } return lambda.NewApplication( @@ -112,15 +112,15 @@ func encodeExpression(s saccharine.Expression) lambda.Expression { func decodeExression(l lambda.Expression) saccharine.Expression { switch l := l.(type) { case lambda.Variable: - return saccharine.NewAtom(l.Name()) + return &saccharine.Atom{Name: l.Name()} case lambda.Abstraction: - return saccharine.NewAbstraction( - []string{l.Parameter()}, - decodeExression(l.Body())) + return &saccharine.Abstraction{ + Parameters: []string{l.Parameter()}, + Body: decodeExression(l.Body())} case lambda.Application: - return saccharine.NewApplication( - decodeExression(l.Abstraction()), - []saccharine.Expression{decodeExression(l.Argument())}) + return &saccharine.Application{ + Abstraction: decodeExression(l.Abstraction()), + Arguments: []saccharine.Expression{decodeExression(l.Argument())}} default: panic(fmt.Errorf("unknown expression type: %T", l)) } diff --git a/pkg/saccharine/expression.go b/pkg/saccharine/expression.go index a0bb7d2..3cf127c 100644 --- a/pkg/saccharine/expression.go +++ b/pkg/saccharine/expression.go @@ -1,7 +1,7 @@ package saccharine type Expression interface { - isExpression() + expression() } /** ------------------------------------------------------------------------- */ @@ -25,25 +25,7 @@ type Clause struct { Returns Expression } -func (Abstraction) isExpression() {} -func (Application) isExpression() {} -func (Atom) isExpression() {} -func (Clause) isExpression() {} - -/** ------------------------------------------------------------------------- */ - -func NewAbstraction(parameter []string, body Expression) *Abstraction { - return &Abstraction{Parameters: parameter, Body: body} -} - -func NewApplication(abstraction Expression, arguments []Expression) *Application { - return &Application{Abstraction: abstraction, Arguments: arguments} -} - -func NewAtom(name string) *Atom { - return &Atom{Name: name} -} - -func NewClause(statements []Statement, returns Expression) *Clause { - return &Clause{Statements: statements, Returns: returns} -} +func (Abstraction) expression() {} +func (Application) expression() {} +func (Atom) expression() {} +func (Clause) expression() {} diff --git a/pkg/saccharine/parse.go b/pkg/saccharine/parse.go index 88c9e72..3bb9285 100644 --- a/pkg/saccharine/parse.go +++ b/pkg/saccharine/parse.go @@ -83,7 +83,7 @@ func parseAbstraction(i *TokenIterator) (*Abstraction, error) { } else if body, err := parseExpression(i); err != nil { return nil, err } else { - return NewAbstraction(parameters, body), nil + return &Abstraction{Parameters: parameters, Body: body}, nil } }) } @@ -97,7 +97,7 @@ func parseApplication(i *TokenIterator) (*Application, error) { } else if _, err := parseToken(i, TokenCloseParen, true); err != nil { return nil, fmt.Errorf("no closing brackets (col %d): %w", i.MustGet().Column, err) } else { - return NewApplication(expressions[0], expressions[1:]), nil + return &Application{Abstraction: expressions[0], Arguments: expressions[1:]}, nil } }) } @@ -106,7 +106,7 @@ func parseAtom(i *TokenIterator) (*Atom, error) { if tok, err := parseToken(i, TokenAtom, true); err != nil { return nil, fmt.Errorf("no variable (col %d): %w", i.Index(), err) } else { - return NewAtom(tok.Value), nil + return &Atom{Name: tok.Value}, nil } } @@ -155,7 +155,7 @@ func parseClause(i *TokenIterator, braces bool) (*Clause, error) { } } - return NewClause(stmts[:len(stmts)-1], last.Value), nil + return &Clause{Statements: stmts[:len(stmts)-1], Returns: last.Value}, nil } func parseExpression(i *TokenIterator) (Expression, error) { @@ -186,7 +186,7 @@ func parseLet(i *TokenIterator) (*LetStatement, error) { } else if body, err := parseExpression(i); err != nil { return nil, err } else { - return NewLet(parameters[0], parameters[1:], body), nil + return &LetStatement{Name: parameters[0], Parameters: parameters[1:], Body: body}, nil } }) } @@ -195,7 +195,7 @@ func parseDeclare(i *TokenIterator) (*DeclareStatement, error) { if value, err := parseExpression(i); err != nil { return nil, err } else { - return NewDeclare(value), nil + return &DeclareStatement{Value: value}, nil } } diff --git a/pkg/saccharine/statement.go b/pkg/saccharine/statement.go index 1d0dd15..03e5302 100644 --- a/pkg/saccharine/statement.go +++ b/pkg/saccharine/statement.go @@ -1,7 +1,7 @@ package saccharine type Statement interface { - IsStatement() + statement() } /** ------------------------------------------------------------------------- */ @@ -16,15 +16,5 @@ type DeclareStatement struct { Value Expression } -func (LetStatement) IsStatement() {} -func (DeclareStatement) IsStatement() {} - -/** ------------------------------------------------------------------------- */ - -func NewLet(name string, parameters []string, body Expression) *LetStatement { - return &LetStatement{Name: name, Parameters: parameters, Body: body} -} - -func NewDeclare(value Expression) *DeclareStatement { - return &DeclareStatement{Value: value} -} +func (LetStatement) statement() {} +func (DeclareStatement) statement() {} -- 2.49.1 From c6186d9c80735034fc7dddf894af8b270e5e6f64 Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Mon, 9 Feb 2026 19:40:38 -0500 Subject: [PATCH 11/15] docs: saccharine expressions/stmts, private tokenIterator --- pkg/saccharine/expression.go | 31 ------------------- pkg/saccharine/parse.go | 44 +++++++++++++------------- pkg/saccharine/saccharine.go | 60 ++++++++++++++++++++++++++++++++++++ pkg/saccharine/statement.go | 20 ------------ 4 files changed, 82 insertions(+), 73 deletions(-) delete mode 100644 pkg/saccharine/expression.go create mode 100644 pkg/saccharine/saccharine.go delete mode 100644 pkg/saccharine/statement.go diff --git a/pkg/saccharine/expression.go b/pkg/saccharine/expression.go deleted file mode 100644 index 3cf127c..0000000 --- a/pkg/saccharine/expression.go +++ /dev/null @@ -1,31 +0,0 @@ -package saccharine - -type Expression interface { - expression() -} - -/** ------------------------------------------------------------------------- */ - -type Abstraction struct { - Parameters []string - Body Expression -} - -type Application struct { - Abstraction Expression - Arguments []Expression -} - -type Atom struct { - Name string -} - -type Clause struct { - Statements []Statement - Returns Expression -} - -func (Abstraction) expression() {} -func (Application) expression() {} -func (Atom) expression() {} -func (Clause) expression() {} diff --git a/pkg/saccharine/parse.go b/pkg/saccharine/parse.go index 3bb9285..60a8736 100644 --- a/pkg/saccharine/parse.go +++ b/pkg/saccharine/parse.go @@ -7,10 +7,10 @@ import ( "git.maximhutz.com/max/lambda/pkg/iterator" ) -type TokenIterator = iterator.Iterator[Token] +type tokenIterator = iterator.Iterator[Token] -func parseRawToken(i *TokenIterator, expected TokenType) (*Token, error) { - return iterator.Do(i, func(i *TokenIterator) (*Token, error) { +func parseRawToken(i *tokenIterator, expected TokenType) (*Token, error) { + return iterator.Do(i, func(i *tokenIterator) (*Token, error) { if tok, err := i.Next(); err != nil { return nil, err } else if tok.Type != expected { @@ -21,7 +21,7 @@ func parseRawToken(i *TokenIterator, expected TokenType) (*Token, error) { }) } -func passSoftBreaks(i *TokenIterator) { +func passSoftBreaks(i *tokenIterator) { for { if _, err := parseRawToken(i, TokenSoftBreak); err != nil { return @@ -29,8 +29,8 @@ func passSoftBreaks(i *TokenIterator) { } } -func parseToken(i *TokenIterator, expected TokenType, ignoreSoftBreaks bool) (*Token, error) { - return iterator.Do(i, func(i *TokenIterator) (*Token, error) { +func parseToken(i *tokenIterator, expected TokenType, ignoreSoftBreaks bool) (*Token, error) { + return iterator.Do(i, func(i *tokenIterator) (*Token, error) { if ignoreSoftBreaks { passSoftBreaks(i) } @@ -39,7 +39,7 @@ func parseToken(i *TokenIterator, expected TokenType, ignoreSoftBreaks bool) (*T }) } -func parseString(i *TokenIterator) (string, error) { +func parseString(i *tokenIterator) (string, error) { if tok, err := parseToken(i, TokenAtom, true); err != nil { return "", fmt.Errorf("no variable (col %d): %w", i.Index(), err) } else { @@ -47,7 +47,7 @@ func parseString(i *TokenIterator) (string, error) { } } -func parseBreak(i *TokenIterator) (*Token, error) { +func parseBreak(i *tokenIterator) (*Token, error) { if tok, softErr := parseRawToken(i, TokenSoftBreak); softErr == nil { return tok, nil } else if tok, hardErr := parseRawToken(i, TokenHardBreak); hardErr == nil { @@ -57,7 +57,7 @@ func parseBreak(i *TokenIterator) (*Token, error) { } } -func parseList[U any](i *TokenIterator, fn func(*TokenIterator) (U, error), minimum int) ([]U, error) { +func parseList[U any](i *tokenIterator, fn func(*tokenIterator) (U, error), minimum int) ([]U, error) { results := []U{} for { @@ -72,8 +72,8 @@ func parseList[U any](i *TokenIterator, fn func(*TokenIterator) (U, error), mini } } -func parseAbstraction(i *TokenIterator) (*Abstraction, error) { - return iterator.Do(i, func(i *TokenIterator) (*Abstraction, error) { +func parseAbstraction(i *tokenIterator) (*Abstraction, error) { + return iterator.Do(i, func(i *tokenIterator) (*Abstraction, error) { if _, err := parseToken(i, TokenSlash, true); err != nil { return nil, fmt.Errorf("no function slash (col %d): %w", i.MustGet().Column, err) } else if parameters, err := parseList(i, parseString, 0); err != nil { @@ -88,8 +88,8 @@ func parseAbstraction(i *TokenIterator) (*Abstraction, error) { }) } -func parseApplication(i *TokenIterator) (*Application, error) { - return iterator.Do(i, func(i *TokenIterator) (*Application, error) { +func parseApplication(i *tokenIterator) (*Application, error) { + return iterator.Do(i, func(i *tokenIterator) (*Application, error) { if _, err := parseToken(i, TokenOpenParen, true); err != nil { return nil, fmt.Errorf("no openning brackets (col %d): %w", i.MustGet().Column, err) } else if expressions, err := parseList(i, parseExpression, 1); err != nil { @@ -102,7 +102,7 @@ func parseApplication(i *TokenIterator) (*Application, error) { }) } -func parseAtom(i *TokenIterator) (*Atom, error) { +func parseAtom(i *tokenIterator) (*Atom, error) { if tok, err := parseToken(i, TokenAtom, true); err != nil { return nil, fmt.Errorf("no variable (col %d): %w", i.Index(), err) } else { @@ -110,7 +110,7 @@ func parseAtom(i *TokenIterator) (*Atom, error) { } } -func parseStatements(i *TokenIterator) ([]Statement, error) { +func parseStatements(i *tokenIterator) ([]Statement, error) { statements := []Statement{} //nolint:errcheck @@ -129,7 +129,7 @@ func parseStatements(i *TokenIterator) ([]Statement, error) { return statements, nil } -func parseClause(i *TokenIterator, braces bool) (*Clause, error) { +func parseClause(i *tokenIterator, braces bool) (*Clause, error) { if braces { if _, err := parseToken(i, TokenOpenBrace, true); err != nil { return nil, err @@ -158,8 +158,8 @@ func parseClause(i *TokenIterator, braces bool) (*Clause, error) { return &Clause{Statements: stmts[:len(stmts)-1], Returns: last.Value}, nil } -func parseExpression(i *TokenIterator) (Expression, error) { - return iterator.Do(i, func(i *TokenIterator) (Expression, error) { +func parseExpression(i *tokenIterator) (Expression, error) { + return iterator.Do(i, func(i *tokenIterator) (Expression, error) { passSoftBreaks(i) switch peek := i.MustGet(); peek.Type { @@ -177,8 +177,8 @@ func parseExpression(i *TokenIterator) (Expression, error) { }) } -func parseLet(i *TokenIterator) (*LetStatement, error) { - return iterator.Do(i, func(i *TokenIterator) (*LetStatement, error) { +func parseLet(i *tokenIterator) (*LetStatement, error) { + return iterator.Do(i, func(i *tokenIterator) (*LetStatement, error) { if parameters, err := parseList(i, parseString, 1); err != nil { return nil, err } else if _, err := parseToken(i, TokenAssign, true); err != nil { @@ -191,7 +191,7 @@ func parseLet(i *TokenIterator) (*LetStatement, error) { }) } -func parseDeclare(i *TokenIterator) (*DeclareStatement, error) { +func parseDeclare(i *tokenIterator) (*DeclareStatement, error) { if value, err := parseExpression(i); err != nil { return nil, err } else { @@ -199,7 +199,7 @@ func parseDeclare(i *TokenIterator) (*DeclareStatement, error) { } } -func parseStatement(i *TokenIterator) (Statement, error) { +func parseStatement(i *tokenIterator) (Statement, error) { if let, letErr := parseLet(i); letErr == nil { return let, nil } else if declare, declErr := parseDeclare(i); declErr == nil { diff --git a/pkg/saccharine/saccharine.go b/pkg/saccharine/saccharine.go new file mode 100644 index 0000000..a4b2d50 --- /dev/null +++ b/pkg/saccharine/saccharine.go @@ -0,0 +1,60 @@ +// Package saccharine defines the AST for the Saccharine language, a sugared +// lambda calculus with let bindings and multi-statement clauses. +package saccharine + +// An Expression is a node in the Saccharine abstract syntax tree. +// It is a sealed interface; only types in this package may implement it. +type Expression interface { + expression() +} + +// An Abstraction is a lambda expression with zero or more parameters. +// A zero-parameter abstraction is treated as a thunk. +type Abstraction struct { + Parameters []string + Body Expression +} + +// An Application applies an expression to zero or more arguments. +type Application struct { + Abstraction Expression + Arguments []Expression +} + +// An Atom is a named variable. +type Atom struct { + Name string +} + +// A Clause is a sequence of statements followed by a return expression. +type Clause struct { + Statements []Statement + Returns Expression +} + +func (Abstraction) expression() {} +func (Application) expression() {} +func (Atom) expression() {} +func (Clause) expression() {} + +// A Statement is a declaration within a Clause. +// It is a sealed interface; only types in this package may implement it. +type Statement interface { + statement() +} + +// A LetStatement binds a name (with optional parameters) to an expression. +type LetStatement struct { + Name string + Parameters []string + Body Expression +} + +// A DeclareStatement evaluates an expression for its side effects within a +// clause. +type DeclareStatement struct { + Value Expression +} + +func (LetStatement) statement() {} +func (DeclareStatement) statement() {} diff --git a/pkg/saccharine/statement.go b/pkg/saccharine/statement.go deleted file mode 100644 index 03e5302..0000000 --- a/pkg/saccharine/statement.go +++ /dev/null @@ -1,20 +0,0 @@ -package saccharine - -type Statement interface { - statement() -} - -/** ------------------------------------------------------------------------- */ - -type LetStatement struct { - Name string - Parameters []string - Body Expression -} - -type DeclareStatement struct { - Value Expression -} - -func (LetStatement) statement() {} -func (DeclareStatement) statement() {} -- 2.49.1 From 08bf24874523c3b4e567cab46503c642a40f26f4 Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Mon, 9 Feb 2026 19:45:58 -0500 Subject: [PATCH 12/15] docs: codec --- cmd/lambda/registry.go | 2 +- pkg/saccharine/codec.go | 15 +++++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/cmd/lambda/registry.go b/cmd/lambda/registry.go index e0b3f57..404eda8 100644 --- a/cmd/lambda/registry.go +++ b/cmd/lambda/registry.go @@ -20,7 +20,7 @@ func GetRegistry() *registry.Registry { // Marshalers (registry.RegisterCodec(r, lambda.Marshaler{}, "lambda")) - (registry.RegisterCodec(r, saccharine.Marshaler{}, "saccharine")) + (registry.RegisterCodec(r, saccharine.Codec{}, "saccharine")) return r } diff --git a/pkg/saccharine/codec.go b/pkg/saccharine/codec.go index bbdb2c4..43c6e84 100644 --- a/pkg/saccharine/codec.go +++ b/pkg/saccharine/codec.go @@ -1,14 +1,15 @@ -// Package "saccharine" provides a simple language built on top of λ-calculus, -// to facilitate productive coding using it. package saccharine import ( "git.maximhutz.com/max/lambda/pkg/codec" ) -type Marshaler struct{} +// A Codec is a [codec.Codec] that serializes Saccharine expressions. +type Codec struct{} -func (m Marshaler) Decode(s string) (Expression, error) { +// Decode parses a string as Saccharine source code. Returns an error +// if it cannot. +func (c Codec) Decode(s string) (Expression, error) { tokens, err := scan(s) if err != nil { return nil, err @@ -17,8 +18,10 @@ func (m Marshaler) Decode(s string) (Expression, error) { return parse(tokens) } -func (m Marshaler) Encode(e Expression) (string, error) { +// Encode turns a Saccharine expression into a string. Returns an error if it +// cannot. +func (c Codec) Encode(e Expression) (string, error) { return stringifyExpression(e), nil } -var _ codec.Codec[Expression] = (*Marshaler)(nil) +var _ codec.Codec[Expression] = (*Codec)(nil) -- 2.49.1 From 9d44f5433ca4b5c16ec1e62c06e9e8481d1e41e0 Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Mon, 9 Feb 2026 19:52:09 -0500 Subject: [PATCH 13/15] feat: lambda expressions are mutable now --- pkg/convert/saccharine_to_lambda.go | 32 ++++++++-------- pkg/engine/normalorder/reduce_once.go | 16 ++++---- pkg/lambda/get_free_variables.go | 10 ++--- pkg/lambda/is_free_variable.go | 6 +-- pkg/lambda/lambda.go | 54 +++------------------------ pkg/lambda/rename.go | 18 ++++----- pkg/lambda/stringify.go | 13 +++++++ pkg/lambda/substitute.go | 16 ++++---- 8 files changed, 67 insertions(+), 98 deletions(-) create mode 100644 pkg/lambda/stringify.go diff --git a/pkg/convert/saccharine_to_lambda.go b/pkg/convert/saccharine_to_lambda.go index c441e8e..a76a968 100644 --- a/pkg/convert/saccharine_to_lambda.go +++ b/pkg/convert/saccharine_to_lambda.go @@ -10,7 +10,7 @@ import ( ) func encodeAtom(n *saccharine.Atom) lambda.Expression { - return lambda.NewVariable(n.Name) + return lambda.Variable{Name: n.Name} } func encodeAbstraction(n *saccharine.Abstraction) lambda.Expression { @@ -27,7 +27,7 @@ func encodeAbstraction(n *saccharine.Abstraction) lambda.Expression { } for i := len(parameters) - 1; i >= 0; i-- { - result = lambda.NewAbstraction(parameters[i], result) + result = lambda.Abstraction{Parameter: parameters[i], Body: result} } return result @@ -43,7 +43,7 @@ func encodeApplication(n *saccharine.Application) lambda.Expression { } for _, argument := range arguments { - result = lambda.NewApplication(result, argument) + result = lambda.Application{Abstraction: result, Argument: argument} } return result @@ -58,19 +58,19 @@ func reduceLet(s *saccharine.LetStatement, e lambda.Expression) lambda.Expressio value = encodeAbstraction(&saccharine.Abstraction{Parameters: s.Parameters, Body: s.Body}) } - return lambda.NewApplication( - lambda.NewAbstraction(s.Name, e), - value, - ) + return lambda.Application{ + Abstraction: lambda.Abstraction{Parameter: s.Name, Body: e}, + Argument: value, + } } func reduceDeclare(s *saccharine.DeclareStatement, e lambda.Expression) lambda.Expression { freshVar := lambda.GenerateFreshName(e.GetFree()) - return lambda.NewApplication( - lambda.NewAbstraction(freshVar, e), - encodeExpression(s.Value), - ) + return lambda.Application{ + Abstraction: lambda.Abstraction{Parameter: freshVar, Body: e}, + Argument: encodeExpression(s.Value), + } } func reduceStatement(s saccharine.Statement, e lambda.Expression) lambda.Expression { @@ -112,15 +112,15 @@ func encodeExpression(s saccharine.Expression) lambda.Expression { func decodeExression(l lambda.Expression) saccharine.Expression { switch l := l.(type) { case lambda.Variable: - return &saccharine.Atom{Name: l.Name()} + return &saccharine.Atom{Name: l.Name} case lambda.Abstraction: return &saccharine.Abstraction{ - Parameters: []string{l.Parameter()}, - Body: decodeExression(l.Body())} + Parameters: []string{l.Parameter}, + Body: decodeExression(l.Body)} case lambda.Application: return &saccharine.Application{ - Abstraction: decodeExression(l.Abstraction()), - Arguments: []saccharine.Expression{decodeExression(l.Argument())}} + Abstraction: decodeExression(l.Abstraction), + Arguments: []saccharine.Expression{decodeExression(l.Argument)}} default: panic(fmt.Errorf("unknown expression type: %T", l)) } diff --git a/pkg/engine/normalorder/reduce_once.go b/pkg/engine/normalorder/reduce_once.go index 734d6a5..50d4d5a 100644 --- a/pkg/engine/normalorder/reduce_once.go +++ b/pkg/engine/normalorder/reduce_once.go @@ -10,25 +10,25 @@ import "git.maximhutz.com/max/lambda/pkg/lambda" func ReduceOnce(e lambda.Expression) (lambda.Expression, bool) { switch e := e.(type) { case lambda.Abstraction: - body, reduced := ReduceOnce(e.Body()) + body, reduced := ReduceOnce(e.Body) if reduced { - return lambda.NewAbstraction(e.Parameter(), body), true + return lambda.Abstraction{Parameter: e.Parameter, Body: body}, true } return e, false case lambda.Application: - if fn, fnOk := e.Abstraction().(lambda.Abstraction); fnOk { - return fn.Body().Substitute(fn.Parameter(), e.Argument()), true + if fn, fnOk := e.Abstraction.(lambda.Abstraction); fnOk { + return fn.Body.Substitute(fn.Parameter, e.Argument), true } - abs, reduced := ReduceOnce(e.Abstraction()) + abs, reduced := ReduceOnce(e.Abstraction) if reduced { - return lambda.NewApplication(abs, e.Argument()), true + return lambda.Application{Abstraction: abs, Argument: e.Argument}, true } - arg, reduced := ReduceOnce(e.Argument()) + arg, reduced := ReduceOnce(e.Argument) if reduced { - return lambda.NewApplication(e.Abstraction(), arg), true + return lambda.Application{Abstraction: e.Abstraction, Argument: arg}, true } return e, false diff --git a/pkg/lambda/get_free_variables.go b/pkg/lambda/get_free_variables.go index 1c2bf91..dbed3e5 100644 --- a/pkg/lambda/get_free_variables.go +++ b/pkg/lambda/get_free_variables.go @@ -3,17 +3,17 @@ package lambda import "git.maximhutz.com/max/lambda/pkg/set" func (e Variable) GetFree() set.Set[string] { - return set.New(e.Name()) + return set.New(e.Name) } func (e Abstraction) GetFree() set.Set[string] { - vars := e.Body().GetFree() - vars.Remove(e.Parameter()) + vars := e.Body.GetFree() + vars.Remove(e.Parameter) return vars } func (e Application) GetFree() set.Set[string] { - vars := e.Abstraction().GetFree() - vars.Merge(e.Argument().GetFree()) + vars := e.Abstraction.GetFree() + vars.Merge(e.Argument.GetFree()) return vars } diff --git a/pkg/lambda/is_free_variable.go b/pkg/lambda/is_free_variable.go index 09d77a6..5db42a6 100644 --- a/pkg/lambda/is_free_variable.go +++ b/pkg/lambda/is_free_variable.go @@ -1,12 +1,12 @@ package lambda func (e Variable) IsFree(n string) bool { - return e.Name() == n + return e.Name == n } func (e Abstraction) IsFree(n string) bool { - return e.Parameter() != n && e.Body().IsFree(n) + return e.Parameter != n && e.Body.IsFree(n) } func (e Application) IsFree(n string) bool { - return e.Abstraction().IsFree(n) || e.Argument().IsFree(n) + return e.Abstraction.IsFree(n) || e.Argument.IsFree(n) } diff --git a/pkg/lambda/lambda.go b/pkg/lambda/lambda.go index b979a09..b3680c5 100644 --- a/pkg/lambda/lambda.go +++ b/pkg/lambda/lambda.go @@ -32,69 +32,25 @@ type Expression interface { /** ------------------------------------------------------------------------- */ type Abstraction struct { - parameter string - body Expression + Parameter string + Body Expression } var _ Expression = Abstraction{} -func (a Abstraction) Parameter() string { - return a.parameter -} - -func (a Abstraction) Body() Expression { - return a.body -} - -func (a Abstraction) String() string { - return "\\" + a.parameter + "." + a.body.String() -} - -func NewAbstraction(parameter string, body Expression) Abstraction { - return Abstraction{parameter, body} -} - /** ------------------------------------------------------------------------- */ type Application struct { - abstraction Expression - argument Expression + Abstraction Expression + Argument Expression } var _ Expression = Application{} -func (a Application) Abstraction() Expression { - return a.abstraction -} - -func (a Application) Argument() Expression { - return a.argument -} - -func (a Application) String() string { - return "(" + a.abstraction.String() + " " + a.argument.String() + ")" -} - -func NewApplication(abstraction Expression, argument Expression) Application { - return Application{abstraction, argument} -} - /** ------------------------------------------------------------------------- */ type Variable struct { - name string + Name string } var _ Expression = Variable{} - -func (v Variable) Name() string { - return v.name -} - -func (v Variable) String() string { - return v.name -} - -func NewVariable(name string) Variable { - return Variable{name} -} diff --git a/pkg/lambda/rename.go b/pkg/lambda/rename.go index 2c39237..10e438d 100644 --- a/pkg/lambda/rename.go +++ b/pkg/lambda/rename.go @@ -2,27 +2,27 @@ package lambda // Rename replaces all occurrences of the target variable name with the new name. func (e Variable) Rename(target string, newName string) Expression { - if e.Name() == target { - return NewVariable(newName) + if e.Name == target { + return Variable{Name: newName} } return e } func (e Abstraction) Rename(target string, newName string) Expression { - newParam := e.Parameter() - if e.Parameter() == target { + newParam := e.Parameter + if e.Parameter == target { newParam = newName } - newBody := e.Body().Rename(target, newName) + newBody := e.Body.Rename(target, newName) - return NewAbstraction(newParam, newBody) + return Abstraction{Parameter: newParam, Body: newBody} } func (e Application) Rename(target string, newName string) Expression { - newAbs := e.Abstraction().Rename(target, newName) - newArg := e.Argument().Rename(target, newName) + newAbs := e.Abstraction.Rename(target, newName) + newArg := e.Argument.Rename(target, newName) - return NewApplication(newAbs, newArg) + return Application{Abstraction: newAbs, Argument: newArg} } diff --git a/pkg/lambda/stringify.go b/pkg/lambda/stringify.go new file mode 100644 index 0000000..a83ff48 --- /dev/null +++ b/pkg/lambda/stringify.go @@ -0,0 +1,13 @@ +package lambda + +func (a Abstraction) String() string { + return "\\" + a.Parameter + "." + a.Body.String() +} + +func (a Application) String() string { + return "(" + a.Abstraction.String() + " " + a.Argument.String() + ")" +} + +func (v Variable) String() string { + return v.Name +} diff --git a/pkg/lambda/substitute.go b/pkg/lambda/substitute.go index 1f6b38e..238b77b 100644 --- a/pkg/lambda/substitute.go +++ b/pkg/lambda/substitute.go @@ -1,7 +1,7 @@ package lambda func (e Variable) Substitute(target string, replacement Expression) Expression { - if e.Name() == target { + if e.Name == target { return replacement } @@ -9,12 +9,12 @@ func (e Variable) Substitute(target string, replacement Expression) Expression { } func (e Abstraction) Substitute(target string, replacement Expression) Expression { - if e.Parameter() == target { + if e.Parameter == target { return e } - body := e.Body() - param := e.Parameter() + body := e.Body + param := e.Parameter if replacement.IsFree(param) { freeVars := replacement.GetFree() freeVars.Merge(body.GetFree()) @@ -24,12 +24,12 @@ func (e Abstraction) Substitute(target string, replacement Expression) Expressio } newBody := body.Substitute(target, replacement) - return NewAbstraction(param, newBody) + return Abstraction{Parameter: param, Body: newBody} } func (e Application) Substitute(target string, replacement Expression) Expression { - abs := e.Abstraction().Substitute(target, replacement) - arg := e.Argument().Substitute(target, replacement) + abs := e.Abstraction.Substitute(target, replacement) + arg := e.Argument.Substitute(target, replacement) - return NewApplication(abs, arg) + return Application{Abstraction: abs, Argument: arg} } -- 2.49.1 From c6d7dd56ff79d5320d45c22e36452d2de92e5517 Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Mon, 9 Feb 2026 20:10:40 -0500 Subject: [PATCH 14/15] feat: lambda is mutable --- pkg/convert/saccharine_to_lambda.go | 4 +- pkg/engine/normalorder/reduce_once.go | 2 +- pkg/lambda/codec.go | 10 ++--- pkg/lambda/get_free_variables.go | 36 ++++++++++------ pkg/lambda/is_free_variable.go | 22 ++++++---- pkg/lambda/lambda.go | 37 ++-------------- pkg/lambda/rename.go | 49 +++++++++++---------- pkg/lambda/stringify.go | 22 ++++++---- pkg/lambda/substitute.go | 62 +++++++++++++++------------ 9 files changed, 121 insertions(+), 123 deletions(-) diff --git a/pkg/convert/saccharine_to_lambda.go b/pkg/convert/saccharine_to_lambda.go index a76a968..77f2753 100644 --- a/pkg/convert/saccharine_to_lambda.go +++ b/pkg/convert/saccharine_to_lambda.go @@ -21,7 +21,7 @@ func encodeAbstraction(n *saccharine.Abstraction) lambda.Expression { // If the function has no parameters, it is a thunk. Lambda calculus still // requires _some_ parameter exists, so generate one. if len(parameters) == 0 { - freeVars := result.GetFree() + freeVars := lambda.GetFree(result) freshName := lambda.GenerateFreshName(freeVars) parameters = append(parameters, freshName) } @@ -65,7 +65,7 @@ func reduceLet(s *saccharine.LetStatement, e lambda.Expression) lambda.Expressio } func reduceDeclare(s *saccharine.DeclareStatement, e lambda.Expression) lambda.Expression { - freshVar := lambda.GenerateFreshName(e.GetFree()) + freshVar := lambda.GenerateFreshName(lambda.GetFree(e)) return lambda.Application{ Abstraction: lambda.Abstraction{Parameter: freshVar, Body: e}, diff --git a/pkg/engine/normalorder/reduce_once.go b/pkg/engine/normalorder/reduce_once.go index 50d4d5a..241c01a 100644 --- a/pkg/engine/normalorder/reduce_once.go +++ b/pkg/engine/normalorder/reduce_once.go @@ -18,7 +18,7 @@ func ReduceOnce(e lambda.Expression) (lambda.Expression, bool) { case lambda.Application: if fn, fnOk := e.Abstraction.(lambda.Abstraction); fnOk { - return fn.Body.Substitute(fn.Parameter, e.Argument), true + return lambda.Substitute(fn.Body, fn.Parameter, e.Argument), true } abs, reduced := ReduceOnce(e.Abstraction) diff --git a/pkg/lambda/codec.go b/pkg/lambda/codec.go index 04cd83c..c1c96bb 100644 --- a/pkg/lambda/codec.go +++ b/pkg/lambda/codec.go @@ -6,14 +6,14 @@ import ( "git.maximhutz.com/max/lambda/pkg/codec" ) -type Marshaler struct{} +type Codec struct{} -func (m Marshaler) Decode(string) (Expression, error) { +func (m Codec) Decode(string) (Expression, error) { return nil, fmt.Errorf("unimplemented") } -func (m Marshaler) Encode(e Expression) (string, error) { - return e.String(), nil +func (m Codec) Encode(e Expression) (string, error) { + return Stringify(e), nil } -var _ codec.Codec[Expression] = (*Marshaler)(nil) +var _ codec.Codec[Expression] = (*Codec)(nil) diff --git a/pkg/lambda/get_free_variables.go b/pkg/lambda/get_free_variables.go index dbed3e5..71d15a1 100644 --- a/pkg/lambda/get_free_variables.go +++ b/pkg/lambda/get_free_variables.go @@ -1,19 +1,27 @@ package lambda -import "git.maximhutz.com/max/lambda/pkg/set" +import ( + "fmt" -func (e Variable) GetFree() set.Set[string] { - return set.New(e.Name) -} + "git.maximhutz.com/max/lambda/pkg/set" +) -func (e Abstraction) GetFree() set.Set[string] { - vars := e.Body.GetFree() - vars.Remove(e.Parameter) - return vars -} - -func (e Application) GetFree() set.Set[string] { - vars := e.Abstraction.GetFree() - vars.Merge(e.Argument.GetFree()) - return vars +// GetFree returns the set of all free variable names in the expression. +// This function does not mutate the input expression. +// The returned set is newly allocated and can be modified by the caller. +func GetFree(e Expression) set.Set[string] { + switch e := e.(type) { + case Variable: + return set.New(e.Name) + case Abstraction: + vars := GetFree(e.Body) + vars.Remove(e.Parameter) + return vars + case Application: + vars := GetFree(e.Abstraction) + vars.Merge(GetFree(e.Argument)) + return vars + default: + panic(fmt.Errorf("unknown expression type: %v", e)) + } } diff --git a/pkg/lambda/is_free_variable.go b/pkg/lambda/is_free_variable.go index 5db42a6..a965668 100644 --- a/pkg/lambda/is_free_variable.go +++ b/pkg/lambda/is_free_variable.go @@ -1,12 +1,18 @@ package lambda -func (e Variable) IsFree(n string) bool { - return e.Name == n -} +import "fmt" -func (e Abstraction) IsFree(n string) bool { - return e.Parameter != n && e.Body.IsFree(n) -} -func (e Application) IsFree(n string) bool { - return e.Abstraction.IsFree(n) || e.Argument.IsFree(n) +// IsFree returns true if the variable name n occurs free in the expression. +// This function does not mutate the input expression. +func IsFree(e Expression, n string) bool { + switch e := e.(type) { + case Variable: + return e.Name == n + case Abstraction: + return e.Parameter != n && IsFree(e.Body, n) + case Application: + return IsFree(e.Abstraction, n) || IsFree(e.Argument, n) + default: + panic(fmt.Errorf("unknown expression type: %v", e)) + } } diff --git a/pkg/lambda/lambda.go b/pkg/lambda/lambda.go index b3680c5..d92ca4d 100644 --- a/pkg/lambda/lambda.go +++ b/pkg/lambda/lambda.go @@ -1,56 +1,27 @@ package lambda -import ( - "fmt" - - "git.maximhutz.com/max/lambda/pkg/set" -) - // Expression is the interface for all lambda calculus expression types. // It embeds the general expr.Expression interface for cross-mode compatibility. type Expression interface { - fmt.Stringer - - // Substitute replaces all free occurrences of the target variable with the - // replacement expression. Alpha-renaming is performed automatically to - // avoid variable capture. - Substitute(target string, replacement Expression) Expression - - // GetFree returns the set of all free variable names in the expression. - // This function does not mutate the input expression. - // The returned set is newly allocated and can be modified by the caller. - GetFree() set.Set[string] - - // Rename replaces all occurrences of the target variable name with the new name. - Rename(target string, newName string) Expression - - // IsFree returns true if the variable name n occurs free in the expression. - // This function does not mutate the input expression. - IsFree(n string) bool + expression() } -/** ------------------------------------------------------------------------- */ - type Abstraction struct { Parameter string Body Expression } -var _ Expression = Abstraction{} - -/** ------------------------------------------------------------------------- */ +func (a Abstraction) expression() {} type Application struct { Abstraction Expression Argument Expression } -var _ Expression = Application{} - -/** ------------------------------------------------------------------------- */ +func (a Application) expression() {} type Variable struct { Name string } -var _ Expression = Variable{} +func (v Variable) expression() {} diff --git a/pkg/lambda/rename.go b/pkg/lambda/rename.go index 10e438d..eaa31ca 100644 --- a/pkg/lambda/rename.go +++ b/pkg/lambda/rename.go @@ -1,28 +1,31 @@ package lambda +import "fmt" + // Rename replaces all occurrences of the target variable name with the new name. -func (e Variable) Rename(target string, newName string) Expression { - if e.Name == target { - return Variable{Name: newName} +func Rename(e Expression, target string, newName string) Expression { + switch e := e.(type) { + case Variable: + if e.Name == target { + return Variable{Name: newName} + } + + return e + case Abstraction: + newParam := e.Parameter + if e.Parameter == target { + newParam = newName + } + + newBody := Rename(e.Body, target, newName) + + return Abstraction{Parameter: newParam, Body: newBody} + case Application: + newAbs := Rename(e.Abstraction, target, newName) + newArg := Rename(e.Argument, target, newName) + + return Application{Abstraction: newAbs, Argument: newArg} + default: + panic(fmt.Errorf("unknown expression type: %v", e)) } - - return e -} - -func (e Abstraction) Rename(target string, newName string) Expression { - newParam := e.Parameter - if e.Parameter == target { - newParam = newName - } - - newBody := e.Body.Rename(target, newName) - - return Abstraction{Parameter: newParam, Body: newBody} -} - -func (e Application) Rename(target string, newName string) Expression { - newAbs := e.Abstraction.Rename(target, newName) - newArg := e.Argument.Rename(target, newName) - - return Application{Abstraction: newAbs, Argument: newArg} } diff --git a/pkg/lambda/stringify.go b/pkg/lambda/stringify.go index a83ff48..6baaef0 100644 --- a/pkg/lambda/stringify.go +++ b/pkg/lambda/stringify.go @@ -1,13 +1,17 @@ package lambda -func (a Abstraction) String() string { - return "\\" + a.Parameter + "." + a.Body.String() -} +import "fmt" -func (a Application) String() string { - return "(" + a.Abstraction.String() + " " + a.Argument.String() + ")" -} - -func (v Variable) String() string { - return v.Name +// Stringify turns an expression as a string. +func Stringify(e Expression) string { + switch e := e.(type) { + case Variable: + return e.Name + case Abstraction: + return "\\" + e.Parameter + "." + Stringify(e.Body) + case Application: + return "(" + Stringify(e.Abstraction) + " " + Stringify(e.Argument) + ")" + default: + panic(fmt.Errorf("unknown expression type: %v", e)) + } } diff --git a/pkg/lambda/substitute.go b/pkg/lambda/substitute.go index 238b77b..8627edf 100644 --- a/pkg/lambda/substitute.go +++ b/pkg/lambda/substitute.go @@ -1,35 +1,41 @@ package lambda -func (e Variable) Substitute(target string, replacement Expression) Expression { - if e.Name == target { - return replacement - } +import "fmt" - return e -} +// Substitute replaces all free occurrences of the target variable with the +// replacement expression. Alpha-renaming is performed automatically to +// avoid variable capture. +func Substitute(e Expression, target string, replacement Expression) Expression { + switch e := e.(type) { + case Variable: + if e.Name == target { + return replacement + } -func (e Abstraction) Substitute(target string, replacement Expression) Expression { - if e.Parameter == target { return e + case Abstraction: + if e.Parameter == target { + return e + } + + body := e.Body + param := e.Parameter + if IsFree(replacement, param) { + freeVars := GetFree(replacement) + freeVars.Merge(GetFree(body)) + freshVar := GenerateFreshName(freeVars) + body = Rename(body, param, freshVar) + param = freshVar + } + + newBody := Substitute(body, target, replacement) + return Abstraction{Parameter: param, Body: newBody} + case Application: + abs := Substitute(e.Abstraction, target, replacement) + arg := Substitute(e.Argument, target, replacement) + + return Application{Abstraction: abs, Argument: arg} + default: + panic(fmt.Errorf("unknown expression type: %v", e)) } - - body := e.Body - param := e.Parameter - if replacement.IsFree(param) { - freeVars := replacement.GetFree() - freeVars.Merge(body.GetFree()) - freshVar := GenerateFreshName(freeVars) - body = body.Rename(param, freshVar) - param = freshVar - } - - newBody := body.Substitute(target, replacement) - return Abstraction{Parameter: param, Body: newBody} -} - -func (e Application) Substitute(target string, replacement Expression) Expression { - abs := e.Abstraction.Substitute(target, replacement) - arg := e.Argument.Substitute(target, replacement) - - return Application{Abstraction: abs, Argument: arg} } -- 2.49.1 From afd4d27695b975d93846aa598c9de2a97775ff88 Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Mon, 9 Feb 2026 20:14:31 -0500 Subject: [PATCH 15/15] feat: lambda --- cmd/lambda/registry.go | 2 +- pkg/lambda/codec.go | 6 ++++++ pkg/lambda/lambda.go | 8 ++++++-- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/cmd/lambda/registry.go b/cmd/lambda/registry.go index 404eda8..bff4fa2 100644 --- a/cmd/lambda/registry.go +++ b/cmd/lambda/registry.go @@ -19,7 +19,7 @@ func GetRegistry() *registry.Registry { (registry.RegisterEngine(r, normalorder.NewProcess, "normalorder", "lambda")) // Marshalers - (registry.RegisterCodec(r, lambda.Marshaler{}, "lambda")) + (registry.RegisterCodec(r, lambda.Codec{}, "lambda")) (registry.RegisterCodec(r, saccharine.Codec{}, "saccharine")) return r diff --git a/pkg/lambda/codec.go b/pkg/lambda/codec.go index c1c96bb..32d19df 100644 --- a/pkg/lambda/codec.go +++ b/pkg/lambda/codec.go @@ -6,12 +6,18 @@ import ( "git.maximhutz.com/max/lambda/pkg/codec" ) +// A Codec is a [codec.Codec] that serializes lambda calculus expressions. +// Decode is not implemented and always returns an error. +// Encode stringifies an expression using standard lambda notation. type Codec struct{} +// Decode parses a string as lambda calculus. Returns an error if it cannot. func (m Codec) Decode(string) (Expression, error) { return nil, fmt.Errorf("unimplemented") } +// Encode turns a lambda calculus expression into a string. Returns an error if +// it cannot. func (m Codec) Encode(e Expression) (string, error) { return Stringify(e), nil } diff --git a/pkg/lambda/lambda.go b/pkg/lambda/lambda.go index d92ca4d..e8cfef0 100644 --- a/pkg/lambda/lambda.go +++ b/pkg/lambda/lambda.go @@ -1,11 +1,13 @@ +// Package lambda defines the AST for the untyped lambda calculus. package lambda -// Expression is the interface for all lambda calculus expression types. -// It embeds the general expr.Expression interface for cross-mode compatibility. +// An Expression is a node in the lambda calculus abstract syntax tree. +// It is a sealed interface; only types in this package may implement it. type Expression interface { expression() } +// An Abstraction binds a single parameter over a body expression. type Abstraction struct { Parameter string Body Expression @@ -13,6 +15,7 @@ type Abstraction struct { func (a Abstraction) expression() {} +// An Application applies an abstraction to a single argument. type Application struct { Abstraction Expression Argument Expression @@ -20,6 +23,7 @@ type Application struct { func (a Application) expression() {} +// A Variable is a named reference to a bound or free variable. type Variable struct { Name string } -- 2.49.1