-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathBrsFileValidator.ts
More file actions
762 lines (701 loc) · 38.1 KB
/
BrsFileValidator.ts
File metadata and controls
762 lines (701 loc) · 38.1 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
import { isAliasStatement, isBlock, isBody, isClassStatement, isConditionalCompileConstStatement, isConditionalCompileErrorStatement, isConditionalCompileStatement, isConstStatement, isDottedGetExpression, isDottedSetStatement, isEnumStatement, isForEachStatement, isForStatement, isFunctionExpression, isFunctionStatement, isIfStatement, isImportStatement, isIndexedGetExpression, isIndexedSetStatement, isInterfaceStatement, isInvalidType, isLibraryStatement, isLiteralExpression, isMethodStatement, isNamespaceStatement, isTypecastExpression, isTypecastStatement, isTypeStatement, isUnaryExpression, isVariableExpression, isVoidType, isWhileStatement } from '../../astUtils/reflection';
import { createVisitor, WalkMode } from '../../astUtils/visitors';
import { DiagnosticMessages } from '../../DiagnosticMessages';
import type { BrsFile } from '../../files/BrsFile';
import type { ExtraSymbolData, OnFileValidateEvent } from '../../interfaces';
import { TokenKind } from '../../lexer/TokenKind';
import type { AstNode, Expression, Statement } from '../../parser/AstNode';
import { CallExpression, type FunctionExpression, type LiteralExpression } from '../../parser/Expression';
import { ParseMode } from '../../parser/Parser';
import type { ContinueStatement, EnumMemberStatement, EnumStatement, ForEachStatement, ForStatement, ImportStatement, LibraryStatement, Body, WhileStatement, TypecastStatement, Block, AliasStatement, IfStatement, ConditionalCompileStatement } from '../../parser/Statement';
import { SymbolTypeFlag } from '../../SymbolTypeFlag';
import { ArrayDefaultTypeReferenceType } from '../../types/ReferenceType';
import { AssociativeArrayType } from '../../types/AssociativeArrayType';
import { DynamicType } from '../../types/DynamicType';
import util from '../../util';
import type { Range } from 'vscode-languageserver';
import type { Token } from '../../lexer/Token';
import type { BrightScriptDoc } from '../../parser/BrightScriptDocParser';
import brsDocParser from '../../parser/BrightScriptDocParser';
import { TypeStatementType } from '../../types/TypeStatementType';
export class BrsFileValidator {
constructor(
public event: OnFileValidateEvent<BrsFile>
) {
}
public process() {
const unlinkGlobalSymbolTable = this.event.file.parser.symbolTable.pushParentProvider(() => this.event.program.globalScope.symbolTable);
util.validateTooDeepFile(this.event.file);
// Invalidate cache on this file
// It could have potentially changed before this from plugins, after this, it will not change
// eslint-disable-next-line @typescript-eslint/dot-notation
this.event.file['_cachedLookups'].invalidate();
// make a copy of the bsConsts, because they might be added to
const bsConstsBackup = new Map<string, boolean>(this.event.file.ast.getBsConsts());
this.walk();
this.flagTopLevelStatements();
//only validate the file if it was actually parsed (skip files containing typedefs)
if (!this.event.file.hasTypedef) {
this.validateTopOfFileStatements();
this.validateTypecastStatements();
}
this.event.file.ast.bsConsts = bsConstsBackup;
unlinkGlobalSymbolTable();
}
/**
* Walk the full AST
*/
private walk() {
const isBrighterscript = this.event.file.parser.options.mode === ParseMode.BrighterScript;
const visitor = createVisitor({
MethodStatement: (node) => {
//add the `super` symbol to class methods
if (isClassStatement(node.parent) && node.parent.hasParentClass()) {
const data: ExtraSymbolData = {};
const parentClassType = node.parent.parentClassName.getType({ flags: SymbolTypeFlag.typetime, data: data });
node.func.body.getSymbolTable().addSymbol('super', { ...data, isInstance: true }, parentClassType, SymbolTypeFlag.runtime);
}
},
CallfuncExpression: (node) => {
if (node.args.length > 5) {
this.event.program.diagnostics.register({
...DiagnosticMessages.callfuncHasToManyArgs(node.args.length),
location: node.tokens.methodName.location
});
}
},
EnumStatement: (node) => {
this.validateDeclarationLocations(node, 'enum', () => util.createBoundingRange(node.tokens.enum, node.tokens.name));
this.validateEnumDeclaration(node);
if (!node.tokens.name) {
return;
}
//register this enum declaration
const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
// eslint-disable-next-line no-bitwise
node.parent.getSymbolTable()?.addSymbol(node.tokens.name.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime | SymbolTypeFlag.runtime);
},
ClassStatement: (node) => {
if (!node?.tokens?.name) {
return;
}
this.validateDeclarationLocations(node, 'class', () => util.createBoundingRange(node.tokens.class, node.tokens.name));
//register this class
const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
node.getSymbolTable().addSymbol('m', { definingNode: node, isInstance: true }, nodeType, SymbolTypeFlag.runtime);
// eslint-disable-next-line no-bitwise
node.parent.getSymbolTable()?.addSymbol(node.tokens.name?.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime | SymbolTypeFlag.runtime);
if (node.findAncestor(isNamespaceStatement)) {
//add the transpiled name for namespaced constructors to the root symbol table
const transpiledClassConstructor = node.getName(ParseMode.BrightScript);
this.event.file.parser.ast.symbolTable.addSymbol(
transpiledClassConstructor,
{ definingNode: node },
node.getConstructorType(),
// eslint-disable-next-line no-bitwise
SymbolTypeFlag.runtime | SymbolTypeFlag.postTranspile
);
}
},
AssignmentStatement: (node) => {
if (!node?.tokens?.name) {
return;
}
const data: ExtraSymbolData = {};
//register this variable
let nodeType = node.getType({ flags: SymbolTypeFlag.runtime, data: data });
if (isInvalidType(nodeType) || isVoidType(nodeType)) {
nodeType = DynamicType.instance;
}
node.parent.getSymbolTable()?.addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true, isFromDocComment: data.isFromDocComment, isFromCallFunc: data.isFromCallFunc }, nodeType, SymbolTypeFlag.runtime);
},
DottedSetStatement: (node) => {
this.validateNoOptionalChainingInVarSet(node, [node.obj]);
},
IndexedSetStatement: (node) => {
this.validateNoOptionalChainingInVarSet(node, [node.obj]);
},
ForEachStatement: (node) => {
//register the for loop variable
const loopTargetType = node.target.getType({ flags: SymbolTypeFlag.runtime });
const loopVarType = new ArrayDefaultTypeReferenceType(loopTargetType);
node.parent.getSymbolTable()?.addSymbol(node.tokens.item.text, { definingNode: node, isInstance: true, canUseInDefinedAstNode: true }, loopVarType, SymbolTypeFlag.runtime);
},
NamespaceStatement: (node) => {
if (!node?.nameExpression) {
return;
}
this.validateDeclarationLocations(node, 'namespace', () => util.createBoundingRange(node.tokens.namespace, node.nameExpression));
//Namespace Types are added at the Scope level - This is handled when the SymbolTables get linked
},
FunctionStatement: (node) => {
this.validateDeclarationLocations(node, 'function', () => util.createBoundingRange(node.func.tokens.functionType, node.tokens.name));
const funcType = node.getType({ flags: SymbolTypeFlag.typetime });
if (node.tokens.name?.text) {
node.parent.getSymbolTable().addSymbol(
node.tokens.name.text,
{ definingNode: node },
funcType,
SymbolTypeFlag.runtime
);
}
const namespace = node.findAncestor(isNamespaceStatement);
//this function is declared inside a namespace
if (namespace) {
namespace.getSymbolTable().addSymbol(
node.tokens.name?.text,
{ definingNode: node },
funcType,
SymbolTypeFlag.runtime
);
if (!node.tokens?.name) {
return;
}
//add the transpiled name for namespaced functions to the root symbol table
const transpiledNamespaceFunctionName = node.getName(ParseMode.BrightScript);
this.event.file.parser.ast.symbolTable.addSymbol(
transpiledNamespaceFunctionName,
{ definingNode: node },
funcType,
// eslint-disable-next-line no-bitwise
SymbolTypeFlag.runtime | SymbolTypeFlag.postTranspile
);
}
},
FunctionExpression: (node) => {
const funcSymbolTable = node.getSymbolTable();
const isInlineFunc = !(isFunctionStatement(node.parent) || isMethodStatement(node.parent));
if (isInlineFunc) {
// symbol table should not include any symbols from parent func
funcSymbolTable.pushParentProvider(() => node.findAncestor<Body>(isBody).getSymbolTable());
}
if (!funcSymbolTable?.hasSymbol('m', SymbolTypeFlag.runtime) || isInlineFunc) {
if (!isTypecastStatement(node.body?.statements?.[0])) {
funcSymbolTable?.addSymbol('m', { isInstance: true }, new AssociativeArrayType(), SymbolTypeFlag.runtime);
}
}
this.validateFunctionParameterCount(node);
},
FunctionParameterExpression: (node) => {
const paramName = node.tokens?.name?.text;
if (!paramName) {
return;
}
const data: ExtraSymbolData = {};
const nodeType = node.getType({ flags: SymbolTypeFlag.typetime, data: data });
// add param symbol at expression level, so it can be used as default value in other params
const funcExpr = node.findAncestor<FunctionExpression>(isFunctionExpression);
const funcSymbolTable = funcExpr?.getSymbolTable();
const extraSymbolData: ExtraSymbolData = {
definingNode: node,
isInstance: true,
isFromDocComment: data.isFromDocComment,
description: data.description
};
funcSymbolTable?.addSymbol(paramName, extraSymbolData, nodeType, SymbolTypeFlag.runtime);
//also add param symbol at block level, as it may be redefined, and if so, should show a union
funcExpr.body.getSymbolTable()?.addSymbol(paramName, extraSymbolData, nodeType, SymbolTypeFlag.runtime);
},
InterfaceStatement: (node) => {
if (!node.tokens.name) {
return;
}
this.validateDeclarationLocations(node, 'interface', () => util.createBoundingRange(node.tokens.interface, node.tokens.name));
const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
// eslint-disable-next-line no-bitwise
node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime);
},
ConstStatement: (node) => {
if (!node.tokens.name) {
return;
}
this.validateDeclarationLocations(node, 'const', () => util.createBoundingRange(node.tokens.const, node.tokens.name));
const nodeType = node.getType({ flags: SymbolTypeFlag.runtime });
node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true }, nodeType, SymbolTypeFlag.runtime);
},
CatchStatement: (node) => {
//brs and bs both support variableExpression for the exception variable
if (isVariableExpression(node.exceptionVariableExpression)) {
node.parent.getSymbolTable().addSymbol(
node.exceptionVariableExpression.getName(),
{ definingNode: node, isInstance: true },
//TODO I think we can produce a slightly more specific type here (like an AA but with the known exception properties)
DynamicType.instance,
SymbolTypeFlag.runtime
);
//brighterscript allows catch without an exception variable
} else if (isBrighterscript && !node.exceptionVariableExpression) {
//this is fine
//brighterscript allows a typecast expression here
} else if (isBrighterscript && isTypecastExpression(node.exceptionVariableExpression) && isVariableExpression(node.exceptionVariableExpression.obj)) {
node.parent.getSymbolTable().addSymbol(
node.exceptionVariableExpression.obj.getName(),
{ definingNode: node, isInstance: true },
node.exceptionVariableExpression.getType({ flags: SymbolTypeFlag.runtime }),
SymbolTypeFlag.runtime
);
//no other expressions are allowed here
} else {
this.event.program.diagnostics.register({
...DiagnosticMessages.expectedExceptionVarToFollowCatch(),
location: node.exceptionVariableExpression?.location ?? node.tokens.catch?.location
});
}
},
DimStatement: (node) => {
if (node.tokens.name) {
node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true }, node.getType({ flags: SymbolTypeFlag.runtime }), SymbolTypeFlag.runtime);
}
},
ReturnStatement: (node) => {
const func = node.findAncestor<FunctionExpression>(isFunctionExpression);
//these situations cannot have a value next to `return`
if (
//`function as void`, `sub as void`
(isVariableExpression(func?.returnTypeExpression?.expression) && func.returnTypeExpression.expression.tokens.name.text?.toLowerCase() === 'void') ||
//`sub` <without return value>
(func.tokens.functionType?.kind === TokenKind.Sub && !func.returnTypeExpression)
) {
//there may not be a return value
if (node.value) {
this.event.program.diagnostics.register({
...DiagnosticMessages.voidFunctionMayNotReturnValue(func.tokens.functionType?.text),
location: node.location
});
}
} else {
//there MUST be a return value
if (!node.value) {
this.event.program.diagnostics.register({
...DiagnosticMessages.nonVoidFunctionMustReturnValue(func?.tokens.functionType?.text),
location: node.location
});
}
}
},
ContinueStatement: (node) => {
this.validateContinueStatement(node);
},
TypecastStatement: (node) => {
node.parent.getSymbolTable().addSymbol('m', { definingNode: node, doNotMerge: true, isInstance: true }, node.getType({ flags: SymbolTypeFlag.typetime }), SymbolTypeFlag.runtime);
},
ConditionalCompileConstStatement: (node) => {
const assign = node.assignment;
const constNameLower = assign.tokens.name?.text.toLowerCase();
const astBsConsts = this.event.file.ast.bsConsts;
if (isLiteralExpression(assign.value)) {
astBsConsts.set(constNameLower, assign.value.tokens.value.text.toLowerCase() === 'true');
} else if (isVariableExpression(assign.value)) {
if (this.validateConditionalCompileConst(assign.value.tokens.name)) {
astBsConsts.set(constNameLower, astBsConsts.get(assign.value.tokens.name.text.toLowerCase()));
}
}
},
ConditionalCompileStatement: (node) => {
this.validateConditionalCompileConst(node.tokens.condition);
},
ConditionalCompileErrorStatement: (node) => {
this.event.program.diagnostics.register({
...DiagnosticMessages.hashError(node.tokens.message.text),
location: node.location
});
},
AliasStatement: (node) => {
// eslint-disable-next-line no-bitwise
const targetType = node.value.getType({ flags: SymbolTypeFlag.typetime | SymbolTypeFlag.runtime });
// eslint-disable-next-line no-bitwise
node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node, doNotMerge: true, isAlias: true }, targetType, SymbolTypeFlag.runtime | SymbolTypeFlag.typetime);
},
TypeStatement: (node) => {
this.validateDeclarationLocations(node, 'type', () => util.createBoundingRange(node.tokens.type, node.tokens.name));
const wrappedNodeType = node.getType({ flags: SymbolTypeFlag.runtime });
const typeStmtType = new TypeStatementType(node.tokens.name.text, wrappedNodeType);
node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node, isFromTypeStatement: true }, typeStmtType, SymbolTypeFlag.typetime);
},
IfStatement: (node) => {
this.setUpComplementSymbolTables(node, isIfStatement);
},
Block: (node) => {
const blockSymbolTable = node.symbolTable;
if (node.findAncestor<Block>(isFunctionExpression)) {
// this block is in a function. order matters!
blockSymbolTable.isOrdered = true;
}
if (!isFunctionExpression(node.parent) && node.parent) {
node.symbolTable.name = `Block-${node.parent.kind}@${node.location?.range?.start?.line}`;
// we're a block inside another block (or body). This block is a pocket in the bigger block
node.parent.getSymbolTable().addPocketTable({
index: node.parent.statementIndex,
table: node.symbolTable,
// code always flows through ConditionalCompiles, because we walk according to defined BSConsts
willAlwaysBeExecuted: isConditionalCompileStatement(node.parent)
});
}
},
AstNode: (node) => {
//check for doc comments
if (!node.leadingTrivia || node.leadingTrivia.length === 0) {
return;
}
const doc = brsDocParser.parseNode(node);
if (doc.tags.length === 0) {
return;
}
let funcExpr = node.findAncestor<FunctionExpression>(isFunctionExpression);
if (funcExpr) {
// handle comment tags inside a function expression
this.processDocTagsInFunction(doc, node, funcExpr);
} else {
//handle comment tags outside of a function expression
this.processDocTagsAtTopLevel(doc, node);
}
}
});
this.event.file.ast.walk((node, parent) => {
visitor(node, parent);
}, {
walkMode: WalkMode.visitAllRecursive
});
}
private processDocTagsInFunction(doc: BrightScriptDoc, node: AstNode, funcExpr: FunctionExpression) {
//TODO: Handle doc tags that influence the function they're in
// For example, declaring variable types:
// const symbolTable = funcExpr.body.getSymbolTable();
// for (const varTag of doc.getAllTags(BrsDocTagKind.Var)) {
// const varName = (varTag as BrsDocParamTag).name;
// const varTypeStr = (varTag as BrsDocParamTag).type;
// const data: ExtraSymbolData = {};
// const type = doc.getTypeFromContext(varTypeStr, node, { flags: SymbolTypeFlag.typetime, fullName: varTypeStr, data: data, tableProvider: () => symbolTable });
// if (type) {
// symbolTable.addSymbol(varName, { ...data, isFromDocComment: true }, type, SymbolTypeFlag.runtime);
// }
// }
}
private processDocTagsAtTopLevel(doc: BrightScriptDoc, node: AstNode) {
//TODO:
// - handle import statements?
// - handle library statements?
// - handle typecast statements?
// - handle alias statements?
// - handle const statements?
// - allow interface definitions?
}
/**
* Validate that a statement is defined in one of these specific locations
* - the root of the AST
* - inside a namespace
* This is applicable to things like FunctionStatement, ClassStatement, NamespaceStatement, EnumStatement, InterfaceStatement
*/
private validateDeclarationLocations(statement: Statement, keyword: string, rangeFactory?: () => (Range | undefined)) {
//if nested inside a namespace, or defined at the root of the AST (i.e. in a body that has no parent)
const isOkDeclarationLocation = (parentNode) => {
return isNamespaceStatement(parentNode?.parent) || (isBody(parentNode) && !parentNode?.parent);
};
if (isOkDeclarationLocation(statement.parent)) {
return;
}
// is this in a top levelconditional compile?
if (isConditionalCompileStatement(statement.parent?.parent)) {
if (isOkDeclarationLocation(statement.parent.parent.parent)) {
return;
}
}
//the statement was defined in the wrong place. Flag it.
this.event.program.diagnostics.register({
...DiagnosticMessages.keywordMustBeDeclaredAtNamespaceLevel(keyword),
location: rangeFactory ? util.createLocationFromFileRange(this.event.file, rangeFactory()) : statement.location
});
}
private validateFunctionParameterCount(func: FunctionExpression) {
if (func.parameters.length > CallExpression.MaximumArguments) {
//flag every parameter over the limit
for (let i = CallExpression.MaximumArguments; i < func.parameters.length; i++) {
this.event.program.diagnostics.register({
...DiagnosticMessages.tooManyCallableParameters(func.parameters.length, CallExpression.MaximumArguments),
location: func.parameters[i]?.tokens.name?.location ?? func.parameters[i]?.location ?? func.location
});
}
}
}
private validateEnumDeclaration(stmt: EnumStatement) {
const members = stmt.getMembers();
//the enum data type is based on the first member value
const enumValueKind = (members.find(x => x.value)?.value as LiteralExpression)?.tokens?.value?.kind ?? TokenKind.IntegerLiteral;
const memberNames = new Set<string>();
for (const member of members) {
const memberNameLower = member.name?.toLowerCase();
/**
* flag duplicate member names
*/
if (memberNames.has(memberNameLower)) {
this.event.program.diagnostics.register({
...DiagnosticMessages.duplicateIdentifier(member.name),
location: member.location
});
} else {
memberNames.add(memberNameLower);
}
//Enforce all member values are the same type
this.validateEnumValueTypes(member, enumValueKind);
}
}
private validateEnumValueTypes(member: EnumMemberStatement, enumValueKind: TokenKind) {
let memberValueKind: TokenKind;
let memberValue: Expression;
if (isUnaryExpression(member.value)) {
memberValueKind = (member.value?.right as LiteralExpression)?.tokens?.value?.kind;
memberValue = member.value?.right;
} else {
memberValueKind = (member.value as LiteralExpression)?.tokens?.value?.kind;
memberValue = member.value;
}
const range = (memberValue ?? member)?.location?.range;
if (
//is integer enum, has value, that value type is not integer
(enumValueKind === TokenKind.IntegerLiteral && memberValueKind && memberValueKind !== enumValueKind) ||
//has value, that value is not a literal
(memberValue && !isLiteralExpression(memberValue))
) {
this.event.program.diagnostics.register({
...DiagnosticMessages.enumValueMustBeType(
enumValueKind.replace(/literal$/i, '').toLowerCase()
),
location: util.createLocationFromFileRange(this.event.file, range)
});
}
//is non integer value
if (enumValueKind !== TokenKind.IntegerLiteral) {
//default value present
if (memberValueKind) {
//member value is same as enum
if (memberValueKind !== enumValueKind) {
this.event.program.diagnostics.register({
...DiagnosticMessages.enumValueMustBeType(
enumValueKind.replace(/literal$/i, '').toLowerCase()
),
location: util.createLocationFromFileRange(this.event.file, range)
});
}
//default value missing
} else {
this.event.program.diagnostics.register({
...DiagnosticMessages.enumValueIsRequired(
enumValueKind.replace(/literal$/i, '').toLowerCase()
),
location: util.createLocationFromFileRange(this.event.file, range)
});
}
}
}
private validateConditionalCompileConst(ccConst: Token) {
const isBool = ccConst.kind === TokenKind.True || ccConst.kind === TokenKind.False;
if (!isBool && !this.event.file.ast.bsConsts.has(ccConst.text.toLowerCase())) {
this.event.program.diagnostics.register({
...DiagnosticMessages.hashConstDoesNotExist(),
location: ccConst.location
});
return false;
}
return true;
}
/**
* Find statements defined at the top level (or inside a namespace body) that are not allowed to be there
*/
private flagTopLevelStatements() {
const statements = [...this.event.file.ast.statements];
while (statements.length > 0) {
const statement = statements.pop();
if (isNamespaceStatement(statement)) {
statements.push(...statement.body.statements);
} else {
//only allow these statement types
if (
!isFunctionStatement(statement) &&
!isClassStatement(statement) &&
!isEnumStatement(statement) &&
!isInterfaceStatement(statement) &&
!isLibraryStatement(statement) &&
!isImportStatement(statement) &&
!isConstStatement(statement) &&
!isTypecastStatement(statement) &&
!isConditionalCompileConstStatement(statement) &&
!isConditionalCompileErrorStatement(statement) &&
!isConditionalCompileStatement(statement) &&
!isAliasStatement(statement) &&
!isTypeStatement(statement)
) {
this.event.program.diagnostics.register({
...DiagnosticMessages.unexpectedStatementOutsideFunction(),
location: statement.location
});
}
}
}
}
private getTopOfFileStatements() {
let topOfFileIncludeStatements = [] as Array<LibraryStatement | ImportStatement | TypecastStatement | AliasStatement>;
for (let stmt of this.event.file.parser.ast.statements) {
//if we found a non-library statement, this statement is not at the top of the file
if (isLibraryStatement(stmt) || isImportStatement(stmt) || isTypecastStatement(stmt) || isAliasStatement(stmt)) {
topOfFileIncludeStatements.push(stmt);
} else {
//break out of the loop, we found all of our library statements
break;
}
}
return topOfFileIncludeStatements;
}
private validateTopOfFileStatements() {
let topOfFileStatements = this.getTopOfFileStatements();
let statements = [
// eslint-disable-next-line @typescript-eslint/dot-notation
...this.event.file['_cachedLookups'].libraryStatements,
// eslint-disable-next-line @typescript-eslint/dot-notation
...this.event.file['_cachedLookups'].importStatements,
// eslint-disable-next-line @typescript-eslint/dot-notation
...this.event.file['_cachedLookups'].aliasStatements
];
for (let result of statements) {
//if this statement is not one of the top-of-file statements,
//then add a diagnostic explaining that it is invalid
if (!topOfFileStatements.includes(result)) {
if (isLibraryStatement(result)) {
this.event.program.diagnostics.register({
...DiagnosticMessages.unexpectedStatementLocation('library', 'at the top of the file'),
location: result.location
});
} else if (isImportStatement(result)) {
this.event.program.diagnostics.register({
...DiagnosticMessages.unexpectedStatementLocation('import', 'at the top of the file'),
location: result.location
});
} else if (isAliasStatement(result)) {
this.event.program.diagnostics.register({
...DiagnosticMessages.unexpectedStatementLocation('alias', 'at the top of the file'),
location: result.location
});
}
}
}
}
private validateTypecastStatements() {
let topOfFileTypecastStatements = this.getTopOfFileStatements().filter(stmt => isTypecastStatement(stmt));
//check only one `typecast` statement at "top" of file (eg. before non import/library statements)
for (let i = 1; i < topOfFileTypecastStatements.length; i++) {
const typecastStmt = topOfFileTypecastStatements[i];
this.event.program.diagnostics.register({
...DiagnosticMessages.unexpectedStatementLocation('typecast', 'at the top of the file or beginning of function or namespace'),
location: typecastStmt.location
});
}
// eslint-disable-next-line @typescript-eslint/dot-notation
for (let result of this.event.file['_cachedLookups'].typecastStatements) {
let isBadTypecastObj = false;
if (!isVariableExpression(result.typecastExpression.obj)) {
isBadTypecastObj = true;
} else if (result.typecastExpression.obj.tokens.name.text.toLowerCase() !== 'm') {
isBadTypecastObj = true;
}
if (isBadTypecastObj) {
this.event.program.diagnostics.register({
...DiagnosticMessages.invalidTypecastStatementApplication(util.getAllDottedGetPartsAsString(result.typecastExpression.obj)),
location: result.typecastExpression.obj.location
});
}
if (topOfFileTypecastStatements.includes(result)) {
// already validated
continue;
}
const block = result.findAncestor<Body | Block>(node => (isBody(node) || isBlock(node)));
const isFirst = block?.statements[0] === result;
const isAllowedBlock = (isBody(block) || isFunctionExpression(block.parent) || isNamespaceStatement(block.parent));
if (!isFirst || !isAllowedBlock) {
this.event.program.diagnostics.register({
...DiagnosticMessages.unexpectedStatementLocation('typecast', 'at the top of the file or beginning of function or namespace'),
location: result.location
});
}
}
}
private validateContinueStatement(statement: ContinueStatement) {
const validateLoopTypeMatch = (expectedLoopType: TokenKind) => {
//coerce ForEach to For
expectedLoopType = expectedLoopType === TokenKind.ForEach ? TokenKind.For : expectedLoopType;
const actualLoopType = statement.tokens.loopType;
if (actualLoopType && expectedLoopType?.toLowerCase() !== actualLoopType.text?.toLowerCase()) {
this.event.program.diagnostics.register({
location: statement.tokens.loopType.location,
...DiagnosticMessages.expectedToken(expectedLoopType)
});
}
};
//find the parent loop statement
const parent = statement.findAncestor<WhileStatement | ForStatement | ForEachStatement>((node) => {
if (isWhileStatement(node)) {
validateLoopTypeMatch(node.tokens.while.kind);
return true;
} else if (isForStatement(node)) {
validateLoopTypeMatch(node.tokens.for.kind);
return true;
} else if (isForEachStatement(node)) {
validateLoopTypeMatch(node.tokens.forEach.kind);
return true;
}
});
//flag continue statements found outside of a loop
if (!parent) {
this.event.program.diagnostics.register({
location: statement.location,
...DiagnosticMessages.illegalContinueStatement()
});
}
}
/**
* Validate that there are no optional chaining operators on the left-hand-side of an assignment, indexed set, or dotted get
*/
private validateNoOptionalChainingInVarSet(parent: AstNode, children: AstNode[]) {
const nodes = [...children, parent];
//flag optional chaining anywhere in the left of this statement
while (nodes.length > 0) {
const node = nodes.shift();
if (
// a?.b = true or a.b?.c = true
((isDottedSetStatement(node) || isDottedGetExpression(node)) && node.tokens.dot?.kind === TokenKind.QuestionDot) ||
// a.b?[2] = true
(isIndexedGetExpression(node) && (node?.tokens.questionDot?.kind === TokenKind.QuestionDot || node.tokens.openingSquare?.kind === TokenKind.QuestionLeftSquare)) ||
// a?[1] = true
(isIndexedSetStatement(node) && node.tokens.openingSquare?.kind === TokenKind.QuestionLeftSquare)
) {
//try to highlight the entire left-hand-side expression if possible
let range: Range;
if (isDottedSetStatement(parent)) {
range = util.createBoundingRange(parent.obj?.location, parent.tokens.dot, parent.tokens.name);
} else if (isIndexedSetStatement(parent)) {
range = util.createBoundingRange(parent.obj?.location, parent.tokens.openingSquare, ...parent.indexes, parent.tokens.closingSquare);
} else {
range = node.location?.range;
}
this.event.program.diagnostics.register({
...DiagnosticMessages.noOptionalChainingInLeftHandSideOfAssignment(),
location: util.createLocationFromFileRange(this.event.file, range)
});
}
if (node === parent) {
break;
} else {
nodes.push(node.parent);
}
}
}
private setUpComplementSymbolTables(node: IfStatement | ConditionalCompileStatement, predicate: (node: AstNode) => boolean) {
if (isBlock(node.elseBranch)) {
const elseTable = node.elseBranch.symbolTable;
let currentNode = node;
while (predicate(currentNode)) {
const thenBranch = (currentNode as IfStatement | ConditionalCompileStatement).thenBranch;
elseTable.complementOtherTable(thenBranch.symbolTable);
currentNode = currentNode.parent as IfStatement | ConditionalCompileStatement;
}
}
}
}