-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparser.jl
481 lines (389 loc) · 11.7 KB
/
parser.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
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
471
472
473
474
475
476
477
478
479
480
481
include("./expressions.jl")
include("./token.jl")
include("./errors.jl")
include("./debug.jl")
function parseTokens(tokens)::Vector{Stmt}
current = 1
# helper functions
# TODO: variable type?
# function match(tokens::Vararg{TokenType,N})
function match(types...)
for t in types
if check(t)
advance()
return true
end
end
return false
end
function check(tt::TokenType)
if isAtEnd()
return false
end
return peek().type == tt
end
function advance()
if !isAtEnd()
current += 1
end
return previous()
end
function isAtEnd()::Bool
return peek().type == EOF
end
function peek()::Token
# return tokens[current - 1]
return tokens[current] # TODO
end
function previous()::Token
# return tokens[current - 2]
return tokens[current - 1]
end
####################
## the grammar
####################
function expression()::LoxExpr
return assignment()
end
function assignment()::LoxExpr
expr = or()
if match(EQUAL)
equals = previous()
value = assignment() # recursive; this makes assignment right-associative
if isa(expr, Variable)
name = expr.name
return Assign(name, value)
elseif isa(expr, GetExpr)
object = expr.object
name = expr.name
return SetExpr(object, name, value)
else
error(equals, "Invalid assignment target.")
end
end
return expr
end
function or()::LoxExpr
expr = and()
while match(OR)
op = previous()
right = and()
expr = Logical(expr, op, right)
end
return expr
end
function and()::LoxExpr
expr = equality()
while match(AND)
op = previous()
right = equality()
expr = Logical(expr, op, right)
end
return expr
end
function equality()::LoxExpr
expr = comparison()
while (match(BANG_EQUAL, EQUAL_EQUAL))
op = previous()
right = comparison()
expr = Binary(expr, op, right)
end
return expr
end
function comparison()::LoxExpr
expr = term()
while (match(GREATER, GREATER_EQUAL, LESS, LESS_EQUAL))
op = previous()
right = term()
expr = Binary(expr, op, right)
end
return expr
end
function term()::LoxExpr
expr = factor()
while (match(MINUS, PLUS))
op = previous()
right = factor()
expr = Binary(expr, op, right)
end
return expr
end
function factor()::LoxExpr
expr = unary()
while match(SLASH, STAR)
op = previous()
right = unary()
expr = Binary(expr, op, right)
end
return expr
end
function unary()::LoxExpr
if match(MINUS, BANG)
op = previous()
right = unary()
return Unary(op, right)
end
return call()
end
function call()::LoxExpr
expr = primary()
while true
if match(LEFT_PAREN)
expr = finishCall(expr)
elseif match(DOT)
name = consume(IDENTIFIER, "Expect property name after '.'.")
expr = GetExpr(expr, name)
else
break
end
end
return expr
end
function finishCall(expr)::LoxExpr
args = []
if !check(RIGHT_PAREN)
while true
if length(args) > 255
error(peek(), "Cannot have more than 255 arguments.")
end
push!(args, expression())
if !match(COMMA)
break
end
end
end
paren = consume(RIGHT_PAREN, "Expect ')' after arguments.")
return Call(expr, paren, args)
end
function primary()::LoxExpr
# literal
if match(FALSE)
return Literal(false)
elseif match(TRUE)
return Literal(true)
elseif match(NIL)
return Literal(nothing)
elseif match(NUMBER, STRING)
return Literal(previous().literal)
elseif match(THIS)
return ThisExpr(previous())
# variable
elseif match(IDENTIFIER)
return Variable(previous())
# grouping
elseif match(LEFT_PAREN)
expr = expression()
consume(RIGHT_PAREN, "Expect ')' after expression.")
return Grouping(expr)
# superclass
elseif match(SUPER)
keyword = previous()
consume(DOT, "Expect '.' after 'super'.")
method = consume(IDENTIFIER, "Expect superclass method name.")
return SuperExpr(keyword, method)
end
error(peek(), "Expect expression.")
throw("ParseError")
end
function consume(type::TokenType, message::String)
if check(type)
return advance()
end
error(peek(), message)
throw("ParseError")
end
function error(token::Token, message::String)
if token.type == EOF
report(token.line, "at end", message)
else
report(token.line, " at $(token.lexeme)", message)
end
end
function synchronize()
advance()
while !isAtEnd()
if previous().type == SEMICOLON
return
end
if in(peek().type, [CLASS, FUN, VAR, FOR, IF, WHILE, PRINT, RETURN])
return
end
advance()
end
end
# statements
function statement()
if match(IF)
return ifStatement()
elseif match(FOR)
return forStatement()
elseif match(PRINT)
return printStatement()
elseif match(RETURN)
return returnStatement()
elseif match(WHILE)
return whileStatement()
elseif match(LEFT_BRACE)
bs = blockStatement()
return bs
end
return expressionStatement()
end
function declaration()
try
if match(FUN)
return functionDeclaration("function")
end
if match(CLASS)
return classDeclaration()
end
if match(VAR)
return varDeclaration()
end
return statement()
catch e
# TODO: for debugging
q("Exception in declaration:", e)
throw(e)
# ---
synchronize()
return nothing
end
end
function blockStatement()
# Lol I had a bug where I used `statements` here and had a variable
# shadowing/scope issue .. while implementing scope/shadowing for 8.5!
bsStatements = []
while !check(RIGHT_BRACE) && !isAtEnd()
push!(bsStatements, declaration())
end
consume(RIGHT_BRACE, "Expect '}' after block")
BlockStmt(bsStatements)
end
function ifStatement()
consume(LEFT_PAREN, "Expect '(' after 'if'.")
condition = expression()
consume(RIGHT_PAREN, "Expect ')' after if condition.")
thenBranch = statement()
elseBranch = nothing
if match(ELSE)
elseBranch = statement()
end
return IfStmt(condition, thenBranch, elseBranch)
end
function whileStatement()
consume(LEFT_PAREN, "Expect '(' after 'while'.")
condition = expression()
consume(RIGHT_PAREN, "Expect ')' after while condition.")
body = statement()
return WhileStmt(condition, body)
end
function forStatement()
consume(LEFT_PAREN, "Expect '(' after 'for'.")
initializer = nothing
if match(SEMICOLON)
initializer = nothing
elseif match(VAR)
initializer = varDeclaration()
else
initializer = expressionStatement()
end
condition = nothing
if !check(SEMICOLON)
condition = expression()
end
consume(SEMICOLON, "Expect ';' after loop condition.")
increment = nothing
if !check(RIGHT_PAREN)
increment = expression()
end
consume(RIGHT_PAREN, "Expect ')' after for clauses.")
body = statement()
# desugar, converting the "for" syntax into a "while"
if increment !== nothing
# add an increment after whatever is inside the for's body
body = BlockStmt([body, ExpressionStmt(increment)])
end
if condition === nothing
# if no condition, then the condition is always true
condition = Literal(true)
end
body = WhileStmt(condition, body)
if initializer !== nothing
# run the initializer once, then run our WhileStmt
body = BlockStmt([initializer, body])
end
return body
end
function printStatement()
value = expression()
consume(SEMICOLON, "Expect ';' after value.")
return PrintStmt(value)
end
function returnStatement()
keyword = previous()
value = nothing
if !check(SEMICOLON)
value = expression()
end
consume(SEMICOLON, "Expect ';' after return value.")
return ReturnStmt(keyword, value)
end
function expressionStatement()
expr = expression()
consume(SEMICOLON, "Expect ';' after expression.")
return ExpressionStmt(expr)
end
function functionDeclaration(kind::String)
# parse function's name
name = consume(IDENTIFIER, "Expect $kind name.")
# parse function's arguments
consume(LEFT_PAREN, "Expect '(' after $kind name.")
params = []
if !check(RIGHT_PAREN)
while true
if length(params) > 255
error(peek(), "Cannot have more than 255 $kind parameters.")
end
push!(params, consume(IDENTIFIER, "Expect $kind parameter name."))
if !match(COMMA)
break
end
end
end
consume(RIGHT_PAREN, "Expect ')' after $kind parameters.")
# parse function's body
consume(LEFT_BRACE, "Expect '{' before $kind body.")
body = blockStatement()
return FnStmt(name, params, body.statements)
end
function classDeclaration()
name = consume(IDENTIFIER, "Expect class name.")
# optionally, a superclass
superclass = nothing
if match(LESS)
consume(IDENTIFIER, "Expect superclass name.")
superclass = Variable(previous())
end
consume(LEFT_BRACE, "Expect '{' before class body.")
methods = []
while !check(RIGHT_BRACE) && !isAtEnd()
push!(methods, functionDeclaration("method"))
end
consume(RIGHT_BRACE, "Expect '}' after class body.")
return ClassStmt(name, superclass, methods)
end
function varDeclaration()
name = consume(IDENTIFIER, "Expect variable name.")
initializer = match(EQUAL) ? expression() : nothing
consume(SEMICOLON, "Expect ';' after variable declaration")
return VarStmt(name, initializer)
end
# core logic
statements = []
while !isAtEnd()
d = declaration()
push!(statements, d)
end
return statements
end