-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
102 lines (92 loc) · 1.8 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
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
var (
disableDebugScanner = true
disableDebugResolveLocals = true
)
var hasErr bool
func run(source string) error {
scanner := newScanner(source)
tokens, err := scanner.scanTokens()
if err != nil {
return err
}
if !disableDebugScanner {
fmt.Println(strings.ToUpper("[debug scanner]"))
for _, token := range tokens {
fmt.Println(token)
}
}
parser := newParser(tokens)
stmts, err := parser.parse()
if err != nil {
return err
}
fmt.Println(strings.ToUpper("[debug execute stmts]"))
intp := newInterpreter()
resolver := newResolver(intp)
if err := resolver.resolveStmts(stmts); err != nil {
return err
}
if !disableDebugResolveLocals {
fmt.Printf("interpreter locals: %+v\n", intp.locals)
}
intp.interpret(stmts)
return nil
}
func printError(line int, msg string) {
fmt.Printf("line: %d, err: %s\n", line, msg)
hasErr = true
}
func runFile(fileName string) error {
bytes, err := os.ReadFile(fileName)
if err != nil {
return err
}
if err := run(string(bytes)); err != nil {
return err
}
if hasErr {
os.Exit(1)
}
return nil
}
func runPrompt() error {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Printf("golox > ")
line, err := reader.ReadString('\n')
if err != nil {
return err
}
fmt.Print("Input: ", line)
if err := run(line); err != nil {
hasErr = true
fmt.Printf("Error: %+v\n", err)
} else {
hasErr = false
}
}
}
func main() {
fmt.Println(strings.ToUpper("welcome to go lox!"))
args := os.Args
lenArgs := len(args)
// fmt.Println("args:", lenArgs)
if lenArgs > 2 {
os.Exit(1)
} else if lenArgs == 2 {
if err := runFile(args[1]); err != nil {
fmt.Println("Run File Error: ", err)
}
} else {
if err := runPrompt(); err != nil {
fmt.Println("Error: ", err)
}
}
}