-
Notifications
You must be signed in to change notification settings - Fork 22
/
parser.grace
3349 lines (3196 loc) · 134 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
dialect "standard"
import "io" as io
import "ast" as ast
import "util" as util
import "errormessages" as errormessages
import "basic" as basic
use basic.open
var tokens := false
var moduleObject
def comments = list [] // so we can request `removeAt`
var auto_count := 0
def noBlocks = false
def blocksOK = true
var values := list [ ]
// The alternative definition below allows pushes and pops of `values`
// to be traced. It can be useful for debugging the parser.
// def values = object {
// def realValues = list [ ]
// var tracing is public := false
// method push(v) {
// if (tracing) then {
// print "pushed {v.toGrace 0} (line {v.line})"
// }
// realValues.push(v)
// }
// method pop {
// def res = realValues.pop
// if (tracing) then {
// print "popped {res.toGrace 0} (line {res.line})"
// }
// res
// }
// method size { realValues.size }
// method filter(b) { realValues.filter(b) }
// method isEmpty { realValues.isEmpty }
// method last { realValues.last }
// method do(b) { realValues.do(b) }
// }
// sym is a module-level field referring to the current token
var sym := object {
def kind is public = "start"
def line is public = 0
def column is public = 0
def indent is public = 0
def value is public = ""
def size is public = 0
method ==(other) {
if (other == false) then {
false
} else {
(other.line == line) && (other.column == column)
}
}
}
var lastToken := sym
var statementToken := lastToken // the token starting the current statement
var comment := false
method next {
// Advance to the next token in the stream, assigning it to sym.
// Put the position in the input into util module variables.
if (tokens.size > 0) then {
nextToken
pushComments
} else {
errormessages.syntaxError("unexpectedly found the end of the input. "
++ "This is often caused by a missing '\}'")
atPosition(sym.line, sym.column)
}
}
method nextToken is confidential {
lastToken := sym
sym := tokens.poll
if (util.verbosity > 110) then { io.error.write "{sym}\n" }
util.setPosition(sym.line, sym.column)
}
method isOnAContinationLine {
// is current token on a line that is a continuation of the previous line?
def currentLine = sym.line
var s := sym
while {s.line == currentLine} do {
if (s.hasPrev.not) then { return false }
s := s.prev
if (s.isSeparator) then { return false }
}
return true
}
method saveParsePosition {
def lexerState = tokens.savePosition
return [lexerState, values.size]
}
method restoreParsePosition(saved) {
tokens.restorePosition(saved.first)
sym := tokens.first.prev
lastToken := sym.prev
def oldValueStackSize = saved.second
if (oldValueStackSize > values.size) then {
ProgrammingError.raise "can't restore parse position; the values stack has been popped"
}
while {oldValueStackSize ≠ values.size} do { values.pop }
}
method findNextToken(tokenMatcher) {
// Search for the next token for which the given block returns true.
// Used for generating suggestions.
if (tokenMatcher.apply(sym)) then {
return sym
}
var n := sym
while {n.isEof.not && { n.indent >= lastToken.indent }} do {
if (tokenMatcher.apply(n)) then {
return n
}
n := n.next
}
n
}
method findNextTokenIndentedAt(tok) {
// Search for the next token for whose indent does not exceed that of tok.
// Used for generating suggestions.
if (((sym.line > tok.line) && (sym.indent <= tok.indent)) || (sym.isEof)) then {
return sym
}
var n := sym
while {n.isEof.not} do {
if ((n.line > tok.line) && (n.indent <= tok.indent)) then {
return n
}
n := n.next
}
n
}
method findNextValidToken(validFollowTokens) {
// returns the next token in validFollowTokens, or the next token
// that could start an expression, or eof
def invalidTokens = set.withAll ["dot", "comma", "colon", "rparen", "rbrace",
"rsquare", "arrow", "assignment"]; // Tokens that cannot start an expression
var candidate := sym
while {candidate.isEof.not} do {
if (validFollowTokens.contains(candidate.kind)) then {
return candidate // candidate is a valid follow token, so return it
}
if (!invalidTokens.contains(candidate.kind)) then {
return candidate // candidate could start an expression, so return it
}
candidate := candidate.next // candidate is invalid, so go to the next one
}
return candidate // candidate is eof
}
method findClosingBrace(opening, inserted) {
// Finds the closing brace correspondng to opening (that is the beginning of a control
// structure) -- an opening brace. Returns an object with two fields: found
// and tok. If a closing brace is found, found is true, and tok is
// the closing brace. Otherwise, found is false, and tok is the
// token after which the closing brace should appear.
var n := sym
var numOpening := if (inserted) then {1} else {0}
var numClosing := 0
def result = object {
var found is public
var tok is public
}
// Count all tokens on the same line first.
while {(n.isEof.not) && (n.line == opening.line)} do {
if (n.isLBrace) then {
numOpening := numOpening + 1
} elseif { n.isRBrace } then {
numClosing := numClosing + 1
}
n := n.next
}
// Count all tokens that have greater indent than the opening brace.
while {(n.isEof.not) && (n.indent > opening.indent)} do {
if (n.isLBrace) then {
numOpening := numOpening + 1
} elseif { n.isRBrace } then {
numClosing := numClosing + 1
}
n := n.next
}
if (n.isRBrace) then {
result.found := true
result.tok := n
} else {
result.found := false
result.tok := n.prev
}
result
}
method accept(t) {
// True if the current token has kind t, where
// t is "num", "string", "keyword", etc.
sym.kind == t
}
method acceptKeyword (kw) {
if (sym.isKeyword.not) then { return false }
def v = sym.value
if (v == kw) then { return true }
return false
}
method acceptKeyword (kw1) or (kw2) {
if (sym.isKeyword.not) then { return false }
def v = sym.value
if (v == kw1) then { return true }
if (v == kw2) then { return true }
return false
}
method acceptKeyword (kw1) or (kw2) or (kw3) {
if (sym.isKeyword.not) then { return false }
def v = sym.value
if (v == kw1) then { return true }
if (v == kw2) then { return true }
if (v == kw3) then { return true }
return false
}
method skipSeparators {
while { sym.isSeparator } do { next }
}
method acceptArgument {
// True if the current token can start an argument to a request
if (sym.isString) then { return true }
if (sym.isNum) then { return true }
if (sym.isLBrace) then { return true }
if (sym.isLSquare) then { return true }
if (sym.isIdentifier) then {
def symValue = sym.value
return (symValue == "true") || (symValue == "false")
}
return false
}
method successfulParse (aParsingBlock) {
// returns true if executing aParsingBlock parses at least one value.
def sz = values.size
aParsingBlock.apply
values.size != sz
}
method unsuccessfulParse (aParsingBlock) {
// returns true if executing aParsingBlock fails to parse any values.
def sz = values.size
aParsingBlock.apply
values.size == sz
}
method pushNum {
// Push the current token onto the output stack as a number
var o := ast.numeral(sym.value)
values.push(o)
next
return o
}
method pushString {
// Push the current token onto the output stack as a string
var o := ast.stringLiteral(sym.value)
o.end := line (sym.line) column (sym.endCol)
values.push(o)
next
return o
}
method pushIdentifier {
// Push the current token onto the output stack as an identifier.
// false means that this identifier has not yet been annotated with a dtype.
util.setPosition(sym.line, sym.column)
def o = if (sym.value == "_") then {
ast.wildcardIdentifier(false)
} else {
ast.identifier(sym.value, false)
}
values.push(o)
next
return o
}
method checkAnnotation(ann) {
if (ann.isCall) then {
for (ann.parts) do {p->
for (p.args) do {a->
if ((a.isIdentifier) && {false != a.dtype}) 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.column, tok.next.endCol)
withSuggestion(suggestion)
}
}
}
}
ann
}
method doannotation {
if (acceptKeyword "is" .not) then {
return false
}
next
def anns = ast.noAnnotations
if (unsuccessfulParse {expression(noBlocks)}) then {
errorMissingAnnotation
}
while {sym.isComma} do {
anns.add(checkAnnotation(values.pop))
next
if (unsuccessfulParse {expression(noBlocks)}) then {
errorMissingAnnotation
}
}
anns.add(checkAnnotation(values.pop))
anns
}
method errorMissingAnnotation {
def suggestions = list [ ]
var suggestion := errormessages.suggestion.new
def nextTok = findNextValidToken ["assignment"]
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'.")
atRange(lastToken.line, lastToken.column, lastToken.endCol)
withSuggestions(suggestions)
}
method typeterm {
if (sym.isIdentifier) then {
pushIdentifier
generic
dotrest(noBlocks)
} elseif {acceptKeyword "outer"} then {
doouter
skipSeparators
if (! sym.isDot) then {
values.pop
// `outer` without a following `.method` is not a valid type
} else {
dotrest(noBlocks)
}
} elseif {acceptKeyword "self"} then {
doself
if (! sym.isDot) then {
values.pop
// `outer` without a following `.method` is not a valid type
} else {
dotrest(noBlocks)
}
} elseif {acceptKeyword "interface"} then {
interfaceLiteral
} elseif {acceptKeyword "Unknown"} then {
values.push(ast.unknownLiteral)
next
} elseif {acceptKeyword "Self"} then {
values.push(ast.selfTypeLiteral)
next
} elseif {acceptKeyword "..."} then {
values.push(ast.ellipsis)
next
}
}
method typeexpression {
var sz := values.size
if (sym.isLParen) then {
def prevStatementToken = statementToken
statementToken := sym
next
if (unsuccessfulParse {typeexpression}) then {
def suggestion = errormessages.suggestion.new
def nextTok = findNextValidToken ["rparen"]
if (nextTok == sym) then {
suggestion.insert("«type expression»")afterToken(lastToken)
} else {
suggestion.replaceTokenRange(sym, nextTok.prev) leading (true)
trailing(false) with "«type expression»"
}
errormessages.syntaxError "parentheses must contain a valid type expression."
atPosition(sym.line, sym.column) withSuggestion(suggestion)
}
if (sym.kind != "rparen") then {
checkBadOperators
def suggestion = errormessages.suggestion.new
suggestion.insert(")")afterToken(lastToken)
errormessages.syntaxError "a type expression beginning with a '(' must end with a ')'."
atRange(lastToken.line, lastToken.column, lastToken.endCol)
withSuggestion(suggestion)
}
statementToken := prevStatementToken
next
} else {
typeterm
}
if (values.size > sz) then {
dotrest(noBlocks)
typeexpressionrest
}
// TODO: check that the expression doesn't contain arbitrary requests or var references.
// This has to happen in the identifier resolution phase.
}
method newIf(cond, thenList, elseList) {
def thenBlock = ast.block(sequence.empty, thenList)
def elseBlock = ast.block(sequence.empty, elseList)
ast.ifExpr(cond, thenBlock, elseBlock)
}
method reportSyntaxError(message) before (expectedTokens) {
def suggestions = list [ ]
var suggestion := errormessages.suggestion.new
def nextTok = findNextValidToken (expectedTokens)
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(message)
atPosition(sym.line, sym.column)
withSuggestions(suggestions)
}
method reportMissingArrow {
def suggestion = errormessages.suggestion.new
if ((sym.isAssignment) || (sym.value == "=")) then {
suggestion.replaceToken(sym)with("->")
} else {
suggestion.insert(" ->")afterToken(lastToken)
}
errormessages.syntaxError("in a block with parameters, the parameters must be followed by '->'")
atPosition(sym.line, sym.column) withSuggestion(suggestion)
}
method reportBadRhs {
// a bind symbol := was not followed by a valid expression.
def suggestions = list [ ]
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.column) withSuggestions(suggestions)
}
method block {
// Parses a block. Since a block is (a) treated as a statement, and
// (b) may have statements inside, we save and restore the setting of the
// global variables relevant to the statement context.
if (sym.isLBrace) then {
def btok = sym
next
skipSeparators
def oldStatementToken = statementToken
statementToken := sym
var isMatchingBlock := false
// a block may start with or without parameters. We assume that
// parameters are present, parse the first expression, and then check.
// If it wasn't a parameter, we back-up the parse position.
def savedPosition = saveParsePosition
def params = blockParameters
if (params.isEmpty) then {
restoreParsePosition(savedPosition)
}
def blockNode = blockBody (params) beginningWith (btok)
values.push(blockNode)
statementToken := oldStatementToken
}
}
method blockParameters {
// parse all the parameters of this block, and return them as a
// collection of identifier nodes.
def params = list [ ]
while {blockParameter(params)} do {
if (sym.isArrow) then {
next
skipSeparators
return params
}
if (sym.isComma) then {
next
} else {
reportMissingArrow
}
}
skipSeparators
return params
}
method blockParameter(params) -> Boolean {
// parse one parameter, if possible, push it onto params, and
// return true. If the next expression is not a parameter, return false.
var paramIsPattern := sym.isLParen
// Parsing the expression ‹(a)› will return an identifierNode‹a› .
// Checking for a paren lets us distinguish parameter from pattern.
if (successfulParse {expression(blocksOK)}) then {
if (sym.isComma || sym.isArrow || sym.isColon) then {
// we have found a parameter
var thisParam := values.pop
if (paramIsPattern || thisParam.isIdentifier.not) then {
paramIsPattern := true
thisParam := ast.wildcardIdentifier(thisParam)
// put the pattern in the type field
}
thisParam.isBindingOccurrence := true
thisParam.isParameter := true
if (paramIsPattern && sym.isColon) then {
reportSyntaxError("a block parameter that's an expression is assumed to mean " ++
"_:‹expression›, and so cannot be followed by a colon")
before ["arrow", "comma"]
}
if (sym.isColon) then {
// We allow an expression for v: <PatternExpression>
next
if (successfulParse {expression(blocksOK)} .not) then {
reportSyntaxError "a block parameter must have a pattern or type expression after the ':'." before ["arrow", "rbrace"]
}
thisParam.dtype := values.pop
}
params.push(thisParam)
return true
} else {
// we just parsed the first expression in the block
return false
}
} else {
return false // we didn't parse anything
}
}
method blockBody(params) beginningWith (btok) {
// returns a block AST node. params is the list of parameters,
// which may be empty, and btok the lbrace that started the block.
// The module variable sym is the first token in the body, and lastToken
// is the preceeding lbrace that started the block, or the arrow that
// terminated the parameter list (if there was one),
// or the comment that appears after the lbrace, if there was one.
def originalValues = values
values := list []
while {sym.isRBrace.not} do {
// Take the body of the block
if (unsuccessfulParse {statement}) then {
def suggestion = errormessages.suggestion.new
suggestion.insert "}" afterToken (lastToken)
errormessages.syntaxError "a block must end with a '}'."
atPosition(sym.line, sym.column) withSuggestion(suggestion)
}
separator
}
def etok = sym // the closing rbrace
next
def body = values
values := originalValues
return ast.block(params, body).setPositionFrom(btok)
}
// 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 (sym.isIdentifier && (sym.value == "if")) then {
def btok = sym
next
def opener = if (sym.isLParen || {sym.isLBrace})
then { sym.value } else { "-missing-" }
def closer = if (opener == "(") then { ")" }
elseif { opener == "\{" } then { "\}" }
else { "-nothing-" }
if (opener == "-missing-") then {
def suggestion = errormessages.suggestion.new
// Look ahead for a rparen or then.
def nextTok = findNextToken { t ->
(t.line == btok.line) && ((t.isRParen) ||
(t.isRBrace) || (t.isLBrace) ||
((t.isIdentifier) && (t.value == "then")))
}
if (false == nextTok) then {
suggestion.insert(" («condition») then \{")afterToken(btok)
} elseif { nextTok.isRParen } then {
if (nextTok == sym) then {
suggestion.insert("(«condition»")beforeToken(sym)
} else {
suggestion.insert("(")beforeToken(sym)
}
} elseif { nextTok.isLBrace } then {
if (nextTok == sym) then {
suggestion.insert(" («condition») then")afterToken(btok)
} else {
suggestion.insert("(")beforeToken(sym)
suggestion.insert(") then")afterToken(nextTok.prev)andTrailingSpace(true)
}
} elseif { nextTok.isIdentifier } then {
if (nextTok == sym) then {
suggestion.insert("(«condition») ")beforeToken(sym)
} else {
suggestion.insert("(")beforeToken(sym)
suggestion.insert(")")afterToken(nextTok.prev)andTrailingSpace(true)
}
}
errormessages.syntaxError("an if statement must have a condition " ++
"in parentheses or braces after the 'if'.")
atPosition(sym.line, sym.column) withSuggestion(suggestion)
}
next
if (unsuccessfulParse {expression(blocksOK)}) then {
def suggestion = errormessages.suggestion.new
// Look ahead for a rparen.
var nextTok := findNextToken { t -> (t.line == lastToken.line) && (t.isRParen) }
if (false == nextTok) 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 a " ++
"condition in parentheses or braces after the 'if'.")
atPosition(sym.line, sym.column)
withSuggestion(suggestion)
} else {
if (nextTok == sym) then {
suggestion.insert("«expression»")afterToken(lastToken)
errormessages.syntaxError("an if statement must have a " ++
"condition in parentheses or braces after the 'if'.")
atPosition(sym.line, sym.column)
withSuggestion(suggestion)
} else {
suggestion.replaceTokenRange(sym, nextTok.prev)
leading(false)trailing(true)with("«expression»")
errormessages.syntaxError("an if statement must have a " ++
"condition in parentheses or braces after the 'if'.")
atRange(sym.line, sym.column, nextTok.column - 1)
withSuggestion(suggestion)
}
}
}
if (sym.value != closer) then {
checkBadOperators
def suggestion = errormessages.suggestion.new
suggestion.insert(")")afterToken(lastToken)
errormessages.syntaxError("an expression beginning with a "++
"'{opener}' must end with a '{closer}'.")
atPosition(lastToken.line, lastToken.column + lastToken.size)
withSuggestion(suggestion)
}
next
var cond := values.pop
var body := list []
var elseblock := list []
var curelse := elseblock
// These two variables are for else/elseif handling. An 'elseif' is
// turned into nested 'if' statements for the AST; `curelse` points
// to the most deeply-nested of those (where any eventual "else"
// blocks will go). `elseblock` contains the statements of the
// top-level 'else' block --- if there are any 'elseif's, that top-
// level 'else' will comprise just one statement: another if.
var v
if (sym.isIdentifier && (sym.value == "then")) then {
next
if (sym.kind != "lbrace") then {
def suggestion = errormessages.suggestion.new
def closingBrace = findClosingBrace(btok, true)
if (closingBrace.found.not) 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.column + lastToken.size)withSuggestion(suggestion)
}
next
while {sym.isRBrace.not} do {
if (unsuccessfulParse {statement}) then {
def suggestion = errormessages.suggestion.new
def closingBrace = findClosingBrace(btok, false)
if (closingBrace.found.not) then {
if (closingBrace.tok == lastToken) then {
suggestion.insert("}")afterToken(lastToken)
} else {
suggestion.addLine(closingBrace.tok.line + 0.1, "}")
}
}
suggestion.deleteToken(sym)
errormessages.syntaxError "the then clause of an if statement must end with a '}'"
atPosition(sym.line, sym.column)
withSuggestion(suggestion)
}
separator
body.push(values.pop)
}
next
var econd
var eif
var newelse
var ebody
while {sym.isIdentifier && (sym.value == "elseif")} do {
// Currently, the parser just accepts arbitrarily many
// "elseifs", turning them into ifs inside the else.
// TODO: allow blocks after elseif to contain a sequence of expressions.
statementToken := sym
next
if (sym.isLBrace.not) then {
def suggestion = errormessages.suggestion.new
// Look ahead for a rbrace or then.
def nextTok = findNextToken { t ->
(t.line == statementToken.line)
&& ((t.isRBrace || t.isLBrace)
|| (t.isIdentifier && (t.value == "then"))) }
if (false == nextTok) then {
suggestion.insert(" \{ «expression» \} then \{")afterToken(statementToken)
} elseif { nextTok.isRBrace } then {
if (nextTok == sym) then {
suggestion.insert("\{ «expression» \}")beforeToken(sym)
} else {
suggestion.insert("\{ ")beforeToken(sym)
}
} elseif { nextTok.isLBrace } 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.isIdentifier } 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 a " ++
"condition in braces after the 'elseif'.")
atPosition(sym.line, sym.column)
withSuggestion(suggestion)
}
next
if (unsuccessfulParse {expression(blocksOK)}) then {
def suggestion = errormessages.suggestion.new
// Look ahead for a rbrace or then.
var nextTok := findNextToken { t ->
(t.line == lastToken.line) && (t.isRBrace)}
if (false == nextTok) 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 clause must have an expression in braces after the 'elseif'.")atPosition(
sym.line, sym.column)withSuggestion(suggestion)
} else {
if (nextTok == sym) then {
suggestion.insert("«expression»")afterToken(lastToken)
errormessages.syntaxError("an elseif clause must have an expression in braces after the 'elseif'.")atPosition(
sym.line, sym.column)withSuggestion(suggestion)
} else {
//checkInvalidExpression
suggestion.replaceTokenRange(sym, nextTok.prev)leading(false)trailing(true)with("«expression»")
errormessages.syntaxError("(4) an elseif statement must have an expression in braces after the 'elseif'.")atRange(
sym.line, sym.column, nextTok.column - 1)withSuggestion(suggestion)
}
}
}
if (sym.value != "\}") then {
checkBadOperators
def suggestion = errormessages.suggestion.new
suggestion.insert "}" afterToken (lastToken)
errormessages.syntaxError("a condition beginning with a " ++
"'\{' must end with a '\}'.")
atPosition(lastToken.line, lastToken.column + lastToken.size)
withSuggestion(suggestion)
}
next
econd := values.pop
if (sym.isIdentifier && (sym.value == "then")) then {
next
ebody := list []
} else {
def suggestion = errormessages.suggestion.new
if (sym.isLBrace) then {
def closingBrace = findClosingBrace(statementToken, false)
if (closingBrace.found.not) 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.not) 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 clause must have 'then' after the expression in braces.")
atPosition(sym.line, sym.column)withSuggestion(suggestion)
}
if (sym.kind != "lbrace") then {
def suggestion = errormessages.suggestion.new
def closingBrace = findClosingBrace(btok, true)
if (closingBrace.found.not) 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 clause must have a '\{' after the 'then'.")atPosition(
lastToken.line, lastToken.column + lastToken.size)withSuggestion(suggestion)
}
next
while { sym.isRBrace.not } do {
if (unsuccessfulParse {statement}) then {
def suggestion = errormessages.suggestion.new
def closingBrace = findClosingBrace(btok, false)
if (closingBrace.found.not) 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' clause must end with a '}'.")atPosition(
sym.line, sym.column)withSuggestion(suggestion)
}
separator
v := values.pop
ebody.push(v)
}
next
newelse := list []
eif := newIf(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 (sym.isIdentifier && (sym.value == "else")) then {
next
if (sym.isLBrace.not) then {
def suggestion = errormessages.suggestion.new
def closingBrace = findClosingBrace(btok, true)
if (closingBrace.found.not) 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 clause must start with a '\{' after the 'else'.")
atPosition(lastToken.line, lastToken.column + lastToken.size - 1)
withSuggestion(suggestion)
}
next
// Just take all the statements and put them into
// curelse.
while {sym.isRBrace.not} do {
if (unsuccessfulParse {statement}) then {
def suggestion = errormessages.suggestion.new
def closingBrace = findClosingBrace(btok, false)
if (closingBrace.found.not) then {
if (sym.isEof) then {
errormessages.syntaxError("end of program " ++
"found while searching for the '}' to close " ++
"an 'else' statement.")
atPosition(sym.line, sym.column)
}
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.column)withSuggestion(suggestion)
}
v := values.pop
curelse.push(v)
separator
}
next
}
util.setPosition(btok.line, btok.column)
var o := newIf(cond, body, elseblock)
values.push(o)
} else {
// Raise an error here, or it will spin nastily forever.
def suggestion = errormessages.suggestion.new
if (sym.isLBrace) then {
def closingBrace = findClosingBrace(btok, false)
if (closingBrace.found.not) 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.not) 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 condition in parentheses.")
atPosition(sym.line, sym.column) withSuggestion(suggestion)
}
}
}
// Accept an identifier. Handle "if" specially by
// passing it to the method above.
method identifier {