Compare commits
5 Commits
31924237b2
...
7750d8615f
| Author | SHA1 | Date | |
|---|---|---|---|
|
7750d8615f
|
|||
|
22e8a99362
|
|||
|
5f6a9f9663
|
|||
|
dc872d15ae
|
|||
|
ca1bb2ffa8
|
@@ -1,67 +1,94 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"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"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Parse CLI arguments.
|
||||
options, err := config.FromArgs()
|
||||
cli.HandleError(err)
|
||||
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, args []string) error {
|
||||
// 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)
|
||||
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)
|
||||
r := GetRegistry()
|
||||
|
||||
// Parse code into syntax tree.
|
||||
ast, err := saccharine.Parse(input)
|
||||
cli.HandleError(err)
|
||||
logger.Info("parsed syntax tree", "tree", ast)
|
||||
// Get input.
|
||||
input, err := options.Source.Extract()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Compile expression to lambda calculus.
|
||||
compiled := convert.SaccharineToLambda(ast)
|
||||
logger.Info("compiled λ expression", "tree", compiled.String())
|
||||
// Parse code into syntax tree.
|
||||
repr, err := r.Unmarshal(input, "saccharine")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Info("parsed syntax tree", "tree", repr)
|
||||
|
||||
// Create reducer with the compiled expression.
|
||||
runtime := normalorder.NewRuntime(compiled)
|
||||
// Compile expression to lambda calculus.
|
||||
compiled, err := r.ConvertTo(repr, "lambda")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Info("compiled λ expression", "tree", compiled)
|
||||
|
||||
// If the user selected to track CPU performance, attach a profiler.
|
||||
if options.Profile != "" {
|
||||
plugins.NewPerformance(options.Profile, runtime)
|
||||
// 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)
|
||||
},
|
||||
}
|
||||
|
||||
// If the user selected to produce a step-by-step explanation, attach an
|
||||
// observer.
|
||||
if options.Explanation {
|
||||
plugins.NewExplanation(runtime)
|
||||
}
|
||||
cmd.PersistentFlags().BoolP("verbose", "v", false, "Enable verbose output")
|
||||
|
||||
// If the user opted to track statistics, attach a tracker.
|
||||
if options.Statistics {
|
||||
plugins.NewStatistics(runtime)
|
||||
}
|
||||
cmd.AddCommand(LambdaConvert())
|
||||
cmd.AddCommand(LambdaEngine())
|
||||
|
||||
// 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)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func main() {
|
||||
lambda := Lambda()
|
||||
if err := lambda.Execute(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
100
cmd/lambda/lambda_convert.go
Normal file
100
cmd/lambda/lambda_convert.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.maximhutz.com/max/lambda/internal/cli"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// inferReprFromPath returns the repr type based on file extension.
|
||||
func inferReprFromPath(path string) (string, error) {
|
||||
switch ext := strings.ToLower(filepath.Ext(path)); ext {
|
||||
case ".lam", ".lambda":
|
||||
return "lambda", nil
|
||||
case ".sac", ".saccharine":
|
||||
return "saccharine", nil
|
||||
default:
|
||||
return "", fmt.Errorf("unknown file extension '%s'", ext)
|
||||
}
|
||||
}
|
||||
|
||||
func LambdaConvert() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "convert <input> <output>",
|
||||
Short: "Convert between lambda calculus representations",
|
||||
Args: cobra.ExactArgs(2),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
inputPath := args[0]
|
||||
outputPath := args[1]
|
||||
|
||||
// Infer repr types from extensions.
|
||||
inputRepr, err := inferReprFromPath(inputPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("input file: %w", err)
|
||||
}
|
||||
|
||||
outputRepr, err := inferReprFromPath(outputPath)
|
||||
if 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)
|
||||
}
|
||||
|
||||
if viper.GetBool("verbose") {
|
||||
fmt.Fprintf(os.Stderr, "Parsed %s from %s\n", inputRepr, inputPath)
|
||||
}
|
||||
|
||||
// Convert to output repr if different.
|
||||
var result cli.Repr
|
||||
if inputRepr != outputRepr {
|
||||
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.
|
||||
output, err := r.Marshal(result)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshaling output: %w", err)
|
||||
}
|
||||
|
||||
// Write output file.
|
||||
err = os.WriteFile(outputPath, []byte(output), 0644)
|
||||
if err != nil {
|
||||
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 cmd
|
||||
}
|
||||
19
cmd/lambda/lambda_engine.go
Normal file
19
cmd/lambda/lambda_engine.go
Normal file
@@ -0,0 +1,19 @@
|
||||
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
|
||||
}
|
||||
26
cmd/lambda/lambda_engine_list.go
Normal file
26
cmd/lambda/lambda_engine_list.go
Normal file
@@ -0,0 +1,26 @@
|
||||
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
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
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.")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -9,18 +9,18 @@ import (
|
||||
"git.maximhutz.com/max/lambda/pkg/saccharine"
|
||||
)
|
||||
|
||||
func MakeRegistry() *registry.Registry {
|
||||
func GetRegistry() *registry.Registry {
|
||||
r := registry.New()
|
||||
|
||||
// Codecs
|
||||
r.AddCodec(cli.ConvertCodec(convert.Saccharine2Lambda{}, "saccharine", "lambda"))
|
||||
r.MustAddConversions(cli.ConvertCodec(convert.Saccharine2Lambda{}, "saccharine", "lambda")...)
|
||||
|
||||
// Engines
|
||||
r.AddEngine(cli.ConvertEngine(normalorder.Engine{}, "normalorder", "lambda"))
|
||||
r.MustAddEngine(cli.ConvertEngine(normalorder.Engine{}, "normalorder", "lambda"))
|
||||
|
||||
// Marshalers
|
||||
r.AddMarshaler(cli.ConvertMarshaler(lambda.Marshaler{}, "lambda"))
|
||||
r.AddMarshaler(cli.ConvertMarshaler(saccharine.Marshaler{}, "saccharine"))
|
||||
r.MustAddMarshaler(cli.ConvertMarshaler(lambda.Marshaler{}, "lambda"))
|
||||
r.MustAddMarshaler(cli.ConvertMarshaler(saccharine.Marshaler{}, "saccharine"))
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
15
go.mod
15
go.mod
@@ -6,6 +6,21 @@ require github.com/stretchr/testify v1.11.1
|
||||
|
||||
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/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/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
|
||||
)
|
||||
|
||||
33
go.sum
33
go.sum
@@ -1,9 +1,42 @@
|
||||
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/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/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/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=
|
||||
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=
|
||||
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/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
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}
|
||||
}
|
||||
67
internal/cli/conversion.go
Normal file
67
internal/cli/conversion.go
Normal file
@@ -0,0 +1,67 @@
|
||||
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.outType)
|
||||
}
|
||||
|
||||
u, err := c.codec.Encode(t)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return NewRepr(c.inType, 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.inType)
|
||||
}
|
||||
|
||||
t, err := c.codec.Decode(u)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return NewRepr(c.outType, 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},
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,9 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.maximhutz.com/max/lambda/pkg/engine"
|
||||
)
|
||||
import "git.maximhutz.com/max/lambda/pkg/engine"
|
||||
|
||||
type Engine interface {
|
||||
engine.Engine[Repr]
|
||||
|
||||
Load() Process
|
||||
Name() string
|
||||
InType() string
|
||||
}
|
||||
@@ -19,31 +14,14 @@ type convertedEngine[T any] struct {
|
||||
inType string
|
||||
}
|
||||
|
||||
func (b convertedEngine[T]) InType() string { return b.inType }
|
||||
func (e convertedEngine[T]) InType() string { return e.inType }
|
||||
|
||||
func (b convertedEngine[T]) Name() string { return b.name }
|
||||
func (e convertedEngine[T]) Name() string { return e.name }
|
||||
|
||||
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 (e convertedEngine[T]) Load() Process {
|
||||
return convertedProcess[T]{e.engine.Load(), e.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}
|
||||
func ConvertEngine[T any](e engine.Engine[T], name, inType string) Engine {
|
||||
return &convertedEngine[T]{e, name, inType}
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
// 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)
|
||||
}
|
||||
41
internal/cli/process.go
Normal file
41
internal/cli/process.go
Normal file
@@ -0,0 +1,41 @@
|
||||
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)
|
||||
}
|
||||
27
internal/registry/converter.go
Normal file
27
internal/registry/converter.go
Normal file
@@ -0,0 +1,27 @@
|
||||
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]
|
||||
}
|
||||
@@ -2,28 +2,38 @@ package registry
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"iter"
|
||||
"maps"
|
||||
|
||||
"git.maximhutz.com/max/lambda/internal/cli"
|
||||
)
|
||||
|
||||
type Registry struct {
|
||||
marshalers map[string]cli.Marshaler
|
||||
codecs []cli.Codec
|
||||
converter *Converter
|
||||
engines map[string]cli.Engine
|
||||
}
|
||||
|
||||
func New() *Registry {
|
||||
return &Registry{
|
||||
marshalers: map[string]cli.Marshaler{},
|
||||
codecs: []cli.Codec{},
|
||||
converter: NewConverter(),
|
||||
engines: map[string]cli.Engine{},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Registry) AddCodec(c cli.Codec) error {
|
||||
r.codecs = append(r.codecs, c)
|
||||
func (r *Registry) AddConversions(conversions ...cli.Conversion) error {
|
||||
for _, conversion := range conversions {
|
||||
r.converter.Add(conversion)
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -34,6 +44,12 @@ 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())
|
||||
@@ -43,7 +59,13 @@ func (r *Registry) AddEngine(e cli.Engine) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Registry) GetEngine(name string) (cli.Engine, error) {
|
||||
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) {
|
||||
e, ok := r.engines[name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("engine '%s' not found", name)
|
||||
@@ -52,8 +74,35 @@ 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) {
|
||||
panic("")
|
||||
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
|
||||
}
|
||||
|
||||
func (r *Registry) Marshal(repr cli.Repr) (string, error) {
|
||||
@@ -73,3 +122,52 @@ 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
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package engine
|
||||
|
||||
type Engine[T any] interface {
|
||||
Load() Process[T]
|
||||
}
|
||||
|
||||
type Process[T any] interface {
|
||||
Get() (T, error)
|
||||
Set(T) error
|
||||
Step(int) bool
|
||||
|
||||
@@ -5,30 +5,38 @@ import (
|
||||
"git.maximhutz.com/max/lambda/pkg/lambda"
|
||||
)
|
||||
|
||||
type Engine struct {
|
||||
type Process struct {
|
||||
expr lambda.Expression
|
||||
}
|
||||
|
||||
func (e Engine) Get() (lambda.Expression, error) {
|
||||
func (e Process) Get() (lambda.Expression, error) {
|
||||
return e.expr, nil
|
||||
}
|
||||
|
||||
func (e Engine) Set(l lambda.Expression) error {
|
||||
func (e *Process) Set(l lambda.Expression) error {
|
||||
e.expr = l
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e Engine) Step(i int) bool {
|
||||
var reduced bool
|
||||
|
||||
func (e *Process) Step(i int) bool {
|
||||
for range i {
|
||||
e.expr, reduced = ReduceOnce(e.expr)
|
||||
next, 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)
|
||||
|
||||
Reference in New Issue
Block a user