docs: document remaining packages and simplify AST types #45
@@ -1,3 +1,4 @@
|
|||||||
|
// Package main defines the 'lambda' command-line interface (CLI).
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ func LambdaEngine() *cobra.Command {
|
|||||||
Use: "engine",
|
Use: "engine",
|
||||||
Aliases: []string{"eng"},
|
Aliases: []string{"eng"},
|
||||||
Short: "Information about available engines",
|
Short: "Information about available engines",
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||||
return cmd.Help()
|
return cmd.Help()
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ func LambdaEngineList() *cobra.Command {
|
|||||||
Use: "list",
|
Use: "list",
|
||||||
Aliases: []string{"ls"},
|
Aliases: []string{"ls"},
|
||||||
Short: "List available engines",
|
Short: "List available engines",
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
RunE: func(*cobra.Command, []string) error {
|
||||||
r := GetRegistry()
|
r := GetRegistry()
|
||||||
|
|
||||||
for engine := range r.ListEngines() {
|
for engine := range r.ListEngines() {
|
||||||
|
|||||||
@@ -19,8 +19,8 @@ func GetRegistry() *registry.Registry {
|
|||||||
(registry.RegisterEngine(r, normalorder.NewProcess, "normalorder", "lambda"))
|
(registry.RegisterEngine(r, normalorder.NewProcess, "normalorder", "lambda"))
|
||||||
|
|
||||||
// Marshalers
|
// Marshalers
|
||||||
(registry.RegisterCodec(r, lambda.Marshaler{}, "lambda"))
|
(registry.RegisterCodec(r, lambda.Codec{}, "lambda"))
|
||||||
(registry.RegisterCodec(r, saccharine.Marshaler{}, "saccharine"))
|
(registry.RegisterCodec(r, saccharine.Codec{}, "saccharine"))
|
||||||
|
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,18 +7,24 @@ import (
|
|||||||
"git.maximhutz.com/max/lambda/pkg/codec"
|
"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 {
|
type Codec interface {
|
||||||
codec.Codec[Expr]
|
codec.Codec[Expr]
|
||||||
|
|
||||||
|
// InType returns the name of the representation this codec handles.
|
||||||
InType() string
|
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]
|
codec codec.Codec[T]
|
||||||
inType string
|
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)
|
t, err := c.codec.Decode(s)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -27,7 +33,7 @@ func (c convertedCodec[T]) Decode(s string) (Expr, error) {
|
|||||||
return NewExpr(c.inType, t), nil
|
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)
|
t, ok := r.Data().(T)
|
||||||
if !ok {
|
if !ok {
|
||||||
dataType := reflect.TypeOf(r.Data())
|
dataType := reflect.TypeOf(r.Data())
|
||||||
@@ -38,13 +44,15 @@ func (c convertedCodec[T]) Encode(r Expr) (string, error) {
|
|||||||
return c.codec.Encode(t)
|
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 {
|
func RegisterCodec[T any](registry *Registry, m codec.Codec[T], inType string) error {
|
||||||
if _, ok := registry.codecs[inType]; ok {
|
if _, ok := registry.codecs[inType]; ok {
|
||||||
return fmt.Errorf("Codec for '%s' already registered", inType)
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,19 +6,29 @@ import (
|
|||||||
"git.maximhutz.com/max/lambda/pkg/codec"
|
"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 {
|
type Conversion interface {
|
||||||
|
// InType returns the name of the source representation.
|
||||||
InType() string
|
InType() string
|
||||||
|
// OutType returns the name of the target representation.
|
||||||
OutType() string
|
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)
|
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]
|
conversion codec.Conversion[T, U]
|
||||||
inType, outType string
|
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)
|
t, ok := expr.Data().(T)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("could not parse '%v' as '%s'", t, c.inType)
|
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
|
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 {
|
// RegisterConversion registers a typed conversion function between two
|
||||||
registry.converter.Add(convertedConversion[T, U]{conversion, inType, outType})
|
// 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
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,18 @@
|
|||||||
package registry
|
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 {
|
type Converter struct {
|
||||||
data map[string][]Conversion
|
data map[string][]Conversion
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewConverter creates an empty Converter with no registered conversions.
|
||||||
func NewConverter() *Converter {
|
func NewConverter() *Converter {
|
||||||
return &Converter{data: map[string][]Conversion{}}
|
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) {
|
func (g *Converter) Add(c Conversion) {
|
||||||
conversionsFromIn, ok := g.data[c.InType()]
|
conversionsFromIn, ok := g.data[c.InType()]
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -18,6 +23,8 @@ func (g *Converter) Add(c Conversion) {
|
|||||||
g.data[c.InType()] = conversionsFromIn
|
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 {
|
func (g *Converter) ConversionsFrom(t string) []Conversion {
|
||||||
return g.data[t]
|
return g.data[t]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,26 +6,36 @@ import (
|
|||||||
"git.maximhutz.com/max/lambda/pkg/engine"
|
"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 {
|
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)
|
Load(Expr) (Process, error)
|
||||||
|
// Name returns the name of this engine.
|
||||||
Name() string
|
Name() string
|
||||||
|
// InType returns the name of the representation this engine operates on.
|
||||||
InType() string
|
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]
|
engine engine.Engine[T]
|
||||||
name string
|
name string
|
||||||
inType 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)
|
t, ok := expr.Data().(T)
|
||||||
if !ok {
|
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)
|
process, err := e.engine(t)
|
||||||
@@ -33,14 +43,16 @@ func (e convertedEngine[T]) Load(expr Expr) (Process, error) {
|
|||||||
return nil, err
|
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 {
|
func RegisterEngine[T any](registry *Registry, e engine.Engine[T], name, inType string) error {
|
||||||
if _, ok := registry.engines[name]; ok {
|
if _, ok := registry.engines[name]; ok {
|
||||||
return fmt.Errorf("engine '%s' already registered", name)
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +1,26 @@
|
|||||||
package registry
|
package registry
|
||||||
|
|
||||||
// A Expr is a lambda calculus expression. It can have any type of
|
// An Expr is a type-erased lambda calculus expression. It can have any type of
|
||||||
// Expresentation, so long as that class is known to the registry it is handled
|
// representation, so long as that type is known to the registry it is handled
|
||||||
// by.
|
// by.
|
||||||
type Expr interface {
|
type Expr interface {
|
||||||
// Repr returns the name of the underlying Expresentation. It is assumed if
|
// Repr returns the name of the underlying representation. Two expressions
|
||||||
// two expressions have the same Repr(), they have the same Expresentation.
|
// with the same Repr() are assumed to have the same representation type.
|
||||||
Repr() string
|
Repr() string
|
||||||
|
|
||||||
// The base expression data.
|
// Data returns the underlying expression data.
|
||||||
Data() any
|
Data() any
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A baseExpr is the default implementation of Expr.
|
||||||
type baseExpr struct {
|
type baseExpr struct {
|
||||||
id string
|
id string
|
||||||
data any
|
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} }
|
func NewExpr(id string, data any) Expr { return baseExpr{id, data} }
|
||||||
|
|||||||
@@ -4,28 +4,32 @@ import (
|
|||||||
"git.maximhutz.com/max/lambda/pkg/engine"
|
"git.maximhutz.com/max/lambda/pkg/engine"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// A Process is a type-erased reduction process that operates on Expr values.
|
||||||
type Process interface {
|
type Process interface {
|
||||||
engine.Process[Expr]
|
engine.Process[Expr]
|
||||||
|
|
||||||
|
// InType returns the name of the representation this process operates on.
|
||||||
InType() string
|
InType() string
|
||||||
}
|
}
|
||||||
|
|
||||||
type convertedProcess[T any] struct {
|
// 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]
|
process engine.Process[T]
|
||||||
inType string
|
inType string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e convertedProcess[T]) InType() string { return e.inType }
|
func (p registeredProcess[T]) InType() string { return p.inType }
|
||||||
|
|
||||||
func (b convertedProcess[T]) Get() (Expr, error) {
|
func (p registeredProcess[T]) Get() (Expr, error) {
|
||||||
s, err := b.process.Get()
|
s, err := p.process.Get()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewExpr(b.inType, s), nil
|
return NewExpr(p.inType, s), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b convertedProcess[T]) Step(i int) bool {
|
func (p registeredProcess[T]) Step(i int) bool {
|
||||||
return b.process.Step(i)
|
return p.process.Step(i)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
// Package registry defines a structure to hold all available representations,
|
||||||
|
// engines, and conversions between them.
|
||||||
package registry
|
package registry
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -6,12 +8,15 @@ import (
|
|||||||
"maps"
|
"maps"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// A Registry holds all representations, conversions, codecs, and engines
|
||||||
|
// available to the program.
|
||||||
type Registry struct {
|
type Registry struct {
|
||||||
codecs map[string]Codec
|
codecs map[string]Codec
|
||||||
converter *Converter
|
converter *Converter
|
||||||
engines map[string]Engine
|
engines map[string]Engine
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// New makes an empty registry.
|
||||||
func New() *Registry {
|
func New() *Registry {
|
||||||
return &Registry{
|
return &Registry{
|
||||||
codecs: map[string]Codec{},
|
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) {
|
func (r Registry) GetEngine(name string) (Engine, error) {
|
||||||
e, ok := r.engines[name]
|
e, ok := r.engines[name]
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -29,10 +36,13 @@ func (r Registry) GetEngine(name string) (Engine, error) {
|
|||||||
return e, nil
|
return e, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListEngines returns all available engines to the registry.
|
||||||
func (r Registry) ListEngines() iter.Seq[Engine] {
|
func (r Registry) ListEngines() iter.Seq[Engine] {
|
||||||
return maps.Values(r.engines)
|
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) {
|
func (r *Registry) GetDefaultEngine(id string) (Engine, error) {
|
||||||
for _, engine := range r.engines {
|
for _, engine := range r.engines {
|
||||||
if engine.InType() == id {
|
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)
|
// 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) {
|
func (r *Registry) ConvertTo(expr Expr, outType string) (Expr, error) {
|
||||||
path, err := r.ConversionPath(expr.Repr(), outType)
|
path, err := r.ConversionPath(expr.Repr(), outType)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -62,6 +78,8 @@ func (r *Registry) ConvertTo(expr Expr, outType string) (Expr, error) {
|
|||||||
return result, err
|
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) {
|
func (r *Registry) Marshal(expr Expr) (string, error) {
|
||||||
m, ok := r.codecs[expr.Repr()]
|
m, ok := r.codecs[expr.Repr()]
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -71,6 +89,8 @@ func (r *Registry) Marshal(expr Expr) (string, error) {
|
|||||||
return m.Encode(expr)
|
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) {
|
func (r *Registry) Unmarshal(s string, outType string) (Expr, error) {
|
||||||
m, ok := r.codecs[outType]
|
m, ok := r.codecs[outType]
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -94,6 +114,9 @@ func reverse[T any](list []T) []T {
|
|||||||
return reversed
|
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) {
|
func (r *Registry) ConversionPath(from, to string) ([]Conversion, error) {
|
||||||
backtrack := map[string]Conversion{}
|
backtrack := map[string]Conversion{}
|
||||||
iteration := []string{from}
|
iteration := []string{from}
|
||||||
|
|||||||
@@ -1,8 +1,20 @@
|
|||||||
|
// Package codec defines processes to convert between different representations
|
||||||
|
// of lambda calculus, and serialize the different representations.
|
||||||
package codec
|
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)
|
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 {
|
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)
|
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)
|
Decode(string) (T, error)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
// Package convert defined some standard conversions between various types of
|
||||||
|
// representations.
|
||||||
package convert
|
package convert
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -8,7 +10,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func encodeAtom(n *saccharine.Atom) lambda.Expression {
|
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 {
|
func encodeAbstraction(n *saccharine.Abstraction) lambda.Expression {
|
||||||
@@ -19,13 +21,13 @@ func encodeAbstraction(n *saccharine.Abstraction) lambda.Expression {
|
|||||||
// If the function has no parameters, it is a thunk. Lambda calculus still
|
// If the function has no parameters, it is a thunk. Lambda calculus still
|
||||||
// requires _some_ parameter exists, so generate one.
|
// requires _some_ parameter exists, so generate one.
|
||||||
if len(parameters) == 0 {
|
if len(parameters) == 0 {
|
||||||
freeVars := result.GetFree()
|
freeVars := lambda.GetFree(result)
|
||||||
freshName := lambda.GenerateFreshName(freeVars)
|
freshName := lambda.GenerateFreshName(freeVars)
|
||||||
parameters = append(parameters, freshName)
|
parameters = append(parameters, freshName)
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := len(parameters) - 1; i >= 0; i-- {
|
for i := len(parameters) - 1; i >= 0; i-- {
|
||||||
result = lambda.NewAbstraction(parameters[i], result)
|
result = lambda.Abstraction{Parameter: parameters[i], Body: result}
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
@@ -41,7 +43,7 @@ func encodeApplication(n *saccharine.Application) lambda.Expression {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, argument := range arguments {
|
for _, argument := range arguments {
|
||||||
result = lambda.NewApplication(result, argument)
|
result = lambda.Application{Abstraction: result, Argument: argument}
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
@@ -53,22 +55,22 @@ func reduceLet(s *saccharine.LetStatement, e lambda.Expression) lambda.Expressio
|
|||||||
if len(s.Parameters) == 0 {
|
if len(s.Parameters) == 0 {
|
||||||
value = encodeExpression(s.Body)
|
value = encodeExpression(s.Body)
|
||||||
} else {
|
} else {
|
||||||
value = encodeAbstraction(saccharine.NewAbstraction(s.Parameters, s.Body))
|
value = encodeAbstraction(&saccharine.Abstraction{Parameters: s.Parameters, Body: s.Body})
|
||||||
}
|
}
|
||||||
|
|
||||||
return lambda.NewApplication(
|
return lambda.Application{
|
||||||
lambda.NewAbstraction(s.Name, e),
|
Abstraction: lambda.Abstraction{Parameter: s.Name, Body: e},
|
||||||
value,
|
Argument: value,
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func reduceDeclare(s *saccharine.DeclareStatement, e lambda.Expression) lambda.Expression {
|
func reduceDeclare(s *saccharine.DeclareStatement, e lambda.Expression) lambda.Expression {
|
||||||
freshVar := lambda.GenerateFreshName(e.GetFree())
|
freshVar := lambda.GenerateFreshName(lambda.GetFree(e))
|
||||||
|
|
||||||
return lambda.NewApplication(
|
return lambda.Application{
|
||||||
lambda.NewAbstraction(freshVar, e),
|
Abstraction: lambda.Abstraction{Parameter: freshVar, Body: e},
|
||||||
encodeExpression(s.Value),
|
Argument: encodeExpression(s.Value),
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func reduceStatement(s saccharine.Statement, e lambda.Expression) lambda.Expression {
|
func reduceStatement(s saccharine.Statement, e lambda.Expression) lambda.Expression {
|
||||||
@@ -110,24 +112,27 @@ func encodeExpression(s saccharine.Expression) lambda.Expression {
|
|||||||
func decodeExression(l lambda.Expression) saccharine.Expression {
|
func decodeExression(l lambda.Expression) saccharine.Expression {
|
||||||
switch l := l.(type) {
|
switch l := l.(type) {
|
||||||
case lambda.Variable:
|
case lambda.Variable:
|
||||||
return saccharine.NewAtom(l.Name())
|
return &saccharine.Atom{Name: l.Name}
|
||||||
case lambda.Abstraction:
|
case lambda.Abstraction:
|
||||||
return saccharine.NewAbstraction(
|
return &saccharine.Abstraction{
|
||||||
[]string{l.Parameter()},
|
Parameters: []string{l.Parameter},
|
||||||
decodeExression(l.Body()))
|
Body: decodeExression(l.Body)}
|
||||||
case lambda.Application:
|
case lambda.Application:
|
||||||
return saccharine.NewApplication(
|
return &saccharine.Application{
|
||||||
decodeExression(l.Abstraction()),
|
Abstraction: decodeExression(l.Abstraction),
|
||||||
[]saccharine.Expression{decodeExression(l.Argument())})
|
Arguments: []saccharine.Expression{decodeExression(l.Argument)}}
|
||||||
default:
|
default:
|
||||||
panic(fmt.Errorf("unknown expression type: %T", l))
|
panic(fmt.Errorf("unknown expression type: %T", l))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Lambda2Saccharine converts a pure lambda calculus expression into its
|
||||||
|
// Saccharine counterpart.
|
||||||
func Lambda2Saccharine(l lambda.Expression) (saccharine.Expression, error) {
|
func Lambda2Saccharine(l lambda.Expression) (saccharine.Expression, error) {
|
||||||
return decodeExression(l), nil
|
return decodeExression(l), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Saccharine2Lambda desugars a saccharine expression into pure lambda calculus.
|
||||||
func Saccharine2Lambda(s saccharine.Expression) (lambda.Expression, error) {
|
func Saccharine2Lambda(s saccharine.Expression) (lambda.Expression, error) {
|
||||||
return encodeExpression(s), nil
|
return encodeExpression(s), nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,11 +2,17 @@
|
|||||||
// expression.
|
// expression.
|
||||||
package engine
|
package engine
|
||||||
|
|
||||||
// A Process handles the reduction of a
|
// A Process handles the reduction of a single expression.
|
||||||
type Process[T any] interface {
|
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)
|
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
|
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)
|
type Engine[T any] = func(T) (Process[T], error)
|
||||||
|
|||||||
@@ -10,25 +10,25 @@ import "git.maximhutz.com/max/lambda/pkg/lambda"
|
|||||||
func ReduceOnce(e lambda.Expression) (lambda.Expression, bool) {
|
func ReduceOnce(e lambda.Expression) (lambda.Expression, bool) {
|
||||||
switch e := e.(type) {
|
switch e := e.(type) {
|
||||||
case lambda.Abstraction:
|
case lambda.Abstraction:
|
||||||
body, reduced := ReduceOnce(e.Body())
|
body, reduced := ReduceOnce(e.Body)
|
||||||
if reduced {
|
if reduced {
|
||||||
return lambda.NewAbstraction(e.Parameter(), body), true
|
return lambda.Abstraction{Parameter: e.Parameter, Body: body}, true
|
||||||
}
|
}
|
||||||
return e, false
|
return e, false
|
||||||
|
|
||||||
case lambda.Application:
|
case lambda.Application:
|
||||||
if fn, fnOk := e.Abstraction().(lambda.Abstraction); fnOk {
|
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())
|
abs, reduced := ReduceOnce(e.Abstraction)
|
||||||
if reduced {
|
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 {
|
if reduced {
|
||||||
return lambda.NewApplication(e.Abstraction(), arg), true
|
return lambda.Application{Abstraction: e.Abstraction, Argument: arg}, true
|
||||||
}
|
}
|
||||||
|
|
||||||
return e, false
|
return e, false
|
||||||
|
|||||||
@@ -1,35 +1,37 @@
|
|||||||
/*
|
// Package iterator defines a generic way to iterator over a slice of data.
|
||||||
Package "iterator"
|
|
||||||
*/
|
|
||||||
package iterator
|
package iterator
|
||||||
|
|
||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
// An iterator over slices.
|
// An Iterator traverses over slices.
|
||||||
type Iterator[T any] struct {
|
type Iterator[T any] struct {
|
||||||
items []T
|
items []T
|
||||||
index int
|
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] {
|
func Of[T any](items []T) *Iterator[T] {
|
||||||
return &Iterator[T]{items: items, index: 0}
|
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 {
|
func (i Iterator[T]) Index() int {
|
||||||
return i.index
|
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] {
|
func (i Iterator[T]) Copy() *Iterator[T] {
|
||||||
return &Iterator[T]{items: i.items, index: i.index}
|
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]) {
|
func (i *Iterator[T]) Sync(o *Iterator[T]) {
|
||||||
i.index = o.index
|
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) {
|
func (i Iterator[T]) Get() (T, error) {
|
||||||
var null T
|
var null T
|
||||||
if i.Done() {
|
if i.Done() {
|
||||||
@@ -39,6 +41,7 @@ func (i Iterator[T]) Get() (T, error) {
|
|||||||
return i.items[i.index], nil
|
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 {
|
func (i Iterator[T]) MustGet() T {
|
||||||
var null T
|
var null T
|
||||||
if i.Done() {
|
if i.Done() {
|
||||||
@@ -48,13 +51,16 @@ func (i Iterator[T]) MustGet() T {
|
|||||||
return i.items[i.index]
|
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() {
|
func (i *Iterator[T]) Forward() {
|
||||||
if !i.Done() {
|
if !i.Done() {
|
||||||
i.index++
|
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) {
|
func (i *Iterator[T]) Next() (T, error) {
|
||||||
item, err := i.Get()
|
item, err := i.Get()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -64,16 +70,20 @@ func (i *Iterator[T]) Next() (T, error) {
|
|||||||
return item, err
|
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() {
|
func (i *Iterator[T]) Back() {
|
||||||
i.index = max(i.index-1, 0)
|
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 {
|
func (i Iterator[T]) Done() bool {
|
||||||
return i.index == len(i.items)
|
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) {
|
func Do[T any, U any](i *Iterator[T], fn func(i *Iterator[T]) (U, error)) (U, error) {
|
||||||
i2 := i.Copy()
|
i2 := i.Copy()
|
||||||
|
|
||||||
|
|||||||
@@ -6,14 +6,20 @@ import (
|
|||||||
"git.maximhutz.com/max/lambda/pkg/codec"
|
"git.maximhutz.com/max/lambda/pkg/codec"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Marshaler struct{}
|
// 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{}
|
||||||
|
|
||||||
func (m Marshaler) Decode(string) (Expression, error) {
|
// 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")
|
return nil, fmt.Errorf("unimplemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Marshaler) Encode(e Expression) (string, error) {
|
// Encode turns a lambda calculus expression into a string. Returns an error if
|
||||||
return e.String(), nil
|
// it cannot.
|
||||||
|
func (m Codec) Encode(e Expression) (string, error) {
|
||||||
|
return Stringify(e), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ codec.Codec[Expression] = (*Marshaler)(nil)
|
var _ codec.Codec[Expression] = (*Codec)(nil)
|
||||||
|
|||||||
@@ -1,100 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
/** ------------------------------------------------------------------------- */
|
|
||||||
|
|
||||||
type Abstraction struct {
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
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}
|
|
||||||
}
|
|
||||||
@@ -1,19 +1,27 @@
|
|||||||
package lambda
|
package lambda
|
||||||
|
|
||||||
import "git.maximhutz.com/max/lambda/pkg/set"
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
func (e Variable) GetFree() set.Set[string] {
|
"git.maximhutz.com/max/lambda/pkg/set"
|
||||||
return set.New(e.Name())
|
)
|
||||||
}
|
|
||||||
|
|
||||||
func (e Abstraction) GetFree() set.Set[string] {
|
// GetFree returns the set of all free variable names in the expression.
|
||||||
vars := e.Body().GetFree()
|
// This function does not mutate the input expression.
|
||||||
vars.Remove(e.Parameter())
|
// 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
|
return vars
|
||||||
}
|
case Application:
|
||||||
|
vars := GetFree(e.Abstraction)
|
||||||
func (e Application) GetFree() set.Set[string] {
|
vars.Merge(GetFree(e.Argument))
|
||||||
vars := e.Abstraction().GetFree()
|
|
||||||
vars.Merge(e.Argument().GetFree())
|
|
||||||
return vars
|
return vars
|
||||||
|
default:
|
||||||
|
panic(fmt.Errorf("unknown expression type: %v", e))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,18 @@
|
|||||||
package lambda
|
package lambda
|
||||||
|
|
||||||
func (e Variable) IsFree(n string) bool {
|
import "fmt"
|
||||||
return e.Name() == n
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e Abstraction) IsFree(n string) bool {
|
// IsFree returns true if the variable name n occurs free in the expression.
|
||||||
return e.Parameter() != n && e.Body().IsFree(n)
|
// This function does not mutate the input expression.
|
||||||
}
|
func IsFree(e Expression, n string) bool {
|
||||||
func (e Application) IsFree(n string) bool {
|
switch e := e.(type) {
|
||||||
return e.Abstraction().IsFree(n) || e.Argument().IsFree(n)
|
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))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
31
pkg/lambda/lambda.go
Normal file
31
pkg/lambda/lambda.go
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
// Package lambda defines the AST for the untyped lambda calculus.
|
||||||
|
package lambda
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a Abstraction) expression() {}
|
||||||
|
|
||||||
|
// An Application applies an abstraction to a single argument.
|
||||||
|
type Application struct {
|
||||||
|
Abstraction Expression
|
||||||
|
Argument Expression
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a Application) expression() {}
|
||||||
|
|
||||||
|
// A Variable is a named reference to a bound or free variable.
|
||||||
|
type Variable struct {
|
||||||
|
Name string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v Variable) expression() {}
|
||||||
@@ -1,28 +1,31 @@
|
|||||||
package lambda
|
package lambda
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
// Rename replaces all occurrences of the target variable name with the new name.
|
// Rename replaces all occurrences of the target variable name with the new name.
|
||||||
func (e Variable) Rename(target string, newName string) Expression {
|
func Rename(e Expression, target string, newName string) Expression {
|
||||||
if e.Name() == target {
|
switch e := e.(type) {
|
||||||
return NewVariable(newName)
|
case Variable:
|
||||||
|
if e.Name == target {
|
||||||
|
return Variable{Name: newName}
|
||||||
}
|
}
|
||||||
|
|
||||||
return e
|
return e
|
||||||
}
|
case Abstraction:
|
||||||
|
newParam := e.Parameter
|
||||||
func (e Abstraction) Rename(target string, newName string) Expression {
|
if e.Parameter == target {
|
||||||
newParam := e.Parameter()
|
|
||||||
if e.Parameter() == target {
|
|
||||||
newParam = newName
|
newParam = newName
|
||||||
}
|
}
|
||||||
|
|
||||||
newBody := e.Body().Rename(target, newName)
|
newBody := Rename(e.Body, target, newName)
|
||||||
|
|
||||||
return NewAbstraction(newParam, newBody)
|
return Abstraction{Parameter: newParam, Body: newBody}
|
||||||
}
|
case Application:
|
||||||
|
newAbs := Rename(e.Abstraction, target, newName)
|
||||||
func (e Application) Rename(target string, newName string) Expression {
|
newArg := Rename(e.Argument, target, newName)
|
||||||
newAbs := e.Abstraction().Rename(target, newName)
|
|
||||||
newArg := e.Argument().Rename(target, newName)
|
return Application{Abstraction: newAbs, Argument: newArg}
|
||||||
|
default:
|
||||||
return NewApplication(newAbs, newArg)
|
panic(fmt.Errorf("unknown expression type: %v", e))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
17
pkg/lambda/stringify.go
Normal file
17
pkg/lambda/stringify.go
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
package lambda
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
// 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))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,35 +1,41 @@
|
|||||||
package lambda
|
package lambda
|
||||||
|
|
||||||
func (e Variable) Substitute(target string, replacement Expression) Expression {
|
import "fmt"
|
||||||
if e.Name() == target {
|
|
||||||
|
// 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
|
return replacement
|
||||||
}
|
}
|
||||||
|
|
||||||
return e
|
return e
|
||||||
}
|
case Abstraction:
|
||||||
|
if e.Parameter == target {
|
||||||
func (e Abstraction) Substitute(target string, replacement Expression) Expression {
|
|
||||||
if e.Parameter() == target {
|
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
|
|
||||||
body := e.Body()
|
body := e.Body
|
||||||
param := e.Parameter()
|
param := e.Parameter
|
||||||
if replacement.IsFree(param) {
|
if IsFree(replacement, param) {
|
||||||
freeVars := replacement.GetFree()
|
freeVars := GetFree(replacement)
|
||||||
freeVars.Merge(body.GetFree())
|
freeVars.Merge(GetFree(body))
|
||||||
freshVar := GenerateFreshName(freeVars)
|
freshVar := GenerateFreshName(freeVars)
|
||||||
body = body.Rename(param, freshVar)
|
body = Rename(body, param, freshVar)
|
||||||
param = freshVar
|
param = freshVar
|
||||||
}
|
}
|
||||||
|
|
||||||
newBody := body.Substitute(target, replacement)
|
newBody := Substitute(body, target, replacement)
|
||||||
return NewAbstraction(param, newBody)
|
return Abstraction{Parameter: param, Body: newBody}
|
||||||
}
|
case Application:
|
||||||
|
abs := Substitute(e.Abstraction, target, replacement)
|
||||||
|
arg := Substitute(e.Argument, target, replacement)
|
||||||
|
|
||||||
func (e Application) Substitute(target string, replacement Expression) Expression {
|
return Application{Abstraction: abs, Argument: arg}
|
||||||
abs := e.Abstraction().Substitute(target, replacement)
|
default:
|
||||||
arg := e.Argument().Substitute(target, replacement)
|
panic(fmt.Errorf("unknown expression type: %v", e))
|
||||||
|
}
|
||||||
return NewApplication(abs, arg)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
// Package "saccharine" provides a simple language built on top of λ-calculus,
|
|
||||||
// to facilitate productive coding using it.
|
|
||||||
package saccharine
|
package saccharine
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"git.maximhutz.com/max/lambda/pkg/codec"
|
"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)
|
tokens, err := scan(s)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -17,8 +18,10 @@ func (m Marshaler) Decode(s string) (Expression, error) {
|
|||||||
return parse(tokens)
|
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
|
return stringifyExpression(e), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ codec.Codec[Expression] = (*Marshaler)(nil)
|
var _ codec.Codec[Expression] = (*Codec)(nil)
|
||||||
|
|||||||
@@ -1,49 +0,0 @@
|
|||||||
package saccharine
|
|
||||||
|
|
||||||
type Expression interface {
|
|
||||||
IsExpression()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** ------------------------------------------------------------------------- */
|
|
||||||
|
|
||||||
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) 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}
|
|
||||||
}
|
|
||||||
@@ -5,13 +5,12 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"git.maximhutz.com/max/lambda/pkg/iterator"
|
"git.maximhutz.com/max/lambda/pkg/iterator"
|
||||||
"git.maximhutz.com/max/lambda/pkg/trace"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type TokenIterator = iterator.Iterator[Token]
|
type tokenIterator = iterator.Iterator[Token]
|
||||||
|
|
||||||
func parseRawToken(i *TokenIterator, expected TokenType) (*Token, error) {
|
func parseRawToken(i *tokenIterator, expected TokenType) (*Token, error) {
|
||||||
return iterator.Do(i, func(i *TokenIterator) (*Token, error) {
|
return iterator.Do(i, func(i *tokenIterator) (*Token, error) {
|
||||||
if tok, err := i.Next(); err != nil {
|
if tok, err := i.Next(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else if tok.Type != expected {
|
} else if tok.Type != expected {
|
||||||
@@ -22,7 +21,7 @@ func parseRawToken(i *TokenIterator, expected TokenType) (*Token, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func passSoftBreaks(i *TokenIterator) {
|
func passSoftBreaks(i *tokenIterator) {
|
||||||
for {
|
for {
|
||||||
if _, err := parseRawToken(i, TokenSoftBreak); err != nil {
|
if _, err := parseRawToken(i, TokenSoftBreak); err != nil {
|
||||||
return
|
return
|
||||||
@@ -30,8 +29,8 @@ func passSoftBreaks(i *TokenIterator) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseToken(i *TokenIterator, expected TokenType, ignoreSoftBreaks bool) (*Token, error) {
|
func parseToken(i *tokenIterator, expected TokenType, ignoreSoftBreaks bool) (*Token, error) {
|
||||||
return iterator.Do(i, func(i *TokenIterator) (*Token, error) {
|
return iterator.Do(i, func(i *tokenIterator) (*Token, error) {
|
||||||
if ignoreSoftBreaks {
|
if ignoreSoftBreaks {
|
||||||
passSoftBreaks(i)
|
passSoftBreaks(i)
|
||||||
}
|
}
|
||||||
@@ -40,15 +39,15 @@ 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 {
|
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 {
|
} else {
|
||||||
return tok.Value, nil
|
return tok.Value, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseBreak(i *TokenIterator) (*Token, error) {
|
func parseBreak(i *tokenIterator) (*Token, error) {
|
||||||
if tok, softErr := parseRawToken(i, TokenSoftBreak); softErr == nil {
|
if tok, softErr := parseRawToken(i, TokenSoftBreak); softErr == nil {
|
||||||
return tok, nil
|
return tok, nil
|
||||||
} else if tok, hardErr := parseRawToken(i, TokenHardBreak); hardErr == nil {
|
} else if tok, hardErr := parseRawToken(i, TokenHardBreak); hardErr == nil {
|
||||||
@@ -58,13 +57,13 @@ 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{}
|
results := []U{}
|
||||||
|
|
||||||
for {
|
for {
|
||||||
if u, err := fn(i); err != nil {
|
if u, err := fn(i); err != nil {
|
||||||
if len(results) < minimum {
|
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
|
return results, nil
|
||||||
} else {
|
} else {
|
||||||
@@ -73,45 +72,45 @@ func parseList[U any](i *TokenIterator, fn func(*TokenIterator) (U, error), mini
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseAbstraction(i *TokenIterator) (*Abstraction, error) {
|
func parseAbstraction(i *tokenIterator) (*Abstraction, error) {
|
||||||
return iterator.Do(i, func(i *TokenIterator) (*Abstraction, error) {
|
return iterator.Do(i, func(i *tokenIterator) (*Abstraction, error) {
|
||||||
if _, err := parseToken(i, TokenSlash, true); err != nil {
|
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 {
|
} else if parameters, err := parseList(i, parseString, 0); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else if _, err = parseToken(i, TokenDot, true); err != nil {
|
} 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 {
|
} else if body, err := parseExpression(i); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else {
|
} else {
|
||||||
return NewAbstraction(parameters, body), nil
|
return &Abstraction{Parameters: parameters, Body: body}, nil
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseApplication(i *TokenIterator) (*Application, error) {
|
func parseApplication(i *tokenIterator) (*Application, error) {
|
||||||
return iterator.Do(i, func(i *TokenIterator) (*Application, error) {
|
return iterator.Do(i, func(i *tokenIterator) (*Application, error) {
|
||||||
if _, err := parseToken(i, TokenOpenParen, true); err != nil {
|
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 {
|
} else if expressions, err := parseList(i, parseExpression, 1); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else if _, err := parseToken(i, TokenCloseParen, true); err != nil {
|
} 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 {
|
} else {
|
||||||
return NewApplication(expressions[0], expressions[1:]), nil
|
return &Application{Abstraction: expressions[0], Arguments: expressions[1:]}, nil
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseAtom(i *TokenIterator) (*Atom, error) {
|
func parseAtom(i *tokenIterator) (*Atom, error) {
|
||||||
if tok, err := parseToken(i, TokenAtom, true); err != nil {
|
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 {
|
} else {
|
||||||
return NewAtom(tok.Value), nil
|
return &Atom{Name: tok.Value}, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseStatements(i *TokenIterator) ([]Statement, error) {
|
func parseStatements(i *tokenIterator) ([]Statement, error) {
|
||||||
statements := []Statement{}
|
statements := []Statement{}
|
||||||
|
|
||||||
//nolint:errcheck
|
//nolint:errcheck
|
||||||
@@ -130,7 +129,7 @@ func parseStatements(i *TokenIterator) ([]Statement, error) {
|
|||||||
return statements, nil
|
return statements, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseClause(i *TokenIterator, braces bool) (*Clause, error) {
|
func parseClause(i *tokenIterator, braces bool) (*Clause, error) {
|
||||||
if braces {
|
if braces {
|
||||||
if _, err := parseToken(i, TokenOpenBrace, true); err != nil {
|
if _, err := parseToken(i, TokenOpenBrace, true); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -156,11 +155,11 @@ 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) {
|
func parseExpression(i *tokenIterator) (Expression, error) {
|
||||||
return iterator.Do(i, func(i *TokenIterator) (Expression, error) {
|
return iterator.Do(i, func(i *tokenIterator) (Expression, error) {
|
||||||
passSoftBreaks(i)
|
passSoftBreaks(i)
|
||||||
|
|
||||||
switch peek := i.MustGet(); peek.Type {
|
switch peek := i.MustGet(); peek.Type {
|
||||||
@@ -178,8 +177,8 @@ func parseExpression(i *TokenIterator) (Expression, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseLet(i *TokenIterator) (*LetStatement, error) {
|
func parseLet(i *tokenIterator) (*LetStatement, error) {
|
||||||
return iterator.Do(i, func(i *TokenIterator) (*LetStatement, error) {
|
return iterator.Do(i, func(i *tokenIterator) (*LetStatement, error) {
|
||||||
if parameters, err := parseList(i, parseString, 1); err != nil {
|
if parameters, err := parseList(i, parseString, 1); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else if _, err := parseToken(i, TokenAssign, true); err != nil {
|
} else if _, err := parseToken(i, TokenAssign, true); err != nil {
|
||||||
@@ -187,20 +186,20 @@ func parseLet(i *TokenIterator) (*LetStatement, error) {
|
|||||||
} else if body, err := parseExpression(i); err != nil {
|
} else if body, err := parseExpression(i); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else {
|
} else {
|
||||||
return NewLet(parameters[0], parameters[1:], body), nil
|
return &LetStatement{Name: parameters[0], Parameters: parameters[1:], Body: body}, nil
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseDeclare(i *TokenIterator) (*DeclareStatement, error) {
|
func parseDeclare(i *tokenIterator) (*DeclareStatement, error) {
|
||||||
if value, err := parseExpression(i); err != nil {
|
if value, err := parseExpression(i); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else {
|
} else {
|
||||||
return NewDeclare(value), nil
|
return &DeclareStatement{Value: value}, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseStatement(i *TokenIterator) (Statement, error) {
|
func parseStatement(i *tokenIterator) (Statement, error) {
|
||||||
if let, letErr := parseLet(i); letErr == nil {
|
if let, letErr := parseLet(i); letErr == nil {
|
||||||
return let, nil
|
return let, nil
|
||||||
} else if declare, declErr := parseDeclare(i); declErr == nil {
|
} else if declare, declErr := parseDeclare(i); declErr == nil {
|
||||||
|
|||||||
60
pkg/saccharine/saccharine.go
Normal file
60
pkg/saccharine/saccharine.go
Normal file
@@ -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() {}
|
||||||
@@ -6,7 +6,6 @@ import (
|
|||||||
"unicode"
|
"unicode"
|
||||||
|
|
||||||
"git.maximhutz.com/max/lambda/pkg/iterator"
|
"git.maximhutz.com/max/lambda/pkg/iterator"
|
||||||
"git.maximhutz.com/max/lambda/pkg/trace"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// isVariables determines whether a rune can be a valid variable.
|
// isVariables determines whether a rune can be a valid variable.
|
||||||
@@ -51,38 +50,38 @@ func scanToken(i *iterator.Iterator[rune]) (*Token, error) {
|
|||||||
|
|
||||||
letter, err := i.Next()
|
letter, err := i.Next()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, trace.Wrap(err, "cannot produce next token")
|
return nil, fmt.Errorf("cannot produce next token: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
switch {
|
switch {
|
||||||
case letter == '(':
|
case letter == '(':
|
||||||
return NewTokenOpenParen(index), nil
|
return NewToken(TokenOpenParen, index), nil
|
||||||
case letter == ')':
|
case letter == ')':
|
||||||
return NewTokenCloseParen(index), nil
|
return NewToken(TokenCloseParen, index), nil
|
||||||
case letter == '.':
|
case letter == '.':
|
||||||
return NewTokenDot(index), nil
|
return NewToken(TokenDot, index), nil
|
||||||
case letter == '\\':
|
case letter == '\\':
|
||||||
return NewTokenSlash(index), nil
|
return NewToken(TokenSlash, index), nil
|
||||||
case letter == '\n':
|
case letter == '\n':
|
||||||
return NewTokenSoftBreak(index), nil
|
return NewToken(TokenSoftBreak, index), nil
|
||||||
case letter == '{':
|
case letter == '{':
|
||||||
return NewTokenOpenBrace(index), nil
|
return NewToken(TokenOpenBrace, index), nil
|
||||||
case letter == '}':
|
case letter == '}':
|
||||||
return NewTokenCloseBrace(index), nil
|
return NewToken(TokenCloseBrace, index), nil
|
||||||
case letter == ':':
|
case letter == ':':
|
||||||
if _, err := scanCharacter(i, '='); err != nil {
|
if _, err := scanCharacter(i, '='); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else {
|
} else {
|
||||||
return NewTokenAssign(index), nil
|
return NewToken(TokenAssign, index), nil
|
||||||
}
|
}
|
||||||
case letter == ';':
|
case letter == ';':
|
||||||
return NewTokenHardBreak(index), nil
|
return NewToken(TokenHardBreak, index), nil
|
||||||
case letter == '#':
|
case letter == '#':
|
||||||
// Skip everything until the next newline or EOF.
|
// Skip everything until the next newline or EOF.
|
||||||
for !i.Done() {
|
for !i.Done() {
|
||||||
r, err := i.Next()
|
r, err := i.Next()
|
||||||
if err != nil {
|
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' {
|
if r == '\n' {
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
package saccharine
|
|
||||||
|
|
||||||
type Statement interface {
|
|
||||||
IsStatement()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** ------------------------------------------------------------------------- */
|
|
||||||
|
|
||||||
type LetStatement struct {
|
|
||||||
Name string
|
|
||||||
Parameters []string
|
|
||||||
Body Expression
|
|
||||||
}
|
|
||||||
|
|
||||||
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}
|
|
||||||
}
|
|
||||||
@@ -2,90 +2,80 @@ package saccharine
|
|||||||
|
|
||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
// All tokens in the pseudo-lambda language.
|
// A TokenType is an identifier for any token in the Saccharine language.
|
||||||
type TokenType int
|
type TokenType int
|
||||||
|
|
||||||
|
// All official tokens of the Saccharine language.
|
||||||
const (
|
const (
|
||||||
TokenOpenParen TokenType = iota // Denotes the '(' token.
|
// TokenOpenParen denotes the '(' token.
|
||||||
TokenCloseParen // Denotes the ')' token.
|
TokenOpenParen TokenType = iota
|
||||||
TokenOpenBrace // Denotes the '{' token.
|
// TokenCloseParen denotes the ')' token.
|
||||||
TokenCloseBrace // Denotes the '}' token.
|
TokenCloseParen
|
||||||
TokenHardBreak // Denotes the ';' token.
|
// TokenOpenBrace denotes the '{' token.
|
||||||
TokenAssign // Denotes the ':=' token.
|
TokenOpenBrace
|
||||||
TokenAtom // Denotes an alpha-numeric variable.
|
// TokenCloseBrace denotes the '}' token.
|
||||||
TokenSlash // Denotes the '/' token.
|
TokenCloseBrace
|
||||||
TokenDot // Denotes the '.' token.
|
// TokenHardBreak denotes the ';' token.
|
||||||
TokenSoftBreak // Denotes a new-line.
|
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 {
|
type Token struct {
|
||||||
Column int // Where the token begins in the source text.
|
Column int // Where the token begins in the source text.
|
||||||
Type TokenType // What type the token is.
|
Type TokenType // What type the token is.
|
||||||
Value string // The value of the token.
|
Value string // The value of the token.
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewTokenOpenParen(column int) *Token {
|
// NewToken creates a [Token] of the given type at the given column.
|
||||||
return &Token{Type: TokenOpenParen, Column: column, Value: "("}
|
// 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()}
|
||||||
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: "\\"}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewTokenAtom creates a [TokenAtom] with the given name at the given column.
|
||||||
func NewTokenAtom(name string, column int) *Token {
|
func NewTokenAtom(name string, column int) *Token {
|
||||||
return &Token{Type: TokenAtom, Column: column, Value: name}
|
return &Token{Type: TokenAtom, Column: column, Value: name}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewTokenSoftBreak(column int) *Token {
|
// Name returns the type of the TokenType, as a string.
|
||||||
return &Token{Type: TokenSoftBreak, Column: column, Value: "\\n"}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t TokenType) Name() string {
|
func (t TokenType) Name() string {
|
||||||
switch t {
|
switch t {
|
||||||
case TokenOpenParen:
|
case TokenOpenParen:
|
||||||
return "("
|
return "("
|
||||||
case TokenCloseParen:
|
case TokenCloseParen:
|
||||||
return ")"
|
return ")"
|
||||||
|
case TokenOpenBrace:
|
||||||
|
return "{"
|
||||||
|
case TokenCloseBrace:
|
||||||
|
return "}"
|
||||||
|
case TokenHardBreak:
|
||||||
|
return ";"
|
||||||
|
case TokenAssign:
|
||||||
|
return ":="
|
||||||
|
case TokenAtom:
|
||||||
|
return "ATOM"
|
||||||
case TokenSlash:
|
case TokenSlash:
|
||||||
return "\\"
|
return "\\"
|
||||||
case TokenDot:
|
case TokenDot:
|
||||||
return "."
|
return "."
|
||||||
case TokenAtom:
|
|
||||||
return "ATOM"
|
|
||||||
case TokenSoftBreak:
|
case TokenSoftBreak:
|
||||||
return "\\n"
|
return "\\n"
|
||||||
case TokenHardBreak:
|
|
||||||
return ";"
|
|
||||||
default:
|
default:
|
||||||
panic(fmt.Errorf("unknown token type %v", t))
|
panic(fmt.Errorf("unknown token type %v", t))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Name returns the type of the Token, as a string.
|
||||||
func (t Token) Name() string {
|
func (t Token) Name() string {
|
||||||
return t.Type.Name()
|
return t.Type.Name()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,41 @@
|
|||||||
|
// Package set defines a generic, mutable unordered set data structure.
|
||||||
package set
|
package set
|
||||||
|
|
||||||
import "iter"
|
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
|
type Set[T comparable] map[T]bool
|
||||||
|
|
||||||
|
// Add appends a list of items into the set.
|
||||||
func (s Set[T]) Add(items ...T) {
|
func (s Set[T]) Add(items ...T) {
|
||||||
for _, item := range items {
|
for _, item := range items {
|
||||||
s[item] = true
|
s[item] = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Has returns true an item is present in the set.
|
||||||
func (s Set[T]) Has(item T) bool {
|
func (s Set[T]) Has(item T) bool {
|
||||||
return s[item]
|
return s[item]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Remove deletes a list of items from the set.
|
||||||
func (s Set[T]) Remove(items ...T) {
|
func (s Set[T]) Remove(items ...T) {
|
||||||
for _, item := range items {
|
for _, item := range items {
|
||||||
delete(s, item)
|
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]) {
|
func (s Set[T]) Merge(o Set[T]) {
|
||||||
for item := range o {
|
for item := range o {
|
||||||
s.Add(item)
|
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 {
|
func (s Set[T]) ToList() []T {
|
||||||
list := []T{}
|
list := []T{}
|
||||||
|
|
||||||
@@ -36,6 +46,8 @@ func (s Set[T]) ToList() []T {
|
|||||||
return list
|
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] {
|
func (s Set[T]) Items() iter.Seq[T] {
|
||||||
return func(yield func(T) bool) {
|
return func(yield func(T) bool) {
|
||||||
for item := range s {
|
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] {
|
func New[T comparable](items ...T) Set[T] {
|
||||||
result := Set[T]{}
|
result := Set[T]{}
|
||||||
|
|
||||||
|
|||||||
@@ -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)
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user