-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
executable file
·1275 lines (1127 loc) · 29 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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package openscad
import (
"fmt"
"strconv"
"github.com/lestrrat-go/openscad/ast"
)
type parser struct {
ch chan *Token
peeked []*Token
readPos int
}
// Parse parses an OpenSCAD source code, and turns it into an internal
// representation that can be used to output the same source code
// afterwrads, programmatically.
//
// Currently comments are out of scope of this implementation.
func Parse(src []byte) (ast.Stmts, error) {
ch := make(chan *Token, 1)
go Lex(ch, src)
p := &parser{
ch: ch,
readPos: -1,
}
stmts, err := p.handleStatements()
if err != nil {
return nil, fmt.Errorf(`failed to parse: %w`, err)
}
return stmts, nil
}
func (p *parser) handleStatement() (ast.Stmt, error) {
tok := p.Peek()
switch tok.Type {
case Percent:
p.Advance()
stmt, err := p.handleStatement()
if err != nil {
return nil, err
}
return ast.NewUnaryOp("%", stmt), nil
case Sharp:
p.Advance()
stmt, err := p.handleStatement()
if err != nil {
return nil, err
}
return ast.NewUnaryOp("#", stmt), nil
case Asterisk:
p.Advance()
stmt, err := p.handleStatement()
if err != nil {
return nil, err
}
return ast.NewUnaryOp("*", stmt), nil
default:
p.Unread()
}
tok = p.Peek()
switch tok.Type {
case Keyword:
switch tok.Value {
case "if":
p.Unread()
return p.handleIfStmt()
case "include":
p.Unread()
return p.handleInclude()
case "use":
p.Unread()
return p.handleUse()
case "let":
p.Unread()
return p.handleLetBlock()
case "module":
p.Unread()
return p.handleModule()
case "function":
p.Unread()
fn, err := p.handleFunction()
if err != nil {
return nil, err
}
tok = p.Next()
if tok.Type != Semicolon {
return nil, fmt.Errorf(`expected semicolon after function declaration for %q, got %q`, fn.Name(), tok.Value)
}
return fn, nil
case "for":
p.Unread()
return p.handleForBlock()
default:
return nil, fmt.Errorf(`unknown keyword %q`, tok.Value)
}
case Ident:
p.Unread()
stmt, semicolon, err := p.handleAssignmentOrFunctionCall(false)
if err != nil {
return nil, err
}
if semicolon {
tok = p.Next()
if tok.Type != Semicolon {
return nil, fmt.Errorf(`expected semicolon after assignment or function call, got %q`, tok.Value)
}
}
return stmt, nil
case OpenBrace:
p.Unread()
return p.handleBlock()
default:
p.Unread()
return nil, fmt.Errorf(`statement: unhandled token %q`, tok.Value)
}
}
func (p *parser) handleStatements() (ast.Stmts, error) {
var stmts ast.Stmts
for {
tok := p.Peek()
switch tok.Type {
case CloseBrace:
p.Unread()
return stmts, nil
case EOF:
return stmts, nil
default:
p.Unread()
stmt, err := p.handleStatement()
if err != nil {
return nil, err
}
stmts = append(stmts, stmt)
}
}
}
// Peek obtains the next token, but retains it in a buffer so that we can backtrack it.
// If we peek and then unread, we would be peeking the previously read, cached token
func (p *parser) Peek() *Token {
// Only read more if we're at the end of the buffer
if len(p.peeked)-1 == p.readPos {
tok := <-p.ch
if tok == nil {
return nil
}
p.peeked = append(p.peeked, tok)
}
p.readPos++
return p.peeked[p.readPos]
}
// Advance is akin to committing the previously peeked reads, effectively
// throwing away every buffered Token up to the current reading position
func (p *parser) Advance() {
if p.readPos > -1 {
p.peeked = p.peeked[p.readPos:]
if len(p.peeked) > 0 {
p.readPos = 0
} else {
p.readPos = -1
}
}
}
func (p *parser) Unread() {
if p.readPos >= 0 {
p.readPos--
}
}
func (p *parser) Next() *Token {
tok := p.Peek()
if tok != nil {
p.Advance()
return tok
}
panic("failed to peek")
}
func (p *parser) handleModule() (*ast.Module, error) {
// module moduleName ( [... args ...]? ) { ... body ... }
tok := p.Next()
if tok.Type != Keyword || tok.Value != `module` {
return nil, fmt.Errorf(`expected module`)
}
tok = p.Next()
moduleName := tok.Value
module := ast.NewModule(moduleName)
params, err := p.handleParameterList()
if err != nil {
return nil, fmt.Errorf(`failed to parse parameter list for module %q: %w`, moduleName, err)
}
stmts, err := p.handleBlock()
if err != nil {
return nil, fmt.Errorf(`failed to parse block for module %q: %w`, moduleName, err)
}
module.Parameters(params...)
module.Body(stmts...)
return module, nil
}
func (p *parser) handleParameterList() ([]*ast.Variable, error) {
tok := p.Next()
if tok.Type != OpenParen {
return nil, fmt.Errorf("expected open parenthesis")
}
var ret []*ast.Variable
OUTER:
for count := 1; ; count++ {
tok = p.Peek()
if tok.Type == CloseParen {
p.Advance()
break OUTER
}
p.Unread()
v, err := p.handleParamDecl()
if err != nil {
return nil, fmt.Errorf(`failed to parse parameter %d: %w`, count, err)
}
ret = append(ret, v)
// if we see a comma, then we expect more
tok = p.Peek()
if tok.Type == Comma {
continue
}
p.Unread()
}
return ret, nil
}
func (p *parser) handleParamDecl() (*ast.Variable, error) {
tok := p.Next()
if tok.Type != Ident {
return nil, fmt.Errorf(`expected ident for param decl, got %q`, tok.Value)
}
name := tok.Value
v := ast.NewVariable(name)
tok = p.Peek()
if tok.Type != Equal {
p.Unread()
} else {
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse expr for param decl: %w`, err)
}
v.Value(expr)
}
return v, nil
}
func (p *parser) handleBlock() (ast.Stmts, error) {
tok := p.Next()
if tok.Type != OpenBrace {
return nil, fmt.Errorf(`block: expected open brace, got %q`, tok.Value)
}
stmts, err := p.handleStatements()
if err != nil {
return nil, fmt.Errorf(`block: failed to parse block statements: %w`, err)
}
tok = p.Next()
if tok.Type != CloseBrace {
return nil, fmt.Errorf(`block: expected close brace, got %q`, tok.Value)
}
// optional semicolons allowed
tok = p.Peek()
if tok.Type == Semicolon {
p.Advance()
} else {
p.Unread()
}
return stmts, nil
}
func (p *parser) handleAssignment() (*ast.Variable, error) {
tok := p.Next()
if tok.Type != Ident {
return nil, fmt.Errorf(`expected identity of variable to assign to, got %q`, tok.Value)
}
varName := tok.Value
v := ast.NewVariable(varName)
tok = p.Next()
if tok.Type != Equal {
return nil, fmt.Errorf(`expected '=', got %q`, tok.Value)
}
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse expression: %w`, err)
}
v.Value(expr)
return v, nil
}
func (p *parser) handleCall() (*ast.Call, bool, error) {
tok := p.Next()
if tok.Type != Ident {
return nil, false, fmt.Errorf(`expected function name, got %q`, tok.Value)
}
callName := tok.Value
call := ast.NewCall(callName)
tok = p.Next()
if tok.Type != OpenParen {
return nil, false, fmt.Errorf(`expected open paren, got %q for function call on %q`, tok.Value, callName)
}
var parameters []interface{}
OUTER:
for {
tok = p.Peek()
if tok.Type == CloseParen {
p.Advance()
break OUTER
}
p.Unread()
expr, err := p.handleExpr()
if err != nil {
return nil, false, fmt.Errorf(`function %q: failed to parse expression in parameter list: %w`, callName, err)
}
parameters = append(parameters, expr)
tok = p.Peek()
switch tok.Type {
case Comma:
continue
default:
p.Unread()
}
}
call.Parameters(parameters...)
// If there is either a block or another function call, that's a child statement
var semicolon bool
tok = p.Peek()
switch tok.Type {
case OpenBrace:
p.Unread()
stmts, err := p.handleBlock()
if err != nil {
return nil, false, fmt.Errorf(`function %q: failed to parse function block: %w`, callName, err)
}
call.Add(stmts...)
semicolon = false
case Ident:
// This should be a function call
p.Unread()
child, childsemicolon, err := p.handleCall()
if err != nil {
return nil, false, fmt.Errorf(`function %q: failed to parse child function call: %w`, callName, err)
}
call.Add(child)
semicolon = childsemicolon
case Keyword:
p.Unread()
// Allow for block after a funciton call()
if tok.Value != "for" {
return nil, false, fmt.Errorf(`function %q: unexpected keyword %q`, callName, tok.Value)
}
forBlock, err := p.handleForBlock()
if err != nil {
return nil, false, fmt.Errorf(`function %q: failed to parse function body: %w`, callName, err)
}
call.Add(forBlock)
semicolon = false
default:
semicolon = true
p.Unread()
}
return call, semicolon, nil
}
func (p *parser) handleParenExpr() (ret interface{}, reterr error) {
tok := p.Next()
if tok.Type != OpenParen {
return nil, fmt.Errorf(`expected open paren, got %q`, tok.Value)
}
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse expression: %w`, err)
}
tok = p.Next()
if tok.Type != CloseParen {
return nil, fmt.Errorf(`expected close paren, got %#v`, tok)
}
return ast.NewGroup(expr), nil
}
func (p *parser) handleExpr() (ret interface{}, reterr error) {
var expr interface{}
tok := p.Next()
switch tok.Type {
case Keyword:
p.Unread()
switch tok.Value {
case "let":
ve, err := p.handleLetExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse let expression: %w`, err)
}
expr = ve
case "for":
fe, err := p.handleForExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse expression: %w`, err)
}
expr = fe
case "if":
ie, err := p.handleIfExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse expression: %w`, err)
}
expr = ie
default:
return nil, fmt.Errorf(`unexpected keyword %q`, tok.Value)
}
case OpenParen:
p.Unread()
pe, err := p.handleParenExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse parenthesized expression: %w`, err)
}
expr = pe
case Minus, Exclamation:
p.Unread()
um, err := p.handleUnary(tok)
if err != nil {
return nil, fmt.Errorf(`failed to parse unary operator: %w`, err)
}
expr = um
case Literal:
expr = tok.Value
case Numeric:
f, err := strconv.ParseFloat(tok.Value, 64)
if err != nil {
return nil, fmt.Errorf(`failed to parse numeric literal %q: %w`, tok.Value, err)
}
expr = f
case Ident:
p.Unread()
// could be a function call, or just a variable
stmt, _, err := p.handleAssignmentOrFunctionCall(true)
if err == nil {
expr = stmt
} else {
expr = ast.NewVariable(tok.Value)
}
case OpenBracket:
// This is a list or a loop range
p.Unread()
list, err := p.handleList()
if err != nil {
return nil, fmt.Errorf(`failed to parse list: %w`, err)
}
expr = list
default:
return nil, fmt.Errorf("unhandled expr %#v", tok)
}
if op, err := p.tryOperator(expr); op != nil && err == nil {
expr = op
}
if expr == nil {
panic(`nil expr!`)
}
return expr, nil
}
func (p *parser) handleTernary(cond interface{}) (interface{}, error) {
tok := p.Next()
if tok.Type != Question {
return nil, fmt.Errorf(`expected question mark, got %q`, tok.Value)
}
trueExpr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse true expression: %w`, err)
}
tok = p.Next()
if tok.Type != Colon {
return nil, fmt.Errorf(`expected colon, got %q`, tok.Value)
}
falseExpr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse false expression: %w`, err)
}
return ast.NewTernaryOp(cond, trueExpr, falseExpr), nil
}
func (p *parser) handleAssignmentOrFunctionCall(eval bool) (ast.Stmt, bool, error) {
tok := p.Peek()
if tok.Type != Ident {
return nil, false, fmt.Errorf(`expected ident, got %q`, tok.Value)
}
name := tok.Value
tok = p.Peek()
switch tok.Type {
case Equal:
p.Unread()
p.Unread()
variable, err := p.handleAssignment()
if err != nil {
return nil, true, fmt.Errorf(`failed to parse assignment: %w`, err)
}
return variable, true, nil
case OpenParen:
p.Unread()
p.Unread()
call, semicolon, err := p.handleCall()
if err != nil {
return nil, false, fmt.Errorf(`failed to parse function call: %w`, err)
}
return call, semicolon, nil
default:
p.Unread()
if eval {
// if we're in the middle of some expression to evaluate the value of a var,
// we can have a standalone ident
return ast.NewVariable(name), false, nil
}
return nil, false, fmt.Errorf(`expected assignment or function call, got %q after ident`, tok.Value)
}
}
func (p *parser) handleList() ([]interface{}, error) {
tok := p.Next()
if tok.Type != OpenBracket {
return nil, fmt.Errorf(`expected open bracket, got %q`, tok.Value)
}
var list []interface{}
for {
tok = p.Peek()
if tok.Type == CloseBracket {
p.Advance()
break
}
p.Unread()
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse expression: %w`, err)
}
list = append(list, expr)
tok = p.Peek()
switch tok.Type {
case Comma:
continue
default:
p.Unread()
}
}
return list, nil
}
func (p *parser) handleFunction() (*ast.Function, error) {
tok := p.Next()
if tok.Type != Keyword && tok.Value != "function" {
return nil, fmt.Errorf(`expected function, got %q`, tok.Value)
}
tok = p.Next()
if tok.Type != Ident {
return nil, fmt.Errorf(`expected function name, got %q`, tok.Value)
}
name := tok.Value
fn := ast.NewFunction(name)
tok = p.Next()
if tok.Type != OpenParen {
return nil, fmt.Errorf(`expected open paren, got %q`, tok.Value)
}
var parameters []interface{}
for {
tok = p.Peek()
if tok.Type == CloseParen {
p.Advance()
break
}
p.Unread()
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse function parameter: %w`, err)
}
parameters = append(parameters, expr)
tok = p.Peek()
switch tok.Type {
case Comma:
continue
default:
p.Unread()
}
}
// TODO for functions, parameters need to be *Variable
vparams := make([]*ast.Variable, len(parameters))
for i, p := range parameters {
switch v := p.(type) {
case *ast.Variable:
vparams[i] = v
default:
return nil, fmt.Errorf(`expected variable in function parameter, got %T`, p)
}
}
fn.Parameters(vparams...)
tok = p.Next()
if tok.Type != Equal {
return nil, fmt.Errorf(`expected equal, got %q`, tok.Value)
}
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse function expression: %w`, err)
}
fn.Body(expr)
return fn, nil
}
func (p *parser) mungeOperatorPrecedence(expr interface{}) interface{} {
bop, ok := expr.(*ast.BinaryOp)
if !ok {
return expr
}
switch rop := bop.Right().(type) {
case *ast.BinaryOp:
return bop.Rearrange(rop)
case *ast.TernaryOp:
// Take the condition of the ternary op, and make it the right hand side
return ast.NewTernaryOp(
ast.NewBinaryOp(bop.Op(), bop.Left(), rop.Condition()),
rop.TrueExpr(),
rop.FalseExpr(),
)
default:
return expr
}
}
func (p *parser) tryOperator(left interface{}) (interface{}, error) {
tok := p.Peek()
var ret interface{}
switch tok.Type {
case And:
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse right hand expression of '&&': %w`, err)
}
ret = ast.NewBinaryOp("&&", left, expr)
case Question:
p.Unread()
ternary, err := p.handleTernary(left)
if err != nil {
return nil, fmt.Errorf(`failed to parse ternary expression: %w`, err)
}
ret = ternary
case Equality:
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse right hand expression of '==': %w`, err)
}
ret = ast.NewBinaryOp("==", left, expr)
case LessThan:
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse right hand expression of '<': %w`, err)
}
ret = ast.NewBinaryOp("<", left, expr)
case LessThanEqual:
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse right hand expression of '<=': %w`, err)
}
ret = ast.NewBinaryOp("<=", left, expr)
case GreaterThan:
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse right hand expression of '>': %w`, err)
}
ret = ast.NewBinaryOp(">", left, expr)
case GreaterThanEqual:
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse right hand expression of '>=': %w`, err)
}
ret = ast.NewBinaryOp(">=", left, expr)
case Asterisk:
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse right hand expression of '*': %w`, err)
}
ret = ast.NewBinaryOp("*", left, expr)
case Slash:
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse right hand expression of '/': %w`, err)
}
ret = ast.NewBinaryOp("/", left, expr)
case Plus:
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse right hand expression of '+': %w`, err)
}
ret = ast.NewBinaryOp("+", left, expr)
case Minus:
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse right hand expression of '-': %w`, err)
}
ret = ast.NewBinaryOp("-", left, expr)
case Percent:
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse right hand expression of '%%': %w`, err)
}
ret = ast.NewBinaryOp("%", left, expr)
case OpenBracket:
p.Unread()
index, err := p.handleIndex(left)
if err != nil {
return nil, fmt.Errorf(`failed to parse index operator: %w`, err)
}
// ONLY in the case of an index operator, try one more time to
// match the next operator
nextop, err := p.tryOperator(index)
if err != nil {
return nil, fmt.Errorf(`failed to parse next operator after index: %w`, err)
}
ret = nextop
default:
p.Unread()
return left, nil
}
ret = p.mungeOperatorPrecedence(ret)
return ret, nil
}
func (p *parser) handleIndex(left interface{}) (interface{}, error) {
for {
tok := p.Next()
if tok.Type != OpenBracket {
return nil, fmt.Errorf(`expected open bracket, got %q`, tok.Value)
}
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse index expression of '[]': %w`, err)
}
tok = p.Next()
if tok.Type != CloseBracket {
return nil, fmt.Errorf(`expected close bracket, got %q`, tok.Value)
}
left = ast.NewIndex(left, expr)
tok = p.Peek()
p.Unread()
if tok.Type != OpenBracket {
return left, nil
}
}
}
func (p *parser) handleForExpr() (*ast.ForExpr, error) {
loopVars, err := p.handleForPreamble()
if err != nil {
return nil, fmt.Errorf(`failed to parse for loop preamble: %w`, err)
}
forExpr := ast.NewForExpr(loopVars)
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse for expression: %w`, err)
}
forExpr.Body(expr)
return forExpr, nil
}
func (p *parser) handleForBlock() (*ast.ForBlock, error) {
loopVars, err := p.handleForPreamble()
if err != nil {
return nil, fmt.Errorf(`failed to parse for loop preamble: %w`, err)
}
forStmt := ast.NewFor(loopVars)
stmts, err := p.handleBlock()
if err != nil {
return nil, fmt.Errorf(`failed to parse for block: %w`, err)
}
forStmt.Body(stmts...)
return forStmt, nil
}
func (p *parser) handleForPreamble() ([]*ast.LoopVar, error) {
tok := p.Next()
if tok.Type != Keyword || tok.Value != "for" {
return nil, fmt.Errorf(`expected for, got %q`, tok.Value)
}
tok = p.Next()
if tok.Type != OpenParen {
return nil, fmt.Errorf(`expected open paren, got %q`, tok.Value)
}
// Multiple for variables can be specified, such as
// for (i=[0:1], j=foobar(), z=[1, 2, 3])
var loopVars []*ast.LoopVar
OUTER:
for {
tok = p.Peek()
if tok.Type == CloseParen {
break OUTER
}
p.Unread()
variable, err := p.handleForLoopVariable()
if err != nil {
return nil, fmt.Errorf(`failed to parse for loop variable: %w`, err)
}
loopVars = append(loopVars, variable)
tok = p.Peek()
if tok.Type == Comma {
p.Advance()
continue
}
p.Unread()
}
return loopVars, nil
}
func (p *parser) handleForRange() (*ast.ForRange, error) {
tok := p.Peek()
if tok.Type != OpenBracket {
p.Unread()
return nil, fmt.Errorf(`expected open bracket, got %q`, tok.Value)
}
// For various reasons, we go all the way until the end of range
// to look for a colon
count := 1
for {
count++
tok = p.Peek()
if tok.Type == EOF || tok.Type == CloseBracket {
for i := 0; i < count; i++ {
p.Unread()
}
return nil, fmt.Errorf(`range does not have colon`)
}
if tok.Type == Colon {
break
}
}
for i := 0; i < count-1; i++ {
p.Unread()
}
initExpr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse first element for range expression: %w`, err)
}
tok = p.Next()
if tok.Type != Colon {
return nil, fmt.Errorf(`expected colon, got %q`, tok.Value)
}
stepExpr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse second element for range expression: %w`, err)
}
var endExpr interface{}
tok = p.Peek()
if tok.Type != Colon {
p.Unread()
endExpr = stepExpr
stepExpr = nil
} else {
// we have a three element range expression
endExpr, err = p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse 'end' element for range expression: %w`, err)
}
}
tok = p.Next()
if tok.Type != CloseBracket {
return nil, fmt.Errorf(`expected close bracket, got %q`, tok.Value)
}
fr := ast.NewForRange(initExpr, endExpr)
if stepExpr != nil {
fr.Increment(stepExpr)
}
return fr, nil
}
func (p *parser) handleForLoopVariable() (*ast.LoopVar, error) {
tok := p.Next()
if tok.Type != Ident {
return nil, fmt.Errorf(`expected loop variable identifier, got %q`, tok.Value)
}
variable := ast.NewVariable(tok.Value)
tok = p.Next()
if tok.Type != Equal {
return nil, fmt.Errorf(`expected '=', got %q`, tok.Value)
}
// First, try a for range expression, if that fails, try expr
var frexpr interface{}
fr, err := p.handleForRange()
if err == nil {
frexpr = fr
} else {
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse for loop variable expression: %w`, err)
}
frexpr = expr
}
return ast.NewLoopVar(variable, frexpr), nil
}
func (p *parser) handleLetExpr() (*ast.LetExpr, error) {
vars, err := p.handleLetPreamble()
if err != nil {
return nil, fmt.Errorf(`failed to parse let preamble: %w`, err)
}
letExpr := ast.NewLetExpr(vars...)
expr, err := p.handleExpr()
if err != nil {
return nil, fmt.Errorf(`failed to parse let expression: %w`, err)
}
letExpr.Expr(expr)
return letExpr, nil
}
func (p *parser) handleLetBlock() (*ast.LetBlock, error) {
vars, err := p.handleLetPreamble()
if err != nil {
return nil, fmt.Errorf(`failed to parse let preamble: %w`, err)
}
letBlock := ast.NewLetBlock(vars...)
stmts, err := p.handleBlock()