-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
83 lines (67 loc) · 2.06 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"flag"
"fmt"
"os"
"github.com/bradford-hamilton/monkey-lang/ast"
"github.com/bradford-hamilton/monkey-lang/compiler"
"github.com/bradford-hamilton/monkey-lang/evaluator"
"github.com/bradford-hamilton/monkey-lang/lexer"
"github.com/bradford-hamilton/monkey-lang/object"
"github.com/bradford-hamilton/monkey-lang/parser"
"github.com/bradford-hamilton/monkey-lang/repl"
"github.com/bradford-hamilton/monkey-lang/vm"
)
func main() {
// Define and parse flag options
engine := flag.String("engine", "vm", "Engine options are \"vm\" or \"eval\"")
console := flag.Bool("console", false, "Provide console flag to enter interactive repl")
flag.Parse()
if *engine != "vm" && *engine != "eval" {
fmt.Printf("Engine must be either 'vm' or 'eval', got %s\n", *engine)
return
}
// If console flag is provided, run interactive console - otherwise read file and execute
if *console {
repl.Start(os.Stdin, os.Stdout, engine)
} else {
if len(flag.Args()) != 1 {
fmt.Println("Incorrect usage. Usage: `monkey [option...] filePath`")
return
}
var result object.Object
filePath := flag.Args()[0]
contents, err := os.ReadFile(filePath)
if err != nil {
fmt.Printf("Failure to read file '%s'. Err: %s", string(contents), err)
}
l := lexer.New(string(contents))
p := parser.New(l)
program := p.ParseProgram()
if *engine == "vm" {
result = compileBytecodeAndRun(program)
} else {
result = evaluateAst(program)
}
fmt.Println(result.Inspect())
}
}
// Evaluate the AST with evaluator
func evaluateAst(program *ast.RootNode) object.Object {
env := object.NewEnvironment()
return evaluator.Eval(program, env)
}
// Compile program to bytecode, pass to VM, and run. Returns the last popped stack element (result)
func compileBytecodeAndRun(program *ast.RootNode) object.Object {
comp := compiler.New()
err := comp.Compile(program)
if err != nil {
fmt.Printf("compiler error: %s", err)
}
vm := vm.New(comp.Bytecode())
err = vm.Run()
if err != nil {
fmt.Printf("vm error: %s", err)
}
return vm.LastPoppedStackElement()
}