-
Notifications
You must be signed in to change notification settings - Fork 2
/
runtime.go
93 lines (77 loc) · 2.04 KB
/
runtime.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
package tlps
import (
"bytes"
"fmt"
"os"
)
// Runtime is struct of Runtime
type Runtime struct {
HadError bool
HadRuntimeError bool
Globals *Environment
Environment *Environment
Locals map[Expr]int
Scopes *ScopeStack
BasePath string
}
// NewRuntime is constructor of Runtime
func NewRuntime() *Runtime {
globals := NewEnvironment(nil)
environment := globals
return &Runtime{
HadError: false,
HadRuntimeError: false,
Globals: globals,
Environment: environment,
Locals: make(map[Expr]int),
Scopes: NewScopeStack(),
BasePath: "",
}
}
// Run runs script
func (r *Runtime) Run(source *bytes.Buffer) {
scanner := NewScanner(r, source)
tokens := scanner.ScanTokens()
// for _, token := range tokens {
// fmt.Println(token)
// }
parser := NewParser(r, tokens)
statements, _ := parser.Parse()
// parser.Parse()
// Stop if there was a syntax error
if r.HadError {
return
}
// fmt.Println(NewAstPrinter().Print(statements))
interpreter := NewInterpreter(r)
resolver := NewResolver(r, interpreter)
resolver.ResolveStmts(statements)
// Stop if there was a resolution error
if r.HadError {
return
}
interpreter.Interpret(statements)
}
// ErrorMessage prints error massage at stderr
func (r *Runtime) ErrorMessage(line int, message string) {
r.report(line, "", message)
}
// ErrorTokenMessage prints error message at stderr
func (r *Runtime) ErrorTokenMessage(token *Token, message string) {
if token.Type == EOFTT {
r.report(token.Line, " at end", message)
} else {
r.report(token.Line, " at '"+token.Lexeme+"'", message)
}
}
// Report prints error masseg at stderr
func (r *Runtime) report(line int, where string, message string) {
fmt.Fprintln(os.Stderr, "[line "+fmt.Sprint(line)+"] Error"+where+": "+message)
r.HadError = true
}
// RuntimeError is error of runtime
func (r *Runtime) RuntimeError(err error) {
e := err.(*CustomError)
fmt.Fprint(os.Stderr, err.Error()+"\n[line "+fmt.Sprint(e.Token.Line)+"]")
r.HadRuntimeError = true
}