From d6455eae22a5231c014966fda96eafcdd27074d4 Mon Sep 17 00:00:00 2001 From: Jairo Litman <130161309+jairo-litman@users.noreply.github.com> Date: Sun, 18 Feb 2024 12:33:23 -0300 Subject: [PATCH] added examples and flag to run code from files --- example/arithmetic.cidoka | 8 +++++++ example/helloworld.cidoka | 1 + main.go | 49 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 example/arithmetic.cidoka create mode 100644 example/helloworld.cidoka diff --git a/example/arithmetic.cidoka b/example/arithmetic.cidoka new file mode 100644 index 0000000..bfd9932 --- /dev/null +++ b/example/arithmetic.cidoka @@ -0,0 +1,8 @@ +let x = 1 +let y = 2 + x +let z = 3 * y + +let result = x + y + z + +print(result) +result \ No newline at end of file diff --git a/example/helloworld.cidoka b/example/helloworld.cidoka new file mode 100644 index 0000000..e75154b --- /dev/null +++ b/example/helloworld.cidoka @@ -0,0 +1 @@ +print("hello world") \ No newline at end of file diff --git a/main.go b/main.go index 2769d5d..7c4ac98 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,13 @@ package main import ( + "cidoka/compiler" + "cidoka/evaluator" + "cidoka/lexer" + "cidoka/object" + "cidoka/parser" "cidoka/repl" + "cidoka/vm" "flag" "fmt" "os" @@ -9,10 +15,16 @@ import ( ) var engine = flag.String("engine", "vm", "use 'vm' or 'eval'") +var input = flag.String("input", "", "input file") func main() { flag.Parse() + if *input != "" { + runFile(*input) + return + } + user, err := user.Current() if err != nil { panic(err) @@ -22,3 +34,40 @@ func main() { fmt.Printf("Feel free to type in commands\n") repl.Start(os.Stdin, os.Stdout, *engine) } + +func runFile(input string) { + f, err := os.ReadFile(input) + if err != nil { + panic(err) + } + + var result object.Object + + l := lexer.New(string(f)) + p := parser.New(l) + program := p.ParseProgram() + + if *engine == "vm" { + comp := compiler.New() + err := comp.Compile(program) + if err != nil { + fmt.Printf("compiler error: %s", err) + return + } + + machine := vm.New(comp.Bytecode()) + + err = machine.Run() + if err != nil { + fmt.Printf("vm error: %s", err) + return + } + + result = machine.LastPoppedStackElem() + } else { + env := object.NewEnvironment() + result = evaluator.Eval(program, env) + } + + fmt.Printf("engine=%s, result=%s\n", *engine, result.Inspect()) +}