-
Notifications
You must be signed in to change notification settings - Fork 11
/
parser.grace
3452 lines (3397 loc) · 148 KB
/
parser.grace
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
#pragma DefaultVisibility=public
import "io" as io
import "ast" as ast
import "util" as util
import "mgcollections" as collections
import "errormessages" as errormessages
var lastline := 0
var linenum := 0
var lastIndent := 0
var indentFreePass := false
var minIndentLevel := 0
var statementIndent := 0
var statementToken
var tokens := false
var values := []
var auto_count := 0
var don'tTakeBlock := false
var braceIsType := false
var defaultDefVisibility := "confidential"
var defaultVarVisibility := "confidential"
var defaultMethodVisibility := "public"
var inMethod := false
// Global object containing the current token
var sym
var lastToken := object {
var kind := "start"
var line := 1
var linePos := 0
var indent := 0
var value := ""
def size = 0
}
var comment := false
// Advance to the next token in the stream, with special handling
// so the magic "line" tokens update the line number for error output.
method next {
lastToken := sym
if (tokens.size > 0) then {
lastline := linenum
lastIndent := sym.indent
sym := tokens.poll
if (sym.kind == "comment") then {
comment := ""
while {(sym.kind == "comment").andAlso {tokens.size > 0}} do {
comment := comment ++ sym.value
sym := tokens.poll
}
}
linenum := sym.line
util.setPosition(sym.line, sym.linePos)
} else {
sym := object {
var kind := "eof"
var line := lastToken.line
var linePos := util.lines[lastToken.line].size + 1
var indent := 0
var value := ""
def size = 0
}
}
}
// Search for the next token that the given block returns true for.
// Used for generating suggestions.
method findNextToken(tokenMatcher) {
if(tokenMatcher.apply(sym)) then {
return sym
}
var nextTok := false
var n := sym
while {(n != false).andAlso { nextTok == false }.andAlso { n.indent >= lastToken.indent }} do {
if(tokenMatcher.apply(n)) then {
nextTok := n
}
n := n.next
}
nextTok
}
method findNextTokenIndentedAt(tok) {
if(((sym.line > tok.line) && (sym.indent <= tok.indent)) || (sym.kind == "eof")) then {
return sym
}
var nextTok := false
var n := sym
while {(n != false).andAlso { nextTok == false }} do {
if(((n.line > tok.line) && (n.indent <= tok.indent)) || (sym.kind == "eof")) then {
nextTok := n
}
n := n.next
}
nextTok
}
method findNextValidToken(*validFollowTokens) {
// Tokens that cannot start an expression.
def invalidTokens = ["dot", "comma", "colon", "rparen", "rbrace", "rsquare", "arrow", "bind"];
var validToken := sym
while {validToken.kind != "eof"} do {
// If the token is a valid follow token, then return that token.
if(validFollowTokens.contains(validToken.kind)) then {
return validToken
}
// If the token is not an invalid token for starting an expression, return that token.
if(!invalidTokens.contains(validToken.kind)) then {
return validToken
}
// The token is invalid, go to the next one.
validToken := validToken.next
}
return validToken
}
// Finds the closing brace for a given token (that is the beginning of a control
// structure with an opening brace. Returns an object with two fields: found
// and tok. If a closing brace is found, found is set to true, and tok is set to
// the closing brace. Otherwise found is set to false, and tok is set to the
// token that the closing brace should appear after.
method findClosingBrace(tok, inserted) {
var n := sym
var numOpening := if(inserted) then {1} else {0}
var numClosing := 0
def result = object {
var found
var tok
}
// Skip all tokens on the same line first.
while {(n.kind != "eof") && (n.line == tok.line)} do {
if(n.kind == "lbrace") then { numOpening := numOpening + 1 }
elseif{n.kind == "rbrace"} then { numClosing := numClosing + 1 }
n := n.next
}
// Skip all tokens that have greater indent than the target closing brace.
while {(n.kind != "eof") && (n.indent > tok.indent)} do {
if(n.kind == "lbrace") then { numOpening := numOpening + 1 }
elseif{n.kind == "rbrace"} then { numClosing := numClosing + 1 }
n := n.next
}
if(n.kind == "rbrace") then {
result.found := true
result.tok := n
} elseif{(n.prev.kind == "rbrace") && (numOpening == numClosing)} then {
// Check that the number of opening and closing braces matches.
result.found := true
result.tok := n.prev
} else {
result.found := false
result.tok := n.prev
}
result
}
// True if the current token (next to be processed) is a t, where
// t is "num", "string", "method", etc.
method accept(t) {
sym.kind == t
}
// True if the current token is a t, and it is on the same logical
// line (either because it's on the same physical line, or because
// it's on an indented continuation line).
method acceptSameLine(t) {
(sym.kind == t) && ((lastline == sym.line) ||
(sym.indent > lastIndent))
}
// True if the current token is a t, and it is on the same logical
// line as a provided token.
method accept(t)onLineOf(other) {
(sym.kind == t) && ((other.line == sym.line) ||
(sym.indent > other.indent))
}
// True if the current token is a t, and it is on the same logical
// line as a provided token.
method accept(t)onLineOfLastOr(other) {
(sym.kind == t) && (((other.line == sym.line) ||
(sym.indent > other.indent)) || (lastToken.line == sym.line))
}
// True if there is a token on the same logical line
method tokenOnSameLine {
(lastline == sym.line) || (sym.indent > lastIndent)
}
// Check if block did consume at least one token.
method didConsume(ablock) {
var sz := tokens.size
ablock.apply
tokens.size != sz
}
// Expect block to consume at least one token, or call fallback code.
method ifConsume(ablock)then(tblock) {
var sz := tokens.size
ablock.apply
if (tokens.size != sz) then {
tblock.apply
}
}
// Push the current token onto the output stack as a number
method pushnum {
var o := ast.numNode.new(sym.value)
values.push(o)
next
}
// Push the current token onto the output stack as an octet literal
method pushoctets {
var o := ast.octetsNode.new(sym.value)
values.push(o)
next
}
// Push the current token onto the output stack as a string
method pushstring {
var o := ast.stringNode.new(sym.value)
values.push(o)
next
}
// Push the current token onto the output stack as an identifier.
// false means that this identifier has not been assigned a dtype (yet).
method pushidentifier {
util.setline(sym.line)
var o := ast.identifierNode.new(sym.value, false)
if (o.value == "_") then {
o.value := "__" ++ auto_count
o.wildcard := true
auto_count := auto_count + 1
}
values.push(o)
next
}
method checkAnnotation(ann) {
if (ann.kind == "call") then {
for (ann.with) do {p->
for (p.args) do {a->
if ((a.kind == "identifier").andAlso {a.dtype != false}) then {
var tok := sym
// Look back from the current token to try and find the tokens that cause this error.
while {tok.value != ":"} do { tok := tok.prev }
def suggestion = errormessages.suggestion.new
suggestion.deleteTokenRange(tok, tok.next)leading(true)trailing(false)
errormessages.syntaxError("An argument to an annotation cannot have a type.")atRange(
tok.line, tok.linePos, tok.next.linePos + tok.next.size - 1)withSuggestion(suggestion)
}
}
}
}
ann
}
method doannotation {
if ((!accept("keyword")).orElse {sym.value != "is"}) then {
return false
}
next
def anns = collections.list.new
don'tTakeBlock := true
if(didConsume({expression}).not) then {
def suggestions = []
var suggestion := errormessages.suggestion.new
def nextTok = findNextValidToken("bind")
if(nextTok == sym) then {
suggestion.insert(" «annotation»")afterToken(lastToken)
} else {
suggestion.replaceTokenRange(sym, nextTok.prev)leading(true)trailing(false)with(" «annotation»")
}
suggestions.push(suggestion)
suggestion := errormessages.suggestion.new
suggestion.deleteTokenRange(lastToken, nextTok.prev)leading(true)trailing(false)
suggestions.push(suggestion)
errormessages.syntaxError("One or more annotations separated by commas must follow 'is'.")atPosition(
lastToken.line, lastToken.linePos + lastToken.size + 1)withSuggestions(suggestions)
}
while {accept("comma")} do {
anns.push(checkAnnotation(values.pop))
next
if(didConsume({expression}).not) then {
def suggestions = []
var suggestion := errormessages.suggestion.new
def nextTok = findNextValidToken("bind")
if(nextTok == sym) then {
suggestion.insert(" «annotation»")afterToken(lastToken)
} else {
suggestion.replaceTokenRange(sym, nextTok.prev)leading(true)trailing(false)with(" «annotation»")
}
suggestions.push(suggestion)
suggestion := errormessages.suggestion.new
suggestion.deleteTokenRange(lastToken, nextTok.prev)leading(true)trailing(false)
suggestions.push(suggestion)
errormessages.syntaxError("One or more annotations separated by commas must follow 'is'.")atPosition(
lastToken.line, lastToken.linePos + lastToken.size + 1)withSuggestions(suggestions)
}
}
don'tTakeBlock := false
anns.push(checkAnnotation(values.pop))
anns
}
method blank {
if (sym.line > (lastToken.line + 1)) then {
if (values.size > 0) then {
if (values.last.kind != "blank") then {
values.push(ast.blankNode.new)
}
}
}
}
method dotypeterm {
if (accept("identifier")) then {
pushidentifier
generic
don'tTakeBlock := true
dotrest
don'tTakeBlock := false
} else {
if (accept("keyword").andAlso { sym.value == "type" }) then {
doanontype
}
}
}
method dotyperef {
var overallType := false
var tp := false
var op := false
def unionTypes = []
if(didConsume({dotypeterm}).not) then {
checkBadAnonymousType
def suggestions = []
var suggestion := errormessages.suggestion.new
suggestion := errormessages.suggestion.new
suggestion.insert(" «type name»")afterToken(lastToken)
suggestions.push(suggestion)
suggestion := errormessages.suggestion.new
suggestion.deleteToken(lastToken)
suggestions.push(suggestion)
suggestion := errormessages.suggestion.new
suggestion.replaceToken(lastToken)with(":=")
suggestions.push(suggestion)
errormessages.syntaxError("A type name or type expression must follow ':'.")atPosition(
sym.line, sym.linePos)withSuggestions(suggestions)
}
overallType := values.pop
while {acceptSameLine("op") && (sym.value == "|")} do {
if (unionTypes.size == 0) then {
unionTypes.push(overallType)
}
next
if(didConsume({dotypeterm}).not) then {
checkBadAnonymousType
def suggestions = []
var suggestion := errormessages.suggestion.new
suggestion.insert(" «type name»")afterToken(lastToken)
suggestions.push(suggestion)
suggestion := errormessages.suggestion.new
suggestion.deleteToken(lastToken)
suggestions.push(suggestion)
errormessages.syntaxError("A type name or type expression must follow '|'.")atPosition(
sym.line, sym.linePos)withSuggestions(suggestions)
}
unionTypes.push(values.pop)
}
if (unionTypes.size > 0) then {
var unionName := "Union<"
for (unionTypes) do {ut->
unionName := "{unionName}|{ut.value}"
}
unionName := "{unionName}|>"
overallType := ast.typeNode.new(unionName, [])
for (unionTypes) do {ut->
overallType.unionTypes.push(ut)
}
}
def intersectionTypes = []
while {acceptSameLine("op") && (sym.value == "&")} do {
if (intersectionTypes.size == 0) then {
intersectionTypes.push(overallType)
}
next
if(didConsume({dotypeterm}).not) then {
checkBadAnonymousType
def suggestions = []
var suggestion := errormessages.suggestion.new
suggestion.insert(" «type name»")afterToken(lastToken)
suggestions.push(suggestion)
suggestion := errormessages.suggestion.new
suggestion.deleteToken(lastToken)
suggestions.push(suggestion)
errormessages.syntaxError("A type name or type expression must follow '&'.")atPosition(
sym.line, sym.linePos)withSuggestions(suggestions)
}
intersectionTypes.push(values.pop)
}
if (intersectionTypes.size > 0) then {
var intersectionName := "Intersection<"
for (intersectionTypes) do {it->
intersectionName := "{intersectionName}&{it.value}"
}
intersectionName := intersectionName ++ "&>"
overallType := ast.typeNode.new(intersectionName, [])
for (intersectionTypes) do {it->
overallType.intersectionTypes.push(it)
}
}
values.push(overallType)
}
// Accept a block
method block {
if (accept("lbrace")) then {
def btok = sym
next
var minInd := statementIndent + 1
var startIndent := statementIndent
var ident1
var s := sym
var tmp
var params := []
var body := []
var havearrow := true
var found := false
var i := 0
var isMatchingBlock := false
statementToken := sym
if (sym.kind == "lparen") then {
isMatchingBlock := true
}
ifConsume {expression} then {
if (accept("comma") || accept("arrow") || accept("colon")) then {
// This block has parameters
ident1 := values.pop
if (accept("colon")) then {
// We allow an expression here for the case of v : T
// patterns, where T may be "Pair(hd, tl)" or similar.
next
braceIsType := true
if(didConsume({expression}).not) then {
def suggestions = []
var suggestion := errormessages.suggestion.new
def nextTok = findNextValidToken("arrow", "rbrace")
if(nextTok == sym) then {
suggestion.insert(" «expression»")afterToken(lastToken)
} else {
suggestion.replaceTokenRange(sym, nextTok.prev)leading(true)trailing(false)with(" «expression»")
}
suggestions.push(suggestion)
suggestion := errormessages.suggestion.new
suggestion.deleteTokenRange(lastToken, nextTok.prev)leading(true)trailing(false)
suggestions.push(suggestion)
errormessages.syntaxError("A block must have an expression after the ':'.")atPosition(
sym.line, sym.linePos)withSuggestions(suggestions)
}
braceIsType := false
ident1.dtype := values.pop
}
params.push(ident1)
if (ident1.kind != "identifier") then {
isMatchingBlock := true
}
if (isMatchingBlock && {accept("comma")}) then {
def suggestions = []
var suggestion
def arrow = findNextToken({ t -> t.kind == "arrow" })
if(arrow != false) then {
suggestion := errormessages.suggestion.new
suggestion.deleteTokenRange(sym, arrow.prev)
suggestions.push(suggestion)
}
suggestion := errormessages.suggestion.new
suggestion.replaceToken(sym)leading(true)trailing(false)with(" |")
suggestions.push(suggestion)
errormessages.syntaxError("A matching block may only have one parameter.")atRange(
sym.line, sym.linePos, sym.linePos)withSuggestions(suggestions)
}
while {accept("comma")} do {
// Keep doing the above for the rest of the parameters.
next
pushidentifier
ident1 := values.pop
if (accept("colon")) then {
next
dotyperef
ident1.dtype := values.pop
}
params.push(ident1)
}
if ((accept("arrow")).not) then {
def suggestion = errormessages.suggestion.new
if((sym.kind == "bind") || (sym.value == "=")) then {
suggestion.replaceToken(sym)with("->")
} else {
suggestion.insert(" ->")afterToken(lastToken)
}
errormessages.syntaxError("A block must have one or more parameters followed by '->' and an expression.")atPosition(
sym.line, sym.linePos)withSuggestion(suggestion)
}
next
} elseif {accept("semicolon")} then {
body.push(values.pop)
next
if (accept("semicolon")) then {
next
if (sym.line == lastToken.line) then {
indentFreePass := true
}
}
} elseif {((values.last.kind == "member")
|| (values.last.kind == "identifier")
|| (values.last.kind == "index"))
&& accept("bind")} then {
var lhs := values.pop
next
if(didConsume({expression}).not) then {
def suggestions = []
var suggestion := errormessages.suggestion.new
def nextTok = findNextValidToken("rbrace")
if(nextTok == sym) then {
suggestion.insert(" «expression»")afterToken(lastToken)
} else {
suggestion.replaceTokenRange(sym, nextTok.prev)leading(true)trailing(false)with(" «expression»")
}
suggestions.push(suggestion)
suggestion := errormessages.suggestion.new
suggestion.deleteTokenRange(lastToken, nextTok.prev)leading(true)trailing(false)
suggestions.push(suggestion)
errormessages.syntaxError("A valid expression must follow ':='.")atPosition(
sym.line, sym.linePos)withSuggestions(suggestions)
}
var rhs := values.pop
body.push(ast.bindNode.new(lhs, rhs))
if (accept("semicolon")) then {
next
if (sym.line == lastToken.line) then {
indentFreePass := true
}
}
} else {
checkUnexpectedTokenAfterStatement
body.push(values.pop)
}
}
if (accept("arrow")) then {
next
}
var ln := values.size
if (sym.line == lastToken.line) then {
minIndentLevel := sym.linePos - 1
} else {
minIndentLevel := minInd
}
while {(accept("rbrace")).not} do {
// Take the body of the block
if(didConsume({statement}).not) then {
def suggestion = errormessages.suggestion.new
suggestion.insert("}")afterToken(lastToken)
errormessages.syntaxError("A block must end with a '}'.")atPosition(
sym.line, sym.linePos)withSuggestion(suggestion)
}
tmp := values.pop
body.push(tmp)
}
minIndentLevel := minInd - 1
statementIndent := startIndent
next
var o := ast.blockNode.new(params, body)
if (isMatchingBlock) then {
if (params.size > 0) then {
o.matchingPattern := params.first
}
}
values.push(o)
}
}
// Accept an "if" statement. This is a special syntactic case, rather
// than just a call with a multi-part method name - it might be possible
// to change that and compensate later on.
method doif {
if (accept("identifier") && (sym.value == "if")) then {
def btok = sym
next
if(sym.kind != "lparen") then {
def suggestion = errormessages.suggestion.new
// Look ahead for a rparen or then.
def nextTok = findNextToken({ t -> (t.line == btok.line)
&& ((t.kind == "rparen") || (t.kind == "lbrace")
|| ((t.kind == "identifier") && (t.value == "then"))) })
if(nextTok == false) then {
suggestion.insert(" («expression») then \{")afterToken(btok)
} elseif{nextTok.kind == "rparen"} then {
if(nextTok == sym) then {
suggestion.insert("(«expression»")beforeToken(sym)
} else {
suggestion.insert("(")beforeToken(sym)
}
} elseif{nextTok.kind == "lbrace"} then {
if(nextTok == sym) then {
suggestion.insert(" («expression») then")afterToken(btok)
} else {
suggestion.insert("(")beforeToken(sym)
suggestion.insert(") then")afterToken(nextTok.prev)andTrailingSpace(true)
}
} elseif{nextTok.kind == "identifier"} then {
if(nextTok == sym) then {
suggestion.insert("(«expression») ")beforeToken(sym)
} else {
suggestion.insert("(")beforeToken(sym)
suggestion.insert(")")afterToken(nextTok.prev)andTrailingSpace(true)
}
}
errormessages.syntaxError("An if statement must have an expression in parentheses after the 'if'.")atPosition(
sym.line, sym.linePos)withSuggestion(suggestion)
}
next
if(didConsume({expression}).not) then {
def suggestion = errormessages.suggestion.new
// Look ahead for a rparen.
var nextTok := findNextToken({ t -> (t.line == lastToken.line) && (t.kind == "rparen") })
if(nextTok == false) then {
nextTok := findNextValidToken("rparen")
if(nextTok == sym) then {
suggestion.insert("«expression») then \{")afterToken(lastToken)
} else {
suggestion.replaceTokenRange(sym, nextTok.prev)leading(true)trailing(false)with("«expression») then \{")
}
errormessages.syntaxError("An if statement must have an expression in parentheses after the 'if'.")atPosition(
sym.line, sym.linePos)withSuggestion(suggestion)
} else {
if(nextTok == sym) then {
suggestion.insert("«expression»")afterToken(lastToken)
errormessages.syntaxError("An if statement must have an expression in parentheses after the 'if'.")atPosition(
sym.line, sym.linePos)withSuggestion(suggestion)
} else {
suggestion.replaceTokenRange(sym, nextTok.prev)leading(false)trailing(true)with("«expression»")
errormessages.syntaxError("An if statement must have an expression in parentheses after the 'if'.")atRange(
sym.line, sym.linePos, nextTok.linePos - 1)withSuggestion(suggestion)
}
}
}
if(sym.kind != "rparen") then {
checkBadOperators
def suggestion = errormessages.suggestion.new
suggestion.insert(")")afterToken(lastToken)
errormessages.syntaxError("An expression beginning with a '(' must end with a ')'.")atPosition(
lastToken.line, lastToken.linePos + lastToken.size)withSuggestion(suggestion)
}
next
var cond := values.pop
var body := []
// These two are for else/elseif handling. elseif is turned into
// nested if statements for the AST, so curelse points to the
// most deeply-nested of those (where any eventual "else" block's
// statements will go). elseblock contains the statements of the
// top-level "else" block - if there are any elseifs, that
// consists of only one statement, another if.
var elseblock := []
var curelse := elseblock
var v
def localMin = minIndentLevel
def localStatementIndent = statementIndent
var minInd := statementIndent + 1
if (accept("identifier") && (sym.value == "then")) then {
next
if(sym.kind != "lbrace") then {
def suggestion = errormessages.suggestion.new
def closingBrace = findClosingBrace(btok, true)
if(closingBrace.found == false) then {
if(closingBrace.tok == lastToken) then {
suggestion.replaceToken(lastToken)leading(false)trailing(true)with("then \{}")
} else {
suggestion.addLine(closingBrace.tok.line + 0.1, "}")
suggestion.replaceToken(lastToken)leading(false)trailing(true)with("then \{")
}
} else {
suggestion.replaceToken(lastToken)leading(false)trailing(true)with("then \{")
}
errormessages.syntaxError("An if statement must have a '\{' after the 'then'.")atPosition(
lastToken.line, lastToken.linePos + lastToken.size)withSuggestion(suggestion)
}
next
if (sym.line == lastToken.line) then {
minIndentLevel := sym.linePos - 1
} else {
minIndentLevel := minInd
}
while {(accept("rbrace")).not} do {
if(didConsume({statement}).not) then {
def suggestion = errormessages.suggestion.new
def closingBrace = findClosingBrace(btok, false)
if(closingBrace.found == false) then {
if(closingBrace.tok == lastToken) then {
suggestion.insert("}")afterToken(lastToken)
} else {
suggestion.addLine(closingBrace.tok.line + 0.1, "}")
}
}
suggestion.deleteToken(sym)
errormessages.syntaxError("An if statement must end with a '}'.")atPosition(
sym.line, sym.linePos)withSuggestion(suggestion)
}
v := values.pop
body.push(v)
}
next
var econd
var eif
var newelse
var ebody
while {accept("identifier") && (sym.value == "elseif")} do {
// Currently, the parser just accepts arbitrarily many
// "elseifs", turning them into ifs inside the else.
statementToken := sym
next
if((sym.kind != "lbrace") && (sym.kind != "lparen")) then {
def suggestion = errormessages.suggestion.new
// Look ahead for a rbrace or then.
def nextTok = findNextToken({ t -> (t.line == statementToken.line)
&& ((t.kind == "rparen") || (t.kind == "lbrace")
|| ((t.kind == "identifier") && (t.value == "then"))) })
if(nextTok == false) then {
suggestion.insert(" \{«expression»} then \{")afterToken(statementToken)
} elseif{nextTok.kind == "rbrace"} then {
if(nextTok == sym) then {
suggestion.insert("\{«expression»")beforeToken(sym)
} else {
suggestion.insert("\{")beforeToken(sym)
}
} elseif{nextTok.kind == "lbrace"} then {
if(nextTok == sym) then {
suggestion.insert(" \{«expression») then")afterToken(statementToken)
} else {
suggestion.insert("\{")beforeToken(sym)
suggestion.insert("} then")afterToken(nextTok.prev)andTrailingSpace(true)
}
} elseif{nextTok.kind == "identifier"} then {
if(nextTok == sym) then {
suggestion.insert("\{«expression»} ")beforeToken(sym)
} else {
suggestion.insert("\{")beforeToken(sym)
suggestion.insert("\}")afterToken(nextTok.prev)andTrailingSpace(true)
}
}
errormessages.syntaxError("An elseif statement must have an expression in braces after the 'elseif'.")atPosition(
sym.line, sym.linePos)withSuggestion(suggestion)
}
def condDelim = sym.kind
next
if(didConsume({expression}).not) then {
def suggestion = errormessages.suggestion.new
// Look ahead for a rbrace or then.
var nextTok := findNextToken({ t -> (t.line == lastToken.line) && (t.kind == "rbrace") })
if(nextTok == false) then {
nextTok := findNextValidToken("rbrace")
if(nextTok == sym) then {
suggestion.insert("«expression»} then \{")afterToken(lastToken)
} else {
suggestion.replaceTokenRange(sym, nextTok.prev)leading(true)trailing(false)with("«expression»} then \{")
}
errormessages.syntaxError("An elseif statement must have an expression in braces after the 'elseif'.")atPosition(
sym.line, sym.linePos)withSuggestion(suggestion)
} else {
if(nextTok == sym) then {
suggestion.insert("«expression»")afterToken(lastToken)
errormessages.syntaxError("An elseif statement must have an expression in bracees after the 'elseif'.")atPosition(
sym.line, sym.linePos)withSuggestion(suggestion)
} else {
//checkInvalidExpression
suggestion.replaceTokenRange(sym, nextTok.prev)leading(false)trailing(true)with("«expression»")
errormessages.syntaxError("An elseif statement must have an expression in braces after the 'elseif'.")atRange(
sym.line, sym.linePos, nextTok.linePos - 1)withSuggestion(suggestion)
}
}
}
if (condDelim == "lparen") then {
if(sym.kind != "rparen") then {
checkBadOperators
def suggestion = errormessages.suggestion.new
suggestion.insert(")")afterToken(lastToken)
errormessages.syntaxError("An expression beginning with a '(' must end with a ')'.")atPosition(
lastToken.line, lastToken.linePos + lastToken.size)withSuggestion(suggestion)
}
} else {
if (sym.kind != "rbrace") then {
checkBadOperators
def suggestion = errormessages.suggestion.new
suggestion.insert("}")afterToken(lastToken)
errormessages.syntaxError("The condition of elseif must be enclosed in braces.")atPosition(
lastToken.line, lastToken.linePos + lastToken.size)withSuggestion(suggestion)
}
}
next
econd := values.pop
if (condDelim == "lparen") then {
econd := ast.memberNode.new("apply", econd)
}
if ((accept("identifier") &&
(sym.value == "then"))) then {
next
ebody := []
} else {
def suggestion = errormessages.suggestion.new
if(sym.kind == "lbrace") then {
def closingBrace = findClosingBrace(statementToken, false)
if(closingBrace.found == false) then {
if(closingBrace.tok == sym) then {
suggestion.replaceToken(sym)leading(true)trailing(false)with(" then \{}")
} else {
suggestion.replaceToken(sym)leading(true)trailing(false)with(" then \{")
suggestion.addLine(closingBrace.tok.line + 0.1, "}")
}
} else {
suggestion.replaceToken(sym)leading(true)trailing(false)with(" then \{")
}
} else {
def closingBrace = findClosingBrace(statementToken, true)
if(closingBrace.found == false) then {
if(closingBrace.tok == lastToken) then {
suggestion.insert(" then \{}")afterToken(lastToken)
} else {
suggestion.insert(" then \{")afterToken(lastToken)
suggestion.addLine(closingBrace.tok.line + 0.1, "}")
}
} else {
suggestion.insert(" then \{")afterToken(lastToken)
}
}
errormessages.syntaxError("An elseif statement must have 'then' after the expression in parentheses.")atPosition(
sym.line, sym.linePos)withSuggestion(suggestion)
}
if(sym.kind != "lbrace") then {
def suggestion = errormessages.suggestion.new
def closingBrace = findClosingBrace(btok, true)
if(closingBrace.found == false) then {
if(closingBrace.tok == lastToken) then {
suggestion.replaceToken(lastToken)leading(false)trailing(true)with("then \{}")
} else {
suggestion.addLine(closingBrace.tok.line + 0.1, "}")
suggestion.replaceToken(lastToken)leading(false)trailing(true)with("then \{")
}
} else {
suggestion.replaceToken(lastToken)leading(false)trailing(true)with("then \{")
}
errormessages.syntaxError("An elseif statement must have a '\{' after the 'then'.")atPosition(
lastToken.line, lastToken.linePos + lastToken.size)withSuggestion(suggestion)
}
next
if (sym.line == lastToken.line) then {
minIndentLevel := sym.linePos - 1
} else {
minIndentLevel := minInd
}
while {(accept("rbrace")).not} do {
if(didConsume({statement}).not) then {
def suggestion = errormessages.suggestion.new
def closingBrace = findClosingBrace(btok, false)
if(closingBrace.found == false) then {
if(closingBrace.tok == lastToken) then {
suggestion.insert("}")afterToken(lastToken)
} else {
suggestion.addLine(closingBrace.tok.line + 0.1, "}")
}
}
suggestion.deleteToken(sym)
errormessages.syntaxError("An elseif statement must end with a '}'.")atPosition(
sym.line, sym.linePos)withSuggestion(suggestion)
}
v := values.pop
ebody.push(v)
}
next
newelse := []
eif := ast.ifNode.new(econd, ebody, newelse)
// Construct the inner "if" AST node, and then push it
// inside the current "else" block.
curelse.push(eif)
// Update curelse to point to the new, empty, nested
// else block.
curelse := newelse
}
if (accept("identifier") && (sym.value == "else")) then {
next
if(sym.kind != "lbrace") then {
def suggestion = errormessages.suggestion.new
def closingBrace = findClosingBrace(btok, true)
if(closingBrace.found == false) then {
if(closingBrace.tok == lastToken) then {
suggestion.replaceToken(lastToken)leading(false)trailing(true)with("else \{}")
} else {
suggestion.addLine(closingBrace.tok.line + 0.1, "}")
suggestion.replaceToken(lastToken)leading(false)trailing(true)with("else \{")
}
} else {
suggestion.replaceToken(lastToken)leading(false)trailing(true)with("else \{")
}
errormessages.syntaxError("An else statement must have a '\{' after the 'else'.")atPosition(
lastToken.line, lastToken.linePos + lastToken.size)withSuggestion(suggestion)
}
next
// Just take all the statements and put them into
// curelse.
if (sym.line == lastToken.line) then {
minIndentLevel := sym.linePos - 1
} else {
minIndentLevel := minInd
}
while {(accept("rbrace")).not} do {
if(didConsume({statement}).not) then {
def suggestion = errormessages.suggestion.new
def closingBrace = findClosingBrace(btok, false)
if(closingBrace.found == false) then {
if(closingBrace.tok == lastToken) then {
suggestion.insert("}")afterToken(lastToken)
} else {
suggestion.addLine(closingBrace.tok.line + 0.1, "}")
}
}
suggestion.deleteToken(sym)
errormessages.syntaxError("An else statement must end with a '}'.")atPosition(
sym.line, sym.linePos)withSuggestion(suggestion)
}
v := values.pop
curelse.push(v)
}
next
}
var o := ast.ifNode.new(cond, body, elseblock)
values.push(o)
} else {
// Raise an error here, or it will spin nastily forever.
def suggestion = errormessages.suggestion.new
if(sym.kind == "lbrace") then {
def closingBrace = findClosingBrace(btok, false)
if(closingBrace.found == false) then {
if(closingBrace.tok == sym) then {
suggestion.replaceToken(sym)leading(true)trailing(false)with(" then \{}")
} else {
suggestion.replaceToken(sym)leading(true)trailing(false)with(" then \{")
suggestion.addLine(closingBrace.tok.line + 0.1, "}")
}
} else {
suggestion.replaceToken(sym)leading(true)trailing(false)with(" then \{")
}
} else {
def closingBrace = findClosingBrace(btok, true)
if(closingBrace.found == false) then {
if(closingBrace.tok == lastToken) then {
suggestion.insert(" then \{}")afterToken(lastToken)
} else {
suggestion.insert(" then \{")afterToken(lastToken)
suggestion.addLine(closingBrace.tok.line + 0.1, "}")
}
} else {
suggestion.insert(" then \{")afterToken(lastToken)
}
}
errormessages.syntaxError("An if statement must have 'then' after the expression in parentheses.")atPosition(
sym.line, sym.linePos)withSuggestion(suggestion)
}
minIndentLevel := localMin
statementIndent := localStatementIndent
}
}
// Accept an identifier. Handle "if", "while", and "for" specially by
// passing them on to the appropriate method above.
method identifier {
if (accept("identifier")) then {
if (sym.value == "if") then {
doif
} else {
pushidentifier
}
}
}
method prefixop {
if (accept("op")) then {
var op := sym.value
var val
next
if (accept("lparen")) then {
next
if(didConsume({expression}).not) then {
def suggestion = errormessages.suggestion.new
def nextTok = findNextValidToken("rparen")
if(nextTok == sym) then {
suggestion.insert("«expression»")afterToken(lastToken)
} else {
suggestion.replaceTokenRange(sym, nextTok.prev)leading(true)trailing(false)with("«expression»")
}
errormessages.syntaxError("Parentheses must contain a valid expression.")atPosition(
sym.line, sym.linePos)withSuggestion(suggestion)
}
if(sym.kind != "rparen") then {
checkBadOperators