-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
74 lines (63 loc) · 1.42 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
package main
import (
"fmt"
"io"
"monkey/compiler"
"monkey/lexer"
"monkey/parser"
"monkey/repl"
"monkey/vm"
"os"
"os/user"
)
func main() {
user, err := user.Current()
if err != nil {
panic(err)
}
if len(os.Args) == 2 {
runScript(os.Args[1])
} else {
fmt.Printf(
"Hello %s! This is the Monkey programming language!\n",
user.Username)
fmt.Print("Feel free to type in commands\n")
repl.Start(os.Stdin, os.Stdout)
}
}
func runScript(file string) {
contents, err := os.ReadFile(file)
if err != nil {
panic(err)
}
lexer := lexer.New(string(contents))
parser := parser.New(lexer)
program := parser.ParseProgram()
if len(parser.Errors()) != 0 {
printErrors(os.Stderr, "Parser", parser.Errors())
return
}
comp := compiler.New()
err = comp.Compile(program)
if err != nil {
printError(os.Stderr, "Compiler", err)
return
}
machine := vm.New(comp.ByteCode())
err = machine.Run()
if err != nil {
printError(os.Stderr, "VM", err)
return
}
io.WriteString(os.Stdout, machine.LastPoppedStackElement().Inspect())
io.WriteString(os.Stdout, "\n")
}
func printErrors(out io.Writer, module string, errors []string) {
io.WriteString(out, fmt.Sprintf("🙈 %s errors occured:\n", module))
for _, msg := range errors {
io.WriteString(out, "\t"+msg+"\n")
}
}
func printError(out io.Writer, module string, err error) {
io.WriteString(out, fmt.Sprintf("🙈 %s error occured: %s\n", module, err))
}