-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
486 lines (384 loc) · 9.52 KB
/
parser.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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
package main
import "fmt"
// Parser implements ExprVisitor, StmtVisitor
// Uses recursive descent parsing
type Parser struct {
tokens []Token
current int
}
func NewParser(tokens []Token) *Parser {
return &Parser{tokens, 0}
}
func (p *Parser) Parse() []Stmt {
statements := []Stmt{}
for !p.isAtEnd() {
statements = append(statements, p.declaration())
}
return statements
}
func (p *Parser) declaration() Stmt {
defer func() {
if err := recover(); err != nil {
if pErr, ok := err.(ParseError); ok {
fmt.Println(pErr)
p.synchronize()
} else {
panic(err)
}
}
}()
switch true {
case p.match(CLASS):
return p.classDeclaration()
case p.match(FUN):
return p.function("function")
case p.match(VAR):
return p.varDeclaration()
}
return p.statement()
}
func (p *Parser) classDeclaration() Stmt {
name := p.consume(IDENTIFIER, "expect class name")
var superclass Variable
if p.match(LESS) {
p.consume(IDENTIFIER, "expect superclass name")
superclass = Variable{p.previous()}
}
p.consume(LEFT_BRACE, "expect '{' before class body")
methods := []Function{}
for !p.check(RIGHT_BRACE) && !p.isAtEnd() {
methods = append(methods, *p.function("method").(*Function))
}
p.consume(RIGHT_BRACE, "expect '}' after class body")
return &Class{name, superclass, methods}
}
// @param kind: "function", "method"
func (p *Parser) function(kind string) Stmt {
name := p.consume(IDENTIFIER, "expect "+kind+" name")
p.consume(LEFT_PAREN, "expect '(' after "+kind+" name")
var parameters []Token
if !p.check(RIGHT_PAREN) {
for {
if len(parameters) >= 255 {
fmt.Println(NewParseError(p.peek(), "can't have more than 255 parameters"))
}
parameters = append(parameters, p.consume(IDENTIFIER, "expect parameter name"))
if !p.match(COMMA) {
break
}
}
}
p.consume(RIGHT_PAREN, "expect ')' after parameters")
p.consume(LEFT_BRACE, "expect '{' before "+kind+" body")
body := p.block()
return &Function{name, parameters, body}
}
func (p *Parser) varDeclaration() Stmt {
name := p.consume(IDENTIFIER, "expect variable name")
var initializer Expr
if p.match(EQUAL) {
initializer = p.expression()
}
p.consume(SEMICOLON, "expect ';' after variable declaration")
return &Var{name, initializer}
}
func (p *Parser) statement() Stmt {
switch {
case p.match(PRINT):
return p.printStatement()
case p.match(RETURN):
return p.returnStatement()
case p.match(BREAK):
return p.breakStatement()
case p.match(IF):
return p.ifStatement()
case p.match(FOR):
return p.forStatement()
case p.match(WHILE):
return p.whileStatement()
case p.match(LEFT_BRACE):
return &Block{p.block()}
}
return p.expressionStatement()
}
func (p *Parser) block() []Stmt {
statements := make([]Stmt, 0)
for !p.check(RIGHT_BRACE) && !p.isAtEnd() {
statements = append(statements, p.declaration())
}
p.consume(RIGHT_BRACE, "expect '}' after block")
return statements
}
func (p *Parser) printStatement() Stmt {
value := p.expression()
p.consume(SEMICOLON, "expect ';' after value")
return &Print{value}
}
func (p *Parser) returnStatement() Stmt {
keyword := p.previous()
var value Expr
if !p.check(SEMICOLON) {
value = p.expression()
}
p.consume(SEMICOLON, "expect ';' after return value")
return &Return{keyword, value}
}
func (p *Parser) breakStatement() Stmt {
keyword := p.previous()
p.consume(SEMICOLON, "expect ';' after break statement")
return &Break{keyword}
}
func (p *Parser) ifStatement() Stmt {
p.consume(LEFT_PAREN, "expect '(' after 'if'")
condition := p.expression()
p.consume(RIGHT_PAREN, "expect ')' after condition")
thenBranch := p.statement()
elseBranch := (Stmt)(nil)
if p.match(ELSE) {
elseBranch = p.statement()
}
return &If{condition, thenBranch, elseBranch}
}
func (p *Parser) forStatement() Stmt {
p.consume(LEFT_PAREN, "expect '(' after 'for'")
initializer := (Stmt)(nil)
if p.match(SEMICOLON) {
initializer = nil
} else if p.match(VAR) {
initializer = p.varDeclaration()
} else {
initializer = p.expressionStatement()
}
condition := (Expr)(nil)
if !p.check(SEMICOLON) {
condition = p.expression()
}
p.consume(SEMICOLON, "expect ';' after loop condition")
increment := (Expr)(nil)
if !p.check(RIGHT_PAREN) {
increment = p.expression()
}
p.consume(RIGHT_PAREN, "expect ')' after for clauses")
body := p.statement()
if increment != nil {
body = &Block{[]Stmt{body, &Expression{increment}}}
}
if condition == nil {
condition = &Literal{true}
}
body = &While{condition, body}
if initializer != nil {
body = &Block{[]Stmt{initializer, body}}
}
return body
}
func (p *Parser) whileStatement() Stmt {
p.consume(LEFT_PAREN, "expect '(' after 'while'")
condition := p.expression()
p.consume(RIGHT_PAREN, "expect ')' after condition")
body := p.statement()
return &While{condition, body}
}
func (p *Parser) expressionStatement() Stmt {
expr := p.expression()
p.consume(SEMICOLON, "expect ';' after expression")
return &Expression{expr}
}
func (p *Parser) expression() Expr {
return p.assignment()
}
func (p *Parser) assignment() Expr {
expr := p.or()
if p.match(EQUAL) {
equals := p.previous()
value := p.assignment()
if e, ok := (expr).(*Variable); ok {
name := e.name
return &Assign{name, value}
} else if e, ok := (expr).(*Get); ok {
return &Set{e.object, e.name, value}
}
fmt.Println(NewParseError(equals, "invalid assignment target"))
}
return expr
}
func (p *Parser) or() Expr {
expr := p.and()
for p.match(OR) {
operator := p.previous()
right := p.and()
expr = &Logical{expr, operator, right}
}
return expr
}
func (p *Parser) and() Expr {
expr := p.equality()
for p.match(AND) {
operator := p.previous()
right := p.equality()
expr = &Logical{expr, operator, right}
}
return expr
}
func (p *Parser) equality() Expr {
expr := p.comparision()
for p.match(BANG_EQUAL, EQUAL_EQUAL) {
operator := p.previous()
right := p.comparision()
expr = &Binary{expr, operator, right}
}
return expr
}
func (p *Parser) comparision() Expr {
expr := p.term()
for p.match(GREATER, GREATER_EQUAL, LESS, LESS_EQUAL) {
operator := p.previous()
right := p.term()
expr = &Binary{expr, operator, right}
}
return expr
}
func (p *Parser) term() Expr {
expr := p.factor()
for p.match(MINUS, PLUS) {
operator := p.previous()
right := p.factor()
expr = &Binary{expr, operator, right}
}
return expr
}
func (p *Parser) factor() Expr {
expr := p.unary()
for p.match(SLASH, STAR) {
operator := p.previous()
right := p.unary()
expr = &Binary{expr, operator, right}
}
return expr
}
func (p *Parser) unary() Expr {
if p.match(BANG, MINUS) {
operator := p.previous()
right := p.unary()
return &Unary{operator, right}
}
return p.call()
}
func (p *Parser) call() Expr {
expr := p.primary()
for {
if p.match(LEFT_PAREN) {
expr = p.finishCall(expr)
} else if p.match(DOT) {
name := p.consume(IDENTIFIER, "expect property name after '.'")
expr = &Get{expr, name}
} else {
break
}
}
return expr
}
func (p *Parser) primary() Expr {
switch {
case p.match(FALSE):
return &Literal{false}
case p.match(TRUE):
return &Literal{true}
case p.match(NIL):
return &Literal{nil}
case p.match(NUMBER, STRING):
return &Literal{p.previous().literal}
case p.match(IDENTIFIER):
return &Variable{p.previous()}
case p.match(THIS):
return &This{p.previous()}
case p.match(SUPER):
keyword := p.previous()
p.consume(DOT, "expect '.' after 'super'")
method := p.consume(IDENTIFIER, "expect superclass method name")
return &Super{keyword, method}
case p.match(LEFT_PAREN):
expr := p.expression()
p.consume(RIGHT_PAREN, "expect ')' after expression.")
return &Grouping{expr}
}
panic(NewParseError(p.peek(), "expect expression"))
}
// match checks if current token matches any given type
func (p *Parser) match(types ...TokenType) bool {
for _, t := range types {
if p.check(t) {
p.advance()
return true
}
}
return false
}
// check returns true for token of given type
func (p *Parser) check(typ TokenType) bool {
if p.isAtEnd() {
return false
}
return p.peek().typ == typ
}
// advance consumes and returns current token
func (p *Parser) advance() Token {
if !p.isAtEnd() {
p.current++
}
return p.previous()
}
// isAtEnd returns true if no tokens are left
func (p *Parser) isAtEnd() bool {
return p.peek().typ == EOF
}
// peek returns current token yet to consume
func (p *Parser) peek() Token {
return p.tokens[p.current]
}
// previous returns last consumed token
func (p *Parser) previous() Token {
return p.tokens[p.current-1]
}
// consume looks for given token, panics if not found
func (p *Parser) consume(t TokenType, msg string) Token {
if p.check(t) {
return p.advance()
}
panic(NewParseError(p.peek(), msg))
}
// synchronize discards token unless at a statement boundary
// restores state on parsing errors
func (p *Parser) synchronize() {
p.advance()
for !p.isAtEnd() {
if p.previous().typ == SEMICOLON {
return
}
switch p.peek().typ {
case CLASS, FUN, VAR, FOR, IF, WHILE, PRINT:
// discard tokens
case RETURN:
return
}
p.advance()
}
}
// finishCall returns a Call AST node with 0 or more arguments
func (p *Parser) finishCall(callee Expr) Expr {
arguments := []Expr{}
if !p.check(RIGHT_PAREN) {
for {
if len(arguments) >= 255 {
fmt.Println(NewParseError(p.peek(), "can't have more than 255 arguments"))
}
arguments = append(arguments, p.expression())
if !p.match(COMMA) {
break
}
}
}
// location context in errors
paren := p.consume(RIGHT_PAREN, "expect ')' after arguments")
return &Call{callee, paren, arguments}
}