-
Notifications
You must be signed in to change notification settings - Fork 2
/
parser.go
789 lines (683 loc) · 14.9 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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
package tlps
// Parser is struct of parser
type Parser struct {
runtime *Runtime
tokens TokenList
current int
}
// NewParser is constructor of Parser
func NewParser(runtime *Runtime, tokens TokenList) *Parser {
return &Parser{
runtime: runtime,
tokens: tokens,
current: 0,
}
}
// Parse parses given tokens
func (p *Parser) Parse() ([]Stmt, error) {
statements := make([]Stmt, 0)
for !p.isAtEnd() {
stmt, err := p.declaration()
if err != nil {
return nil, err
}
statements = append(statements, stmt)
}
return statements, nil
}
func (p *Parser) expression() (Expr, error) {
return p.assignment()
}
func (p *Parser) declaration() (Stmt, error) {
if p.match(ClassTT) {
return p.classDeclaration()
}
if p.match(FunTT) {
return p.function("function")
}
if p.match(IncludeTT) {
return p.include()
}
if p.match(VarTT) {
stmt, err := p.varDecralation()
if err != nil {
p.synchronize()
return nil, err
}
return stmt, nil
}
stmt, err := p.statement()
if err != nil {
p.synchronize()
}
return stmt, nil
}
func (p *Parser) classDeclaration() (Stmt, error) {
name, err := p.consume(IdentifierTT, "Expect class name.")
if err != nil {
return nil, err
}
var superclass *Variable
if p.match(LeftParenTT) {
p.consume(IdentifierTT, "Expect superclass name.")
superclass = NewVariable(p.previous()).(*Variable)
p.consume(RightParenTT, "Expect ')' after superclass name.")
}
_, err = p.consume(ColonTT, "Expect ':' after class name.")
if err != nil {
return nil, err
}
_, err = p.consume(NewlineTT, "Expect '\\n' after ':'.")
if err != nil {
return nil, err
}
_, err = p.consume(LeftBraceTT, "Expect '{' before class body.")
if err != nil {
return nil, err
}
methods := make([]*Function, 0)
for !p.check(RightBraceTT) && !p.isAtEnd() {
// if p.match(PassTT) {
// p.consume(NewlineTT, "Expect '\\n' after pass")
// continue
// }
fun, err := p.function("method")
if err != nil {
return nil, err
}
methods = append(methods, fun.(*Function))
}
_, err = p.consume(RightBraceTT, "Expect '}' after class body")
return NewClass(name, superclass, methods), nil
}
func (p *Parser) statement() (Stmt, error) {
if p.match(ForTT) {
return p.forStatement()
}
if p.match(IfTT) {
return p.ifStatement()
}
if p.match(ReturnTT) {
return p.returnStatement()
}
if p.match(WhileTT) {
return p.whileStatement()
}
if p.match(LeftBraceTT) {
return p.blockStatement(NoneBlock)
}
return p.expressionStatement()
}
func (p *Parser) blockStatement(typ BlockType) (Stmt, error) {
keyword := p.previous() // => '{'
b, err := p.block()
if err != nil {
return nil, err
}
return NewBlock(b, keyword, typ), nil
}
func (p *Parser) forStatement() (Stmt, error) {
var initializer Stmt
var err error
if p.match(SemicolonTT) {
initializer = nil
} else if p.match(VarTT) {
initializer, err = p.varDecralation()
if err != nil {
return nil, err
}
} else {
initializer, err = p.expressionStatement()
if err != nil {
return nil, err
}
}
var condition Expr
if !p.check(SemicolonTT) {
condition, err = p.expression()
if err != nil {
return nil, err
}
}
_, err = p.consume(SemicolonTT, "Expect ';' after loop condition")
if err != nil {
return nil, err
}
var increment Expr
if !p.check(ColonTT) {
increment, err = p.expression()
if err != nil {
return nil, err
}
}
_, err = p.consume(ColonTT, "Expect ':' after for clauses.")
if err != nil {
return nil, err
}
_, err = p.consume(NewlineTT, "Expect '\\n' after for clauses.")
if err != nil {
return nil, err
}
keyword, err := p.consume(LeftBraceTT, "Expect '{' for `for` loop body")
if err != nil {
return nil, err
}
body, err := p.blockStatement(ForBlock)
if err != nil {
return nil, err
}
if increment != nil {
body = NewBlock([]Stmt{body, NewExpression(increment)}, keyword, ForBlock)
}
if condition == nil {
condition = NewLiteral(true)
}
body = NewWhile(condition, body)
if initializer != nil {
body = NewBlock([]Stmt{initializer, body}, keyword, ForBlock)
}
return body, nil
}
func (p *Parser) ifStatement() (Stmt, error) {
condition, err := p.expression()
if err != nil {
return nil, err
}
_, err = p.consume(ColonTT, "Expect ':' after if condition.")
if err != nil {
return nil, err
}
_, err = p.consume(NewlineTT, "Expect '\\n' after if condition")
if err != nil {
return nil, err
}
_, err = p.consume(LeftBraceTT, "Expect '{' for if then block")
thenBranch, err := p.blockStatement(IfBlock)
if err != nil {
return nil, err
}
var elseBranch Stmt = nil
if p.match(ElseifTT) {
elseBranch, err = p.ifStatement()
if err != nil {
return nil, err
}
return NewIf(condition, thenBranch, elseBranch), nil
}
if p.match(ElseTT) {
_, err := p.consume(ColonTT, "Expect ':' after else.")
if err != nil {
return nil, err
}
_, err = p.consume(NewlineTT, "Expect '\\n' after else")
if err != nil {
return nil, err
}
_, err = p.consume(LeftBraceTT, "Expect '{' for if else block")
if err != nil {
return nil, err
}
elseBranch, err = p.blockStatement(IfBlock)
if err != nil {
return nil, err
}
}
return NewIf(condition, thenBranch, elseBranch), nil
}
func (p *Parser) returnStatement() (Stmt, error) {
keyword := p.previous()
var value Expr = nil
var err error
if !p.check(SemicolonTT) {
value, err = p.expression()
if err != nil {
return nil, err
}
}
_, err = p.consumeTerm()
if err != nil {
return nil, err
}
return NewReturn(keyword, value), nil
}
func (p *Parser) whileStatement() (Stmt, error) {
condition, err := p.expression()
if err != nil {
return nil, err
}
_, err = p.consume(ColonTT, "Expect ':' after condition")
if err != nil {
return nil, err
}
_, err = p.consume(NewlineTT, "Expect '\\n' after condition")
if err != nil {
return nil, err
}
_, err = p.consume(LeftBraceTT, "Expect '{' for while body")
if err != nil {
return nil, err
}
body, err := p.blockStatement(WhileBlock)
if err != nil {
return nil, err
}
return NewWhile(condition, body), nil
}
func (p *Parser) varDecralation() (Stmt, error) {
name, err := p.consume(IdentifierTT, "Expect variable name.")
if err != nil {
return nil, err
}
var initializer Expr
if p.match(EqualTT) {
initializer, err = p.expression()
if err != nil {
return nil, err
}
}
_, err = p.consumeTerm()
if err != nil {
return nil, err
}
return NewVar(name, initializer), nil
}
func (p *Parser) expressionStatement() (Stmt, error) {
expr, err := p.expression()
if err != nil {
return nil, err
}
// _, err = p.consume(Semicolon, "Expect ';' after expression")
_, err = p.consumeTerm()
if err != nil {
return nil, err
}
return NewExpression(expr), nil
}
func (p *Parser) function(kind string) (Stmt, error) {
if p.match(PassTT) {
// dummy function
_, err := p.consumeTerm()
if err != nil {
return nil, err
}
return NewFunction(
p.previous(),
[]*Token{},
[]Stmt{
NewExpression(NewLiteral("pass")),
},
), nil
}
name, err := p.consume(IdentifierTT, "Expect "+kind+" name.")
if err != nil {
return nil, err
}
_, err = p.consume(LeftParenTT, "Expect '(' after "+kind+" name.")
if err != nil {
return nil, err
}
parameters := make([]*Token, 0)
if !p.check(RightParenTT) {
for {
if len(parameters) >= 255 {
return nil, p.NewParseError(p.peek(), "Can't have more than 255 parameters.")
}
token, err := p.consume(IdentifierTT, "Expect parameter name.")
if err != nil {
return nil, err
}
parameters = append(parameters, token)
if !p.match(CommaTT) {
break
}
}
}
_, err = p.consume(RightParenTT, "Expect ')' after parameters.")
if err != nil {
return nil, err
}
_, err = p.consume(ColonTT, "Expect ':' after '('")
if err != nil {
return nil, err
}
_, err = p.consume(NewlineTT, "Expect '\\n' before "+kind+" body.")
if err != nil {
return nil, err
}
_, err = p.consume(LeftBraceTT, "Expected an indented block as "+kind+" body.")
if err != nil {
return nil, err
}
body, err := p.block()
if err != nil {
return nil, err
}
return NewFunction(name, parameters, body), nil
}
func (p *Parser) include() (Stmt, error) {
s, err := p.consume(StringTT, "Expect string after include")
if err != nil {
return nil, err
}
_, err = p.consumeTerm()
if err != nil {
return nil, err
}
return NewInclude(s), nil
}
func (p *Parser) block() ([]Stmt, error) {
statements := make([]Stmt, 0)
for !p.check(RightBraceTT) && !p.isAtEnd() {
stmt, err := p.declaration()
if err != nil {
return nil, err
}
statements = append(statements, stmt)
}
p.consume(RightBraceTT, "Expect '}' after block.")
return statements, nil
}
func (p *Parser) assignment() (Expr, error) {
expr, err := p.or()
if err != nil {
return nil, err
}
if p.match(EqualTT) {
equals := p.previous()
value, err := p.assignment()
if err != nil {
return nil, err
}
if expr.IsType(&Variable{}) {
name := expr.(*Variable).Name
return NewAssign(name, value), nil
} else if expr.IsType(&Get{}) {
get := expr.(*Get)
return NewSet(get.Object, get.Name, value), nil
}
p.runtime.ErrorTokenMessage(equals, "Invalid assignment target.")
}
return expr, nil
}
func (p *Parser) or() (Expr, error) {
expr, err := p.and()
if err != nil {
return nil, err
}
for p.match(OrTT) {
operator := p.previous()
right, err := p.and()
if err != nil {
return nil, err
}
expr = NewLogical(expr, operator, right)
}
return expr, nil
}
func (p *Parser) and() (Expr, error) {
expr, err := p.equality()
if err != nil {
return nil, err
}
for p.match(AndTT) {
operator := p.previous()
right, err := p.equality()
if err != nil {
return nil, err
}
expr = NewLogical(expr, operator, right)
}
return expr, nil
}
func (p *Parser) equality() (Expr, error) {
expr, err := p.comparison()
if err != nil {
return nil, err
}
for p.match(BangEqualTT, EqualEqualTT) {
operator := p.previous()
right, err := p.comparison()
if err != nil {
return nil, err
}
expr = NewBinary(expr, operator, right)
}
return expr, nil
}
func (p *Parser) comparison() (Expr, error) {
expr, err := p.term()
if err != nil {
return nil, err
}
for p.match(GreaterTT, GreaterEqualTT, LessTT, LessEqualTT) {
operator := p.previous()
right, err := p.term()
if err != nil {
return nil, err
}
expr = NewBinary(expr, operator, right)
}
return expr, nil
}
func (p *Parser) term() (Expr, error) {
expr, err := p.factor()
if err != nil {
return nil, err
}
for p.match(MinusTT, PlusTT) {
operator := p.previous()
right, err := p.factor()
if err != nil {
return nil, err
}
expr = NewBinary(expr, operator, right)
}
return expr, nil
}
func (p *Parser) factor() (Expr, error) {
expr, err := p.unary()
if err != nil {
return nil, err
}
for p.match(SlashTT, StarTT) {
operator := p.previous()
right, err := p.unary()
if err != nil {
return nil, err
}
expr = NewBinary(expr, operator, right)
}
return expr, nil
}
func (p *Parser) unary() (Expr, error) {
if p.match(BangTT, MinusTT) {
operator := p.previous()
right, err := p.unary()
if err != nil {
return nil, err
}
return NewUnary(operator, right), nil
}
return p.call()
}
func (p *Parser) call() (Expr, error) {
expr, err := p.primary()
if err != nil {
return nil, err
}
for {
if p.match(LeftParenTT) {
expr, err = p.finishCall(expr)
if err != nil {
return nil, err
}
} else if p.match(DotTT) {
name, err := p.consume(IdentifierTT, "Expect property name after '.'.")
if err != nil {
return nil, err
}
expr = NewGet(expr, name)
} else {
break
}
}
return expr, nil
}
func (p *Parser) finishCall(callee Expr) (Expr, error) {
arguments := make([]Expr, 0)
if !p.check(RightParenTT) {
for {
expr, err := p.expression()
if err != nil {
return nil, err
}
if len(arguments) >= 255 {
return nil, p.NewParseError(p.peek(), "Can't have more than 255 arguments.")
}
arguments = append(arguments, expr)
if !p.match(CommaTT) {
break
}
}
}
paren, err := p.consume(RightParenTT, "Expect ')' after arguments.")
if err != nil {
return nil, err
}
return NewCall(callee, paren, arguments), nil
}
func (p *Parser) primary() (Expr, error) {
if p.match(FalseTT) {
return NewLiteral(false), nil
}
if p.match(TrueTT) {
return NewLiteral(true), nil
}
if p.match(NilTT) {
return NewLiteral(nil), nil
}
if p.match(PassTT) {
return NewLiteral("pass"), nil
}
if p.match(NumberTT, StringTT) {
return NewLiteral(p.previous().Literal), nil
}
if p.match(SuperTT) {
keyword := p.previous()
_, err := p.consume(DotTT, "Expect '.' after 'super'.")
if err != nil {
return nil, err
}
method, err := p.consume(IdentifierTT, "Expect supercrlass method name.")
if err != nil {
return nil, err
}
return NewSuper(keyword, method), nil
}
if p.match(ThisTT) {
return NewThis(p.previous()), nil
}
if p.match(IdentifierTT) {
return NewVariable(p.previous()), nil
}
if p.match(LeftParenTT) {
expr, err := p.expression()
if err != nil {
return nil, err
}
_, err = p.consume(RightParenTT, "Expect ')' after expression.")
if err != nil {
return nil, err
}
return NewGrouping(expr), nil
}
if p.match(NewlineTT) {
return NewLiteral('\n'), nil
}
return nil, p.NewParseError(p.peek(), "Expect expression.")
}
func (p *Parser) match(types ...TokenType) bool {
for _, typ := range types {
if p.check(typ) {
p.advance()
return true
}
}
return false
}
func (p *Parser) consume(typ TokenType, message string) (*Token, error) {
if p.check(typ) {
return p.advance(), nil
}
return nil, p.NewParseError(p.peek(), message)
}
func (p *Parser) consumeTerm() (*Token, error) {
if p.check(NewlineTT) {
return p.advance(), nil
}
if p.check(SemicolonTT) {
t := p.advance()
if p.check(NewlineTT) {
p.advance()
}
return t, nil
}
return nil, p.NewParseError(p.peek(), "Expect ';' or '\\n' after expression")
}
func (p *Parser) check(typ TokenType) bool {
if p.isAtEnd() {
return false
}
return p.peek().Type == typ
}
func (p *Parser) advance() *Token {
if !p.isAtEnd() {
p.current++
}
return p.previous()
}
func (p *Parser) isAtEnd() bool {
return p.peek().Type == EOFTT
}
func (p *Parser) peek() *Token {
return p.tokens[p.current]
}
func (p *Parser) previous() *Token {
return p.tokens[p.current-1]
}
func (p *Parser) synchronize() {
p.advance()
for !p.isAtEnd() {
switch p.previous().Type {
case SemicolonTT:
return
case NewlineTT:
return
}
// if p.previous().Type == Semicolon {
// return
// }
switch p.peek().Type {
case ClassTT:
return
case FunTT:
return
case VarTT:
return
case ForTT:
return
case IfTT:
return
case WhileTT:
return
case ReturnTT:
return
}
p.advance()
}
}
// NewParseError is constructor of ParseError
func (p *Parser) NewParseError(token *Token, message string) error {
p.runtime.ErrorTokenMessage(token, message)
return ParseError.New(token, message)
}