-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
89 lines (79 loc) · 1.89 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
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"github.com/mbassale/glox/glox"
)
const EXIT_BAD_ARGS = 64
const EXIT_ERROR = 65
const EXIT_RUNTIME_ERROR = 70
var hadError bool = false
var hadRuntimeError bool = false
func runFile(path string) {
contents, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
var errorReporter glox.ErrorReporter = glox.NewConsoleErrorReporter()
var interpreter glox.Interpreter = glox.NewInterpreter(errorReporter)
run(string(contents), &interpreter, errorReporter)
if hadError {
os.Exit(EXIT_ERROR)
}
if hadRuntimeError {
os.Exit(EXIT_RUNTIME_ERROR)
}
}
func runPrompt() {
scanner := bufio.NewScanner(os.Stdin)
var errorReporter glox.ErrorReporter = glox.NewConsoleErrorReporter()
var interpreter glox.Interpreter = glox.NewInterpreter(errorReporter)
for {
fmt.Print("> ")
if !scanner.Scan() {
break
}
line := scanner.Text()
run(line, &interpreter, errorReporter)
errorReporter.ClearError()
}
}
func run(source string, interpreter *glox.Interpreter, errorReporter glox.ErrorReporter) {
scanner := glox.NewScanner(source, errorReporter)
if (errorReporter).HasError() {
hadError = true
return
}
tokens := scanner.ScanTokens()
for _, token := range tokens {
fmt.Printf("Token: %v\n", token)
}
parser := glox.NewParser(tokens, errorReporter)
statements := parser.Parse()
if errorReporter.HasError() {
hadError = true
return
}
astPrinter := glox.AstPrinter{}
fmt.Println(astPrinter.Print(statements))
resolver := glox.NewResolver(interpreter)
resolver.ResolveStatements(statements)
lastValue, _ := interpreter.Interpret(statements)
fmt.Printf("=%v\n", lastValue)
if errorReporter.HasError() {
hadRuntimeError = true
return
}
}
func main() {
if len(os.Args) > 2 {
fmt.Println("Usage: glox [script]")
os.Exit(EXIT_BAD_ARGS)
} else if len(os.Args) == 2 {
runFile(os.Args[1])
} else {
runPrompt()
}
}