-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinterpreter.jl
419 lines (351 loc) · 11.1 KB
/
interpreter.jl
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
include("./statements.jl")
include("./environment.jl")
include("./token.jl")
include("./types.jl")
function interpret(statements::Vector{Stmt}, locals::Dict)
globals = Environment()
environment = globals
#################
## expressions ##
#################
function evaluate(expr::LoxExpr)
q("Evaluate: $expr")
visit(expr)
end
function visit(literal::Literal)
q("Visit literal: $literal")
return literal.value
end
function visit(expr::GetExpr)
obj = evaluate(expr.object)
if isa(obj, LoxInstance)
return get(obj, expr.name)
end
throw(RuntimeError(expr.name, "Only instances have properties"))
end
function visit(expr::SetExpr)
obj = evaluate(expr.object)
if ! isa(obj, LoxInstance)
throw(RuntimeError(expr.name, "Only instances have fields"))
end
val = evaluate(expr.value)
obj.fields[expr.name.lexeme] = val
return val
end
function visit(group::Grouping)
return evaluate(group.expression)
end
function visit(unary::Unary)
right = evaluate(unary.right)
t = unary.operator.type
if t == MINUS
checkNumberOperand(unary.operator, right)
return -right
elseif t == BANG
return !isTruthy(right)
end
throw("unreachable")
end
function visit(expr::Call)
q("expr= $expr")
callee = evaluate(expr.callee)
q("callee = $callee")
args = []
for arg in expr.arguments
push!(args, evaluate(arg))
end
ctype = typeof(callee)
if ctype != LoxFunction && ctype != NativeFunction && ctype != LoxClass
q("ctype = $ctype")
throw(RuntimeError(expr.paren, "Can only call functions and classes."))
end
if length(args) != arity(callee)
throw(RuntimeError(expr.paren, "Expected $(callee.arity) arguments but got $(length(args))."))
end
return call(callee, args)
end
function visit(expr::Variable)
return lookupVariable(expr.name, expr)
end
function lookupVariable(name::Token, expr::LoxExpr)
distance = get(locals, pointer_from_objref(expr), nothing)
if distance !== nothing
# get from locals
return getat(environment, distance, name)
end
# get from globals
return get(globals, name)
end
function visit(expr::SuperExpr)
distance = get(locals, pointer_from_objref(expr), nothing)
superclass = getat(environment, distance, "super")
instance = getat(environment, distance - 1, "this")
method = findMethod(superclass, expr.method.lexeme)
if method === nothing
throw(RuntimeError(expr.method, "Undefined property '$(expr.method.lexeme)'."))
end
return bind(method, instance)
end
function visit(expr::Assign)
value = evaluate(expr.value)
distance = get(locals, pointer_from_objref(expr), nothing)
if distance !== nothing
assignAt(environment, distance, expr.name, value)
else
assignenv(globals, expr.name, value)
end
return value
end
function visit(expr::Logical)
left = evaluate(expr.left)
# check if we can short circuit
if expr.operator.type == OR
if isTruthy(left)
return left
end
else # it's an AND
if !isTruthy(left)
return left
end
end
return evaluate(expr.right)
end
function visit(binary::Binary)
left = evaluate(binary.left)
right = evaluate(binary.right)
t = binary.operator.type
if t == MINUS
return left - right
elseif t == SLASH
return left / right
elseif t == STAR
return left * right
elseif t == PLUS
if isa(left, Number) && isa(right, Number)
return left + right
elseif isa(left, String) && isa(right, String)
return "$left$right"
else
throw("Operands must be numbers")
end
elseif t == GREATER
checkNumberOperands(binary.operator, left, right)
return left > right
elseif t == GREATER_EQUAL
checkNumberOperands(binary.operator, left, right)
return left >= right
elseif t == LESS
checkNumberOperands(binary.operator, left, right)
return left < right
elseif t == LESS_EQUAL
checkNumberOperands(binary.operator, left, right)
return left <= right
elseif t == BANG_EQUAL
checkNumberOperands(binary.operator, left, right)
return !isEqual(left, right)
elseif t == EQUAL_EQUAL
checkNumberOperands(binary.operator, left, right)
return isEqual(left, right)
end
throw("unreachable")
end
function isTruthy(value::Bool)
return value
end
function isTruthy(value::Any)
return value !== nothing
end
function isEqual(a, b)
# TODO: is this sufficient? I think Julia equality may be same idea as in Lox
return a == b
end
function checkNumberOperand(operator::Token, operand::Any)
if isa(operand, Number)
return
end
throw(RuntimeError(operator, ""))
end
function checkNumberOperands(operator::Token, left::Any, right::Any)
if isa(left, Number) && isa(right, Number)
return
end
throw(RuntimeError(operator, ""))
end
function visit(expr::ThisExpr)
return lookupVariable(expr.keyword, expr)
end
################
## statements ##
################
function execute(stmt::Stmt)
visit(stmt)
end
function visit(stmt::ClassStmt)
superclass = nothing
if stmt.superclass !== nothing
superclass = evaluate(stmt.superclass)
if ! isa(superclass, LoxClass)
throw(RuntimeError(stmt.superclass.name, "Superclass must be a class."))
end
end
defineenv(environment, stmt.name, nothing)
if stmt.superclass !== nothing
environment = Environment(environment)
defineenv(environment, "super", superclass)
end
methods = Dict{String,LoxFunction}()
for m in stmt.methods
isInitializer = m.name.lexeme == "init"
fn = LoxFunction(m, environment, isInitializer)
methods[m.name.lexeme] = fn
end
klass = LoxClass(stmt.name.lexeme, superclass, methods)
if stmt.superclass !== nothing
environment = environment.Enclosing
end
assignenv(environment, stmt.name, klass)
end
function visit(stmt::ExpressionStmt)
evaluate(stmt.expression)
return nothing
end
function stringify(obj)
if obj === nothing
return "nil"
elseif isa(obj, Number)
if obj - floor(obj) == 0
return Integer(floor(obj))
end
elseif isa(obj, LoxClass)
return obj.name
elseif isa(obj, LoxInstance)
return "$(obj.klass.name) instance"
end
return obj
end
function visit(stmt::PrintStmt)
value = evaluate(stmt.expression)
println(stringify(value))
return nothing
end
function visit(stmt::VarStmt)
value = stmt.initializer !== nothing ? evaluate(stmt.initializer) : nothing
defineenv(environment, stmt.name, value)
return nothing
end
function visit(stmt::BlockStmt)
executeBlock(stmt.statements, Environment(environment))
return nothing
end
function visit(stmt::IfStmt)
if isTruthy(evaluate(stmt.condition))
execute(stmt.thenBranch)
elseif stmt.elseBranch !== nothing
execute(stmt.elseBranch)
end
return nothing
end
function visit(stmt::WhileStmt)
while isTruthy(evaluate(stmt.condition))
execute(stmt.body)
end
return nothing
end
function visit(stmt::FnStmt)
fn = LoxFunction(stmt, environment, false)
defineenv(environment, stmt.name.lexeme, fn)
return nothing
end
function visit(stmt::ReturnStmt)
value = nothing
if stmt.value !== nothing
value = evaluate(stmt.value)
end
# When we execute a return statement, we’ll use an exception to unwind
# the interpreter past the visit methods of all of the containing
# statements back to the code that began executing the body.
throw(Return(value))
end
# TODO: This was the core logic before -- could we call there too?
function executeBlock(statements::Vector{Stmt}, env::Environment)
previous = environment
try
environment = env
for s in statements
execute(s)
end
catch err
environment = previous
throw(err)
end
environment = previous
end
#################
## Callables
#################
function call(callable::LoxFunction, args::Vector{Any})
env = Environment(callable.closure)
for (idx, param) in enumerate(callable.declaration.params)
defineenv(env, param.lexeme, args[idx])
end
try
executeBlock(callable.declaration.body, env)
catch executeException
if isa(executeException, Return)
if (callable.isInitializer)
return getat(callable.closure, 0, "this")
end
return executeException.value
end
throw(executeException)
end
if callable.isInitializer
# `init()` always returns `this`
return getat(callable.closure, 0, "this")
end
return nothing
end
function arity(callable::LoxFunction)
return length(callable.declaration.params)
end
function call(callable::NativeFunction, args::Vector{Any})
return callable.callee(args)
end
function arity(callable::NativeFunction)
return callable.arity
end
function call(callable::LoxClass, args::Vector{Any})
instance = LoxInstance(callable, Dict{String,Any}())
initializer = findMethod(callable, "init")
if initializer !== nothing
boundMethod = bind(initializer, instance)
call(boundMethod, args)
end
return instance
end
function arity(callable::LoxClass)
initializer = findMethod(callable, "init")
if initializer !== nothing
return arity(initializer)
end
return 0
end
######################
# Core
######################
## Setup Global fns
defineenv(globals, "clock", NativeFunction(0, time))
## Main logic
try
for s in statements
execute(s)
end
catch e
if isa(e, RuntimeError)
println("$(e.details)\n[line $(e.token.line)]")
exit(70)
else
throw(e)
end
end
end