-
Notifications
You must be signed in to change notification settings - Fork 43
/
Parser.ts
1616 lines (1385 loc) · 56.6 KB
/
Parser.ts
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
import { EventEmitter } from "events";
import * as Expr from "./Expression";
type Expression = Expr.Expression;
import * as Stmt from "./Statement";
type Statement = Stmt.Statement;
import { Lexeme, Token, Identifier, Location, ReservedWords } from "../lexer";
import { ParseError } from "./ParseError";
import {
BrsInvalid,
BrsBoolean,
BrsString,
Int32,
ValueKind,
Argument,
StdlibArgument,
} from "../brsTypes";
/** Set of all keywords that end blocks. */
type BlockTerminator =
| Lexeme.ElseIf
| Lexeme.Else
| Lexeme.EndFor
| Lexeme.Next
| Lexeme.EndIf
| Lexeme.EndWhile
| Lexeme.EndSub
| Lexeme.EndFunction;
/** The set of operators valid for use in assignment statements. */
const assignmentOperators = [
Lexeme.Equal,
Lexeme.MinusEqual,
Lexeme.PlusEqual,
Lexeme.StarEqual,
Lexeme.SlashEqual,
Lexeme.BackslashEqual,
Lexeme.LeftShiftEqual,
Lexeme.RightShiftEqual,
];
/** List of Lexemes that are permitted as property names. */
const allowedProperties = [
Lexeme.And,
Lexeme.Box,
Lexeme.CreateObject,
Lexeme.Dim,
Lexeme.Else,
Lexeme.ElseIf,
Lexeme.End,
Lexeme.EndFunction,
Lexeme.EndFor,
Lexeme.EndIf,
Lexeme.EndSub,
Lexeme.EndWhile,
Lexeme.Eval,
Lexeme.Exit,
Lexeme.ExitFor,
Lexeme.ExitWhile,
Lexeme.False,
Lexeme.For,
Lexeme.ForEach,
Lexeme.Function,
Lexeme.GetGlobalAA,
Lexeme.GetLastRunCompileError,
Lexeme.GetLastRunRunTimeError,
Lexeme.Goto,
Lexeme.If,
Lexeme.Invalid,
Lexeme.Let,
Lexeme.Next,
Lexeme.Not,
Lexeme.ObjFun,
Lexeme.Or,
Lexeme.Pos,
Lexeme.Print,
Lexeme.Rem,
Lexeme.Return,
Lexeme.Step,
Lexeme.Stop,
Lexeme.Sub,
Lexeme.Tab,
Lexeme.To,
Lexeme.True,
Lexeme.Type,
Lexeme.While,
];
/** List of Lexeme that are allowed as local var identifiers. */
const allowedIdentifiers = [Lexeme.EndFor, Lexeme.ExitFor, Lexeme.ForEach];
/**
* List of string versions of Lexeme that are NOT allowed as local var identifiers.
* Used to throw more helpful "you can't use a reserved word as an identifier" errors.
*/
const disallowedIdentifiers = new Set(
[
Lexeme.And,
Lexeme.Box,
Lexeme.CreateObject,
Lexeme.Dim,
Lexeme.Else,
Lexeme.ElseIf,
Lexeme.End,
Lexeme.EndFunction,
Lexeme.EndIf,
Lexeme.EndSub,
Lexeme.EndWhile,
Lexeme.Eval,
Lexeme.Exit,
Lexeme.ExitWhile,
Lexeme.False,
Lexeme.For,
Lexeme.Function,
Lexeme.GetGlobalAA,
Lexeme.GetLastRunCompileError,
Lexeme.GetLastRunRunTimeError,
Lexeme.Goto,
Lexeme.If,
Lexeme.Invalid,
Lexeme.Let,
Lexeme.Next,
Lexeme.Not,
Lexeme.ObjFun,
Lexeme.Or,
Lexeme.Pos,
Lexeme.Print,
Lexeme.Rem,
Lexeme.Return,
Lexeme.Step,
Lexeme.Sub,
Lexeme.Tab,
Lexeme.To,
Lexeme.True,
Lexeme.Type,
Lexeme.While,
].map(x => Lexeme[x].toLowerCase())
);
/** The results of a Parser's parsing pass. */
interface ParseResults {
/** The statements produced by the parser. */
statements: Stmt.Statement[];
/** The errors encountered by the Parser. */
errors: ParseError[];
}
export class Parser {
/** Allows consumers to observe errors as they're detected. */
readonly events = new EventEmitter();
/**
* A convenience function, equivalent to `new Parser().parse(toParse)`, that parses an array of
* `Token`s into an abstract syntax tree that can be executed with the `Interpreter`.
* @param toParse the array of tokens to parse
* @returns an array of `Statement` objects that together form the abstract syntax tree of the
* program
*/
static parse(toParse: ReadonlyArray<Token>) {
return new Parser().parse(toParse);
}
/**
* Convenience function to subscribe to the `err` events emitted by `parser.events`.
* @param errorHandler the function to call for every Parser error emitted after subscribing
* @returns an object with a `dispose` function, used to unsubscribe from errors
*/
public onError(errorHandler: (err: ParseError) => void) {
this.events.on("err", errorHandler);
return {
dispose: () => {
this.events.removeListener("err", errorHandler);
},
};
}
/**
* Convenience function to subscribe to a single `err` event emitted by `parser.events`.
* @param errorHandler the function to call for the first Parser error emitted after subscribing
*/
public onErrorOnce(errorHandler: (err: ParseError) => void) {
this.events.once("err", errorHandler);
}
/**
* Parses an array of `Token`s into an abstract syntax tree that can be executed with the `Interpreter`.
* @param toParse the array of tokens to parse
* @returns an array of `Statement` objects that together form the abstract syntax tree of the
* program
*/
parse(toParse: ReadonlyArray<Token>): ParseResults {
let current = 0;
let tokens = toParse;
//the depth of the calls to function declarations. Helps some checks know if they are at the root or not.
let functionDeclarationLevel = 0;
function isAtRootLevel() {
return functionDeclarationLevel === 0;
}
let statements: Statement[] = [];
let errors: ParseError[] = [];
/**
* Add an error to the parse results.
* @param token - the token where the error occurred
* @param message - the message for this error
* @returns an error object that can be thrown if the calling code needs to abort parsing
*/
const addError = (token: Token, message: string) => {
let err = new ParseError(token, message);
errors.push(err);
this.events.emit("err", err);
return err;
};
/**
* Add an error at the given location.
* @param location
* @param message
*/
const addErrorAtLocation = (location: Location, message: string) => {
addError({ location: location } as any, message);
};
if (toParse.length === 0) {
return {
statements: [],
errors: [],
};
}
try {
while (!isAtEnd()) {
let dec = declaration();
if (dec) {
statements.push(dec);
}
}
return { statements, errors };
} catch (parseError) {
return {
statements: [],
errors: errors,
};
}
/**
* A simple wrapper around `check` to make tests for a `end` identifier.
* `end` is a keyword, but not reserved, so associative arrays can have properties
* called `end`; the parser takes on this task.
* @returns `true` if the next token is an identifier with text `end`, otherwise `false`
*/
function checkEnd() {
return check(Lexeme.Identifier) && peek().text.toLowerCase() === "end";
}
function declaration(...additionalTerminators: BlockTerminator[]): Statement | undefined {
try {
// consume any leading newlines
while (match(Lexeme.Newline));
if (check(Lexeme.Sub, Lexeme.Function)) {
return functionDeclaration(false);
}
if (checkLibrary()) {
return libraryStatement();
}
// BrightScript is like python, in that variables can be declared without a `var`,
// `let`, (...) keyword. As such, we must check the token *after* an identifier to figure
// out what to do with it.
if (
check(Lexeme.Identifier, ...allowedIdentifiers) &&
checkNext(...assignmentOperators)
) {
return assignment(...additionalTerminators);
}
return statement(...additionalTerminators);
} catch (error) {
synchronize();
return;
}
}
function functionDeclaration(isAnonymous: true): Expr.Function;
function functionDeclaration(isAnonymous: false): Stmt.Function;
function functionDeclaration(isAnonymous: boolean) {
try {
//certain statements need to know if they are contained within a function body
//so track the depth here
functionDeclarationLevel++;
let startingKeyword = peek();
let isSub = check(Lexeme.Sub);
let functionType = advance();
let name: Identifier;
let returnType: ValueKind;
let leftParen: Token;
let rightParen: Token;
if (isSub) {
returnType = ValueKind.Void;
} else {
returnType = ValueKind.Dynamic;
}
if (isAnonymous) {
leftParen = consume(
`Expected '(' after ${functionType.text}`,
Lexeme.LeftParen
);
} else {
name = consume(
`Expected ${functionType.text} name after '${functionType.text}'`,
Lexeme.Identifier
) as Identifier;
leftParen = consume(
`Expected '(' after ${functionType.text} name`,
Lexeme.LeftParen
);
//prevent functions from ending with type designators
let lastChar = name.text[name.text.length - 1];
if (["$", "%", "!", "#", "&"].includes(lastChar)) {
//don't throw this error; let the parser continue
addError(
name,
`Function name '${name.text}' cannot end with type designator '${lastChar}'`
);
}
}
let args: Argument[] = [];
if (!check(Lexeme.RightParen)) {
do {
if (args.length >= Expr.Call.MaximumArguments) {
throw addError(
peek(),
`Cannot have more than ${Expr.Call.MaximumArguments} arguments`
);
}
args.push(signatureArgument());
} while (match(Lexeme.Comma));
}
rightParen = advance();
let maybeAs = peek();
if (check(Lexeme.Identifier) && maybeAs.text.toLowerCase() === "as") {
advance();
let typeToken = advance();
let typeString = typeToken.text || "";
let maybeReturnType = ValueKind.fromString(typeString);
if (!maybeReturnType) {
throw addError(
typeToken,
`Function return type '${typeString}' is invalid`
);
}
returnType = maybeReturnType;
}
args.reduce((haveFoundOptional: boolean, arg: Argument) => {
if (haveFoundOptional && !arg.defaultValue) {
throw addError(
{
kind: Lexeme.Identifier,
text: arg.name.text,
isReserved: ReservedWords.has(arg.name.text),
location: arg.location,
},
`Argument '${arg.name.text}' has no default value, but comes after arguments with default values`
);
}
return haveFoundOptional || !!arg.defaultValue;
}, false);
consume(
`Expected newline or ':' after ${functionType.text} signature`,
Lexeme.Newline,
Lexeme.Colon
);
//support ending the function with `end sub` OR `end function`
let body = block(Lexeme.EndSub, Lexeme.EndFunction);
if (!body) {
throw addError(
peek(),
`Expected 'end ${functionType.text}' to terminate ${functionType.text} block`
);
}
// consume 'end sub' or 'end function'
let endingKeyword = advance();
let expectedEndKind = isSub ? Lexeme.EndSub : Lexeme.EndFunction;
//if `function` is ended with `end sub`, or `sub` is ended with `end function`, then
//add an error but don't hard-fail so the AST can continue more gracefully
if (endingKeyword.kind !== expectedEndKind) {
addError(
endingKeyword,
`Expected 'end ${functionType.text}' to terminate ${functionType.text} block`
);
}
let func = new Expr.Function(
args,
returnType,
body,
startingKeyword,
endingKeyword
);
if (isAnonymous) {
return func;
} else {
// only consume trailing newlines in the statement context; expressions
// expect to handle their own trailing whitespace
while (match(Lexeme.Newline));
return new Stmt.Function(name!, func);
}
} finally {
functionDeclarationLevel--;
}
}
function signatureArgument(): Argument {
if (!check(Lexeme.Identifier)) {
throw addError(
peek(),
`Expected argument name, but received '${peek().text || ""}'`
);
}
let name = advance();
let type: ValueKind = ValueKind.Dynamic;
let typeToken: Token | undefined;
let defaultValue;
// parse argument default value
if (match(Lexeme.Equal)) {
// it seems any expression is allowed here -- including ones that operate on other arguments!
defaultValue = expression();
}
let next = peek();
if (check(Lexeme.Identifier) && next.text && next.text.toLowerCase() === "as") {
// 'as' isn't a reserved word, so it can't be lexed into an As token without the lexer
// understanding language context. That's less than ideal, so we'll have to do some
// more intelligent comparisons to detect the 'as' sometimes-keyword here.
advance();
typeToken = advance();
let typeValueKind = ValueKind.fromString(typeToken.text);
if (!typeValueKind) {
throw addError(
typeToken,
`Function parameter '${name.text}' is of invalid type '${typeToken.text}'`
);
}
type = typeValueKind;
}
return {
name: name,
type: {
kind: type,
location: typeToken ? typeToken.location : StdlibArgument.InternalLocation,
},
defaultValue: defaultValue,
location: {
file: name.location.file,
start: name.location.start,
end: typeToken ? typeToken.location.end : name.location.end,
},
};
}
function assignment(...additionalterminators: Lexeme[]): Stmt.Assignment {
let name = advance() as Identifier;
//add error if name is a reserved word that cannot be used as an identifier
if (disallowedIdentifiers.has(name.text.toLowerCase())) {
//don't throw...this is fully recoverable
addError(name, `Cannot use reserved word "${name.text}" as an identifier`);
}
let operator = consume(
`Expected operator ('=', '+=', '-=', '*=', '/=', '\\=', '^=', '<<=', or '>>=') after idenfifier '${name.text}'`,
...assignmentOperators
);
let value = expression();
if (!check(...additionalterminators)) {
consume(
"Expected newline or ':' after assignment",
Lexeme.Newline,
Lexeme.Colon,
Lexeme.Eof,
...additionalterminators
);
}
if (operator.kind === Lexeme.Equal) {
return new Stmt.Assignment({ equals: operator }, name, value);
} else {
return new Stmt.Assignment(
{ equals: operator },
name,
new Expr.Binary(new Expr.Variable(name), operator, value)
);
}
}
function checkLibrary() {
let isLibraryIdentifier =
check(Lexeme.Identifier) && peek().text.toLowerCase() === "library";
//if we are at the top level, any line that starts with "library" should be considered a library statement
if (isAtRootLevel() && isLibraryIdentifier) {
return true;
}
//not at root level, library statements are all invalid here, but try to detect if the tokens look
//like a library statement (and let the libraryStatement function handle emitting the errors)
else if (isLibraryIdentifier && checkNext(Lexeme.String)) {
return true;
}
//definitely not a library statement
else {
return false;
}
}
function statement(...additionalterminators: BlockTerminator[]): Statement | undefined {
if (checkLibrary()) {
return libraryStatement();
}
if (check(Lexeme.Stop)) {
return stopStatement();
}
if (check(Lexeme.If)) {
return ifStatement();
}
if (check(Lexeme.Print)) {
return printStatement(...additionalterminators);
}
if (check(Lexeme.While)) {
return whileStatement();
}
if (check(Lexeme.ExitWhile)) {
return exitWhile();
}
if (check(Lexeme.For)) {
return forStatement();
}
if (check(Lexeme.ForEach)) {
return forEachStatement();
}
if (check(Lexeme.ExitFor)) {
return exitFor();
}
if (checkEnd()) {
return endStatement();
}
if (match(Lexeme.Return)) {
return returnStatement();
}
if (check(Lexeme.Goto)) {
return gotoStatement();
}
//does this line look like a label? (i.e. `someIdentifier:` )
if (check(Lexeme.Identifier) && checkNext(Lexeme.Colon)) {
return labelStatement();
}
// TODO: support multi-statements
return setStatement(...additionalterminators);
}
function whileStatement(): Stmt.While {
const whileKeyword = advance();
const condition = expression();
consume("Expected newline after 'while ...condition...'", Lexeme.Newline);
const whileBlock = block(Lexeme.EndWhile);
if (!whileBlock) {
throw addError(peek(), "Expected 'end while' to terminate while-loop block");
}
const endWhile = advance();
while (match(Lexeme.Newline));
return new Stmt.While(
{ while: whileKeyword, endWhile: endWhile },
condition,
whileBlock
);
}
function exitWhile(): Stmt.ExitWhile {
let keyword = advance();
consume("Expected newline after 'exit while'", Lexeme.Newline);
while (match(Lexeme.Newline)) {}
return new Stmt.ExitWhile({ exitWhile: keyword });
}
function forStatement(): Stmt.For {
const forKeyword = advance();
const initializer = assignment(Lexeme.To);
const to = advance();
const finalValue = expression();
let increment: Expression | undefined;
let step: Token | undefined;
if (check(Lexeme.Step)) {
step = advance();
increment = expression();
} else {
// BrightScript for/to/step loops default to a step of 1 if no `step` is provided
increment = new Expr.Literal(new Int32(1), peek().location);
}
while (match(Lexeme.Newline));
let body = block(Lexeme.EndFor, Lexeme.Next);
if (!body) {
throw addError(peek(), "Expected 'end for' or 'next' to terminate for-loop block");
}
let endFor = advance();
while (match(Lexeme.Newline));
// WARNING: BrightScript doesn't delete the loop initial value after a for/to loop! It just
// stays around in scope with whatever value it was when the loop exited.
return new Stmt.For(
{
for: forKeyword,
to: to,
step: step,
endFor: endFor,
},
initializer,
finalValue,
increment,
body
);
}
function forEachStatement(): Stmt.ForEach {
let forEach = advance();
let name = advance();
let maybeIn = peek();
if (check(Lexeme.Identifier) && maybeIn.text.toLowerCase() === "in") {
advance();
} else {
throw addError(maybeIn, "Expected 'in' after 'for each <name>'");
}
let target = expression();
if (!target) {
throw addError(peek(), "Expected target object to iterate over");
}
advance();
while (match(Lexeme.Newline));
let body = block(Lexeme.EndFor, Lexeme.Next);
if (!body) {
throw addError(peek(), "Expected 'end for' or 'next' to terminate for-loop block");
}
let endFor = advance();
while (match(Lexeme.Newline));
return new Stmt.ForEach(
{
forEach: forEach,
in: maybeIn,
endFor: endFor,
},
name,
target,
body
);
}
function exitFor(): Stmt.ExitFor {
let keyword = advance();
consume("Expected newline after 'exit for'", Lexeme.Newline);
while (match(Lexeme.Newline)) {}
return new Stmt.ExitFor({ exitFor: keyword });
}
function libraryStatement(): Stmt.Library | undefined {
let libraryStatement = new Stmt.Library({
library: advance(),
//grab the next token only if it's a string
filePath: check(Lexeme.String) ? advance() : undefined,
});
//no token following library keyword token
if (!libraryStatement.tokens.filePath && check(Lexeme.Newline, Lexeme.Colon)) {
addErrorAtLocation(
libraryStatement.tokens.library.location,
`Missing string literal after ${libraryStatement.tokens.library.text} keyword`
);
}
//does not have a string literal as next token
else if (!libraryStatement.tokens.filePath && peek().kind === Lexeme.Newline) {
addErrorAtLocation(
peek().location,
`Expected string literal after ${libraryStatement.tokens.library.text} keyword`
);
}
//consume all tokens until the end of the line
let invalidTokens = consumeUntil(Lexeme.Newline, Lexeme.Eof, Lexeme.Colon);
if (invalidTokens.length > 0) {
//add an error for every invalid token
for (let invalidToken of invalidTokens) {
addErrorAtLocation(
invalidToken.location,
`Found unexpected token '${invalidToken.text}' after library statement`
);
}
}
//libraries must be at the very top of the file before any other declarations.
let isAtTopOfFile = true;
for (let statement of statements) {
//if we found a non-library statement, this statement is not at the top of the file
if (!(statement instanceof Stmt.Library)) {
isAtTopOfFile = false;
}
}
//libraries must be a root-level statement (i.e. NOT nested inside of functions)
if (!isAtRootLevel() || !isAtTopOfFile) {
addErrorAtLocation(
libraryStatement.location,
"Library statements may only appear at the top of a file"
);
}
//consume to the next newline, eof, or colon
while (match(Lexeme.Newline, Lexeme.Eof, Lexeme.Colon));
return libraryStatement;
}
function ifStatement(): Stmt.If {
const ifToken = advance();
const startingLine = ifToken.location;
const condition = expression();
let thenBranch: Stmt.Block;
let elseIfBranches: Stmt.ElseIf[] = [];
let elseBranch: Stmt.Block | undefined;
let thenToken: Token | undefined;
let elseIfTokens: Token[] = [];
let endIfToken: Token | undefined;
/**
* A simple wrapper around `check`, to make tests for a `then` identifier.
* As with many other words, "then" is a keyword but not reserved, so associative
* arrays can have properties called "then". It's a valid identifier sometimes, so the
* parser has to take on the burden of understanding that I guess.
* @returns `true` if the next token is an identifier with text "then", otherwise `false`.
*/
function checkThen() {
return check(Lexeme.Identifier) && peek().text.toLowerCase() === "then";
}
if (checkThen()) {
// `then` is optional after `if ...condition...`, so only advance to the next token if `then` is present
thenToken = advance();
}
if (match(Lexeme.Newline) || match(Lexeme.Colon)) {
//consume until no more colons
while (check(Lexeme.Colon)) {
advance();
}
//consume exactly 1 newline, if found
if (check(Lexeme.Newline)) {
advance();
}
//keep track of the current error count, because if the then branch fails,
//we will trash them in favor of a single error on if
let errorsLengthBeforeBlock = errors.length;
// we're parsing a multi-line ("block") form of the BrightScript if/then/else and must find
// a trailing "end if"
let maybeThenBranch = block(Lexeme.EndIf, Lexeme.Else, Lexeme.ElseIf);
if (!maybeThenBranch) {
//throw out any new errors created as a result of a `then` block parse failure.
//the block() function will discard the current line, so any discarded errors will
//resurface if they are legitimate, and not a result of a malformed if statement
errors.splice(errorsLengthBeforeBlock, errors.length - errorsLengthBeforeBlock);
//this whole if statement is bogus...add error to the if token and hard-fail
throw addError(
ifToken,
"Expected 'end if', 'else if', or 'else' to terminate 'then' block"
);
}
let blockEnd = previous();
if (blockEnd.kind === Lexeme.EndIf) {
endIfToken = blockEnd;
}
thenBranch = maybeThenBranch;
match(Lexeme.Newline);
// attempt to read a bunch of "else if" clauses
while (check(Lexeme.ElseIf)) {
elseIfTokens.push(advance());
let elseIfCondition = expression();
if (checkThen()) {
// `then` is optional after `else if ...condition...`, so only advance to the next token if `then` is present
advance();
}
//consume any trailing colons
while (check(Lexeme.Colon)) {
advance();
}
match(Lexeme.Newline);
let elseIfThen = block(Lexeme.EndIf, Lexeme.Else, Lexeme.ElseIf);
if (!elseIfThen) {
throw addError(
peek(),
"Expected 'end if', 'else if', or 'else' to terminate 'then' block"
);
}
let blockEnd = previous();
if (blockEnd.kind === Lexeme.EndIf) {
endIfToken = blockEnd;
}
elseIfBranches.push({
condition: elseIfCondition,
thenBranch: elseIfThen,
});
}
if (match(Lexeme.Else)) {
//consume any trailing colons
while (check(Lexeme.Colon)) {
advance();
}
match(Lexeme.Newline);
elseBranch = block(Lexeme.EndIf);
let endIfToken = advance(); // skip past "end if"
//ensure that single-line `if` statements have a colon right before 'end if'
if (ifToken.location.start.line === endIfToken.location.start.line) {
let index = tokens.indexOf(endIfToken);
let previousToken = tokens[index - 1];
if (previousToken.kind !== Lexeme.Colon) {
addError(endIfToken, "Expected ':' to preceed 'end if'");
}
}
match(Lexeme.Newline);
} else {
match(Lexeme.Newline);
endIfToken = consume(
`Expected 'end if' to close 'if' statement started on line ${startingLine}`,
Lexeme.EndIf
);
//ensure that single-line `if` statements have a colon right before 'end if'
if (ifToken.location.start.line === endIfToken.location.start.line) {
let index = tokens.indexOf(endIfToken);
let previousToken = tokens[index - 1];
if (previousToken.kind !== Lexeme.Colon) {
addError(endIfToken, "Expected ':' to preceed 'end if'");
}
}
match(Lexeme.Newline);
}
} else {
let thenStatement = declaration(Lexeme.ElseIf, Lexeme.Else);
if (!thenStatement) {
throw addError(
peek(),
"Expected a statement to follow 'if ...condition... then'"
);
}
thenBranch = new Stmt.Block([thenStatement], peek().location);
while (match(Lexeme.ElseIf)) {
let elseIf = previous();
let elseIfCondition = expression();
if (checkThen()) {
// `then` is optional after `else if ...condition...`, so only advance to the next token if `then` is present
advance();
}
let elseIfThen = declaration(Lexeme.ElseIf, Lexeme.Else);
if (!elseIfThen) {
throw addError(
peek(),
`Expected a statement to follow '${elseIf.text} ...condition... then'`
);
}
elseIfBranches.push({
condition: elseIfCondition,
thenBranch: new Stmt.Block([elseIfThen], peek().location),
});
}
if (match(Lexeme.Else)) {
let elseStatement = declaration();
if (!elseStatement) {
throw addError(peek(), `Expected a statement to follow 'else'`);
}
elseBranch = new Stmt.Block([elseStatement], peek().location);
}
}
return new Stmt.If(
{
if: ifToken,
then: thenToken,
elseIfs: elseIfTokens,
endIf: endIfToken,
},
condition,
thenBranch,
elseIfBranches,
elseBranch
);
}
function setStatement(
...additionalTerminators: BlockTerminator[]
): Stmt.DottedSet | Stmt.IndexedSet | Stmt.Expression | Stmt.Increment {
/**
* Attempts to find an expression-statement or an increment statement.
* While calls are valid expressions _and_ statements, increment (e.g. `foo++`)
* statements aren't valid expressions. They _do_ however fall under the same parsing
* priority as standalone function calls though, so we cann parse them in the same way.
*/
function _expressionStatement(): Stmt.Expression | Stmt.Increment {
let expressionStart = peek();
if (check(Lexeme.PlusPlus, Lexeme.MinusMinus)) {
let operator = advance();
if (check(Lexeme.PlusPlus, Lexeme.MinusMinus)) {
throw addError(
peek(),
"Consecutive increment/decrement operators are not allowed"
);
} else if (expr instanceof Expr.Call) {
throw addError(
expressionStart,
"Increment/decrement operators are not allowed on the result of a function call"
);
}
while (match(Lexeme.Newline, Lexeme.Colon));
return new Stmt.Increment(expr, operator);
}
if (!check(...additionalTerminators)) {
consume(
"Expected newline or ':' after expression statement",
Lexeme.Newline,
Lexeme.Colon,
Lexeme.Eof
);
}
if (expr instanceof Expr.Call) {