-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
108 lines (89 loc) · 2.52 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"flag"
"fmt"
"io"
"os"
"os/user"
"github.com/vit0rr/mumu/compiler"
"github.com/vit0rr/mumu/evaluator"
"github.com/vit0rr/mumu/lexer"
"github.com/vit0rr/mumu/object"
"github.com/vit0rr/mumu/parser"
"github.com/vit0rr/mumu/repl"
"github.com/vit0rr/mumu/vm"
)
func main() {
var (
useCompiler = flag.Bool("compiler", false, "Flag without argument to use compiler to run Monkey code.")
filePath = flag.String("file", "", "Flag to run Monkey code from file.")
help = flag.Bool("help", false, "List available commands and their descriptions.")
)
flag.Parse()
user, err := user.Current()
if err != nil {
panic(err)
}
if *help {
fmt.Printf("Hello %s! This is the Monkey programming language!\n", user.Username)
flag.PrintDefaults()
return
}
if *useCompiler && *filePath == "" {
fmt.Printf("Hello %s! This is the Monkey programming language!\n", user.Username)
fmt.Println("Compiler mode with REPL")
repl.Start(os.Stdin, os.Stdout, *useCompiler)
return
} else if *useCompiler && *filePath != "" {
if err := runFile(*filePath, *useCompiler); err != nil {
fmt.Fprintf(os.Stderr, "Error reading file: %v\n", err)
return
}
} else if !*useCompiler && *filePath == "" {
fmt.Printf("Hello %s! This is the Monkey programming language!\n", user.Username)
fmt.Println("Interpreter mode with REPL")
repl.Start(os.Stdin, os.Stdout, *useCompiler)
} else {
if err := runFile(*filePath, *useCompiler); err != nil {
fmt.Fprintf(os.Stderr, "Error reading file: %v\n", err)
return
}
}
}
func runFile(filePath string, useCompiler bool) error {
env := object.NewEnvironment()
content, err := os.ReadFile(filePath)
if err != nil {
return err
}
line := string(content)
l := lexer.New(line)
p := parser.New(l)
program := p.ParseProgram()
if len(p.Errors()) != 0 {
repl.PrintParserErrors(os.Stdout, p.Errors())
return fmt.Errorf("parse errors in file")
}
if useCompiler {
comp := compiler.New()
err := comp.Compile(program)
if err != nil {
return fmt.Errorf("woops! Compilation failed: %s", err)
}
machine := vm.New(comp.Bytecode())
err = machine.Run()
if err != nil {
return fmt.Errorf("woops! Executing bytecode failed:\n %s", err)
}
lastPopped := machine.LastPoppedStackElem()
io.WriteString(os.Stdout, lastPopped.Inspect())
io.WriteString(os.Stdout, "\n")
return nil
}
evaluated := evaluator.Eval(program, env)
if evaluated != nil {
io.WriteString(os.Stdout, evaluated.Inspect())
io.WriteString(os.Stdout, "\n")
}
return nil
}