4 Commits

Author SHA1 Message Date
31924237b2 feat: saccharine marshaler 2026-01-30 20:16:57 -05:00
68cc1624c7 feat: registry, normalorder engine, lambda codec and marshaler 2026-01-30 20:07:35 -05:00
0cdce0e42c feat: cli versions 2026-01-30 17:54:47 -05:00
0ec52008bb feat: repr, codec 2026-01-30 16:24:17 -05:00
25 changed files with 276 additions and 604 deletions

View File

@@ -3,29 +3,65 @@ package main
import (
"os"
"github.com/spf13/cobra"
"git.maximhutz.com/max/lambda/internal/cli"
"git.maximhutz.com/max/lambda/internal/config"
"git.maximhutz.com/max/lambda/internal/plugins"
"git.maximhutz.com/max/lambda/pkg/convert"
"git.maximhutz.com/max/lambda/pkg/normalorder"
"git.maximhutz.com/max/lambda/pkg/saccharine"
)
func Lambda() *cobra.Command {
cmd := &cobra.Command{
Use: "lambda",
Short: "Lambda calculus interpreter",
Long: "A lambda calculus interpreter supporting multiple representations.",
RunE: func(cmd *cobra.Command, _ []string) error {
return cmd.Help()
},
}
cmd.AddCommand(LambdaConvert())
cmd.AddCommand(LambdaEngine())
cmd.AddCommand(LambdaReduce())
return cmd
}
func main() {
lambda := Lambda()
if err := lambda.Execute(); err != nil {
os.Exit(1)
// Parse CLI arguments.
options, err := config.FromArgs()
cli.HandleError(err)
logger := options.GetLogger()
logger.Info("using program arguments", "args", os.Args)
logger.Info("parsed CLI options", "options", options)
// Get input.
input, err := options.Source.Extract()
cli.HandleError(err)
// Parse code into syntax tree.
ast, err := saccharine.Parse(input)
cli.HandleError(err)
logger.Info("parsed syntax tree", "tree", ast)
// Compile expression to lambda calculus.
compiled := convert.SaccharineToLambda(ast)
logger.Info("compiled λ expression", "tree", compiled.String())
// Create reducer with the compiled expression.
runtime := normalorder.NewRuntime(compiled)
// If the user selected to track CPU performance, attach a profiler.
if options.Profile != "" {
plugins.NewPerformance(options.Profile, runtime)
}
// If the user selected to produce a step-by-step explanation, attach an
// observer.
if options.Explanation {
plugins.NewExplanation(runtime)
}
// If the user opted to track statistics, attach a tracker.
if options.Statistics {
plugins.NewStatistics(runtime)
}
// If the user selected for verbose debug logs, attach a reduction tracker.
if options.Verbose {
plugins.NewLogs(logger, runtime)
}
// Run reduction.
runtime.Run()
// Return the final reduced result.
result := runtime.Expression().String()
err = options.Destination.Write(result)
cli.HandleError(err)
}

View File

@@ -1,94 +0,0 @@
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/spf13/cobra"
)
// inferReprFromPath returns the repr type based on file extension.
func inferReprFromPath(path string) (string, error) {
switch ext := strings.ToLower(filepath.Ext(path)); ext {
case ".lambda", ".lam", ".lc":
return "lambda", nil
case ".saccharine", ".sch":
return "saccharine", nil
default:
return "", fmt.Errorf("unknown file extension '%s'", ext)
}
}
func LambdaConvert() *cobra.Command {
var inputReprFlag, outputReprFlag string
cmd := &cobra.Command{
Use: "convert <input-file> <output-file>",
Short: "Convert between lambda calculus representations",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
return cmd.Help()
}
var err error
inputPath, outputPath := args[0], args[1]
// Use flag if provided, otherwise infer from extension.
inputRepr := inputReprFlag
if inputRepr == "" {
if inputRepr, err = inferReprFromPath(inputPath); err != nil {
return fmt.Errorf("input file: %w", err)
}
}
outputRepr := outputReprFlag
if outputRepr == "" {
if outputRepr, err = inferReprFromPath(outputPath); err != nil {
return fmt.Errorf("output file: %w", err)
}
}
// Read input file.
input, err := os.ReadFile(inputPath)
if err != nil {
return fmt.Errorf("reading input file: %w", err)
}
r := GetRegistry()
// Parse input into syntax tree.
repr, err := r.Unmarshal(string(input), inputRepr)
if err != nil {
return fmt.Errorf("parsing input: %w", err)
}
// Convert to output repr if different.
result, err := r.ConvertTo(repr, outputRepr)
if err != nil {
return fmt.Errorf("converting %s to %s: %w", inputRepr, outputRepr, err)
}
// Marshal output.
output, err := r.Marshal(result)
if err != nil {
return fmt.Errorf("unmarshaling output: %w", err)
}
// Write output file.
err = os.WriteFile(outputPath, []byte(output), 0644)
if err != nil {
return fmt.Errorf("writing output file: %w", err)
}
return nil
},
}
cmd.Flags().StringVar(&inputReprFlag, "from", "", "Input representation (inferred from extension if unset)")
cmd.Flags().StringVar(&outputReprFlag, "to", "", "Output representation (inferred from extension if unset)")
return cmd
}

View File

@@ -1,19 +0,0 @@
package main
import (
"github.com/spf13/cobra"
)
func LambdaEngine() *cobra.Command {
cmd := &cobra.Command{
Use: "engine",
Short: "Information about available engines",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
cmd.AddCommand(LambdaEngineList())
return cmd
}

View File

@@ -1,26 +0,0 @@
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func LambdaEngineList() *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Aliases: []string{"ls"},
Short: "List available engines",
RunE: func(cmd *cobra.Command, args []string) error {
r := GetRegistry()
for engine := range r.ListEngines() {
fmt.Println(engine.Name())
}
return nil
},
}
return cmd
}

View File

@@ -1,109 +0,0 @@
package main
import (
"fmt"
"github.com/spf13/cobra"
"git.maximhutz.com/max/lambda/internal/cli"
"git.maximhutz.com/max/lambda/internal/config"
)
func LambdaReduce() *cobra.Command {
var inputReprFlag string
var engineFlag string
cmd := &cobra.Command{
Use: "reduce <input-file>",
Short: "Reduce a lambda calculus expression",
SilenceUsage: true,
Aliases: []string{"run"},
RunE: func(cmd *cobra.Command, args []string) error {
var err error
if len(args) != 1 {
return cmd.Help()
}
inputPath := args[0]
// Get input source.
var source config.Source
if inputPath == "-" {
source = config.StdinSource{}
} else {
source = config.FileSource{Path: inputPath}
}
destination := config.StdoutDestination{}
r := GetRegistry()
// Get input.
input, err := source.Extract()
if err != nil {
return err
}
// Use flag if provided, otherwise infer from extension.
inputRepr := inputReprFlag
if inputRepr == "" {
if inputRepr, err = inferReprFromPath(inputPath); err != nil {
return fmt.Errorf("input file: %w", err)
}
}
// Find engine.
var engine cli.Engine
if engineFlag == "" {
if engine, err = r.GetDefaultEngine(inputRepr); err != nil {
return err
}
} else {
if engine, err = r.GetEngine(engineFlag); err != nil {
return err
}
}
// Parse code into syntax tree.
repr, err := r.Unmarshal(input, inputRepr)
if err != nil {
return err
}
// Compile expression to lambda calculus.
compiled, err := r.ConvertTo(repr, "lambda")
if err != nil {
return err
}
// Create process.
process := engine.Load()
err = process.Set(compiled)
if err != nil {
return err
}
// Run reduction.
for process.Step(1) {
}
// Return the final reduced result.
result, err := process.Get()
if err != nil {
return err
}
output, err := r.Marshal(result)
if err != nil {
return err
}
return destination.Write(output)
},
}
cmd.Flags().StringVar(&inputReprFlag, "from", "", "Input representation (inferred from extension if unset)")
cmd.Flags().StringVarP(&engineFlag, "engine", "e", "", "Reduction engine (inferred from '--input' if unset)")
return cmd
}

85
cmd/lambda/lambda_test.go Normal file
View File

@@ -0,0 +1,85 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
"git.maximhutz.com/max/lambda/pkg/convert"
"git.maximhutz.com/max/lambda/pkg/normalorder"
"git.maximhutz.com/max/lambda/pkg/saccharine"
"github.com/stretchr/testify/assert"
)
// Helper function to run a single sample through the lambda runtime.
func runSample(samplePath string) (string, error) {
// Read the sample file.
input, err := os.ReadFile(samplePath)
if err != nil {
return "", err
}
// Parse code into syntax tree.
ast, err := saccharine.Parse(string(input))
if err != nil {
return "", err
}
// Compile expression to lambda calculus.
compiled := convert.SaccharineToLambda(ast)
// Create and run the reducer.
reducer := normalorder.NewRuntime(compiled)
reducer.Run()
return reducer.Expression().String() + "\n", nil
}
// Test that all samples produce expected output.
func TestSamplesValidity(t *testing.T) {
// Discover all .test files in the tests directory.
testFiles, err := filepath.Glob("../../tests/*.test")
assert.NoError(t, err, "Failed to read tests directory.")
assert.NotEmpty(t, testFiles, "No '*.test' files found in directory.")
for _, testPath := range testFiles {
// Build expected file path.
expectedPath := strings.TrimSuffix(testPath, filepath.Ext(testPath)) + ".expected"
name := strings.TrimSuffix(filepath.Base(testPath), filepath.Ext(testPath))
t.Run(name, func(t *testing.T) {
// Run the sample and capture output.
actual, err := runSample(testPath)
assert.NoError(t, err, "Failed to run sample.")
// Read expected output.
expectedBytes, err := os.ReadFile(expectedPath)
assert.NoError(t, err, "Failed to read expected output.")
expected := string(expectedBytes)
// Compare outputs.
assert.Equal(t, expected, actual, "Output does not match expected.")
})
}
}
// Benchmark all samples using sub-benchmarks.
func BenchmarkSamples(b *testing.B) {
// Discover all .test files in the tests directory.
testFiles, err := filepath.Glob("../../tests/*.test")
assert.NoError(b, err, "Failed to read tests directory.")
assert.NotEmpty(b, testFiles, "No '*.test' files found in directory.")
for _, path := range testFiles {
name := strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
b.Run(name, func(b *testing.B) {
for b.Loop() {
_, err := runSample(path)
assert.NoError(b, err, "Failed to run sample.")
}
})
}
}

View File

@@ -9,18 +9,18 @@ import (
"git.maximhutz.com/max/lambda/pkg/saccharine"
)
func GetRegistry() *registry.Registry {
func MakeRegistry() *registry.Registry {
r := registry.New()
// Codecs
r.MustAddConversions(cli.ConvertCodec(convert.Saccharine2Lambda{}, "saccharine", "lambda")...)
r.AddCodec(cli.ConvertCodec(convert.Saccharine2Lambda{}, "saccharine", "lambda"))
// Engines
r.MustAddEngine(cli.ConvertEngine(normalorder.Engine{}, "normalorder", "lambda"))
r.AddEngine(cli.ConvertEngine(normalorder.Engine{}, "normalorder", "lambda"))
// Marshalers
r.MustAddMarshaler(cli.ConvertMarshaler(lambda.Marshaler{}, "lambda"))
r.MustAddMarshaler(cli.ConvertMarshaler(saccharine.Marshaler{}, "saccharine"))
r.AddMarshaler(cli.ConvertMarshaler(lambda.Marshaler{}, "lambda"))
r.AddMarshaler(cli.ConvertMarshaler(saccharine.Marshaler{}, "saccharine"))
return r
}

7
go.mod
View File

@@ -2,9 +2,10 @@ module git.maximhutz.com/max/lambda
go 1.25.5
require github.com/spf13/cobra v1.10.2
require github.com/stretchr/testify v1.11.1
require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

18
go.sum
View File

@@ -1,11 +1,9 @@
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

55
internal/cli/codec.go Normal file
View File

@@ -0,0 +1,55 @@
package cli
import (
"fmt"
"git.maximhutz.com/max/lambda/pkg/codec"
)
type Codec interface {
codec.Codec[Repr, Repr]
InType() string
OutType() string
}
type convertedCodec[T, U any] struct {
codec codec.Codec[T, U]
inType, outType string
}
func (c convertedCodec[T, U]) Decode(r Repr) (Repr, error) {
u, ok := r.Data().(U)
if !ok {
return nil, fmt.Errorf("could not parse '%v' as '%s'", r, c.inType)
}
t, err := c.codec.Decode(u)
if err != nil {
return nil, err
}
return NewRepr(c.outType, t), nil
}
func (c convertedCodec[T, U]) Encode(r Repr) (Repr, error) {
t, ok := r.Data().(T)
if !ok {
return nil, fmt.Errorf("could not parse '%v' as '%s'", t, c.outType)
}
u, err := c.codec.Encode(t)
if err != nil {
return nil, err
}
return NewRepr(c.inType, u), nil
}
func (c convertedCodec[T, U]) InType() string { return c.inType }
func (c convertedCodec[T, U]) OutType() string { return c.outType }
func ConvertCodec[T, U any](e codec.Codec[T, U], inType, outType string) Codec {
return convertedCodec[T, U]{e, inType, outType}
}

View File

@@ -1,67 +0,0 @@
package cli
import (
"fmt"
"git.maximhutz.com/max/lambda/pkg/codec"
)
type Conversion interface {
InType() string
OutType() string
Run(Repr) (Repr, error)
}
type forwardCodec[T, U any] struct {
codec codec.Codec[T, U]
inType, outType string
}
func (c forwardCodec[T, U]) Run(r Repr) (Repr, error) {
t, ok := r.Data().(T)
if !ok {
return nil, fmt.Errorf("could not parse '%v' as '%s'", t, c.inType)
}
u, err := c.codec.Encode(t)
if err != nil {
return nil, err
}
return NewRepr(c.outType, u), nil
}
func (c forwardCodec[T, U]) InType() string { return c.inType }
func (c forwardCodec[T, U]) OutType() string { return c.outType }
type backwardCodec[T, U any] struct {
codec codec.Codec[T, U]
inType, outType string
}
func (c backwardCodec[T, U]) Run(r Repr) (Repr, error) {
u, ok := r.Data().(U)
if !ok {
return nil, fmt.Errorf("could not parse '%v' as '%s'", r, c.outType)
}
t, err := c.codec.Decode(u)
if err != nil {
return nil, err
}
return NewRepr(c.inType, t), nil
}
func (c backwardCodec[T, U]) InType() string { return c.outType }
func (c backwardCodec[T, U]) OutType() string { return c.inType }
func ConvertCodec[T, U any](e codec.Codec[T, U], inType, outType string) []Conversion {
return []Conversion{
forwardCodec[T, U]{e, inType, outType},
backwardCodec[T, U]{e, inType, outType},
}
}

View File

@@ -1,9 +1,14 @@
package cli
import "git.maximhutz.com/max/lambda/pkg/engine"
import (
"fmt"
"git.maximhutz.com/max/lambda/pkg/engine"
)
type Engine interface {
Load() Process
engine.Engine[Repr]
Name() string
InType() string
}
@@ -14,14 +19,31 @@ type convertedEngine[T any] struct {
inType string
}
func (e convertedEngine[T]) InType() string { return e.inType }
func (b convertedEngine[T]) InType() string { return b.inType }
func (e convertedEngine[T]) Name() string { return e.name }
func (b convertedEngine[T]) Name() string { return b.name }
func (e convertedEngine[T]) Load() Process {
return convertedProcess[T]{e.engine.Load(), e.inType}
func (b convertedEngine[T]) Get() (Repr, error) {
s, err := b.engine.Get()
if err != nil {
return nil, err
}
return NewRepr(b.inType, s), nil
}
func ConvertEngine[T any](e engine.Engine[T], name, inType string) Engine {
return &convertedEngine[T]{e, name, inType}
func (b convertedEngine[T]) Set(r Repr) error {
if t, ok := r.Data().(T); ok {
return b.engine.Set(t)
}
return fmt.Errorf("Incorrent format '%s' for engine '%s'.", r.Id(), b.inType)
}
func (b convertedEngine[T]) Step(i int) bool {
return b.engine.Step(i)
}
func ConvertEngine[T any](e engine.Engine[T], name string, inType string) Engine {
return convertedEngine[T]{e, name, inType}
}

18
internal/cli/exit.go Normal file
View File

@@ -0,0 +1,18 @@
// Package "cli" provides miscellaneous helper functions.
package cli
import (
"fmt"
"os"
)
// A helper function to handle errors in the program. If it is given an error,
// the program will exist, and print the error.
func HandleError(err error) {
if err == nil {
return
}
fmt.Fprintln(os.Stderr, "ERROR:", err)
os.Exit(1)
}

View File

@@ -2,7 +2,6 @@ package cli
import (
"fmt"
"reflect"
"git.maximhutz.com/max/lambda/pkg/codec"
)
@@ -30,9 +29,7 @@ func (c convertedMarshaler[T]) Decode(s string) (Repr, error) {
func (c convertedMarshaler[T]) Encode(r Repr) (string, error) {
t, ok := r.Data().(T)
if !ok {
dataType := reflect.TypeOf(r.Data())
allowedType := reflect.TypeFor[T]()
return "", fmt.Errorf("marshaler for '%s' cannot parse '%s'", allowedType, dataType)
return "", fmt.Errorf("could not parse '%v' as 'string'", t)
}
return c.codec.Encode(t)

View File

@@ -1,41 +0,0 @@
package cli
import (
"fmt"
"git.maximhutz.com/max/lambda/pkg/engine"
)
type Process interface {
engine.Process[Repr]
InType() string
}
type convertedProcess[T any] struct {
process engine.Process[T]
inType string
}
func (e convertedProcess[T]) InType() string { return e.inType }
func (b convertedProcess[T]) Get() (Repr, error) {
s, err := b.process.Get()
if err != nil {
return nil, err
}
return NewRepr(b.inType, s), nil
}
func (b convertedProcess[T]) Set(r Repr) error {
if t, ok := r.Data().(T); ok {
return b.process.Set(t)
}
return fmt.Errorf("Incorrent format '%s' for engine '%s'.", r.Id(), b.inType)
}
func (b convertedProcess[T]) Step(i int) bool {
return b.process.Step(i)
}

View File

@@ -1,27 +0,0 @@
package registry
import (
"git.maximhutz.com/max/lambda/internal/cli"
)
type Converter struct {
data map[string][]cli.Conversion
}
func NewConverter() *Converter {
return &Converter{data: map[string][]cli.Conversion{}}
}
func (g *Converter) Add(c cli.Conversion) {
conversionsFromIn, ok := g.data[c.InType()]
if !ok {
conversionsFromIn = []cli.Conversion{}
}
conversionsFromIn = append(conversionsFromIn, c)
g.data[c.InType()] = conversionsFromIn
}
func (g *Converter) ConversionsFrom(t string) []cli.Conversion {
return g.data[t]
}

View File

@@ -2,38 +2,28 @@ package registry
import (
"fmt"
"iter"
"maps"
"git.maximhutz.com/max/lambda/internal/cli"
)
type Registry struct {
marshalers map[string]cli.Marshaler
converter *Converter
codecs []cli.Codec
engines map[string]cli.Engine
}
func New() *Registry {
return &Registry{
marshalers: map[string]cli.Marshaler{},
converter: NewConverter(),
codecs: []cli.Codec{},
engines: map[string]cli.Engine{},
}
}
func (r *Registry) AddConversions(conversions ...cli.Conversion) error {
for _, conversion := range conversions {
r.converter.Add(conversion)
}
func (r *Registry) AddCodec(c cli.Codec) error {
r.codecs = append(r.codecs, c)
return nil
}
func (r *Registry) MustAddConversions(conversions ...cli.Conversion) {
if err := r.AddConversions(conversions...); err != nil {
panic(err)
}
}
func (r *Registry) AddMarshaler(c cli.Marshaler) error {
if _, ok := r.marshalers[c.InType()]; ok {
@@ -44,12 +34,6 @@ func (r *Registry) AddMarshaler(c cli.Marshaler) error {
return nil
}
func (r *Registry) MustAddMarshaler(c cli.Marshaler) {
if err := r.AddMarshaler(c); err != nil {
panic(err)
}
}
func (r *Registry) AddEngine(e cli.Engine) error {
if _, ok := r.engines[e.Name()]; ok {
return fmt.Errorf("engine '%s' already registered", e.Name())
@@ -59,13 +43,7 @@ func (r *Registry) AddEngine(e cli.Engine) error {
return nil
}
func (r *Registry) MustAddEngine(e cli.Engine) {
if err := r.AddEngine(e); err != nil {
panic(err)
}
}
func (r Registry) GetEngine(name string) (cli.Engine, error) {
func (r *Registry) GetEngine(name string) (cli.Engine, error) {
e, ok := r.engines[name]
if !ok {
return nil, fmt.Errorf("engine '%s' not found", name)
@@ -74,35 +52,8 @@ func (r Registry) GetEngine(name string) (cli.Engine, error) {
return e, nil
}
func (r Registry) ListEngines() iter.Seq[cli.Engine] {
return maps.Values(r.engines)
}
func (r *Registry) GetDefaultEngine(id string) (cli.Engine, error) {
for _, engine := range r.engines {
if engine.InType() == id {
return engine, nil
}
}
return nil, fmt.Errorf("no engine for '%s'", id)
}
func (r *Registry) ConvertTo(repr cli.Repr, outType string) (cli.Repr, error) {
path, err := r.ConversionPath(repr.Id(), outType)
if err != nil {
return nil, err
}
result := repr
for _, conversion := range path {
result, err = conversion.Run(result)
if err != nil {
return nil, fmt.Errorf("converting '%s' to '%s': %w", conversion.InType(), conversion.OutType(), err)
}
}
return result, err
panic("")
}
func (r *Registry) Marshal(repr cli.Repr) (string, error) {
@@ -122,52 +73,3 @@ func (r *Registry) Unmarshal(s string, outType string) (cli.Repr, error) {
return m.Decode(s)
}
func reverse[T any](list []T) []T {
if list == nil {
return list
}
reversed := []T{}
for i := len(list) - 1; i >= 0; i-- {
reversed = append(reversed, list[i])
}
return reversed
}
func (r *Registry) ConversionPath(from, to string) ([]cli.Conversion, error) {
backtrack := map[string]cli.Conversion{}
iteration := []string{from}
for len(iteration) > 0 {
nextIteration := []string{}
for _, item := range iteration {
for _, conversion := range r.converter.ConversionsFrom(item) {
if _, ok := backtrack[conversion.OutType()]; ok {
continue
}
nextIteration = append(nextIteration, conversion.OutType())
backtrack[conversion.OutType()] = conversion
}
}
iteration = nextIteration
}
reversedPath := []cli.Conversion{}
current := to
for current != from {
conversion, ok := backtrack[current]
if !ok {
return nil, fmt.Errorf("no valid conversion from '%s' to '%s'", from, to)
}
reversedPath = append(reversedPath, conversion)
current = conversion.InType()
}
return reverse(reversedPath), nil
}

View File

@@ -1,9 +0,0 @@
package registrynew
// Conversion
type Conversion interface {
InRepr() string
OutRepr() string
Run(Expr) (Expr, error)
}

View File

@@ -1,12 +0,0 @@
package registrynew
type Process interface {
Get() (Expr, error)
Step(int) bool
}
type Engine interface {
Load(Expr) Process
Name() string
InRepr() string
}

View File

@@ -1,7 +0,0 @@
package registrynew
type Expr interface {
Repr() string
Data() any
}

View File

@@ -1,5 +0,0 @@
package registrynew
type Marshaler interface {
InType() string
}

View File

@@ -1,10 +0,0 @@
package registrynew
import "iter"
type Registry interface {
ListEngines() iter.Seq[string]
GetEngine(name string) (Engine, error)
ListReprs() iter.Seq[string]
}

View File

@@ -1,4 +0,0 @@
package registrynew
type Repr interface {
}

View File

@@ -1,10 +1,6 @@
package engine
type Engine[T any] interface {
Load() Process[T]
}
type Process[T any] interface {
Get() (T, error)
Set(T) error
Step(int) bool

View File

@@ -5,38 +5,30 @@ import (
"git.maximhutz.com/max/lambda/pkg/lambda"
)
type Process struct {
type Engine struct {
expr lambda.Expression
}
func (e Process) Get() (lambda.Expression, error) {
func (e Engine) Get() (lambda.Expression, error) {
return e.expr, nil
}
func (e *Process) Set(l lambda.Expression) error {
func (e Engine) Set(l lambda.Expression) error {
e.expr = l
return nil
}
func (e *Process) Step(i int) bool {
func (e Engine) Step(i int) bool {
var reduced bool
for range i {
next, reduced := ReduceOnce(e.expr)
e.expr, reduced = ReduceOnce(e.expr)
if !reduced {
return false
}
e.expr = next
}
return true
}
type Engine struct {
}
func (e Engine) Load() engine.Process[lambda.Expression] {
return &Process{}
}
var _ engine.Process[lambda.Expression] = (*Process)(nil)
var _ engine.Engine[lambda.Expression] = (*Engine)(nil)