-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathScopeValidator.ts
More file actions
1642 lines (1486 loc) · 79.5 KB
/
ScopeValidator.ts
File metadata and controls
1642 lines (1486 loc) · 79.5 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 { DiagnosticTag, type Range } from 'vscode-languageserver';
import { isAliasStatement, isArrayType, isAssignmentStatement, isAssociativeArrayType, isBinaryExpression, isBooleanTypeLike, isBrsFile, isCallExpression, isCallFuncableTypeLike, isCallableType, isCallfuncExpression, isClassStatement, isClassType, isComponentType, isCompoundType, isDottedGetExpression, isDynamicType, isEnumMemberType, isEnumType, isFunctionExpression, isFunctionParameterExpression, isIterableType, isLiteralExpression, isNamespaceStatement, isNamespaceType, isNewExpression, isNumberTypeLike, isObjectType, isPrimitiveType, isReferenceType, isReturnStatement, isStringTypeLike, isTypeStatementType, isTypedFunctionType, isUnionType, isVariableExpression, isVoidType, isXmlScope } from '../../astUtils/reflection';
import type { DiagnosticInfo } from '../../DiagnosticMessages';
import { DiagnosticMessages } from '../../DiagnosticMessages';
import type { BrsFile } from '../../files/BrsFile';
import type { BsDiagnostic, CallableContainer, ExtraSymbolData, FileReference, GetTypeOptions, ValidateScopeEvent, TypeChainEntry, TypeChainProcessResult, TypeCompatibilityData } from '../../interfaces';
import { SymbolTypeFlag } from '../../SymbolTypeFlag';
import type { AssignmentStatement, AugmentedAssignmentStatement, ClassStatement, DottedSetStatement, ForEachStatement, ForStatement, IncrementStatement, NamespaceStatement, ReturnStatement } from '../../parser/Statement';
import { util } from '../../util';
import { nodes, components } from '../../roku-types';
import type { BRSComponentData } from '../../roku-types';
import type { Token } from '../../lexer/Token';
import { AstNodeKind } from '../../parser/AstNode';
import type { AstNode } from '../../parser/AstNode';
import type { Expression } from '../../parser/AstNode';
import type { VariableExpression, DottedGetExpression, BinaryExpression, UnaryExpression, NewExpression, LiteralExpression, FunctionExpression, CallfuncExpression } from '../../parser/Expression';
import { CallExpression } from '../../parser/Expression';
import { createVisitor, WalkMode } from '../../astUtils/visitors';
import type { BscType } from '../../types/BscType';
import type { BscFile } from '../../files/BscFile';
import { InsideSegmentWalkMode } from '../../AstValidationSegmenter';
import { TokenKind } from '../../lexer/TokenKind';
import { ParseMode } from '../../parser/Parser';
import { BsClassValidator } from '../../validators/ClassValidator';
import { globalCallableMap } from '../../globalCallables';
import type { XmlScope } from '../../XmlScope';
import type { XmlFile } from '../../files/XmlFile';
import { SGFieldTypes } from '../../parser/SGTypes';
import { DynamicType } from '../../types/DynamicType';
import { BscTypeKind } from '../../types/BscTypeKind';
import type { BrsDocWithType } from '../../parser/BrightScriptDocParser';
import brsDocParser from '../../parser/BrightScriptDocParser';
import type { Location } from 'vscode-languageserver';
import { InvalidType } from '../../types/InvalidType';
import { VoidType } from '../../types/VoidType';
import { LogLevel } from '../../Logger';
import { Stopwatch } from '../../Stopwatch';
import chalk from 'chalk';
import { IntegerType } from '../../types/IntegerType';
/**
* The lower-case names of all platform-included scenegraph nodes
*/
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const platformNodeNames = nodes ? new Set((Object.values(nodes) as { name: string }[]).map(x => x?.name.toLowerCase())) : new Set();
const platformComponentNames = components ? new Set((Object.values(components) as { name: string }[]).map(x => x?.name.toLowerCase())) : new Set();
const enum ScopeValidatorDiagnosticTag {
Imports = 'ScopeValidatorImports',
NamespaceCollisions = 'ScopeValidatorNamespaceCollisions',
DuplicateFunctionDeclaration = 'ScopeValidatorDuplicateFunctionDeclaration',
FunctionCollisions = 'ScopeValidatorFunctionCollisions',
Classes = 'ScopeValidatorClasses',
XMLInterface = 'ScopeValidatorXML',
XMLImports = 'ScopeValidatorXMLImports',
Default = 'ScopeValidator',
Segment = 'ScopeValidatorSegment'
}
/**
* A validator that handles all scope validations for a program validation cycle.
* You should create ONE of these to handle all scope events between beforeValidateProgram and afterValidateProgram,
* and call reset() before using it again in the next cycle
*/
export class ScopeValidator {
/**
* The event currently being processed. This will change multiple times throughout the lifetime of this validator
*/
private event: ValidateScopeEvent;
private segmentsMetrics = new Map<string, { segments: number; time: string }>();
private validationKindsMetrics = new Map<string, { timeMs: number; count: number }>();
public processEvent(event: ValidateScopeEvent) {
this.event = event;
if (this.event.program.globalScope === this.event.scope) {
return;
}
const logger = this.event.program.logger;
const metrics = {
fileWalkTime: '',
flagDuplicateFunctionTime: '',
classValidationTime: '',
scriptImportValidationTime: '',
xmlValidationTime: ''
};
this.segmentsMetrics.clear();
this.validationKindsMetrics.clear();
const validationStopwatch = new Stopwatch();
logger.time(LogLevel.debug, ['Validating scope', this.event.scope.name], () => {
metrics.fileWalkTime = validationStopwatch.getDurationTextFor(() => {
this.walkFiles();
}).durationText;
this.currentSegmentBeingValidated = null;
metrics.flagDuplicateFunctionTime = validationStopwatch.getDurationTextFor(() => {
this.flagDuplicateFunctionDeclarations();
}).durationText;
metrics.scriptImportValidationTime = validationStopwatch.getDurationTextFor(() => {
this.validateScriptImportPaths();
}).durationText;
metrics.classValidationTime = validationStopwatch.getDurationTextFor(() => {
this.validateClasses();
}).durationText;
metrics.xmlValidationTime = validationStopwatch.getDurationTextFor(() => {
if (isXmlScope(this.event.scope)) {
//detect when the child imports a script that its ancestor also imports
this.diagnosticDetectDuplicateAncestorScriptImports(this.event.scope);
//validate component interface
this.validateXmlInterface(this.event.scope);
}
}).durationText;
});
logger.debug(this.event.scope.name, 'segment metrics:');
let totalSegments = 0;
for (const [filePath, metric] of this.segmentsMetrics) {
this.event.program.logger.debug(' - ', filePath, metric.segments, metric.time);
totalSegments += metric.segments;
}
logger.debug(this.event.scope.name, 'total segments validated', totalSegments);
this.logValidationMetrics(metrics);
}
// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style
private logValidationMetrics(metrics: { [key: string]: number | string }) {
let logs = [] as string[];
for (let key in metrics) {
logs.push(`${key}=${chalk.yellow(metrics[key].toString())}`);
}
this.event.program.logger.debug(`Validation Metrics (Scope: ${this.event.scope.name}): ${logs.join(', ')}`);
let kindsLogs = [] as string[];
const kindsArray = Array.from(this.validationKindsMetrics.keys()).sort();
for (let key of kindsArray) {
const timeData = this.validationKindsMetrics.get(key);
kindsLogs.push(`${key}=${chalk.yellow(timeData.timeMs.toFixed(3).toString()) + 'ms'} (${timeData.count})`);
}
this.event.program.logger.debug(`Validation Walk Metrics (Scope: ${this.event.scope.name}): ${kindsLogs.join(', ')}`);
}
public reset() {
this.event = undefined;
}
private walkFiles() {
const hasChangeInfo = this.event.changedFiles && this.event.changedSymbols;
//do many per-file checks for every file in this (and parent) scopes
this.event.scope.enumerateBrsFiles((file) => {
if (!isBrsFile(file)) {
return;
}
const thisFileHasChanges = this.event.changedFiles.includes(file);
if (thisFileHasChanges || this.doesFileProvideChangedSymbol(file, this.event.changedSymbols)) {
this.diagnosticDetectFunctionCollisions(file);
}
});
const fileWalkStopWatch = new Stopwatch();
this.event.scope.enumerateOwnFiles((file) => {
if (isBrsFile(file)) {
if (this.event.program.diagnostics.shouldFilterFile(file)) {
return;
}
fileWalkStopWatch.reset();
fileWalkStopWatch.start();
const fileUri = util.pathToUri(file.srcPath);
const thisFileHasChanges = this.event.changedFiles.includes(file);
const hasUnvalidatedSegments = file.validationSegmenter.hasUnvalidatedSegments();
if (hasChangeInfo && !hasUnvalidatedSegments) {
return;
}
const validationVisitor = createVisitor({
VariableExpression: (varExpr) => {
this.addValidationKindMetric('VariableExpression', () => {
this.validateVariableAndDottedGetExpressions(file, varExpr);
});
},
DottedGetExpression: (dottedGet) => {
this.addValidationKindMetric('DottedGetExpression', () => {
this.validateVariableAndDottedGetExpressions(file, dottedGet);
});
},
CallExpression: (functionCall) => {
this.addValidationKindMetric('CallExpression', () => {
this.validateCallExpression(file, functionCall);
this.validateCreateObjectCall(file, functionCall);
this.validateComponentMethods(file, functionCall);
});
},
CallfuncExpression: (functionCall) => {
this.addValidationKindMetric('CallfuncExpression', () => {
this.validateCallFuncExpression(file, functionCall);
});
},
ReturnStatement: (returnStatement) => {
this.addValidationKindMetric('ReturnStatement', () => {
this.validateReturnStatement(file, returnStatement);
});
},
DottedSetStatement: (dottedSetStmt) => {
this.addValidationKindMetric('DottedSetStatement', () => {
this.validateDottedSetStatement(file, dottedSetStmt);
});
},
BinaryExpression: (binaryExpr) => {
this.addValidationKindMetric('BinaryExpression', () => {
this.validateBinaryExpression(file, binaryExpr);
});
},
UnaryExpression: (unaryExpr) => {
this.addValidationKindMetric('UnaryExpression', () => {
this.validateUnaryExpression(file, unaryExpr);
});
},
AssignmentStatement: (assignStmt) => {
this.addValidationKindMetric('AssignmentStatement', () => {
this.validateAssignmentStatement(file, assignStmt);
// Note: this also includes For statements
this.detectShadowedLocalVar(file, {
expr: assignStmt,
name: assignStmt.tokens.name.text,
type: this.getNodeTypeWrapper(file, assignStmt, { flags: SymbolTypeFlag.runtime }),
nameRange: assignStmt.tokens.name.location?.range
});
});
},
AugmentedAssignmentStatement: (binaryExpr) => {
this.addValidationKindMetric('AugmentedAssignmentStatement', () => {
this.validateBinaryExpression(file, binaryExpr);
});
},
IncrementStatement: (stmt) => {
this.addValidationKindMetric('IncrementStatement', () => {
this.validateIncrementStatement(file, stmt);
});
},
NewExpression: (newExpr) => {
this.addValidationKindMetric('NewExpression', () => {
this.validateNewExpression(file, newExpr);
});
},
ForEachStatement: (forEachStmt) => {
this.addValidationKindMetric('ForEachStatement', () => {
this.detectShadowedLocalVar(file, {
expr: forEachStmt,
name: forEachStmt.tokens.item.text,
type: this.getNodeTypeWrapper(file, forEachStmt, { flags: SymbolTypeFlag.runtime }),
nameRange: forEachStmt.tokens.item.location?.range
});
this.validateForEachStatement(file, forEachStmt);
});
},
FunctionParameterExpression: (funcParam) => {
this.addValidationKindMetric('FunctionParameterExpression', () => {
this.detectShadowedLocalVar(file, {
expr: funcParam,
name: funcParam.tokens.name.text,
type: this.getNodeTypeWrapper(file, funcParam, { flags: SymbolTypeFlag.runtime }),
nameRange: funcParam.tokens.name.location?.range
});
});
},
FunctionExpression: (func) => {
if (file.isTypedef) {
return;
}
this.addValidationKindMetric('FunctionExpression', () => {
this.validateFunctionExpressionForReturn(func);
});
},
ForStatement: (forStmt) => {
this.addValidationKindMetric('ForStatement', () => {
this.validateForStatement(file, forStmt);
});
},
AstNode: (node) => {
//check for doc comments
if (!node.leadingTrivia || node.leadingTrivia.filter(triviaToken => triviaToken.kind === TokenKind.Comment).length === 0) {
return;
}
this.addValidationKindMetric('AstNode', () => {
this.validateDocComments(node);
});
}
});
// validate only what's needed in the file
const segmentsToWalkForValidation = thisFileHasChanges
? file.validationSegmenter.getAllUnvalidatedSegments()
: file.validationSegmenter.getSegmentsWithChangedSymbols(this.event.changedSymbols);
let segmentsValidated = 0;
if (thisFileHasChanges) {
// clear all ScopeValidatorSegment diagnostics for this file
this.event.program.diagnostics.clearByFilter({ scope: this.event.scope, fileUri: fileUri, tag: ScopeValidatorDiagnosticTag.Segment });
}
for (const segment of segmentsToWalkForValidation) {
if (!thisFileHasChanges && !file.validationSegmenter.checkIfSegmentNeedsRevalidation(segment, this.event.changedSymbols)) {
continue;
}
this.currentSegmentBeingValidated = segment;
if (!thisFileHasChanges) {
// just clear the affected diagnostics
this.event.program.diagnostics.clearByFilter({ scope: this.event.scope, fileUri: fileUri, segment: segment, tag: ScopeValidatorDiagnosticTag.Segment });
}
segmentsValidated++;
segment.walk(validationVisitor, {
walkMode: InsideSegmentWalkMode
});
file.markSegmentAsValidated(segment);
this.currentSegmentBeingValidated = null;
}
fileWalkStopWatch.stop();
const timeString = fileWalkStopWatch.getDurationText();
this.segmentsMetrics.set(file.pkgPath, { segments: segmentsValidated, time: timeString });
}
});
}
private addValidationKindMetric(name: string, funcToTime: () => void) {
if (!this.validationKindsMetrics.has(name)) {
this.validationKindsMetrics.set(name, { timeMs: 0, count: 0 });
}
const timeData = this.validationKindsMetrics.get(name);
const validationKindStopWatch = new Stopwatch();
validationKindStopWatch.start();
funcToTime();
validationKindStopWatch.stop();
this.validationKindsMetrics.set(name, { timeMs: timeData.timeMs + validationKindStopWatch.totalMilliseconds, count: timeData.count + 1 });
}
private doesFileProvideChangedSymbol(file: BrsFile, changedSymbols: Map<SymbolTypeFlag, Set<string>>) {
if (!changedSymbols) {
return true;
}
for (const flag of [SymbolTypeFlag.runtime, SymbolTypeFlag.typetime]) {
const providedSymbolKeysFlag = file.providedSymbols.symbolMap.get(flag).keys();
const changedSymbolSetForFlag = changedSymbols.get(flag);
for (let providedKey of providedSymbolKeysFlag) {
if (changedSymbolSetForFlag.has(providedKey)) {
return true;
}
}
}
return false;
}
private currentSegmentBeingValidated: AstNode;
private isTypeKnown(exprType: BscType) {
let isKnownType = exprType?.isResolvable();
return isKnownType;
}
private getCircularReference(exprType: BscType) {
if (exprType?.isResolvable()) {
return { isCircularReference: false };
}
if (isReferenceType(exprType)) {
const info = exprType.getCircularReferenceInfo();
return info;
}
return { isCircularReference: false };
}
/**
* If this is the lhs of an assignment, we don't need to flag it as unresolved
*/
private hasValidDeclaration(expression: Expression, exprType: BscType, definingNode?: AstNode) {
if (!isVariableExpression(expression)) {
return false;
}
let assignmentAncestor: AssignmentStatement;
if (isAssignmentStatement(definingNode) && definingNode.tokens.equals.kind === TokenKind.Equal) {
// this symbol was defined in a "normal" assignment (eg. not a compound assignment)
assignmentAncestor = definingNode;
return assignmentAncestor?.tokens.name?.text.toLowerCase() === expression?.tokens.name?.text.toLowerCase();
} else if (isFunctionParameterExpression(definingNode)) {
// this symbol was defined in a function param
return true;
} else {
assignmentAncestor = expression?.findAncestor(isAssignmentStatement);
}
return assignmentAncestor?.tokens.name === expression?.tokens.name && isUnionType(exprType);
}
/**
* Validate every function call to `CreateObject`.
* Ideally we would create better type checking/handling for this, but in the mean time, we know exactly
* what these calls are supposed to look like, and this is a very common thing for brs devs to do, so just
* do this manually for now.
*/
protected validateCreateObjectCall(file: BrsFile, call: CallExpression) {
//skip non CreateObject function calls
const callName = util.getAllDottedGetPartsAsString(call.callee)?.toLowerCase();
if (callName !== 'createobject' || !isLiteralExpression(call?.args[0])) {
return;
}
const firstParamToken = (call?.args[0] as LiteralExpression)?.tokens?.value;
const firstParamStringValue = firstParamToken?.text?.replace(/"/g, '');
if (!firstParamStringValue) {
return;
}
const firstParamStringValueLower = firstParamStringValue.toLowerCase();
//if this is a `createObject('roSGNode'` call, only support known sg node types
if (firstParamStringValueLower === 'rosgnode' && isLiteralExpression(call?.args[1])) {
const componentName: Token = call?.args[1]?.tokens.value;
this.checkComponentName(componentName);
if (call?.args.length !== 2) {
// roSgNode should only ever have 2 args in `createObject`
this.addDiagnostic({
...DiagnosticMessages.mismatchCreateObjectArgumentCount(firstParamStringValue, [2], call?.args.length),
location: call.location
});
}
} else if (!platformComponentNames.has(firstParamStringValueLower)) {
this.addDiagnostic({
...DiagnosticMessages.unknownBrightScriptComponent(firstParamStringValue),
location: firstParamToken.location
});
} else {
// This is valid brightscript component
// Test for invalid arg counts
const brightScriptComponent: BRSComponentData = components[firstParamStringValueLower];
// Valid arg counts for createObject are 1+ number of args for constructor
let validArgCounts = brightScriptComponent?.constructors.map(cnstr => cnstr.params.length + 1);
if (validArgCounts.length === 0) {
// no constructors for this component, so createObject only takes 1 arg
validArgCounts = [1];
}
if (!validArgCounts.includes(call?.args.length)) {
// Incorrect number of arguments included in `createObject()`
this.addDiagnostic({
...DiagnosticMessages.mismatchCreateObjectArgumentCount(firstParamStringValue, validArgCounts, call?.args.length),
location: call.location
});
}
// Test for deprecation
if (brightScriptComponent?.isDeprecated) {
this.addDiagnostic({
...DiagnosticMessages.itemIsDeprecated(firstParamStringValue, brightScriptComponent.deprecatedDescription),
location: call.location
});
}
}
}
private checkComponentName(componentName: Token) {
//don't validate any components with a colon in their name (probably component libraries, but regular components can have them too).
if (!componentName || componentName?.text?.includes(':')) {
return;
}
//add diagnostic for unknown components
const unquotedComponentName = componentName?.text?.replace(/"/g, '');
if (unquotedComponentName && !platformNodeNames.has(unquotedComponentName.toLowerCase()) && !this.event.program.getComponent(unquotedComponentName)) {
this.addDiagnostic({
...DiagnosticMessages.unknownRoSGNode(unquotedComponentName),
location: componentName.location
});
}
}
/**
* Validate every method call to `component.callfunc()`, `component.createChild()`, etc.
*/
protected validateComponentMethods(file: BrsFile, call: CallExpression) {
const lowerMethodNamesChecked = ['callfunc', 'createchild'];
if (!isDottedGetExpression(call.callee)) {
return;
}
const callName = call.callee.tokens?.name?.text?.toLowerCase();
if (!callName || !lowerMethodNamesChecked.includes(callName) || !isLiteralExpression(call?.args[0])) {
return;
}
const callerType = call.callee.obj?.getType({ flags: SymbolTypeFlag.runtime });
if (!isCallFuncableTypeLike(callerType)) {
return;
}
const firstArgToken = call?.args[0]?.tokens.value;
if (callName === 'createchild') {
this.checkComponentName(firstArgToken);
} else if (callName === 'callfunc' && !util.isGenericNodeType(callerType)) {
const funcType = util.getCallFuncType(call, firstArgToken, { flags: SymbolTypeFlag.runtime, ignoreCall: true });
if (!funcType?.isResolvable()) {
const functionName = firstArgToken.text.replace(/"/g, '');
const functionFullname = `${callerType.toString()}@.${functionName}`;
this.addMultiScopeDiagnostic({
...DiagnosticMessages.cannotFindCallFuncFunction(functionName, functionFullname, callerType.toString()),
location: firstArgToken?.location
});
} else {
this.validateFunctionCall(file, call, funcType, firstArgToken.location, call.args, 1);
}
}
}
private validateCallExpression(file: BrsFile, expression: CallExpression) {
const getTypeOptions = { flags: SymbolTypeFlag.runtime, data: {} };
let funcType = this.getNodeTypeWrapper(file, expression?.callee, getTypeOptions);
if (funcType?.isResolvable() && isClassType(funcType)) {
// We're calling a class - get the constructor
funcType = funcType.getMemberType('new', getTypeOptions);
}
const callErrorLocation = expression?.callee?.location;
return this.validateFunctionCall(file, expression.callee, funcType, callErrorLocation, expression.args);
}
private validateCallFuncExpression(file: BrsFile, expression: CallfuncExpression) {
const callerType = expression.callee?.getType({ flags: SymbolTypeFlag.runtime });
if (isDynamicType(callerType)) {
return;
}
const methodToken = expression.tokens.methodName;
const methodName = methodToken?.text ?? '';
const functionFullname = `${callerType.toString()}@.${methodName}`;
const callErrorLocation = expression.location;
if (util.isGenericNodeType(callerType) || isObjectType(callerType) || isDynamicType(callerType)) {
// ignore "general" node
return;
}
const funcType = util.getCallFuncType(expression, methodToken, { flags: SymbolTypeFlag.runtime, ignoreCall: true });
if (!funcType?.isResolvable()) {
this.addMultiScopeDiagnostic({
...DiagnosticMessages.cannotFindCallFuncFunction(methodName, functionFullname, callerType.toString()),
location: callErrorLocation
});
}
return this.validateFunctionCall(file, expression, funcType, callErrorLocation, expression.args);
}
/**
* Detect calls to functions with the incorrect number of parameters, or wrong types of arguments
*/
private validateFunctionCall(file: BrsFile, callee: Expression, funcType: BscType, callErrorLocation: Location, args: Expression[], argOffset = 0) {
while (isTypeStatementType(funcType)) {
funcType = funcType.wrappedType;
}
if (!funcType?.isResolvable() || !isCallableType(funcType) || isCompoundType(funcType)) {
const funcName = util.getAllDottedGetPartsAsString(callee, ParseMode.BrighterScript, isCallfuncExpression(callee) ? '@.' : '.');
if (isUnionType(funcType)) {
if (!util.isUnionOfFunctions(funcType) && !isCallfuncExpression(callee)) {
// union of func and non func. not callable
this.addMultiScopeDiagnostic({
...DiagnosticMessages.notCallable(funcName),
location: callErrorLocation
});
return;
}
const callablesInUnion = funcType.types.filter(isCallableType);
const funcsInUnion = callablesInUnion.filter(isTypedFunctionType);
if (funcsInUnion.length < callablesInUnion.length) {
// potentially a non-typed func in union
// cannot validate
return;
}
// check all funcs to see if they work
for (let i = 1; i < funcsInUnion.length; i++) {
const compatibilityData: TypeCompatibilityData = {};
if (!funcsInUnion[0].isTypeCompatible(funcsInUnion[i], compatibilityData)) {
if (!compatibilityData.returnTypeMismatch) {
// param differences!
this.addMultiScopeDiagnostic({
...DiagnosticMessages.incompatibleSymbolDefinition(
funcName,
{ isUnion: true, data: compatibilityData }),
location: callErrorLocation
});
return;
}
}
}
// The only thing different was return type
funcType = util.getFunctionTypeFromUnion(funcType);
}
if (funcType && !isCallableType(funcType) && !isReferenceType(funcType)) {
const globalFuncWithVarName = globalCallableMap.get(funcName.toLowerCase());
if (globalFuncWithVarName) {
funcType = globalFuncWithVarName.type;
} else {
this.addMultiScopeDiagnostic({
...DiagnosticMessages.notCallable(funcName),
location: callErrorLocation
});
return;
}
}
}
if (!isTypedFunctionType(funcType)) {
// non typed function. nothing to check
return;
}
//get min/max parameter count for callable
let minParams = 0;
let maxParams = 0;
for (let param of funcType.params) {
maxParams++;
//optional parameters must come last, so we can assume that minParams won't increase once we hit
//the first isOptional
if (param.isOptional !== true) {
minParams++;
}
}
if (funcType.isVariadic) {
// function accepts variable number of arguments
maxParams = CallExpression.MaximumArguments;
}
const argsForCall = argOffset < 1 ? args : args.slice(argOffset);
let expCallArgCount = argsForCall.length;
if (expCallArgCount > maxParams || expCallArgCount < minParams) {
let minMaxParamsText = minParams === maxParams ? maxParams + argOffset : `${minParams + argOffset}-${maxParams + argOffset}`;
this.addMultiScopeDiagnostic({
...DiagnosticMessages.mismatchArgumentCount(minMaxParamsText, expCallArgCount + argOffset),
location: callErrorLocation
});
}
let paramIndex = 0;
for (let arg of argsForCall) {
const data = {} as ExtraSymbolData;
let argType = this.getNodeTypeWrapper(file, arg, { flags: SymbolTypeFlag.runtime, data: data });
const paramType = funcType.params[paramIndex]?.type;
if (!paramType) {
// unable to find a paramType -- maybe there are more args than params
break;
}
if (isCallableType(paramType) && isClassType(argType) && isClassStatement(data.definingNode)) {
argType = data.definingNode.getConstructorType();
}
const compatibilityData: TypeCompatibilityData = {};
const isAllowedArgConversion = this.checkAllowedArgConversions(paramType, argType);
if (!isAllowedArgConversion && !paramType?.isTypeCompatible(argType, compatibilityData)) {
this.addMultiScopeDiagnostic({
...DiagnosticMessages.argumentTypeMismatch(argType?.toString() ?? 'unknown', paramType?.toString() ?? 'unknown', compatibilityData),
location: arg.location
});
}
paramIndex++;
}
}
private checkAllowedArgConversions(paramType: BscType, argType: BscType): boolean {
if (isNumberTypeLike(argType) && isBooleanTypeLike(paramType)) {
return true;
}
return false;
}
/**
* Detect return statements with incompatible types vs. declared return type
*/
private validateReturnStatement(file: BrsFile, returnStmt: ReturnStatement) {
const data: ExtraSymbolData = {};
const getTypeOptions = { flags: SymbolTypeFlag.runtime, data: data };
let funcType = returnStmt.findAncestor(isFunctionExpression)?.getType({ flags: SymbolTypeFlag.typetime });
if (isTypedFunctionType(funcType)) {
let actualReturnType = returnStmt?.value
? this.getNodeTypeWrapper(file, returnStmt?.value, getTypeOptions)
: VoidType.instance;
const compatibilityData: TypeCompatibilityData = {};
// `return` statement by itself in non-built-in function will actually result in `invalid`
const valueReturnType = isVoidType(actualReturnType) ? InvalidType.instance : actualReturnType;
if (funcType.returnType.isResolvable()) {
if (!returnStmt?.value && isVoidType(funcType.returnType)) {
// allow empty return when function is return `as void`
// eslint-disable-next-line no-useless-return
return;
} else if (!funcType.returnType.isTypeCompatible(valueReturnType, compatibilityData)) {
this.addMultiScopeDiagnostic({
...DiagnosticMessages.returnTypeMismatch(actualReturnType.toString(), funcType.returnType.toString(), compatibilityData),
location: returnStmt.value?.location ?? returnStmt.location
});
}
}
}
}
/**
* Detect assigned type different from expected member type
*/
private validateDottedSetStatement(file: BrsFile, dottedSetStmt: DottedSetStatement) {
const typeChainExpectedLHS = [] as TypeChainEntry[];
const getTypeOpts = { flags: SymbolTypeFlag.runtime };
const expectedLHSType = this.getNodeTypeWrapper(file, dottedSetStmt, { ...getTypeOpts, data: {}, typeChain: typeChainExpectedLHS });
const actualRHSType = this.getNodeTypeWrapper(file, dottedSetStmt?.value, getTypeOpts);
const compatibilityData: TypeCompatibilityData = {};
const typeChainScan = util.processTypeChain(typeChainExpectedLHS);
// check if anything in typeChain is an AA - if so, just allow it
if (typeChainExpectedLHS.find(typeChainItem => isAssociativeArrayType(typeChainItem.type))) {
// something in the chain is an AA
// treat members as dynamic - they could have been set without the type system's knowledge
return;
}
if (!expectedLHSType || !expectedLHSType?.isResolvable()) {
this.addMultiScopeDiagnostic({
...DiagnosticMessages.cannotFindName(typeChainScan.itemName, typeChainScan.fullNameOfItem, typeChainScan.itemParentTypeName, this.getParentTypeDescriptor(typeChainScan)),
location: typeChainScan?.location
});
return;
}
let accessibilityIsOk = this.checkMemberAccessibility(file, dottedSetStmt, typeChainExpectedLHS);
//Most Component fields can be set with strings
//TODO: be more precise about which fields can actually accept strings
//TODO: if RHS is a string literal, we can do more validation to make sure it's the correct type
if (isComponentType(dottedSetStmt.obj?.getType({ flags: SymbolTypeFlag.runtime }))) {
if (isStringTypeLike(actualRHSType)) {
return;
}
}
if (accessibilityIsOk && !expectedLHSType?.isTypeCompatible(actualRHSType, compatibilityData)) {
this.addMultiScopeDiagnostic({
...DiagnosticMessages.assignmentTypeMismatch(actualRHSType?.toString() ?? 'unknown', expectedLHSType?.toString() ?? 'unknown', compatibilityData),
location: dottedSetStmt.location
});
}
}
/**
* Detect when declared type does not match rhs type
*/
private validateAssignmentStatement(file: BrsFile, assignStmt: AssignmentStatement) {
if (!assignStmt?.typeExpression) {
// nothing to check
return;
}
const typeChainExpectedLHS = [];
const getTypeOpts = { flags: SymbolTypeFlag.runtime };
const expectedLHSType = this.getNodeTypeWrapper(file, assignStmt.typeExpression, { ...getTypeOpts, data: {}, typeChain: typeChainExpectedLHS });
const actualRHSType = this.getNodeTypeWrapper(file, assignStmt.value, getTypeOpts);
const compatibilityData: TypeCompatibilityData = {};
if (!expectedLHSType || !expectedLHSType.isResolvable()) {
// LHS is not resolvable... handled elsewhere
} else if (!expectedLHSType?.isTypeCompatible(actualRHSType, compatibilityData)) {
this.addMultiScopeDiagnostic({
...DiagnosticMessages.assignmentTypeMismatch(actualRHSType.toString(), expectedLHSType.toString(), compatibilityData),
location: assignStmt.location
});
}
}
/**
* Detect invalid use of a binary operator
*/
private validateBinaryExpression(file: BrsFile, binaryExpr: BinaryExpression | AugmentedAssignmentStatement) {
const getTypeOpts = { flags: SymbolTypeFlag.runtime };
if (util.isInTypeExpression(binaryExpr)) {
return;
}
let leftType = isBinaryExpression(binaryExpr)
? this.getNodeTypeWrapper(file, binaryExpr.left, getTypeOpts)
: this.getNodeTypeWrapper(file, binaryExpr.item, getTypeOpts);
let rightType = isBinaryExpression(binaryExpr)
? this.getNodeTypeWrapper(file, binaryExpr.right, getTypeOpts)
: this.getNodeTypeWrapper(file, binaryExpr.value, getTypeOpts);
if (!leftType || !rightType || !leftType.isResolvable() || !rightType.isResolvable()) {
// Can not find the type. error handled elsewhere
return;
}
let leftTypeToTest = leftType;
let rightTypeToTest = rightType;
if (isEnumMemberType(leftType) || isEnumType(leftType)) {
leftTypeToTest = leftType.underlyingType;
}
if (isEnumMemberType(rightType) || isEnumType(rightType)) {
rightTypeToTest = rightType.underlyingType;
}
if (isUnionType(leftType) || isUnionType(rightType)) {
// TODO: it is possible to validate based on innerTypes, but more complicated
// Because you need to verify each combination of types
return;
}
const opResult = util.binaryOperatorResultType(leftTypeToTest, binaryExpr.tokens.operator, rightTypeToTest);
if (!opResult) {
// if the result was dynamic or void, that means there wasn't a valid operation
this.addMultiScopeDiagnostic({
...DiagnosticMessages.operatorTypeMismatch(binaryExpr.tokens.operator.text, leftType.toString(), rightType.toString()),
location: binaryExpr.location
});
}
}
/**
* Detect invalid use of a Unary operator
*/
private validateUnaryExpression(file: BrsFile, unaryExpr: UnaryExpression) {
const getTypeOpts = { flags: SymbolTypeFlag.runtime };
let rightType = this.getNodeTypeWrapper(file, unaryExpr.right, getTypeOpts);
if (!rightType.isResolvable()) {
// Can not find the type. error handled elsewhere
return;
}
let rightTypeToTest = rightType;
if (isEnumMemberType(rightType)) {
rightTypeToTest = rightType.underlyingType;
}
if (isUnionType(rightTypeToTest)) {
// TODO: it is possible to validate based on innerTypes, but more complicated
// Because you need to verify each combination of types
} else if (isDynamicType(rightTypeToTest) || isObjectType(rightTypeToTest)) {
// operand is basically "any" type... ignore;
} else if (isPrimitiveType(rightType)) {
const opResult = util.unaryOperatorResultType(unaryExpr.tokens.operator, rightTypeToTest);
if (!opResult) {
this.addMultiScopeDiagnostic({
...DiagnosticMessages.operatorTypeMismatch(unaryExpr.tokens.operator.text, rightType.toString()),
location: unaryExpr.location
});
}
} else {
// rhs is not a primitive, so no binary operator is allowed
this.addMultiScopeDiagnostic({
...DiagnosticMessages.operatorTypeMismatch(unaryExpr.tokens.operator.text, rightType.toString()),
location: unaryExpr.location
});
}
}
private validateIncrementStatement(file: BrsFile, incStmt: IncrementStatement) {
const getTypeOpts = { flags: SymbolTypeFlag.runtime };
let rightType = this.getNodeTypeWrapper(file, incStmt.value, getTypeOpts);
if (!rightType.isResolvable()) {
// Can not find the type. error handled elsewhere
return;
}
if (isUnionType(rightType)) {
// TODO: it is possible to validate based on innerTypes, but more complicated
// because you need to verify each combination of types
} else if (isDynamicType(rightType) || isObjectType(rightType)) {
// operand is basically "any" type... ignore
} else if (isNumberTypeLike(rightType)) {
// operand is a number.. this is ok
} else {
// rhs is not a number, so no increment operator is not allowed
this.addMultiScopeDiagnostic({
...DiagnosticMessages.operatorTypeMismatch(incStmt.tokens.operator.text, rightType.toString()),
location: incStmt.location
});
}
}
validateVariableAndDottedGetExpressions(file: BrsFile, expression: VariableExpression | DottedGetExpression) {
if (isDottedGetExpression(expression.parent)) {
// We validate dottedGetExpressions at the top-most level
return;
}
if (isVariableExpression(expression)) {
if (isAssignmentStatement(expression.parent) && expression.parent.tokens.name === expression.tokens.name) {
// Don't validate LHS of assignments
return;
} else if (isNamespaceStatement(expression.parent)) {
return;
}
}
let symbolType = SymbolTypeFlag.runtime;
let oppositeSymbolType = SymbolTypeFlag.typetime;
const isUsedAsType = util.isInTypeExpression(expression);
if (isUsedAsType) {
// This is used in a TypeExpression - only look up types from SymbolTable
symbolType = SymbolTypeFlag.typetime;
oppositeSymbolType = SymbolTypeFlag.runtime;
}
// Do a complete type check on all DottedGet and Variable expressions
// this will create a diagnostic if an invalid member is accessed
const typeChain: TypeChainEntry[] = [];
const typeData = {} as ExtraSymbolData;
let exprType = this.getNodeTypeWrapper(file, expression, {
flags: symbolType,
typeChain: typeChain,
data: typeData
});
const hasValidDeclaration = this.hasValidDeclaration(expression, exprType, typeData?.definingNode);
//include a hint diagnostic if this type is marked as deprecated
if (typeData.flags & SymbolTypeFlag.deprecated) { // eslint-disable-line no-bitwise
this.addMultiScopeDiagnostic({
...DiagnosticMessages.itemIsDeprecated(),
location: expression.tokens.name.location,
tags: [DiagnosticTag.Deprecated]
});
}
if (!this.isTypeKnown(exprType) && !hasValidDeclaration) {
if (this.getNodeTypeWrapper(file, expression, { flags: oppositeSymbolType, isExistenceTest: true })?.isResolvable()) {
const oppoSiteTypeChain = [];
const invalidlyUsedResolvedType = this.getNodeTypeWrapper(file, expression, { flags: oppositeSymbolType, typeChain: oppoSiteTypeChain, isExistenceTest: true });
const typeChainScan = util.processTypeChain(oppoSiteTypeChain);
if (isUsedAsType) {
this.addMultiScopeDiagnostic({
...DiagnosticMessages.itemCannotBeUsedAsType(typeChainScan.fullChainName),
location: expression.location
});
} else if (invalidlyUsedResolvedType && !isReferenceType(invalidlyUsedResolvedType)) {
if (!isAliasStatement(expression.parent)) {
// alias rhs CAN be a type!
this.addMultiScopeDiagnostic({
...DiagnosticMessages.itemCannotBeUsedAsVariable(invalidlyUsedResolvedType.toString()),
location: expression.location
});
}
} else {
const typeChainScan = util.processTypeChain(typeChain);
//if this is a function call, provide a different diagnostic code
if (isCallExpression(typeChainScan.astNode.parent) && typeChainScan.astNode.parent.callee === expression) {
this.addMultiScopeDiagnostic({
...DiagnosticMessages.cannotFindFunction(typeChainScan.itemName, typeChainScan.fullNameOfItem, typeChainScan.itemParentTypeName, this.getParentTypeDescriptor(typeChainScan)),
location: typeChainScan?.location
});
} else {
this.addMultiScopeDiagnostic({
...DiagnosticMessages.cannotFindName(typeChainScan.itemName, typeChainScan.fullNameOfItem, typeChainScan.itemParentTypeName, this.getParentTypeDescriptor(typeChainScan)),
location: typeChainScan?.location
});
}
}
} else if (!(typeData?.isFromDocComment)) {
// only show "cannot find... " errors if the type is not defined from a doc comment
const typeChainScan = util.processTypeChain(typeChain);
const circularReferenceInfo = this.getCircularReference(exprType);
if (isCallExpression(typeChainScan.astNode.parent) && typeChainScan.astNode.parent.callee === expression) {
this.addMultiScopeDiagnostic({
...DiagnosticMessages.cannotFindFunction(typeChainScan.itemName, typeChainScan.fullNameOfItem, typeChainScan.itemParentTypeName, this.getParentTypeDescriptor(typeChainScan)),
location: typeChainScan?.location
});
} else if (circularReferenceInfo?.isCircularReference) {
let diagnosticDetail = util.getCircularReferenceDiagnosticDetail(circularReferenceInfo, typeChainScan.fullNameOfItem);
this.addMultiScopeDiagnostic({
...DiagnosticMessages.circularReferenceDetected(diagnosticDetail),
location: typeChainScan?.location
});
} else {
this.addMultiScopeDiagnostic({
...DiagnosticMessages.cannotFindName(typeChainScan.itemName, typeChainScan.fullNameOfItem, typeChainScan.itemParentTypeName, this.getParentTypeDescriptor(typeChainScan)),
location: typeChainScan?.location
});
}
}
}
if (isUsedAsType) {
return;