-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathParser.ts
More file actions
3272 lines (2838 loc) · 116 KB
/
Parser.ts
File metadata and controls
3272 lines (2838 loc) · 116 KB
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 type { Token, Identifier } from '../lexer/Token';
import { isToken } from '../lexer/Token';
import type { BlockTerminator } from '../lexer/TokenKind';
import { Lexer } from '../lexer/Lexer';
import {
AllowedLocalIdentifiers,
AllowedProperties,
AssignmentOperators,
BrighterScriptSourceLiterals,
DeclarableTypes,
DisallowedFunctionIdentifiersText,
DisallowedLocalIdentifiersText,
TokenKind
} from '../lexer/TokenKind';
import type {
PrintSeparatorSpace,
PrintSeparatorTab
} from './Statement';
import {
AssignmentStatement,
Block,
Body,
CatchStatement,
ContinueStatement,
ClassStatement,
ConstStatement,
CommentStatement,
DimStatement,
DottedSetStatement,
EndStatement,
EnumMemberStatement,
EnumStatement,
ExitForStatement,
ExitWhileStatement,
ExpressionStatement,
FieldStatement,
ForEachStatement,
ForStatement,
FunctionStatement,
GotoStatement,
IfStatement,
ImportStatement,
IncrementStatement,
IndexedSetStatement,
InterfaceFieldStatement,
InterfaceMethodStatement,
InterfaceStatement,
LabelStatement,
LibraryStatement,
MethodStatement,
NamespaceStatement,
PrintStatement,
ReturnStatement,
StopStatement,
ThrowStatement,
TryCatchStatement,
WhileStatement
} from './Statement';
import type { DiagnosticInfo } from '../DiagnosticMessages';
import { DiagnosticMessages } from '../DiagnosticMessages';
import { util } from '../util';
import {
AALiteralExpression,
AAMemberExpression,
AnnotationExpression,
ArrayLiteralExpression,
BinaryExpression,
CallExpression,
CallfuncExpression,
DottedGetExpression,
EscapedCharCodeLiteralExpression,
FunctionExpression,
FunctionParameterExpression,
GroupingExpression,
IndexedGetExpression,
LiteralExpression,
NamespacedVariableNameExpression,
NewExpression,
NullCoalescingExpression,
RegexLiteralExpression,
SourceLiteralExpression,
TaggedTemplateStringExpression,
TemplateStringExpression,
TemplateStringQuasiExpression,
TernaryExpression,
UnaryExpression,
VariableExpression,
XmlAttributeGetExpression
} from './Expression';
import type { Diagnostic, Range } from 'vscode-languageserver';
import { Logger } from '../Logger';
import { isAAMemberExpression, isAnnotationExpression, isBinaryExpression, isCallExpression, isCallfuncExpression, isMethodStatement, isCommentStatement, isDottedGetExpression, isIfStatement, isIndexedGetExpression, isVariableExpression } from '../astUtils/reflection';
import { createVisitor, WalkMode } from '../astUtils/visitors';
import { createStringLiteral, createToken } from '../astUtils/creators';
import { Cache } from '../Cache';
import type { Expression, Statement } from './AstNode';
export class Parser {
/**
* The array of tokens passed to `parse()`
*/
public tokens = [] as Token[];
/**
* The current token index
*/
public current: number;
/**
* The list of statements for the parsed file
*/
public ast = new Body([]);
public get statements() {
return this.ast.statements;
}
/**
* The top-level symbol table for the body of this file.
*/
public get symbolTable() {
return this.ast.symbolTable;
}
/**
* References for significant statements/expressions in the parser.
* These are initially extracted during parse-time to improve performance, but will also be dynamically regenerated if need be.
*
* If a plugin modifies the AST, then the plugin should call Parser#invalidateReferences() to force this object to refresh
*/
public get references() {
//build the references object if it's missing.
if (!this._references) {
this.findReferences();
}
return this._references;
}
private _references = new References();
/**
* Invalidates (clears) the references collection. This should be called anytime the AST has been manipulated.
*/
invalidateReferences() {
this._references = undefined;
}
private addPropertyHints(item: Token | AALiteralExpression) {
if (isToken(item)) {
const name = item.text;
this._references.propertyHints[name.toLowerCase()] = name;
} else {
for (const member of item.elements) {
if (!isCommentStatement(member)) {
const name = member.keyToken.text;
if (!name.startsWith('"')) {
this._references.propertyHints[name.toLowerCase()] = name;
}
}
}
}
}
/**
* The list of diagnostics found during the parse process
*/
public diagnostics: Diagnostic[];
/**
* The depth of the calls to function declarations. Helps some checks know if they are at the root or not.
*/
private namespaceAndFunctionDepth: number;
/**
* The options used to parse the file
*/
public options: ParseOptions;
private globalTerminators = [] as TokenKind[][];
/**
* When a FunctionExpression has been started, this gets set. When it's done, this gets unset.
* It's useful for passing the function into statements and expressions that need to be located
* by function later on.
*/
private currentFunctionExpression: FunctionExpression;
/**
* A list of identifiers that are permitted to be used as local variables. We store this in a property because we augment the list in the constructor
* based on the parse mode
*/
private allowedLocalIdentifiers: TokenKind[];
/**
* Annotations collected which should be attached to the next statement
*/
private pendingAnnotations: AnnotationExpression[];
/**
* Get the currently active global terminators
*/
private peekGlobalTerminators() {
return this.globalTerminators[this.globalTerminators.length - 1] ?? [];
}
/**
* Static wrapper around creating a new parser and parsing a list of tokens
*/
public static parse(toParse: Token[] | string, options?: ParseOptions): Parser {
return new Parser().parse(toParse, options);
}
/**
* Parses an array of `Token`s into an abstract syntax tree
* @param toParse the array of tokens to parse. May not contain any whitespace tokens
* @returns the same instance of the parser which contains the diagnostics and statements
*/
public parse(toParse: Token[] | string, options?: ParseOptions) {
let tokens: Token[];
if (typeof toParse === 'string') {
tokens = Lexer.scan(toParse).tokens;
} else {
tokens = toParse;
}
this.logger = options?.logger ?? new Logger();
this.tokens = tokens;
this.options = this.sanitizeParseOptions(options);
this.allowedLocalIdentifiers = [
...AllowedLocalIdentifiers,
//when in plain brightscript mode, the BrighterScript source literals can be used as regular variables
...(this.options.mode === ParseMode.BrightScript ? BrighterScriptSourceLiterals : [])
];
this.current = 0;
this.diagnostics = [];
this.namespaceAndFunctionDepth = 0;
this.pendingAnnotations = [];
this.ast = this.body();
return this;
}
private logger: Logger;
private body() {
const parentAnnotations = this.enterAnnotationBlock();
let body = new Body([]);
if (this.tokens.length > 0) {
this.consumeStatementSeparators(true);
try {
while (
//not at end of tokens
!this.isAtEnd() &&
//the next token is not one of the end terminators
!this.checkAny(...this.peekGlobalTerminators())
) {
let dec = this.declaration();
if (dec) {
if (!isAnnotationExpression(dec)) {
this.consumePendingAnnotations(dec);
body.statements.push(dec);
//ensure statement separator
this.consumeStatementSeparators(false);
} else {
this.consumeStatementSeparators(true);
}
}
}
} catch (parseError) {
//do nothing with the parse error for now. perhaps we can remove this?
console.error(parseError);
}
}
this.exitAnnotationBlock(parentAnnotations);
return body;
}
private sanitizeParseOptions(options: ParseOptions) {
return {
mode: 'brightscript',
...(options || {})
} as ParseOptions;
}
/**
* Determine if the parser is currently parsing tokens at the root level.
*/
private isAtRootLevel() {
return this.namespaceAndFunctionDepth === 0;
}
/**
* Throws an error if the input file type is not BrighterScript
*/
private warnIfNotBrighterScriptMode(featureName: string) {
if (this.options.mode !== ParseMode.BrighterScript) {
let diagnostic = {
...DiagnosticMessages.bsFeatureNotSupportedInBrsFiles(featureName),
range: this.peek().range
} as Diagnostic;
this.diagnostics.push(diagnostic);
}
}
/**
* Throws an exception using the last diagnostic message
*/
private lastDiagnosticAsError() {
let error = new Error(this.diagnostics[this.diagnostics.length - 1]?.message ?? 'Unknown error');
(error as any).isDiagnostic = true;
return error;
}
private declaration(): Statement | AnnotationExpression | undefined {
try {
if (this.checkAny(TokenKind.Sub, TokenKind.Function)) {
return this.functionDeclaration(false);
}
if (this.checkLibrary()) {
return this.libraryStatement();
}
if (this.check(TokenKind.Const) && this.checkAnyNext(TokenKind.Identifier, ...this.allowedLocalIdentifiers)) {
return this.constDeclaration();
}
if (this.check(TokenKind.At) && this.checkNext(TokenKind.Identifier)) {
return this.annotationExpression();
}
if (this.check(TokenKind.Comment)) {
return this.commentStatement();
}
//catch certain global terminators to prevent unnecessary lookahead (i.e. like `end namespace`, no need to continue)
if (this.checkAny(...this.peekGlobalTerminators())) {
return;
}
return this.statement();
} catch (error: any) {
//if the error is not a diagnostic, then log the error for debugging purposes
if (!error.isDiagnostic) {
this.logger.error(error);
}
this.synchronize();
}
}
/**
* Try to get an identifier. If not found, add diagnostic and return undefined
*/
private tryIdentifier(...additionalTokenKinds: TokenKind[]): Identifier | undefined {
const identifier = this.tryConsume(
DiagnosticMessages.expectedIdentifier(),
TokenKind.Identifier,
...additionalTokenKinds
) as Identifier;
if (identifier) {
// force the name into an identifier so the AST makes some sense
identifier.kind = TokenKind.Identifier;
return identifier;
}
}
private identifier(...additionalTokenKinds: TokenKind[]) {
const identifier = this.consume(
DiagnosticMessages.expectedIdentifier(),
TokenKind.Identifier,
...additionalTokenKinds
) as Identifier;
// force the name into an identifier so the AST makes some sense
identifier.kind = TokenKind.Identifier;
return identifier;
}
private enumMemberStatement() {
const statement = new EnumMemberStatement({} as any);
statement.tokens.name = this.consume(
DiagnosticMessages.expectedClassFieldIdentifier(),
TokenKind.Identifier,
...AllowedProperties
) as Identifier;
//look for `= SOME_EXPRESSION`
if (this.check(TokenKind.Equal)) {
statement.tokens.equal = this.advance();
statement.value = this.expression();
}
return statement;
}
/**
* Create a new InterfaceMethodStatement. This should only be called from within `interfaceDeclaration`
*/
private interfaceFieldStatement() {
const name = this.identifier(...AllowedProperties);
let asToken = this.consumeToken(TokenKind.As);
let typeToken = this.typeToken();
const type = util.tokenToBscType(typeToken);
if (!type) {
this.diagnostics.push({
...DiagnosticMessages.functionParameterTypeIsInvalid(name.text, typeToken.text),
range: typeToken.range
});
throw this.lastDiagnosticAsError();
}
return new InterfaceFieldStatement(name, asToken, typeToken, type);
}
/**
* Create a new InterfaceMethodStatement. This should only be called from within `interfaceDeclaration()`
*/
private interfaceMethodStatement() {
const functionType = this.advance();
const name = this.identifier(...AllowedProperties);
const leftParen = this.consumeToken(TokenKind.LeftParen);
const params = [];
const rightParen = this.consumeToken(TokenKind.RightParen);
let asToken = null as Token;
let returnTypeToken = null as Token;
if (this.check(TokenKind.As)) {
asToken = this.advance();
returnTypeToken = this.typeToken();
const returnType = util.tokenToBscType(returnTypeToken);
if (!returnType) {
this.diagnostics.push({
...DiagnosticMessages.functionParameterTypeIsInvalid(name.text, returnTypeToken.text),
range: returnTypeToken.range
});
throw this.lastDiagnosticAsError();
}
}
return new InterfaceMethodStatement(
functionType,
name,
leftParen,
params,
rightParen,
asToken,
returnTypeToken,
util.tokenToBscType(returnTypeToken)
);
}
private interfaceDeclaration(): InterfaceStatement {
this.warnIfNotBrighterScriptMode('interface declarations');
const parentAnnotations = this.enterAnnotationBlock();
const interfaceToken = this.consume(
DiagnosticMessages.expectedKeyword(TokenKind.Interface),
TokenKind.Interface
);
const nameToken = this.identifier();
let extendsToken: Token;
let parentInterfaceName: NamespacedVariableNameExpression;
if (this.peek().text.toLowerCase() === 'extends') {
extendsToken = this.advance();
parentInterfaceName = this.getNamespacedVariableNameExpression();
}
this.consumeStatementSeparators();
//gather up all interface members (Fields, Methods)
let body = [] as Statement[];
while (this.checkAny(TokenKind.Comment, TokenKind.Identifier, TokenKind.At, ...AllowedProperties)) {
try {
let decl: Statement;
//collect leading annotations
if (this.check(TokenKind.At)) {
this.annotationExpression();
}
//fields
if (this.checkAny(TokenKind.Identifier, ...AllowedProperties) && this.checkNext(TokenKind.As)) {
decl = this.interfaceFieldStatement();
//methods (function/sub keyword followed by opening paren)
} else if (this.checkAny(TokenKind.Function, TokenKind.Sub) && this.checkAny(TokenKind.Identifier, ...AllowedProperties)) {
decl = this.interfaceMethodStatement();
//comments
} else if (this.check(TokenKind.Comment)) {
decl = this.commentStatement();
}
if (decl) {
this.consumePendingAnnotations(decl);
body.push(decl);
} else {
//we didn't find a declaration...flag tokens until next line
this.flagUntil(TokenKind.Newline, TokenKind.Colon, TokenKind.Eof);
}
} catch (e) {
//throw out any failed members and move on to the next line
this.flagUntil(TokenKind.Newline, TokenKind.Colon, TokenKind.Eof);
}
//ensure statement separator
this.consumeStatementSeparators();
//break out of this loop if we encountered the `EndInterface` token not followed by `as`
if (this.check(TokenKind.EndInterface) && !this.checkNext(TokenKind.As)) {
break;
}
}
//consume the final `end interface` token
const endInterfaceToken = this.consumeToken(TokenKind.EndInterface);
const statement = new InterfaceStatement(
interfaceToken,
nameToken,
extendsToken,
parentInterfaceName,
body,
endInterfaceToken
);
this._references.interfaceStatements.push(statement);
this.exitAnnotationBlock(parentAnnotations);
return statement;
}
private enumDeclaration(): EnumStatement {
const result = new EnumStatement({} as any, []);
this.warnIfNotBrighterScriptMode('enum declarations');
const parentAnnotations = this.enterAnnotationBlock();
result.tokens.enum = this.consume(
DiagnosticMessages.expectedKeyword(TokenKind.Enum),
TokenKind.Enum
);
result.tokens.name = this.tryIdentifier();
this.consumeStatementSeparators();
//gather up all members
while (this.checkAny(TokenKind.Comment, TokenKind.Identifier, TokenKind.At, ...AllowedProperties)) {
try {
let decl: EnumMemberStatement | CommentStatement;
//collect leading annotations
if (this.check(TokenKind.At)) {
this.annotationExpression();
}
//members
if (this.checkAny(TokenKind.Identifier, ...AllowedProperties)) {
decl = this.enumMemberStatement();
//comments
} else if (this.check(TokenKind.Comment)) {
decl = this.commentStatement();
}
if (decl) {
this.consumePendingAnnotations(decl);
result.body.push(decl);
} else {
//we didn't find a declaration...flag tokens until next line
this.flagUntil(TokenKind.Newline, TokenKind.Colon, TokenKind.Eof);
}
} catch (e) {
//throw out any failed members and move on to the next line
this.flagUntil(TokenKind.Newline, TokenKind.Colon, TokenKind.Eof);
}
//ensure statement separator
this.consumeStatementSeparators();
//break out of this loop if we encountered the `EndEnum` token
if (this.check(TokenKind.EndEnum)) {
break;
}
}
//consume the final `end interface` token
result.tokens.endEnum = this.consumeToken(TokenKind.EndEnum);
this._references.enumStatements.push(result);
this.exitAnnotationBlock(parentAnnotations);
return result;
}
/**
* A BrighterScript class declaration
*/
private classDeclaration(): ClassStatement {
this.warnIfNotBrighterScriptMode('class declarations');
const parentAnnotations = this.enterAnnotationBlock();
let classKeyword = this.consume(
DiagnosticMessages.expectedKeyword(TokenKind.Class),
TokenKind.Class
);
let extendsKeyword: Token;
let parentClassName: NamespacedVariableNameExpression;
//get the class name
let className = this.tryConsume(DiagnosticMessages.expectedIdentifierAfterKeyword('class'), TokenKind.Identifier, ...this.allowedLocalIdentifiers) as Identifier;
//see if the class inherits from parent
if (this.peek().text.toLowerCase() === 'extends') {
extendsKeyword = this.advance();
parentClassName = this.getNamespacedVariableNameExpression();
}
//ensure statement separator
this.consumeStatementSeparators();
//gather up all class members (Fields, Methods)
let body = [] as Statement[];
while (this.checkAny(TokenKind.Public, TokenKind.Protected, TokenKind.Private, TokenKind.Function, TokenKind.Sub, TokenKind.Comment, TokenKind.Identifier, TokenKind.At, ...AllowedProperties)) {
try {
let decl: Statement;
let accessModifier: Token;
if (this.check(TokenKind.At)) {
this.annotationExpression();
}
if (this.checkAny(TokenKind.Public, TokenKind.Protected, TokenKind.Private)) {
//use actual access modifier
accessModifier = this.advance();
}
let overrideKeyword: Token;
if (this.peek().text.toLowerCase() === 'override') {
overrideKeyword = this.advance();
}
//methods (function/sub keyword OR identifier followed by opening paren)
if (this.checkAny(TokenKind.Function, TokenKind.Sub) || (this.checkAny(TokenKind.Identifier, ...AllowedProperties) && this.checkNext(TokenKind.LeftParen))) {
const funcDeclaration = this.functionDeclaration(false, false);
//remove this function from the lists because it's not a callable
const functionStatement = this._references.functionStatements.pop();
//if we have an overrides keyword AND this method is called 'new', that's not allowed
if (overrideKeyword && funcDeclaration.name.text.toLowerCase() === 'new') {
this.diagnostics.push({
...DiagnosticMessages.cannotUseOverrideKeywordOnConstructorFunction(),
range: overrideKeyword.range
});
}
decl = new MethodStatement(
accessModifier,
funcDeclaration.name,
funcDeclaration.func,
overrideKeyword
);
//refer to this statement as parent of the expression
functionStatement.func.functionStatement = decl as MethodStatement;
//fields
} else if (this.checkAny(TokenKind.Identifier, ...AllowedProperties)) {
decl = this.fieldDeclaration(accessModifier);
//class fields cannot be overridden
if (overrideKeyword) {
this.diagnostics.push({
...DiagnosticMessages.classFieldCannotBeOverridden(),
range: overrideKeyword.range
});
}
//comments
} else if (this.check(TokenKind.Comment)) {
decl = this.commentStatement();
}
if (decl) {
this.consumePendingAnnotations(decl);
body.push(decl);
}
} catch (e) {
//throw out any failed members and move on to the next line
this.flagUntil(TokenKind.Newline, TokenKind.Colon, TokenKind.Eof);
}
//ensure statement separator
this.consumeStatementSeparators();
}
let endingKeyword = this.advance();
if (endingKeyword.kind !== TokenKind.EndClass) {
this.diagnostics.push({
...DiagnosticMessages.couldNotFindMatchingEndKeyword('class'),
range: endingKeyword.range
});
}
const result = new ClassStatement(
classKeyword,
className,
body,
endingKeyword,
extendsKeyword,
parentClassName
);
this._references.classStatements.push(result);
this.exitAnnotationBlock(parentAnnotations);
return result;
}
private fieldDeclaration(accessModifier: Token | null) {
let name = this.consume(
DiagnosticMessages.expectedClassFieldIdentifier(),
TokenKind.Identifier,
...AllowedProperties
) as Identifier;
let asToken: Token;
let fieldType: Token;
//look for `as SOME_TYPE`
if (this.check(TokenKind.As)) {
asToken = this.advance();
fieldType = this.typeToken();
//no field type specified
if (!util.tokenToBscType(fieldType)) {
this.diagnostics.push({
...DiagnosticMessages.expectedValidTypeToFollowAsKeyword(),
range: this.peek().range
});
}
}
let initialValue: Expression;
let equal: Token;
//if there is a field initializer
if (this.check(TokenKind.Equal)) {
equal = this.advance();
initialValue = this.expression();
}
return new FieldStatement(
accessModifier,
name,
asToken,
fieldType,
equal,
initialValue
);
}
/**
* An array of CallExpression for the current function body
*/
private callExpressions = [];
private functionDeclaration(isAnonymous: true, checkIdentifier?: boolean, onlyCallableAsMember?: boolean): FunctionExpression;
private functionDeclaration(isAnonymous: false, checkIdentifier?: boolean, onlyCallableAsMember?: boolean): FunctionStatement;
private functionDeclaration(isAnonymous: boolean, checkIdentifier = true, onlyCallableAsMember = false) {
let previousCallExpressions = this.callExpressions;
this.callExpressions = [];
try {
//track depth to help certain statements need to know if they are contained within a function body
this.namespaceAndFunctionDepth++;
let functionType: Token;
if (this.checkAny(TokenKind.Sub, TokenKind.Function)) {
functionType = this.advance();
} else {
this.diagnostics.push({
...DiagnosticMessages.missingCallableKeyword(),
range: this.peek().range
});
functionType = {
isReserved: true,
kind: TokenKind.Function,
text: 'function',
//zero-length location means derived
range: {
start: this.peek().range.start,
end: this.peek().range.start
},
leadingWhitespace: ''
};
}
let isSub = functionType?.kind === TokenKind.Sub;
let functionTypeText = isSub ? 'sub' : 'function';
let name: Identifier;
let leftParen: Token;
if (isAnonymous) {
leftParen = this.consume(
DiagnosticMessages.expectedLeftParenAfterCallable(functionTypeText),
TokenKind.LeftParen
);
} else {
name = this.consume(
DiagnosticMessages.expectedNameAfterCallableKeyword(functionTypeText),
TokenKind.Identifier,
...AllowedProperties
) as Identifier;
leftParen = this.consume(
DiagnosticMessages.expectedLeftParenAfterCallableName(functionTypeText),
TokenKind.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
this.diagnostics.push({
...DiagnosticMessages.functionNameCannotEndWithTypeDesignator(functionTypeText, name.text, lastChar),
range: name.range
});
}
//flag functions with keywords for names (only for standard functions)
if (checkIdentifier && DisallowedFunctionIdentifiersText.has(name.text.toLowerCase())) {
this.diagnostics.push({
...DiagnosticMessages.cannotUseReservedWordAsIdentifier(name.text),
range: name.range
});
}
}
let params = [] as FunctionParameterExpression[];
let asToken: Token;
let typeToken: Token;
if (!this.check(TokenKind.RightParen)) {
do {
if (params.length >= CallExpression.MaximumArguments) {
this.diagnostics.push({
...DiagnosticMessages.tooManyCallableParameters(params.length, CallExpression.MaximumArguments),
range: this.peek().range
});
}
params.push(this.functionParameter());
} while (this.match(TokenKind.Comma));
}
let rightParen = this.advance();
if (this.check(TokenKind.As)) {
asToken = this.advance();
typeToken = this.typeToken();
if (!util.tokenToBscType(typeToken, this.options.mode === ParseMode.BrighterScript)) {
this.diagnostics.push({
...DiagnosticMessages.invalidFunctionReturnType(typeToken.text ?? ''),
range: typeToken.range
});
}
}
params.reduce((haveFoundOptional: boolean, param: FunctionParameterExpression) => {
if (haveFoundOptional && !param.defaultValue) {
this.diagnostics.push({
...DiagnosticMessages.requiredParameterMayNotFollowOptionalParameter(param.name.text),
range: param.range
});
}
return haveFoundOptional || !!param.defaultValue;
}, false);
this.consumeStatementSeparators(true);
let func = new FunctionExpression(
params,
undefined, //body
functionType,
undefined, //ending keyword
leftParen,
rightParen,
asToken,
typeToken,
this.currentFunctionExpression
);
//if there is a parent function, register this function with the parent
if (this.currentFunctionExpression) {
this.currentFunctionExpression.childFunctionExpressions.push(func);
}
// add the function to the relevant symbol tables
if (!onlyCallableAsMember && name) {
const funcType = func.getFunctionType();
funcType.setName(name.text);
}
this._references.functionExpressions.push(func);
let previousFunctionExpression = this.currentFunctionExpression;
this.currentFunctionExpression = func;
//make sure to restore the currentFunctionExpression even if the body block fails to parse
try {
//support ending the function with `end sub` OR `end function`
func.body = this.block();
} finally {
this.currentFunctionExpression = previousFunctionExpression;
}
if (!func.body) {
this.diagnostics.push({
...DiagnosticMessages.callableBlockMissingEndKeyword(functionTypeText),
range: this.peek().range
});
throw this.lastDiagnosticAsError();
}
// consume 'end sub' or 'end function'
func.end = this.advance();
let expectedEndKind = isSub ? TokenKind.EndSub : TokenKind.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 (func.end.kind !== expectedEndKind) {
this.diagnostics.push({
...DiagnosticMessages.mismatchedEndCallableKeyword(functionTypeText, func.end.text),
range: this.peek().range
});
}
func.callExpressions = this.callExpressions;
if (isAnonymous) {
return func;
} else {
let result = new FunctionStatement(name, func);
func.functionStatement = result;
this._references.functionStatements.push(result);
return result;
}
} finally {
this.namespaceAndFunctionDepth--;
//restore the previous CallExpression list
this.callExpressions = previousCallExpressions;
}
}
private functionParameter(): FunctionParameterExpression {
if (!this.checkAny(TokenKind.Identifier, ...this.allowedLocalIdentifiers)) {
this.diagnostics.push({
...DiagnosticMessages.expectedParameterNameButFound(this.peek().text),
range: this.peek().range
});
throw this.lastDiagnosticAsError();
}
let name = this.advance() as Identifier;
// force the name into an identifier so the AST makes some sense
name.kind = TokenKind.Identifier;
let typeToken: Token | undefined;
let defaultValue;
// parse argument default value
if (this.match(TokenKind.Equal)) {
// it seems any expression is allowed here -- including ones that operate on other arguments!
defaultValue = this.expression();
}
let asToken = null;
if (this.check(TokenKind.As)) {
asToken = this.advance();
typeToken = this.typeToken();
if (!util.tokenToBscType(typeToken, this.options.mode === ParseMode.BrighterScript)) {
this.diagnostics.push({
...DiagnosticMessages.functionParameterTypeIsInvalid(name.text, typeToken.text),
range: typeToken.range
});
throw this.lastDiagnosticAsError();
}
}
return new FunctionParameterExpression(
name,
typeToken,
defaultValue,
asToken
);
}
private assignment(): AssignmentStatement {
let name = this.advance() as Identifier;
//add diagnostic if name is a reserved word that cannot be used as an identifier
if (DisallowedLocalIdentifiersText.has(name.text.toLowerCase())) {
this.diagnostics.push({
...DiagnosticMessages.cannotUseReservedWordAsIdentifier(name.text),
range: name.range
});
}