9 Commits

13 changed files with 157 additions and 200 deletions

View File

@@ -1,8 +1,10 @@
package main package main
import ( import (
"fmt"
"os" "os"
"git.maximhutz.com/max/lambda/internal/config"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -11,14 +13,74 @@ func Lambda() *cobra.Command {
Use: "lambda", Use: "lambda",
Short: "Lambda calculus interpreter", Short: "Lambda calculus interpreter",
Long: "A lambda calculus interpreter supporting multiple representations.", Long: "A lambda calculus interpreter supporting multiple representations.",
RunE: func(cmd *cobra.Command, _ []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help() // Legacy behavior when no subcommand is given.
options, err := config.FromArgs()
if err != nil {
return err
}
logger := options.GetLogger()
logger.Info("using program arguments", "args", os.Args)
logger.Info("parsed CLI options", "options", options)
r := GetRegistry()
// Get input.
input, err := options.Source.Extract()
if err != nil {
return err
}
// Parse code into syntax tree.
repr, err := r.Unmarshal(input, "saccharine")
if err != nil {
return err
}
logger.Info("parsed syntax tree", "tree", repr)
// Compile expression to lambda calculus.
compiled, err := r.ConvertTo(repr, "lambda")
if err != nil {
return err
}
logger.Info("compiled λ expression", "tree", compiled)
// Create reducer with the compiled expression.
engine, err := r.GetDefaultEngine("lambda")
if err != nil {
return err
}
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 options.Destination.Write(output)
}, },
} }
cmd.PersistentFlags().BoolP("verbose", "v", false, "Enable verbose output")
cmd.AddCommand(LambdaConvert()) cmd.AddCommand(LambdaConvert())
cmd.AddCommand(LambdaEngine()) cmd.AddCommand(LambdaEngine())
cmd.AddCommand(LambdaReduce())
return cmd return cmd
} }
@@ -26,6 +88,7 @@ func Lambda() *cobra.Command {
func main() { func main() {
lambda := Lambda() lambda := Lambda()
if err := lambda.Execute(); err != nil { if err := lambda.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1) os.Exit(1)
} }
} }

View File

@@ -6,15 +6,17 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"git.maximhutz.com/max/lambda/internal/cli"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper"
) )
// inferReprFromPath returns the repr type based on file extension. // inferReprFromPath returns the repr type based on file extension.
func inferReprFromPath(path string) (string, error) { func inferReprFromPath(path string) (string, error) {
switch ext := strings.ToLower(filepath.Ext(path)); ext { switch ext := strings.ToLower(filepath.Ext(path)); ext {
case ".lambda", ".lam", ".lc": case ".lam", ".lambda":
return "lambda", nil return "lambda", nil
case ".saccharine", ".sch": case ".sac", ".saccharine":
return "saccharine", nil return "saccharine", nil
default: default:
return "", fmt.Errorf("unknown file extension '%s'", ext) return "", fmt.Errorf("unknown file extension '%s'", ext)
@@ -22,33 +24,23 @@ func inferReprFromPath(path string) (string, error) {
} }
func LambdaConvert() *cobra.Command { func LambdaConvert() *cobra.Command {
var inputReprFlag, outputReprFlag string
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "convert <input-file> <output-file>", Use: "convert <input> <output>",
Short: "Convert between lambda calculus representations", Short: "Convert between lambda calculus representations",
SilenceUsage: true, Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 2 { inputPath := args[0]
return cmd.Help() outputPath := args[1]
// Infer repr types from extensions.
inputRepr, err := inferReprFromPath(inputPath)
if err != nil {
return fmt.Errorf("input file: %w", err)
} }
var err error outputRepr, err := inferReprFromPath(outputPath)
inputPath, outputPath := args[0], args[1] if err != nil {
return fmt.Errorf("output file: %w", 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)
}
}
outputRepr := outputReprFlag
if outputRepr == "" {
if outputRepr, err = inferReprFromPath(outputPath); err != nil {
return fmt.Errorf("output file: %w", err)
}
} }
// Read input file. // Read input file.
@@ -65,16 +57,29 @@ func LambdaConvert() *cobra.Command {
return fmt.Errorf("parsing input: %w", err) return fmt.Errorf("parsing input: %w", err)
} }
if viper.GetBool("verbose") {
fmt.Fprintf(os.Stderr, "Parsed %s from %s\n", inputRepr, inputPath)
}
// Convert to output repr if different. // Convert to output repr if different.
result, err := r.ConvertTo(repr, outputRepr) var result cli.Repr
if err != nil { if inputRepr != outputRepr {
return fmt.Errorf("converting %s to %s: %w", inputRepr, outputRepr, err) result, err = r.ConvertTo(repr, outputRepr)
if err != nil {
return fmt.Errorf("converting %s to %s: %w", inputRepr, outputRepr, err)
}
if viper.GetBool("verbose") {
fmt.Fprintf(os.Stderr, "Converted to %s\n", outputRepr)
}
} else {
result = repr
} }
// Marshal output. // Marshal output.
output, err := r.Marshal(result) output, err := r.Marshal(result)
if err != nil { if err != nil {
return fmt.Errorf("unmarshaling output: %w", err) return fmt.Errorf("marshaling output: %w", err)
} }
// Write output file. // Write output file.
@@ -83,12 +88,13 @@ func LambdaConvert() *cobra.Command {
return fmt.Errorf("writing output file: %w", err) return fmt.Errorf("writing output file: %w", err)
} }
if viper.GetBool("verbose") {
fmt.Fprintf(os.Stderr, "Wrote %s to %s\n", outputRepr, outputPath)
}
return nil 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 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
}

18
go.mod
View File

@@ -2,9 +2,25 @@ module git.maximhutz.com/max/lambda
go 1.25.5 go 1.25.5
require github.com/spf13/cobra v1.10.2 require github.com/stretchr/testify v1.11.1
require ( require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/pflag v1.0.10 // indirect github.com/spf13/pflag v1.0.10 // indirect
github.com/spf13/viper v1.21.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/sys v0.29.0 // indirect
golang.org/x/text v0.28.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
) )

31
go.sum
View File

@@ -1,11 +1,42 @@
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
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/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
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/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= 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.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 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=

View File

@@ -21,7 +21,7 @@ type forwardCodec[T, U any] struct {
func (c forwardCodec[T, U]) Run(r Repr) (Repr, error) { func (c forwardCodec[T, U]) Run(r Repr) (Repr, error) {
t, ok := r.Data().(T) t, ok := r.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.outType)
} }
u, err := c.codec.Encode(t) u, err := c.codec.Encode(t)
@@ -29,7 +29,7 @@ func (c forwardCodec[T, U]) Run(r Repr) (Repr, error) {
return nil, err return nil, err
} }
return NewRepr(c.outType, u), nil return NewRepr(c.inType, u), nil
} }
func (c forwardCodec[T, U]) InType() string { return c.inType } func (c forwardCodec[T, U]) InType() string { return c.inType }
@@ -44,7 +44,7 @@ type backwardCodec[T, U any] struct {
func (c backwardCodec[T, U]) Run(r Repr) (Repr, error) { func (c backwardCodec[T, U]) Run(r Repr) (Repr, error) {
u, ok := r.Data().(U) u, ok := r.Data().(U)
if !ok { if !ok {
return nil, fmt.Errorf("could not parse '%v' as '%s'", r, c.outType) return nil, fmt.Errorf("could not parse '%v' as '%s'", r, c.inType)
} }
t, err := c.codec.Decode(u) t, err := c.codec.Decode(u)
@@ -52,7 +52,7 @@ func (c backwardCodec[T, U]) Run(r Repr) (Repr, error) {
return nil, err return nil, err
} }
return NewRepr(c.inType, t), nil return NewRepr(c.outType, t), nil
} }
func (c backwardCodec[T, U]) InType() string { return c.outType } func (c backwardCodec[T, U]) InType() string { return c.outType }

View File

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

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 {
}