-
Notifications
You must be signed in to change notification settings - Fork 0
/
interpreter.go
470 lines (407 loc) · 10.1 KB
/
interpreter.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
package lox
import (
"fmt"
"io"
"os"
"strings"
)
type Callable interface {
Arity() int
Call(i *Interpreter, args []any) any
}
// ----
type returnSignal struct {
value any
}
type function struct {
name string
params []Token
body []Stmt
closure *Environment
isInit bool
}
func (f function) bind(obj object) function {
env := f.closure.Child(staticEnvironment)
env.Define("this", obj)
return function{f.name, f.params, f.body, env, f.isInit}
}
func (f function) getThis() instance {
// In a method, the only variable stored in the environment is 'this'.
return f.closure.GetStatic(0, 0).(instance)
}
func (f function) Arity() int {
return len(f.params)
}
func (f function) Call(i *Interpreter, args []any) (result any) {
env := f.closure.Child(staticEnvironment)
for i, param := range f.params {
env.Define(param.Lexeme, args[i])
}
defer func() {
if r := recover(); r != nil {
if res, ok := r.(returnSignal); ok {
result = res.value
} else {
panic(r)
}
}
if f.isInit {
result = f.getThis()
}
}()
i.executeBlock(f.body, env)
return nil
}
func (f function) String() string {
return fmt.Sprintf("<fn %s>", f.name)
}
// ----
type loopState int
const (
sequentialLoop loopState = iota
breakLoop
continueLoop
)
type loopSignal struct {
state loopState
}
// ----
type localPosition struct {
distance int
index int
}
type Interpreter struct {
globals *Environment
env *Environment
value any
stdout io.Writer
locals map[Expr]localPosition
}
func NewInterpreter() *Interpreter {
env := builtin.Child(dynamicEnvironment)
return &Interpreter{
globals: env,
env: env,
stdout: os.Stdout,
locals: make(map[Expr]localPosition),
}
}
func (i *Interpreter) SetStdout(w io.Writer) {
i.stdout = w
}
func (i *Interpreter) Interpret(stmts []Stmt) (err error) {
defer func() {
if err_ := recover(); err_ != nil {
if runtimeErr, ok := err_.(runtimeError); ok {
err = runtimeErr
} else {
panic(err_)
}
}
}()
for _, stmt := range stmts {
i.execute(stmt)
}
return nil
}
func (i *Interpreter) Debug() string {
var b strings.Builder
b.WriteString("locals:\n")
for expr, pos := range i.locals {
dist, idx := pos.distance, pos.index
fmt.Fprintf(&b, " '%[1]p %[1]v': {dist: %[2]d, idx: %[3]d}\n", expr, dist, idx)
}
b.WriteString("environment:\n")
b.WriteString(i.env.Debug())
return b.String()
}
// ----
func (i *Interpreter) resolve(expr Expr, depth int, index int) {
i.locals[expr] = localPosition{depth, index}
}
func (i *Interpreter) lookupVariable(name Token, expr Expr) any {
pos, ok := i.locals[expr]
if ok {
return i.env.GetStatic(pos.distance, pos.index)
}
return i.globals.Get(name)
}
func (i *Interpreter) execute(stmt Stmt) {
stmt.Accept(i)
}
func (i *Interpreter) executeBlock(stmts []Stmt, env *Environment) {
defer func(prev *Environment) { i.env = prev }(i.env)
i.env = env
for _, stmt := range stmts {
i.execute(stmt)
}
}
// ----
func (i *Interpreter) VisitExpressionStmt(stmt ExpressionStmt) {
i.evaluate(stmt.Expression)
}
func (i *Interpreter) VisitPrintStmt(stmt PrintStmt) {
v := i.evaluate(stmt.Expression)
if v == nil {
v = "nil"
}
fmt.Fprintln(i.stdout, v)
}
func (i *Interpreter) VisitVarStmt(stmt VarStmt) {
var value any
if stmt.Init != nil {
value = i.evaluate(stmt.Init)
}
i.env.Define(stmt.Name.Lexeme, value)
}
func (i *Interpreter) VisitIfStmt(stmt IfStmt) {
cond := i.evaluate(stmt.Condition)
if isTruthy(cond) {
i.execute(stmt.Then)
} else if stmt.Else != nil {
i.execute(stmt.Else)
}
}
func (i *Interpreter) VisitBlockStmt(stmt BlockStmt) {
i.executeBlock(stmt.Statements, i.env.Child(staticEnvironment))
}
func (i *Interpreter) VisitLoopStmt(stmt LoopStmt) {
for isTruthy(i.evaluate(stmt.Condition)) {
state := i.runLoopBody(stmt.Body)
if state == breakLoop {
break
}
if stmt.OnLoop != nil {
i.evaluate(stmt.OnLoop)
}
}
}
func (i *Interpreter) runLoopBody(stmt Stmt) (s loopState) {
defer func() {
if r := recover(); r != nil {
if signal, ok := r.(loopSignal); ok {
s = signal.state
} else {
panic(r)
}
}
}()
i.execute(stmt)
return sequentialLoop
}
func (i *Interpreter) VisitBreakStmt(stmt BreakStmt) {
panic(loopSignal{breakLoop})
}
func (i *Interpreter) VisitContinueStmt(stmt ContinueStmt) {
panic(loopSignal{continueLoop})
}
func (i *Interpreter) VisitFunctionStmt(stmt FunctionStmt) {
name := stmt.Name.Lexeme
isInit := false
f := function{name, stmt.Params, stmt.Body, i.env, isInit}
i.env.Define(name, f)
}
func (i *Interpreter) VisitReturnStmt(stmt ReturnStmt) {
var value any
if stmt.Result != nil {
value = i.evaluate(stmt.Result)
}
panic(returnSignal{value})
}
func (i *Interpreter) VisitClassStmt(stmt ClassStmt) {
className := stmt.Name.Lexeme
cl := newClass(newMetaClass(className))
for _, method := range stmt.StaticMethods {
methodName := method.Name.Lexeme
isInit := false
cl.meta.methods[methodName] = function{methodName, method.Params, method.Body, i.env, isInit}
}
for _, decl := range stmt.StaticVars {
var value any = nil
if decl.Init != nil {
value = i.evaluate(decl.Init)
}
cl.static.set(decl.Name, value)
}
for _, decl := range stmt.Vars {
fieldInit := fieldInitializer{name: decl.Name}
if decl.Init != nil {
fieldInit.value = i.evaluate(decl.Init)
}
cl.fieldInits = append(cl.fieldInits, fieldInit)
}
classEnv := i.env.Child(staticEnvironment)
for _, method := range stmt.Methods {
methodName := method.Name.Lexeme
isInit := (methodName == "init")
cl.instanceBehavior.methods[methodName] = function{methodName, method.Params, method.Body, classEnv, isInit}
}
i.env.Define(className, cl)
}
// ----
func (i *Interpreter) evaluate(expr Expr) any {
expr.Accept(i)
return i.value
}
func (i *Interpreter) VisitBinaryExpr(expr *BinaryExpr) {
left := i.evaluate(expr.Left)
right := i.evaluate(expr.Right)
i.value = operate2(expr.Operator, left, right)
}
func (i *Interpreter) VisitGroupingExpr(expr *GroupingExpr) {
i.evaluate(expr.Expression)
}
func (i *Interpreter) VisitLiteralExpr(expr *LiteralExpr) {
i.value = expr.Value
}
func (i *Interpreter) VisitUnaryExpr(expr *UnaryExpr) {
right := i.evaluate(expr.Right)
i.value = operate1(expr.Operator, right)
}
func (i *Interpreter) VisitVariableExpr(expr *VariableExpr) {
i.value = i.lookupVariable(expr.Name, expr)
}
func (i *Interpreter) VisitAssignmentExpr(expr *AssignmentExpr) {
value := i.evaluate(expr.Value)
pos, ok := i.locals[expr]
if ok {
i.env.SetStatic(pos.distance, pos.index, value)
} else {
i.globals.Set(expr.Name, value)
}
}
func (i *Interpreter) VisitLogicExpr(expr *LogicExpr) {
left := i.evaluate(expr.Left)
if expr.Operator.TokenType == Or && isTruthy(left) {
return
}
if expr.Operator.TokenType == And && !isTruthy(left) {
return
}
i.evaluate(expr.Right)
}
func (i *Interpreter) VisitCallExpr(expr *CallExpr) {
callee := i.evaluate(expr.Callee)
args := make([]any, len(expr.Args))
for index, arg := range expr.Args {
args[index] = i.evaluate(arg)
}
f, ok := callee.(Callable)
if !ok {
panic(runtimeError{expr.Paren, fmt.Sprintf("value %v (%T) is not callable", callee, callee)})
}
if f.Arity() != len(args) {
panic(runtimeError{expr.Paren, fmt.Sprintf("expecting %d arguments but got %d", f.Arity(), len(args))})
}
i.value = f.Call(i, args)
}
func (i *Interpreter) VisitFunctionExpr(expr *FunctionExpr) {
isInit := false
i.value = function{"anonymous", expr.Params, expr.Body, i.env, isInit}
}
func (i *Interpreter) VisitGetExpr(expr *GetExpr) {
obj := i.evaluate(expr.Object)
is, ok := obj.(object)
if !ok {
panic(runtimeError{expr.Name, fmt.Sprintf("want an object for property access, got %[1]T (%[1]v)", obj)})
}
i.value = is.get(expr.Name)
}
func (i *Interpreter) VisitSetExpr(expr *SetExpr) {
obj := i.evaluate(expr.Object)
is, ok := obj.(object)
if !ok {
panic(runtimeError{expr.Name, fmt.Sprintf("want an object for field access, got %[1]T (%[1]v)", obj)})
}
value := i.evaluate(expr.Value)
is.set(expr.Name, value)
i.value = value
}
func (i *Interpreter) VisitThisExpr(expr *ThisExpr) {
i.value = i.lookupVariable(expr.Keyword, expr)
}
// ----
func operate2(token Token, left, right any) any {
switch token.TokenType {
case BangEqual:
return left != right
case EqualEqual:
return left == right
case Greater:
a, b := checkNumberOperands(token, left, right)
return a > b
case GreaterEqual:
a, b := checkNumberOperands(token, left, right)
return a >= b
case Less:
a, b := checkNumberOperands(token, left, right)
return a < b
case LessEqual:
a, b := checkNumberOperands(token, left, right)
return a <= b
case Minus:
a, b := checkNumberOperands(token, left, right)
return a - b
case Plus:
aNum, ok1 := left.(float64)
bNum, ok2 := right.(float64)
if ok1 && ok2 {
return aNum + bNum
}
aStr, ok3 := left.(string)
bStr, ok4 := right.(string)
if ok3 && ok4 {
return aStr + bStr
}
panic(runtimeError{token, "operands must be two numbers or two strings"})
case Slash:
a, b := checkNumberOperands(token, left, right)
return a / b
case Star:
a, b := checkNumberOperands(token, left, right)
return a * b
}
panic(fmt.Errorf("compiler error: unimplemented binary operator %s", token.TokenType))
}
func operate1(token Token, right any) any {
switch token.TokenType {
case Bang:
return !isTruthy(right)
case Minus:
num := checkNumberOperand(token, right)
return -num
}
panic(fmt.Errorf("compiler error: unimplemented unary operator %s", token.TokenType))
}
func isTruthy(v any) bool {
if v == nil {
return false
}
if b, ok := v.(bool); ok {
return b
}
return true
}
// -----
type runtimeError struct {
token Token
msg string
}
func (err runtimeError) Error() string {
return fmt.Sprintf("token '%s' in line %d: %s", err.token.Lexeme, err.token.Line, err.msg)
}
func checkNumberOperand(token Token, right any) float64 {
b, ok := right.(float64)
if ok {
return b
}
panic(runtimeError{token, "operand must be number"})
}
func checkNumberOperands(token Token, left, right any) (float64, float64) {
a, ok1 := left.(float64)
b, ok2 := right.(float64)
if ok1 && ok2 {
return a, b
}
panic(runtimeError{token, "operands must be numbers"})
}