-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathglox.go
116 lines (92 loc) · 1.95 KB
/
glox.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
109
110
111
112
113
114
115
116
package glox
import (
"bufio"
"bytes"
"fmt"
"os"
)
var interpreter *Interpreter
type Runtime struct {
hadError bool
hadRuntimeError bool
}
func NewRuntime() *Runtime {
r := &Runtime{
hadError: false,
}
interpreter = NewInterpreter(r)
return r
}
func (r *Runtime) Run(args []string) {
if len(args) > 1 {
fmt.Println("Usage: glox [script]")
os.Exit(64)
} else if len(args) == 1 {
r.RunFile(args[0])
} else {
r.RunPrompt()
}
}
func (r *Runtime) RunFile(path string) {
data, err := os.ReadFile(path)
if err != nil {
fmt.Printf("error reading file: %s\n", err.Error())
return
}
r.run(string(data))
if r.hadError {
os.Exit(65)
}
if r.hadRuntimeError {
os.Exit(70)
}
}
func (r *Runtime) RunPrompt() {
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print(">>> ")
// Scans a line from the standard input
scanner.Scan()
line := scanner.Text()
if line == "" {
break
}
r.run(line)
r.hadError = false
}
}
func (r *Runtime) Error(line int, message string) {
r.report(line, "", message)
}
func (r *Runtime) run(source string) {
scanner := NewScanner(bytes.NewBuffer([]byte(source)), r)
tokens := scanner.ScanTokens()
parser := NewParser(tokens, r)
statements := parser.Parse()
if r.hadError {
return
}
resolver := NewResolver(interpreter, r)
resolver.resolveStatements(statements)
if r.hadError {
return
}
interpreter.Interpret(statements)
}
func (r *Runtime) report(line int, where string, message string) {
errMessage := fmt.Sprintf("[line %d] Error%s: %s", line, where, message)
r.hadError = true
fmt.Println(errMessage)
}
func (r *Runtime) runtimeError(err error) {
runErr := err.(*RuntimeError)
fmt.Printf("%s \n[line %d ]\n", runErr.Error(), runErr.token.Line)
r.hadRuntimeError = true
}
func (r *Runtime) tokenError(token Token, message string) {
if token.Type == Eof {
r.report(token.Line, " at end ", message)
} else {
r.report(token.Line, " at '"+token.Lexeme+"'", message)
}
}