/
parser.nim
417 lines (307 loc) · 10.6 KB
/
parser.nim
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
{.this: self.}
import token
import tokenType
import expr
import literalType
import stmt
from error import nil
type
Parser* = object
tokens*: seq[Token]
current*: int
ParseError* = ref object of Exception
proc newParser*(tokens: seq[Token]): Parser =
return Parser(tokens: tokens, current: 0)
# Forward Declaration
proc andExpr(self: var Parser): Expr
proc orExpr(self: var Parser): Expr
proc assignment(self: var Parser): Expr
proc expression(self: var Parser): Expr
proc equality(self: var Parser): Expr
proc match(self: var Parser, types: varargs[TokenType]): bool
proc check(self: var Parser, tokentype: TokenType): bool
proc advance(self: var Parser): Token
proc peek(self: var Parser): Token
proc isAtEnd(self: var Parser): bool
proc previous(self: var Parser): Token
proc comparison(self: var Parser): Expr
proc addition(self: var Parser): Expr
proc multiplication(self: var Parser): Expr
proc call(self: var Parser): Expr
proc unary(self: var Parser): Expr
proc primary(self: var Parser): Expr
proc consume(self: var Parser, tktype: TokenType, message: string): Token
proc error(self: var Parser, token: Token, message: string): ParseError
proc synchronize(self: var Parser)
proc parseBlock(self: var Parser): seq[Stmt]
proc ifStatement(self: var Parser): Stmt
proc whileStatement(self: var Parser): Stmt
proc forStatement(self: var Parser): Stmt
proc statement(self: var Parser): Stmt
proc printStatement(self: var Parser): Stmt
proc expressionStatement(self: var Parser): Stmt
proc declaration(self: var Parser): Stmt
proc varDeclaration(self: var Parser): Stmt
proc parse*(self: var Parser): seq[Stmt]
# Proc
proc andExpr(self: var Parser): Expr =
var expr = equality()
while match(AND):
var operator = previous()
var right = equality()
expr = newLogical(expr, operator, right)
return expr
proc orExpr(self: var Parser): Expr =
var expr = andExpr()
while match(OR):
var operator = previous()
var right = andExpr()
expr = newLogical(expr, operator, right)
return expr
proc assignment(self: var Parser): Expr =
var expr = orExpr()
if match(EQUAL):
var equals = previous()
var value = assignment()
if expr of Variable:
var name = Variable(expr).name
return newAssign(name, value)
elif expr of GetExpr:
var get = GetExpr(expr)
return newSetExpr(get.obj, get.name, value)
error.error(equals, "Invalid assignment target.")
return expr
proc expression(self: var Parser): Expr =
return assignment()
proc equality(self: var Parser): Expr =
var expr = comparison()
while match(BANG_EQUAL, EQUAL_EQUAL):
var operator = previous()
var right = comparison()
expr = newBinary(expr, operator, right)
return expr
proc match(self: var Parser, types: varargs[TokenType]): bool =
for ty in types:
if check(ty):
discard advance()
return true
return false
proc check(self: var Parser, tokentype: TokenType): bool =
if isAtEnd(): return false
return peek().tkType == tokenType
proc advance(self: var Parser): Token =
if not isAtEnd(): current += 1
return previous()
proc isAtEnd(self: var Parser): bool =
return peek().tkType == EOF
proc peek(self: var Parser): Token =
return tokens[current]
proc previous(self: var Parser): Token =
return tokens[current - 1]
proc comparison(self: var Parser): Expr =
var expr = addition()
while match(GREATER, GREATER_EQUAL, LESS, LESS_EQUAL):
var operator = previous()
var right = addition()
expr = newBinary(expr, operator, right)
return expr
proc addition(self: var Parser): Expr =
var expr = multiplication()
while match(MINUS, PLUS):
var operator = previous()
var right = multiplication()
expr = newBinary(expr, operator, right)
return expr
proc multiplication(self: var Parser): Expr =
var expr = unary()
while match(SLASH, STAR):
var operator = previous()
var right = unary()
expr = newBinary(expr, operator, right)
return expr
proc unary(self: var Parser): Expr =
if match(BANG, MINUS):
var operator = previous()
var right = unary()
return newUnary(operator, right)
return call()
proc finishCall(self: var Parser, callee: Expr): Expr =
var arguments: seq[Expr]
if not check(RIGHT_PAREN):
arguments.add(expression())
while match(COMMA):
if arguments.len >= 8:
error.error(peek(), "Cannot have more than 8 arguments.")
arguments.add(expression())
var paren = consume(RIGHT_PAREN, "Expect ')' after arguments.")
return newCall(callee, paren, arguments)
proc call(self: var Parser): Expr =
var expr = primary()
while true:
if match(LEFT_PAREN):
expr = finishCall(expr)
elif match(DOT):
var name = consume(IDENTIFIER, "Expect property name after '.'.")
expr = newGetExpr(expr, name)
else:
break
return expr
proc primary(self: var Parser): Expr =
if match(FALSE): return newLiteral(newBoolLit(false))
if match(TRUE): return newLiteral(newBoolLit(true))
if match(NIL): return newLiteral(newNilLit())
if match(NUMBER, STRING):
return newLiteral(previous().literal)
if match(SUPER):
var keyword = previous()
discard consume(DOT, "Expect '.' after 'super'.")
var m = consume(IDENTIFIER, "Expect superclass method name.")
return newSuperExpr(keyword, m)
if match(THIS):
return newThisExpr(previous())
if match(IDENTIFIER):
return newVariable(previous())
if match(LEFT_PAREN):
var expr = expression()
discard consume(RIGHT_PAREN, "Expect ')' after expression")
return newGrouping(expr)
raise error(peek(), "Expect expression.")
proc consume(self: var Parser, tktype: TokenType, message: string): Token =
if check(tktype): return advance()
raise error(peek(), message)
proc error(self: var Parser, token: Token, message: string): ParseError =
error.error(token, message)
return ParseError()
proc synchronize(self: var Parser) =
discard advance()
while not isAtEnd():
if previous().tkType == SEMICOLON: return
case peek().tkType
of CLASS, FUN, VAR, FOR, IF, WHILE, PRINT, RETURN: return
else: discard
discard advance()
proc parseBlock(self: var Parser): seq[Stmt] =
var statements: seq[Stmt]
while not check(RIGHT_BRACE) and not isAtEnd():
statements.add(declaration())
discard consume(RIGHT_BRACE, "Expect '}' after block.")
return statements
proc ifStatement(self: var Parser): Stmt =
discard consume(LEFT_PAREN, "Expect '(' after 'if'.")
var condition = expression()
discard consume(RIGHT_PAREN, "Expect ')' after if condition.")
var thenBranch = statement()
var elseBranch: Stmt = nil
if match(ELSE):
elseBranch = statement()
return newIfStmt(condition, thenBranch, elseBranch)
proc whileStatement(self: var Parser): Stmt =
discard consume(LEFT_PAREN, "Expect '(' after 'while'.")
var condition = expression()
discard consume(RIGHT_PAREN, "Expect ')' after condition.")
var body = statement()
return newWhileStmt(condition, body)
proc forStatement(self: var Parser): Stmt =
discard consume(LEFT_PAREN, "Expect '(' after 'for'.")
var initializer: Stmt
if match(SEMICOLON):
initializer = nil
elif match(VAR):
initializer = varDeclaration()
else:
initializer = expressionStatement()
var condition: Expr = nil
if not check(SEMICOLON):
condition = expression()
discard consume(SEMICOLON, "Expect ';' after loop condition.")
var increment: Expr = nil
if not check(RIGHT_PAREN):
increment = expression()
discard consume(RIGHT_PAREN, "Expect ')' after for clauses.")
var body = statement()
if increment != nil:
body = newBlockStmt(@[body, newExprStmt(increment)])
if condition == nil:
condition = newLiteral(newBoolLit(true))
body = newWhileStmt(condition, body)
if initializer != nil:
body = newBlockStmt(@[initializer, body])
return body
proc returnStatement(self: var Parser): Stmt =
var keyword = previous()
var value: Expr
if not check(SEMICOLON):
value = expression()
discard consume(SEMICOLON, "Expect ';' after return value.")
return newReturnStmt(keyword, value)
proc statement(self: var Parser): Stmt =
if match(FOR):
return forStatement()
if match(IF):
return ifStatement()
if match(PRINT):
return printStatement()
if match(RETURN):
return returnStatement()
if match(WHILE):
return whileStatement()
if match(LEFT_BRACE):
return newBlockStmt(parseBlock())
return expressionStatement()
proc printStatement(self: var Parser): Stmt =
var value = expression()
discard consume(SEMICOLON, "Expect ';' after value.")
return newPrintStmt(value)
proc expressionStatement(self: var Parser): Stmt =
var expr = expression()
discard consume(SEMICOLON, "Expect ';' after expression.")
return newExprStmt(expr)
proc function(self: var Parser, kind: string): FuncStmt =
var name = consume(IDENTIFIER, "Expect " & kind & " name.")
discard consume(LEFT_PAREN, "Expect '(' after " & kind & " name.")
var parameters: seq[Token]
if not check(RIGHT_PAREN):
parameters.add(consume(IDENTIFIER, "Expect parameter name."))
while match(COMMA):
if parameters.len >= 8:
error.error(peek(), "Cannot have more than 8 parameters.")
parameters.add(consume(IDENTIFIER, "Expect parameter name."))
discard consume(RIGHT_PAREN, "Expect ')' after parameters.")
discard consume(LEFT_BRACE, "Expect '{' before " & kind & " body.")
var body = parseBlock()
return newFuncStmt(name, parameters, body)
proc classDeclaration(self: var Parser): Stmt =
var name = consume(IDENTIFIER, "Expect class name.")
var superclass: Variable = nil
if match(LESS):
discard consume(IDENTIFIER, "Expect superclass name.")
superclass = newVariable(previous())
discard consume(LEFT_BRACE, "Expect '{' before class body.")
var methods: seq[FuncStmt]
while not check(RIGHT_BRACE) and not isAtEnd():
methods.add(function("method"))
discard consume(RIGHT_BRACE, "Expect '}' after class body.")
return newClassStmt(name, superclass, methods)
proc declaration(self: var Parser): Stmt =
try:
if match(CLASS): return classDeclaration()
if match(FUN): return function("function")
if match(VAR): return varDeclaration()
return statement()
except ParseError:
synchronize()
return nil
proc varDeclaration(self: var Parser): Stmt =
var name = consume(IDENTIFIER, "Expect variable name")
var initializer: Expr
if match(EQUAL):
initializer = expression()
else:
initializer = nil
discard consume(SEMICOLON, "Expect ';' after variable declaration.")
return newVarStmt(name, initializer)
proc parse*(self: var Parser): seq[Stmt] =
var statements: seq[Stmt]
while not isAtEnd():
statements.add(declaration())
return statements