• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

rokucommunity / brighterscript / #13040

06 Sep 2024 01:54PM UTC coverage: 86.524% (+0.01%) from 86.512%
#13040

push

web-flow
Merge b2bbc792d into 43cbf8b72

10841 of 13320 branches covered (81.39%)

Branch coverage included in aggregate %.

213 of 221 new or added lines in 8 files covered. (96.38%)

147 existing lines in 6 files now uncovered.

12537 of 13699 relevant lines covered (91.52%)

27494.65 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.43
/src/bscPlugin/validation/ScopeValidator.ts
1
import { DiagnosticTag, type Range } from 'vscode-languageserver';
1✔
2
import { isAliasStatement, isAssignmentStatement, isAssociativeArrayType, isBinaryExpression, isBooleanType, isBrsFile, isCallExpression, isCallableType, isClassStatement, isClassType, isComponentType, isDottedGetExpression, isDynamicType, isEnumMemberType, isEnumType, isFunctionExpression, isFunctionParameterExpression, isLiteralExpression, isNamespaceStatement, isNamespaceType, isNewExpression, isNumberType, isObjectType, isPrimitiveType, isReferenceType, isStringType, isTypedFunctionType, isUnionType, isVariableExpression, isXmlScope } from '../../astUtils/reflection';
1✔
3
import type { DiagnosticInfo } from '../../DiagnosticMessages';
4
import { DiagnosticMessages } from '../../DiagnosticMessages';
1✔
5
import type { BrsFile } from '../../files/BrsFile';
6
import type { BsDiagnostic, CallableContainer, ExtraSymbolData, FileReference, GetTypeOptions, OnScopeValidateEvent, TypeChainEntry, TypeChainProcessResult, TypeCompatibilityData } from '../../interfaces';
7
import { SymbolTypeFlag } from '../../SymbolTypeFlag';
1✔
8
import type { AssignmentStatement, AugmentedAssignmentStatement, ClassStatement, DottedSetStatement, IncrementStatement, NamespaceStatement, ReturnStatement } from '../../parser/Statement';
9
import { util } from '../../util';
1✔
10
import { nodes, components } from '../../roku-types';
1✔
11
import type { BRSComponentData } from '../../roku-types';
12
import type { Token } from '../../lexer/Token';
13
import { AstNodeKind } from '../../parser/AstNode';
1✔
14
import type { AstNode } from '../../parser/AstNode';
15
import type { Expression } from '../../parser/AstNode';
16
import type { VariableExpression, DottedGetExpression, BinaryExpression, UnaryExpression, NewExpression, LiteralExpression } from '../../parser/Expression';
17
import { CallExpression } from '../../parser/Expression';
1✔
18
import { createVisitor } from '../../astUtils/visitors';
1✔
19
import type { BscType } from '../../types/BscType';
20
import type { BscFile } from '../../files/BscFile';
21
import { InsideSegmentWalkMode } from '../../AstValidationSegmenter';
1✔
22
import { TokenKind } from '../../lexer/TokenKind';
1✔
23
import { ParseMode } from '../../parser/Parser';
1✔
24
import { BsClassValidator } from '../../validators/ClassValidator';
1✔
25
import { globalCallableMap } from '../../globalCallables';
1✔
26
import type { XmlScope } from '../../XmlScope';
27
import type { XmlFile } from '../../files/XmlFile';
28
import { SGFieldTypes } from '../../parser/SGTypes';
1✔
29
import { DynamicType } from '../../types';
1✔
30
import { BscTypeKind } from '../../types/BscTypeKind';
1✔
31
import type { BrsDocWithType } from '../../parser/BrightScriptDocParser';
32
import brsDocParser from '../../parser/BrightScriptDocParser';
1✔
33

34
/**
35
 * The lower-case names of all platform-included scenegraph nodes
36
 */
37
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
38
const platformNodeNames = nodes ? new Set((Object.values(nodes) as { name: string }[]).map(x => x?.name.toLowerCase())) : new Set();
95!
39
const platformComponentNames = components ? new Set((Object.values(components) as { name: string }[]).map(x => x?.name.toLowerCase())) : new Set();
64!
40

41
const enum ScopeValidatorDiagnosticTag {
1✔
42
    Imports = 'ScopeValidatorImports',
1✔
43
    NamespaceCollisions = 'ScopeValidatorNamespaceCollisions',
1✔
44
    DuplicateFunctionDeclaration = 'ScopeValidatorDuplicateFunctionDeclaration',
1✔
45
    FunctionCollisions = 'ScopeValidatorFunctionCollisions',
1✔
46
    Classes = 'ScopeValidatorClasses',
1✔
47
    XMLInterface = 'ScopeValidatorXML',
1✔
48
    XMLImports = 'ScopeValidatorXMLImports',
1✔
49
    Default = 'ScopeValidator',
1✔
50
    Segment = 'ScopeValidatorSegment'
1✔
51
}
52

53
/**
54
 * A validator that handles all scope validations for a program validation cycle.
55
 * You should create ONE of these to handle all scope events between beforeProgramValidate and afterProgramValidate,
56
 * and call reset() before using it again in the next cycle
57
 */
58
export class ScopeValidator {
1✔
59

60
    /**
61
     * The event currently being processed. This will change multiple times throughout the lifetime of this validator
62
     */
63
    private event: OnScopeValidateEvent;
64

65
    private metrics = new Map<string, number>();
1,590✔
66

67

68
    public processEvent(event: OnScopeValidateEvent) {
69
        this.event = event;
3,184✔
70
        if (this.event.program.globalScope === this.event.scope) {
3,184✔
71
            return;
1,590✔
72
        }
73
        this.metrics.clear();
1,594✔
74
        this.walkFiles();
1,594✔
75
        this.currentSegmentBeingValidated = null;
1,594✔
76
        this.flagDuplicateFunctionDeclarations();
1,594✔
77
        this.validateScriptImportPaths();
1,594✔
78
        this.validateClasses();
1,594✔
79
        if (isXmlScope(event.scope)) {
1,594✔
80
            //detect when the child imports a script that its ancestor also imports
81
            this.diagnosticDetectDuplicateAncestorScriptImports(event.scope);
429✔
82
            //validate component interface
83
            this.validateXmlInterface(event.scope);
429✔
84
        }
85

86
        this.event.program.logger.debug(this.event.scope.name, 'metrics:');
1,594✔
87
        let total = 0;
1,594✔
88
        for (const [filePath, num] of this.metrics) {
1,594✔
89
            this.event.program.logger.debug(' - ', filePath, num);
1,562✔
90
            total += num;
1,562✔
91
        }
92
        this.event.program.logger.debug(this.event.scope.name, 'total segments validated', total);
1,594✔
93
    }
94

95
    public reset() {
96
        this.event = undefined;
1,281✔
97
    }
98

99
    private walkFiles() {
100
        const hasChangeInfo = this.event.changedFiles && this.event.changedSymbols;
1,594✔
101

102
        //do many per-file checks for every file in this (and parent) scopes
103
        this.event.scope.enumerateBrsFiles((file) => {
1,594✔
104
            if (!isBrsFile(file)) {
1,973!
105
                return;
×
106
            }
107

108
            const thisFileHasChanges = this.event.changedFiles.includes(file);
1,973✔
109

110
            if (thisFileHasChanges || this.doesFileProvideChangedSymbol(file, this.event.changedSymbols)) {
1,973✔
111
                this.diagnosticDetectFunctionCollisions(file);
1,830✔
112
            }
113
        });
114

115
        this.event.scope.enumerateOwnFiles((file) => {
1,594✔
116
            if (isBrsFile(file)) {
2,392✔
117

118
                const fileUri = util.pathToUri(file.srcPath);
1,963✔
119
                const thisFileHasChanges = this.event.changedFiles.includes(file);
1,963✔
120

121
                const hasUnvalidatedSegments = file.validationSegmenter.hasUnvalidatedSegments();
1,963✔
122

123
                if (hasChangeInfo && !hasUnvalidatedSegments) {
1,963✔
124
                    return;
401✔
125
                }
126

127
                const validationVisitor = createVisitor({
1,562✔
128
                    VariableExpression: (varExpr) => {
129
                        this.validateVariableAndDottedGetExpressions(file, varExpr);
3,381✔
130
                    },
131
                    DottedGetExpression: (dottedGet) => {
132
                        this.validateVariableAndDottedGetExpressions(file, dottedGet);
1,409✔
133
                    },
134
                    CallExpression: (functionCall) => {
135
                        this.validateFunctionCall(file, functionCall);
854✔
136
                        this.validateCreateObjectCall(file, functionCall);
854✔
137
                    },
138
                    ReturnStatement: (returnStatement) => {
139
                        this.validateReturnStatement(file, returnStatement);
261✔
140
                    },
141
                    DottedSetStatement: (dottedSetStmt) => {
142
                        this.validateDottedSetStatement(file, dottedSetStmt);
82✔
143
                    },
144
                    BinaryExpression: (binaryExpr) => {
145
                        this.validateBinaryExpression(file, binaryExpr);
230✔
146
                    },
147
                    UnaryExpression: (unaryExpr) => {
148
                        this.validateUnaryExpression(file, unaryExpr);
33✔
149
                    },
150
                    AssignmentStatement: (assignStmt) => {
151
                        this.validateAssignmentStatement(file, assignStmt);
596✔
152
                        // Note: this also includes For statements
153
                        this.detectShadowedLocalVar(file, {
596✔
154
                            expr: assignStmt,
155
                            name: assignStmt.tokens.name.text,
156
                            type: this.getNodeTypeWrapper(file, assignStmt, { flags: SymbolTypeFlag.runtime }),
157
                            nameRange: assignStmt.tokens.name.location?.range
1,788✔
158
                        });
159
                    },
160
                    AugmentedAssignmentStatement: (binaryExpr) => {
161
                        this.validateBinaryExpression(file, binaryExpr);
48✔
162
                    },
163
                    IncrementStatement: (stmt) => {
164
                        this.validateIncrementStatement(file, stmt);
9✔
165
                    },
166
                    NewExpression: (newExpr) => {
167
                        this.validateNewExpression(file, newExpr);
114✔
168
                    },
169
                    ForEachStatement: (forEachStmt) => {
170
                        this.detectShadowedLocalVar(file, {
24✔
171
                            expr: forEachStmt,
172
                            name: forEachStmt.tokens.item.text,
173
                            type: this.getNodeTypeWrapper(file, forEachStmt, { flags: SymbolTypeFlag.runtime }),
174
                            nameRange: forEachStmt.tokens.item.location?.range
72✔
175
                        });
176
                    },
177
                    FunctionParameterExpression: (funcParam) => {
178
                        this.detectShadowedLocalVar(file, {
1,037✔
179
                            expr: funcParam,
180
                            name: funcParam.tokens.name.text,
181
                            type: this.getNodeTypeWrapper(file, funcParam, { flags: SymbolTypeFlag.runtime }),
182
                            nameRange: funcParam.tokens.name.location?.range
3,111✔
183
                        });
184
                    },
185
                    AstNode: (node) => {
186
                        //check for doc comments
187
                        if (!node.leadingTrivia || node.leadingTrivia.filter(triviaToken => triviaToken.kind === TokenKind.Comment).length === 0) {
22,464✔
188
                            return;
17,276✔
189
                        }
190

191
                        this.validateDocComments(node);
228✔
192

193
                    }
194
                });
195
                // validate only what's needed in the file
196

197
                const segmentsToWalkForValidation = thisFileHasChanges
1,562✔
198
                    ? file.validationSegmenter.getAllUnvalidatedSegments()
1,562✔
199
                    : file.validationSegmenter.getSegmentsWithChangedSymbols(this.event.changedSymbols);
200

201
                let segmentsValidated = 0;
1,562✔
202
                for (const segment of segmentsToWalkForValidation) {
1,562✔
203
                    if (!file.validationSegmenter.checkIfSegmentNeedsRevalidation(segment, this.event.changedSymbols)) {
3,001!
204
                        continue;
×
205
                    }
206
                    this.currentSegmentBeingValidated = segment;
3,001✔
207
                    this.event.program.diagnostics.clearByFilter({ scope: this.event.scope, fileUri: fileUri, segment: segment, tag: ScopeValidatorDiagnosticTag.Segment });
3,001✔
208
                    segmentsValidated++;
3,001✔
209
                    segment.walk(validationVisitor, {
3,001✔
210
                        walkMode: InsideSegmentWalkMode
211
                    });
212
                    file.markSegmentAsValidated(segment);
3,001✔
213
                    this.currentSegmentBeingValidated = null;
3,001✔
214
                }
215
                this.metrics.set(file.pkgPath, segmentsValidated);
1,562✔
216
            }
217
        });
218
    }
219

220
    private doesFileProvideChangedSymbol(file: BrsFile, changedSymbols: Map<SymbolTypeFlag, Set<string>>) {
221
        if (!changedSymbols) {
143!
222
            return true;
×
223
        }
224
        for (const flag of [SymbolTypeFlag.runtime, SymbolTypeFlag.typetime]) {
143✔
225
            const providedSymbolKeysFlag = file.providedSymbols.symbolMap.get(flag).keys();
286✔
226
            const changedSymbolSetForFlag = changedSymbols.get(flag);
286✔
227

228
            for (let providedKey of providedSymbolKeysFlag) {
286✔
229
                if (changedSymbolSetForFlag.has(providedKey)) {
270!
230
                    return true;
×
231
                }
232
            }
233
        }
234
        return false;
143✔
235
    }
236

237
    private currentSegmentBeingValidated: AstNode;
238

239

240
    private isTypeKnown(exprType: BscType) {
241
        let isKnownType = exprType?.isResolvable();
3,481✔
242
        return isKnownType;
3,481✔
243
    }
244

245
    /**
246
     * If this is the lhs of an assignment, we don't need to flag it as unresolved
247
     */
248
    private hasValidDeclaration(expression: Expression, exprType: BscType, definingNode?: AstNode) {
249
        if (!isVariableExpression(expression)) {
3,481✔
250
            return false;
1,003✔
251
        }
252
        let assignmentAncestor: AssignmentStatement;
253
        if (isAssignmentStatement(definingNode) && definingNode.tokens.equals.kind === TokenKind.Equal) {
2,478✔
254
            // this symbol was defined in a "normal" assignment (eg. not a compound assignment)
255
            assignmentAncestor = definingNode;
295✔
256
            return assignmentAncestor?.tokens.name?.text.toLowerCase() === expression?.tokens.name?.text.toLowerCase();
295!
257
        } else if (isFunctionParameterExpression(definingNode)) {
2,183✔
258
            // this symbol was defined in a function param
259
            return true;
436✔
260
        } else {
261
            assignmentAncestor = expression?.findAncestor(isAssignmentStatement);
1,747!
262
        }
263
        return assignmentAncestor?.tokens.name === expression?.tokens.name && isUnionType(exprType);
1,747!
264
    }
265

266
    /**
267
     * Validate every function call to `CreateObject`.
268
     * Ideally we would create better type checking/handling for this, but in the mean time, we know exactly
269
     * what these calls are supposed to look like, and this is a very common thing for brs devs to do, so just
270
     * do this manually for now.
271
     */
272
    protected validateCreateObjectCall(file: BrsFile, call: CallExpression) {
273

274
        //skip non CreateObject function calls
275
        const callName = util.getAllDottedGetPartsAsString(call.callee)?.toLowerCase();
854✔
276
        if (callName !== 'createobject' || !isLiteralExpression(call?.args[0])) {
854!
277
            return;
793✔
278
        }
279
        const firstParamToken = (call?.args[0] as LiteralExpression)?.tokens?.value;
61!
280
        const firstParamStringValue = firstParamToken?.text?.replace(/"/g, '');
61!
281
        if (!firstParamStringValue) {
61!
282
            return;
×
283
        }
284
        const firstParamStringValueLower = firstParamStringValue.toLowerCase();
61✔
285

286
        //if this is a `createObject('roSGNode'` call, only support known sg node types
287
        if (firstParamStringValueLower === 'rosgnode' && isLiteralExpression(call?.args[1])) {
61!
288
            const componentName: Token = call?.args[1]?.tokens.value;
25!
289
            //don't validate any components with a colon in their name (probably component libraries, but regular components can have them too).
290
            if (!componentName || componentName?.text?.includes(':')) {
25!
291
                return;
3✔
292
            }
293
            //add diagnostic for unknown components
294
            const unquotedComponentName = componentName?.text?.replace(/"/g, '');
22!
295
            if (unquotedComponentName && !platformNodeNames.has(unquotedComponentName.toLowerCase()) && !this.event.program.getComponent(unquotedComponentName)) {
22✔
296
                this.addDiagnostic({
4✔
297
                    ...DiagnosticMessages.unknownRoSGNode(unquotedComponentName),
298
                    location: componentName.location
299
                });
300
            } else if (call?.args.length !== 2) {
18!
301
                // roSgNode should only ever have 2 args in `createObject`
302
                this.addDiagnostic({
1✔
303
                    ...DiagnosticMessages.mismatchCreateObjectArgumentCount(firstParamStringValue, [2], call?.args.length),
3!
304
                    location: call.location
305
                });
306
            }
307
        } else if (!platformComponentNames.has(firstParamStringValueLower)) {
36✔
308
            this.addDiagnostic({
7✔
309
                ...DiagnosticMessages.unknownBrightScriptComponent(firstParamStringValue),
310
                location: firstParamToken.location
311
            });
312
        } else {
313
            // This is valid brightscript component
314
            // Test for invalid arg counts
315
            const brightScriptComponent: BRSComponentData = components[firstParamStringValueLower];
29✔
316
            // Valid arg counts for createObject are 1+ number of args for constructor
317
            let validArgCounts = brightScriptComponent?.constructors.map(cnstr => cnstr.params.length + 1);
33!
318
            if (validArgCounts.length === 0) {
29✔
319
                // no constructors for this component, so createObject only takes 1 arg
320
                validArgCounts = [1];
1✔
321
            }
322
            if (!validArgCounts.includes(call?.args.length)) {
29!
323
                // Incorrect number of arguments included in `createObject()`
324
                this.addDiagnostic({
4✔
325
                    ...DiagnosticMessages.mismatchCreateObjectArgumentCount(firstParamStringValue, validArgCounts, call?.args.length),
12!
326
                    location: call.location
327
                });
328
            }
329

330
            // Test for deprecation
331
            if (brightScriptComponent?.isDeprecated) {
29!
332
                this.addDiagnostic({
×
333
                    ...DiagnosticMessages.deprecatedBrightScriptComponent(firstParamStringValue, brightScriptComponent.deprecatedDescription),
334
                    location: call.location
335
                });
336
            }
337
        }
338

339
    }
340

341
    /**
342
     * Detect calls to functions with the incorrect number of parameters, or wrong types of arguments
343
     */
344
    private validateFunctionCall(file: BrsFile, expression: CallExpression) {
345
        const getTypeOptions = { flags: SymbolTypeFlag.runtime, data: {} };
854✔
346
        let funcType = this.getNodeTypeWrapper(file, expression?.callee, getTypeOptions);
854!
347
        if (funcType?.isResolvable() && isClassType(funcType)) {
854✔
348
            // We're calling a class - get the constructor
349
            funcType = funcType.getMemberType('new', getTypeOptions);
123✔
350
        }
351
        if (funcType?.isResolvable() && isTypedFunctionType(funcType)) {
854✔
352
            //funcType.setName(expression.callee. .name);
353

354
            //get min/max parameter count for callable
355
            let minParams = 0;
603✔
356
            let maxParams = 0;
603✔
357
            for (let param of funcType.params) {
603✔
358
                maxParams++;
832✔
359
                //optional parameters must come last, so we can assume that minParams won't increase once we hit
360
                //the first isOptional
361
                if (param.isOptional !== true) {
832✔
362
                    minParams++;
452✔
363
                }
364
            }
365
            if (funcType.isVariadic) {
603✔
366
                // function accepts variable number of arguments
367
                maxParams = CallExpression.MaximumArguments;
3✔
368
            }
369
            let expCallArgCount = expression.args.length;
603✔
370
            if (expCallArgCount > maxParams || expCallArgCount < minParams) {
603✔
371
                let minMaxParamsText = minParams === maxParams ? maxParams : `${minParams}-${maxParams}`;
31✔
372
                this.addMultiScopeDiagnostic({
31✔
373
                    ...DiagnosticMessages.mismatchArgumentCount(minMaxParamsText, expCallArgCount),
374
                    location: expression.callee.location
375
                });
376
            }
377
            let paramIndex = 0;
603✔
378
            for (let arg of expression.args) {
603✔
379
                const data = {} as ExtraSymbolData;
522✔
380
                let argType = this.getNodeTypeWrapper(file, arg, { flags: SymbolTypeFlag.runtime, data: data });
522✔
381

382
                const paramType = funcType.params[paramIndex]?.type;
522✔
383
                if (!paramType) {
522✔
384
                    // unable to find a paramType -- maybe there are more args than params
385
                    break;
16✔
386
                }
387

388
                if (isCallableType(paramType) && isClassType(argType) && isClassStatement(data.definingNode)) {
506✔
389
                    argType = data.definingNode.getConstructorType();
2✔
390
                }
391

392
                const compatibilityData: TypeCompatibilityData = {};
506✔
393
                const isAllowedArgConversion = this.checkAllowedArgConversions(paramType, argType);
506✔
394
                if (!isAllowedArgConversion && !paramType?.isTypeCompatible(argType, compatibilityData)) {
506!
395
                    this.addMultiScopeDiagnostic({
32✔
396
                        ...DiagnosticMessages.argumentTypeMismatch(argType.toString(), paramType.toString(), compatibilityData),
397
                        location: arg.location
398
                    });
399
                }
400
                paramIndex++;
506✔
401
            }
402

403
        }
404
    }
405

406
    private checkAllowedArgConversions(paramType: BscType, argType: BscType): boolean {
407
        if (isNumberType(argType) && isBooleanType(paramType)) {
506✔
408
            return true;
8✔
409
        }
410
        return false;
498✔
411
    }
412

413

414
    /**
415
     * Detect return statements with incompatible types vs. declared return type
416
     */
417
    private validateReturnStatement(file: BrsFile, returnStmt: ReturnStatement) {
418
        const data: ExtraSymbolData = {};
261✔
419
        const getTypeOptions = { flags: SymbolTypeFlag.runtime, data: data };
261✔
420
        let funcType = returnStmt.findAncestor(isFunctionExpression).getType({ flags: SymbolTypeFlag.typetime });
261✔
421
        if (isTypedFunctionType(funcType)) {
261!
422
            const actualReturnType = this.getNodeTypeWrapper(file, returnStmt?.value, getTypeOptions);
261!
423
            const compatibilityData: TypeCompatibilityData = {};
261✔
424

425
            if (funcType.returnType.isResolvable() && actualReturnType && !funcType.returnType.isTypeCompatible(actualReturnType, compatibilityData)) {
261✔
426
                this.addMultiScopeDiagnostic({
12✔
427
                    ...DiagnosticMessages.returnTypeMismatch(actualReturnType.toString(), funcType.returnType.toString(), compatibilityData),
428
                    location: returnStmt.value.location
429
                });
430

431
            }
432
        }
433
    }
434

435
    /**
436
     * Detect assigned type different from expected member type
437
     */
438
    private validateDottedSetStatement(file: BrsFile, dottedSetStmt: DottedSetStatement) {
439
        const typeChainExpectedLHS = [] as TypeChainEntry[];
82✔
440
        const getTypeOpts = { flags: SymbolTypeFlag.runtime };
82✔
441

442
        const expectedLHSType = this.getNodeTypeWrapper(file, dottedSetStmt, { ...getTypeOpts, data: {}, typeChain: typeChainExpectedLHS });
82✔
443
        const actualRHSType = this.getNodeTypeWrapper(file, dottedSetStmt?.value, getTypeOpts);
82!
444
        const compatibilityData: TypeCompatibilityData = {};
82✔
445
        const typeChainScan = util.processTypeChain(typeChainExpectedLHS);
82✔
446
        // check if anything in typeChain is an AA - if so, just allow it
447
        if (typeChainExpectedLHS.find(typeChainItem => isAssociativeArrayType(typeChainItem.type))) {
133✔
448
            // something in the chain is an AA
449
            // treat members as dynamic - they could have been set without the type system's knowledge
450
            return;
37✔
451
        }
452
        if (!expectedLHSType || !expectedLHSType?.isResolvable()) {
45!
453
            this.addMultiScopeDiagnostic({
7✔
454
                ...DiagnosticMessages.cannotFindName(typeChainScan.itemName, typeChainScan.fullNameOfItem, typeChainScan.itemParentTypeName, this.getParentTypeDescriptor(typeChainScan)),
455
                location: typeChainScan?.location
21!
456
            });
457
            return;
7✔
458
        }
459

460
        let accessibilityIsOk = this.checkMemberAccessibility(file, dottedSetStmt, typeChainExpectedLHS);
38✔
461

462
        //Most Component fields can be set with strings
463
        //TODO: be more precise about which fields can actually accept strings
464
        //TODO: if RHS is a string literal, we can do more validation to make sure it's the correct type
465
        if (isComponentType(dottedSetStmt.obj?.getType({ flags: SymbolTypeFlag.runtime }))) {
38!
466
            if (isStringType(actualRHSType)) {
12✔
467
                return;
4✔
468
            }
469
        }
470

471
        if (accessibilityIsOk && !expectedLHSType?.isTypeCompatible(actualRHSType, compatibilityData)) {
34!
472
            this.addMultiScopeDiagnostic({
7✔
473
                ...DiagnosticMessages.assignmentTypeMismatch(actualRHSType.toString(), expectedLHSType.toString(), compatibilityData),
474
                location: dottedSetStmt.location
475
            });
476
        }
477
    }
478

479
    /**
480
     * Detect when declared type does not match rhs type
481
     */
482
    private validateAssignmentStatement(file: BrsFile, assignStmt: AssignmentStatement) {
483
        if (!assignStmt?.typeExpression) {
596!
484
            // nothing to check
485
            return;
589✔
486
        }
487

488
        const typeChainExpectedLHS = [];
7✔
489
        const getTypeOpts = { flags: SymbolTypeFlag.runtime };
7✔
490
        const expectedLHSType = this.getNodeTypeWrapper(file, assignStmt.typeExpression, { ...getTypeOpts, data: {}, typeChain: typeChainExpectedLHS });
7✔
491
        const actualRHSType = this.getNodeTypeWrapper(file, assignStmt.value, getTypeOpts);
7✔
492
        const compatibilityData: TypeCompatibilityData = {};
7✔
493
        if (!expectedLHSType || !expectedLHSType.isResolvable()) {
7✔
494
            // LHS is not resolvable... handled elsewhere
495
        } else if (!expectedLHSType?.isTypeCompatible(actualRHSType, compatibilityData)) {
6!
496
            this.addMultiScopeDiagnostic({
1✔
497
                ...DiagnosticMessages.assignmentTypeMismatch(actualRHSType.toString(), expectedLHSType.toString(), compatibilityData),
498
                location: assignStmt.location
499
            });
500
        }
501
    }
502

503
    /**
504
     * Detect invalid use of a binary operator
505
     */
506
    private validateBinaryExpression(file: BrsFile, binaryExpr: BinaryExpression | AugmentedAssignmentStatement) {
507
        const getTypeOpts = { flags: SymbolTypeFlag.runtime };
278✔
508

509
        if (util.isInTypeExpression(binaryExpr)) {
278✔
510
            return;
13✔
511
        }
512

513
        let leftType = isBinaryExpression(binaryExpr)
265✔
514
            ? this.getNodeTypeWrapper(file, binaryExpr.left, getTypeOpts)
265✔
515
            : this.getNodeTypeWrapper(file, binaryExpr.item, getTypeOpts);
516
        let rightType = isBinaryExpression(binaryExpr)
265✔
517
            ? this.getNodeTypeWrapper(file, binaryExpr.right, getTypeOpts)
265✔
518
            : this.getNodeTypeWrapper(file, binaryExpr.value, getTypeOpts);
519

520
        if (!leftType.isResolvable() || !rightType.isResolvable()) {
265✔
521
            // Can not find the type. error handled elsewhere
522
            return;
12✔
523
        }
524
        let leftTypeToTest = leftType;
253✔
525
        let rightTypeToTest = rightType;
253✔
526

527
        if (isEnumMemberType(leftType) || isEnumType(leftType)) {
253✔
528
            leftTypeToTest = leftType.underlyingType;
11✔
529
        }
530
        if (isEnumMemberType(rightType) || isEnumType(rightType)) {
253✔
531
            rightTypeToTest = rightType.underlyingType;
10✔
532
        }
533

534
        if (isUnionType(leftType) || isUnionType(rightType)) {
253!
535
            // TODO: it is possible to validate based on innerTypes, but more complicated
536
            // Because you need to verify each combination of types
UNCOV
537
            return;
×
538
        }
539
        const leftIsPrimitive = isPrimitiveType(leftTypeToTest);
253✔
540
        const rightIsPrimitive = isPrimitiveType(rightTypeToTest);
253✔
541
        const leftIsAny = isDynamicType(leftTypeToTest) || isObjectType(leftTypeToTest);
253✔
542
        const rightIsAny = isDynamicType(rightTypeToTest) || isObjectType(rightTypeToTest);
253✔
543

544

545
        if (leftIsAny && rightIsAny) {
253✔
546
            // both operands are basically "any" type... ignore;
547
            return;
19✔
548
        } else if ((leftIsAny && rightIsPrimitive) || (leftIsPrimitive && rightIsAny)) {
234✔
549
            // one operand is basically "any" type... ignore;
550
            return;
43✔
551
        }
552
        const opResult = util.binaryOperatorResultType(leftTypeToTest, binaryExpr.tokens.operator, rightTypeToTest);
191✔
553

554
        if (isDynamicType(opResult)) {
191✔
555
            // if the result was dynamic, that means there wasn't a valid operation
556
            this.addMultiScopeDiagnostic({
7✔
557
                ...DiagnosticMessages.operatorTypeMismatch(binaryExpr.tokens.operator.text, leftType.toString(), rightType.toString()),
558
                location: binaryExpr.location
559
            });
560
        }
561
    }
562

563
    /**
564
     * Detect invalid use of a Unary operator
565
     */
566
    private validateUnaryExpression(file: BrsFile, unaryExpr: UnaryExpression) {
567
        const getTypeOpts = { flags: SymbolTypeFlag.runtime };
33✔
568

569
        let rightType = this.getNodeTypeWrapper(file, unaryExpr.right, getTypeOpts);
33✔
570

571
        if (!rightType.isResolvable()) {
33!
572
            // Can not find the type. error handled elsewhere
UNCOV
573
            return;
×
574
        }
575
        let rightTypeToTest = rightType;
33✔
576
        if (isEnumMemberType(rightType)) {
33!
UNCOV
577
            rightTypeToTest = rightType.underlyingType;
×
578
        }
579

580

581
        if (isUnionType(rightTypeToTest)) {
33✔
582
            // TODO: it is possible to validate based on innerTypes, but more complicated
583
            // Because you need to verify each combination of types
584

585
        } else if (isDynamicType(rightTypeToTest) || isObjectType(rightTypeToTest)) {
32✔
586
            // operand is basically "any" type... ignore;
587

588
        } else if (isPrimitiveType(rightType)) {
27!
589
            const opResult = util.unaryOperatorResultType(unaryExpr.tokens.operator, rightTypeToTest);
27✔
590
            if (isDynamicType(opResult)) {
27✔
591
                this.addMultiScopeDiagnostic({
1✔
592
                    ...DiagnosticMessages.operatorTypeMismatch(unaryExpr.tokens.operator.text, rightType.toString()),
593
                    location: unaryExpr.location
594
                });
595
            }
596
        } else {
597
            // rhs is not a primitive, so no binary operator is allowed
UNCOV
598
            this.addMultiScopeDiagnostic({
×
599
                ...DiagnosticMessages.operatorTypeMismatch(unaryExpr.tokens.operator.text, rightType.toString()),
600
                location: unaryExpr.location
601
            });
602
        }
603
    }
604

605
    private validateIncrementStatement(file: BrsFile, incStmt: IncrementStatement) {
606
        const getTypeOpts = { flags: SymbolTypeFlag.runtime };
9✔
607

608
        let rightType = this.getNodeTypeWrapper(file, incStmt.value, getTypeOpts);
9✔
609

610
        if (!rightType.isResolvable()) {
9!
611
            // Can not find the type. error handled elsewhere
UNCOV
612
            return;
×
613
        }
614

615
        if (isUnionType(rightType)) {
9!
616
            // TODO: it is possible to validate based on innerTypes, but more complicated
617
            // because you need to verify each combination of types
618
        } else if (isDynamicType(rightType) || isObjectType(rightType)) {
9✔
619
            // operand is basically "any" type... ignore
620
        } else if (isNumberType(rightType)) {
7✔
621
            // operand is a number.. this is ok
622
        } else {
623
            // rhs is not a number, so no increment operator is not allowed
624
            this.addMultiScopeDiagnostic({
1✔
625
                ...DiagnosticMessages.operatorTypeMismatch(incStmt.tokens.operator.text, rightType.toString()),
626
                location: incStmt.location
627
            });
628
        }
629
    }
630

631

632
    validateVariableAndDottedGetExpressions(file: BrsFile, expression: VariableExpression | DottedGetExpression) {
633
        if (isDottedGetExpression(expression.parent)) {
4,790✔
634
            // We validate dottedGetExpressions at the top-most level
635
            return;
1,306✔
636
        }
637
        if (isVariableExpression(expression)) {
3,484✔
638
            if (isAssignmentStatement(expression.parent) && expression.parent.tokens.name === expression.tokens.name) {
2,481!
639
                // Don't validate LHS of assignments
UNCOV
640
                return;
×
641
            } else if (isNamespaceStatement(expression.parent)) {
2,481✔
642
                return;
3✔
643
            }
644
        }
645

646
        let symbolType = SymbolTypeFlag.runtime;
3,481✔
647
        let oppositeSymbolType = SymbolTypeFlag.typetime;
3,481✔
648
        const isUsedAsType = util.isInTypeExpression(expression);
3,481✔
649
        if (isUsedAsType) {
3,481✔
650
            // This is used in a TypeExpression - only look up types from SymbolTable
651
            symbolType = SymbolTypeFlag.typetime;
1,102✔
652
            oppositeSymbolType = SymbolTypeFlag.runtime;
1,102✔
653
        }
654

655
        // Do a complete type check on all DottedGet and Variable expressions
656
        // this will create a diagnostic if an invalid member is accessed
657
        const typeChain: TypeChainEntry[] = [];
3,481✔
658
        const typeData = {} as ExtraSymbolData;
3,481✔
659
        let exprType = this.getNodeTypeWrapper(file, expression, {
3,481✔
660
            flags: symbolType,
661
            typeChain: typeChain,
662
            data: typeData
663
        });
664

665
        const hasValidDeclaration = this.hasValidDeclaration(expression, exprType, typeData?.definingNode);
3,481!
666

667
        //include a hint diagnostic if this type is marked as deprecated
668
        if (typeData.flags & SymbolTypeFlag.deprecated) { // eslint-disable-line no-bitwise
3,481✔
669
            this.addMultiScopeDiagnostic({
2✔
670
                ...DiagnosticMessages.itemIsDeprecated(),
671
                location: expression.tokens.name.location,
672
                tags: [DiagnosticTag.Deprecated]
673
            });
674
        }
675

676
        if (!this.isTypeKnown(exprType) && !hasValidDeclaration) {
3,481✔
677
            if (this.getNodeTypeWrapper(file, expression, { flags: oppositeSymbolType, isExistenceTest: true })?.isResolvable()) {
229!
678
                const oppoSiteTypeChain = [];
5✔
679
                const invalidlyUsedResolvedType = this.getNodeTypeWrapper(file, expression, { flags: oppositeSymbolType, typeChain: oppoSiteTypeChain, isExistenceTest: true });
5✔
680
                const typeChainScan = util.processTypeChain(oppoSiteTypeChain);
5✔
681
                if (isUsedAsType) {
5✔
682
                    this.addMultiScopeDiagnostic({
2✔
683
                        ...DiagnosticMessages.itemCannotBeUsedAsType(typeChainScan.fullChainName),
684
                        location: expression.location
685
                    });
686
                } else if (invalidlyUsedResolvedType && !isReferenceType(invalidlyUsedResolvedType)) {
3✔
687
                    if (!isAliasStatement(expression.parent)) {
1!
688
                        // alias rhs CAN be a type!
UNCOV
689
                        this.addMultiScopeDiagnostic({
×
690
                            ...DiagnosticMessages.itemCannotBeUsedAsVariable(invalidlyUsedResolvedType.toString()),
691
                            location: expression.location
692
                        });
693
                    }
694
                } else {
695
                    const typeChainScan = util.processTypeChain(typeChain);
2✔
696
                    //if this is a function call, provide a different diganostic code
697
                    if (isCallExpression(typeChainScan.astNode.parent) && typeChainScan.astNode.parent.callee === expression) {
2✔
698
                        this.addMultiScopeDiagnostic({
1✔
699
                            ...DiagnosticMessages.cannotFindFunction(typeChainScan.itemName, typeChainScan.fullNameOfItem, typeChainScan.itemParentTypeName, this.getParentTypeDescriptor(typeChainScan)),
700
                            location: typeChainScan?.location
3!
701
                        });
702
                    } else {
703
                        this.addMultiScopeDiagnostic({
1✔
704
                            ...DiagnosticMessages.cannotFindName(typeChainScan.itemName, typeChainScan.fullNameOfItem, typeChainScan.itemParentTypeName, this.getParentTypeDescriptor(typeChainScan)),
705
                            location: typeChainScan?.location
3!
706
                        });
707
                    }
708
                }
709

710
            } else if (!typeData?.isFromDocComment) {
224!
711
                // only show "cannot find... " errors if the type is not defined from a doc comment
712
                const typeChainScan = util.processTypeChain(typeChain);
222✔
713
                if (isCallExpression(typeChainScan.astNode.parent) && typeChainScan.astNode.parent.callee === expression) {
222✔
714
                    this.addMultiScopeDiagnostic({
25✔
715
                        ...DiagnosticMessages.cannotFindFunction(typeChainScan.itemName, typeChainScan.fullNameOfItem, typeChainScan.itemParentTypeName, this.getParentTypeDescriptor(typeChainScan)),
716
                        location: typeChainScan?.location
75!
717
                    });
718
                } else {
719
                    this.addMultiScopeDiagnostic({
197✔
720
                        ...DiagnosticMessages.cannotFindName(typeChainScan.itemName, typeChainScan.fullNameOfItem, typeChainScan.itemParentTypeName, this.getParentTypeDescriptor(typeChainScan)),
721
                        location: typeChainScan?.location
591!
722
                    });
723
                }
724

725
            }
726
        }
727
        if (isUsedAsType) {
3,481✔
728
            return;
1,102✔
729
        }
730

731
        const containingNamespace = expression.findAncestor<NamespaceStatement>(isNamespaceStatement);
2,379✔
732
        const containingNamespaceName = containingNamespace?.getName(ParseMode.BrighterScript);
2,379✔
733

734
        if (!(isCallExpression(expression.parent) && isNewExpression(expression.parent?.parent))) {
2,379!
735
            const classUsedAsVarEntry = this.checkTypeChainForClassUsedAsVar(typeChain, containingNamespaceName);
2,265✔
736
            const isClassInNamespace = containingNamespace?.getSymbolTable().hasSymbol(typeChain[0].name, SymbolTypeFlag.runtime);
2,265✔
737
            if (classUsedAsVarEntry && !isClassInNamespace) {
2,265!
738

UNCOV
739
                this.addMultiScopeDiagnostic({
×
740
                    ...DiagnosticMessages.itemCannotBeUsedAsVariable(classUsedAsVarEntry.toString()),
741
                    location: expression.location
742
                });
UNCOV
743
                return;
×
744
            }
745
        }
746

747
        const lastTypeInfo = typeChain[typeChain.length - 1];
2,379✔
748
        const parentTypeInfo = typeChain[typeChain.length - 2];
2,379✔
749

750
        this.checkMemberAccessibility(file, expression, typeChain);
2,379✔
751

752
        if (isNamespaceType(exprType) && !isAliasStatement(expression.parent)) {
2,379✔
753
            this.addMultiScopeDiagnostic({
22✔
754
                ...DiagnosticMessages.itemCannotBeUsedAsVariable('namespace'),
755
                location: expression.location
756
            });
757
        } else if (isEnumType(exprType) && !isAliasStatement(expression.parent)) {
2,357✔
758
            const enumStatement = this.event.scope.getEnum(util.getAllDottedGetPartsAsString(expression));
15✔
759
            if (enumStatement) {
15✔
760
                // there's an enum with this name
761
                this.addMultiScopeDiagnostic({
2✔
762
                    ...DiagnosticMessages.itemCannotBeUsedAsVariable('enum'),
763
                    location: expression.location
764
                });
765
            }
766
        } else if (isDynamicType(exprType) && isEnumType(parentTypeInfo?.type) && isDottedGetExpression(expression)) {
2,342✔
767
            const enumFileLink = this.event.scope.getEnumFileLink(util.getAllDottedGetPartsAsString(expression.obj));
8✔
768
            const typeChainScanForParent = util.processTypeChain(typeChain.slice(0, -1));
8✔
769
            if (enumFileLink) {
8✔
770
                this.addMultiScopeDiagnostic({
5✔
771
                    ...DiagnosticMessages.unknownEnumValue(lastTypeInfo?.name, typeChainScanForParent.fullChainName),
15!
772
                    location: lastTypeInfo?.location,
15!
773
                    relatedInformation: [{
774
                        message: 'Enum declared here',
775
                        location: util.createLocationFromRange(
776
                            util.pathToUri(enumFileLink?.file.srcPath),
15!
777
                            enumFileLink?.item?.tokens.name.location?.range
45!
778
                        )
779
                    }]
780
                });
781
            }
782
        }
783
    }
784

785
    private checkTypeChainForClassUsedAsVar(typeChain: TypeChainEntry[], containingNamespaceName: string) {
786
        const ignoreKinds = [AstNodeKind.TypecastExpression, AstNodeKind.NewExpression];
2,265✔
787
        let lowerNameSoFar = '';
2,265✔
788
        let classUsedAsVar;
789
        let isFirst = true;
2,265✔
790
        for (let i = 0; i < typeChain.length - 1; i++) { // do not look at final entry - we CAN use the constructor as a variable
2,265✔
791
            const tce = typeChain[i];
1,220✔
792
            lowerNameSoFar += `${lowerNameSoFar ? '.' : ''}${tce.name.toLowerCase()}`;
1,220✔
793
            if (!isNamespaceType(tce.type)) {
1,220✔
794
                if (isFirst && containingNamespaceName) {
564✔
795
                    lowerNameSoFar = `${containingNamespaceName.toLowerCase()}.${lowerNameSoFar}`;
71✔
796
                }
797
                if (!tce.astNode || ignoreKinds.includes(tce.astNode.kind)) {
564✔
798
                    break;
12✔
799
                } else if (isClassType(tce.type) && lowerNameSoFar.toLowerCase() === tce.type.name.toLowerCase()) {
552✔
800
                    classUsedAsVar = tce.type;
1✔
801
                }
802
                break;
552✔
803
            }
804
            isFirst = false;
656✔
805
        }
806

807
        return classUsedAsVar;
2,265✔
808
    }
809

810
    /**
811
     * Adds diagnostics for accibility mismatches
812
     *
813
     * @param file file
814
     * @param expression containing expression
815
     * @param typeChain type chain to check
816
     * @returns true if member accesiibility is okay
817
     */
818
    private checkMemberAccessibility(file: BscFile, expression: Expression, typeChain: TypeChainEntry[]) {
819
        for (let i = 0; i < typeChain.length - 1; i++) {
2,417✔
820
            const parentChainItem = typeChain[i];
1,357✔
821
            const childChainItem = typeChain[i + 1];
1,357✔
822
            if (isClassType(parentChainItem.type)) {
1,357✔
823
                const containingClassStmt = expression.findAncestor<ClassStatement>(isClassStatement);
153✔
824
                const classStmtThatDefinesChildMember = childChainItem.data?.definingNode?.findAncestor<ClassStatement>(isClassStatement);
153!
825
                if (classStmtThatDefinesChildMember) {
153✔
826
                    const definingClassName = classStmtThatDefinesChildMember.getName(ParseMode.BrighterScript);
151✔
827
                    const inMatchingClassStmt = containingClassStmt?.getName(ParseMode.BrighterScript).toLowerCase() === parentChainItem.type.name.toLowerCase();
151✔
828
                    // eslint-disable-next-line no-bitwise
829
                    if (childChainItem.data.flags & SymbolTypeFlag.private) {
151✔
830
                        if (!inMatchingClassStmt || childChainItem.data.memberOfAncestor) {
15✔
831
                            this.addMultiScopeDiagnostic({
4✔
832
                                ...DiagnosticMessages.memberAccessibilityMismatch(childChainItem.name, childChainItem.data.flags, definingClassName),
833
                                location: expression.location
834
                            });
835
                            // there's an error... don't worry about the rest of the chain
836
                            return false;
4✔
837
                        }
838
                    }
839

840
                    // eslint-disable-next-line no-bitwise
841
                    if (childChainItem.data.flags & SymbolTypeFlag.protected) {
147✔
842
                        const containingClassName = containingClassStmt?.getName(ParseMode.BrighterScript);
13✔
843
                        const containingNamespaceName = expression.findAncestor<NamespaceStatement>(isNamespaceStatement)?.getName(ParseMode.BrighterScript);
13✔
844
                        const ancestorClasses = this.event.scope.getClassHierarchy(containingClassName, containingNamespaceName).map(link => link.item);
13✔
845
                        const isSubClassOfDefiningClass = ancestorClasses.includes(classStmtThatDefinesChildMember);
13✔
846

847
                        if (!isSubClassOfDefiningClass) {
13✔
848
                            this.addMultiScopeDiagnostic({
5✔
849
                                ...DiagnosticMessages.memberAccessibilityMismatch(childChainItem.name, childChainItem.data.flags, definingClassName),
850
                                location: expression.location
851
                            });
852
                            // there's an error... don't worry about the rest of the chain
853
                            return false;
5✔
854
                        }
855
                    }
856
                }
857

858
            }
859
        }
860
        return true;
2,408✔
861
    }
862

863
    /**
864
     * Find all "new" statements in the program,
865
     * and make sure we can find a class with that name
866
     */
867
    private validateNewExpression(file: BrsFile, newExpression: NewExpression) {
868
        const newExprType = this.getNodeTypeWrapper(file, newExpression, { flags: SymbolTypeFlag.typetime });
114✔
869
        if (isClassType(newExprType)) {
114✔
870
            return;
106✔
871
        }
872

873
        let potentialClassName = newExpression.className.getName(ParseMode.BrighterScript);
8✔
874
        const namespaceName = newExpression.findAncestor<NamespaceStatement>(isNamespaceStatement)?.getName(ParseMode.BrighterScript);
8!
875
        let newableClass = this.event.scope.getClass(potentialClassName, namespaceName);
8✔
876

877
        if (!newableClass) {
8!
878
            //try and find functions with this name.
879
            let fullName = util.getFullyQualifiedClassName(potentialClassName, namespaceName);
8✔
880

881
            this.addMultiScopeDiagnostic({
8✔
882
                ...DiagnosticMessages.expressionIsNotConstructable(fullName),
883
                location: newExpression.className.location
884
            });
885

886
        }
887
    }
888

889
    /**
890
     * Create diagnostics for any duplicate function declarations
891
     */
892
    private flagDuplicateFunctionDeclarations() {
893
        this.event.program.diagnostics.clearByFilter({ scope: this.event.scope, tag: ScopeValidatorDiagnosticTag.DuplicateFunctionDeclaration });
1,594✔
894

895
        //for each list of callables with the same name
896
        for (let [lowerName, callableContainers] of this.event.scope.getCallableContainerMap()) {
1,594✔
897

898
            let globalCallables = [] as CallableContainer[];
119,676✔
899
            let nonGlobalCallables = [] as CallableContainer[];
119,676✔
900
            let ownCallables = [] as CallableContainer[];
119,676✔
901
            let ancestorNonGlobalCallables = [] as CallableContainer[];
119,676✔
902

903

904
            for (let container of callableContainers) {
119,676✔
905
                if (container.scope === this.event.program.globalScope) {
126,086✔
906
                    globalCallables.push(container);
124,332✔
907
                } else {
908
                    nonGlobalCallables.push(container);
1,754✔
909
                    if (container.scope === this.event.scope) {
1,754✔
910
                        ownCallables.push(container);
1,724✔
911
                    } else {
912
                        ancestorNonGlobalCallables.push(container);
30✔
913
                    }
914
                }
915
            }
916

917
            //add info diagnostics about child shadowing parent functions
918
            if (ownCallables.length > 0 && ancestorNonGlobalCallables.length > 0) {
119,676✔
919
                for (let container of ownCallables) {
24✔
920
                    //skip the init function (because every component will have one of those){
921
                    if (lowerName !== 'init') {
24✔
922
                        let shadowedCallable = ancestorNonGlobalCallables[ancestorNonGlobalCallables.length - 1];
23✔
923
                        if (!!shadowedCallable && shadowedCallable.callable.file === container.callable.file) {
23✔
924
                            //same file: skip redundant imports
925
                            continue;
20✔
926
                        }
927
                        this.addMultiScopeDiagnostic({
3✔
928
                            ...DiagnosticMessages.overridesAncestorFunction(
929
                                container.callable.name,
930
                                container.scope.name,
931
                                shadowedCallable.callable.file.destPath,
932
                                //grab the last item in the list, which should be the closest ancestor's version
933
                                shadowedCallable.scope.name
934
                            ),
935
                            location: util.createLocationFromFileRange(container.callable.file, container.callable.nameRange)
936
                        }, ScopeValidatorDiagnosticTag.DuplicateFunctionDeclaration);
937
                    }
938
                }
939
            }
940

941
            //add error diagnostics about duplicate functions in the same scope
942
            if (ownCallables.length > 1) {
119,676✔
943

944
                for (let callableContainer of ownCallables) {
5✔
945
                    let callable = callableContainer.callable;
10✔
946
                    const related = [];
10✔
947
                    for (const ownCallable of ownCallables) {
10✔
948
                        const thatNameRange = ownCallable.callable.nameRange;
20✔
949
                        if (ownCallable.callable.nameRange !== callable.nameRange) {
20✔
950
                            related.push({
10✔
951
                                message: `Function declared here`,
952
                                location: util.createLocationFromRange(
953
                                    util.pathToUri(ownCallable.callable.file?.srcPath),
30!
954
                                    thatNameRange
955
                                )
956
                            });
957
                        }
958
                    }
959

960
                    this.addMultiScopeDiagnostic({
10✔
961
                        ...DiagnosticMessages.duplicateFunctionImplementation(callable.name),
962
                        location: util.createLocationFromFileRange(callable.file, callable.nameRange),
963
                        relatedInformation: related
964
                    }, ScopeValidatorDiagnosticTag.DuplicateFunctionDeclaration);
965
                }
966
            }
967
        }
968
    }
969

970
    /**
971
     * Verify that all of the scripts imported by each file in this scope actually exist, and have the correct case
972
     */
973
    private validateScriptImportPaths() {
974
        this.event.program.diagnostics.clearByFilter({ scope: this.event.scope, tag: ScopeValidatorDiagnosticTag.Imports });
1,594✔
975

976
        let scriptImports = this.event.scope.getOwnScriptImports();
1,594✔
977
        //verify every script import
978
        for (let scriptImport of scriptImports) {
1,594✔
979
            let referencedFile = this.event.scope.getFileByRelativePath(scriptImport.destPath);
496✔
980
            //if we can't find the file
981
            if (!referencedFile) {
496✔
982
                //skip the default bslib file, it will exist at transpile time but should not show up in the program during validation cycle
983
                if (scriptImport.destPath === this.event.program.bslibPkgPath) {
17✔
984
                    continue;
2✔
985
                }
986
                let dInfo: DiagnosticInfo;
987
                if (scriptImport.text.trim().length === 0) {
15✔
988
                    dInfo = DiagnosticMessages.scriptSrcCannotBeEmpty();
1✔
989
                } else {
990
                    dInfo = DiagnosticMessages.referencedFileDoesNotExist();
14✔
991
                }
992

993
                this.addMultiScopeDiagnostic({
15✔
994
                    ...dInfo,
995
                    location: util.createLocationFromFileRange(scriptImport.sourceFile, scriptImport.filePathRange)
996
                }, ScopeValidatorDiagnosticTag.Imports);
997
                //if the character casing of the script import path does not match that of the actual path
998
            } else if (scriptImport.destPath !== referencedFile.destPath) {
479✔
999
                this.addMultiScopeDiagnostic({
2✔
1000
                    ...DiagnosticMessages.scriptImportCaseMismatch(referencedFile.destPath),
1001
                    location: util.createLocationFromFileRange(scriptImport.sourceFile, scriptImport.filePathRange)
1002
                }, ScopeValidatorDiagnosticTag.Imports);
1003
            }
1004
        }
1005
    }
1006

1007
    /**
1008
     * Validate all classes defined in this scope
1009
     */
1010
    private validateClasses() {
1011
        this.event.program.diagnostics.clearByFilter({ scope: this.event.scope, tag: ScopeValidatorDiagnosticTag.Classes });
1,594✔
1012

1013
        let validator = new BsClassValidator(this.event.scope);
1,594✔
1014
        validator.validate();
1,594✔
1015
        for (const diagnostic of validator.diagnostics) {
1,594✔
1016
            this.addMultiScopeDiagnostic({
29✔
1017
                ...diagnostic
1018
            }, ScopeValidatorDiagnosticTag.Classes);
1019
        }
1020
    }
1021

1022

1023
    /**
1024
     * Find various function collisions
1025
     */
1026
    private diagnosticDetectFunctionCollisions(file: BrsFile) {
1027
        const fileUri = util.pathToUri(file.srcPath);
1,830✔
1028
        this.event.program.diagnostics.clearByFilter({ scope: this.event.scope, fileUri: fileUri, tag: ScopeValidatorDiagnosticTag.FunctionCollisions });
1,830✔
1029
        for (let func of file.callables) {
1,830✔
1030
            const funcName = func.getName(ParseMode.BrighterScript);
1,593✔
1031
            const lowerFuncName = funcName?.toLowerCase();
1,593!
1032
            if (lowerFuncName) {
1,593!
1033

1034
                //find function declarations with the same name as a stdlib function
1035
                if (globalCallableMap.has(lowerFuncName)) {
1,593✔
1036
                    this.addMultiScopeDiagnostic({
5✔
1037
                        ...DiagnosticMessages.scopeFunctionShadowedByBuiltInFunction(),
1038
                        location: util.createLocationFromRange(fileUri, func.nameRange)
1039

1040
                    });
1041
                }
1042
            }
1043
        }
1044
    }
1045

1046
    public detectShadowedLocalVar(file: BrsFile, varDeclaration: { expr: AstNode; name: string; type: BscType; nameRange: Range }) {
1047
        const varName = varDeclaration.name;
1,657✔
1048
        const lowerVarName = varName.toLowerCase();
1,657✔
1049
        const callableContainerMap = this.event.scope.getCallableContainerMap();
1,657✔
1050
        const containingNamespace = varDeclaration.expr?.findAncestor<NamespaceStatement>(isNamespaceStatement);
1,657!
1051
        const localVarIsInNamespace = util.isVariableMemberOfNamespace(varDeclaration.name, varDeclaration.expr, containingNamespace);
1,657✔
1052

1053
        const varIsFunction = () => {
1,657✔
1054
            return isCallableType(varDeclaration.type);
11✔
1055
        };
1056

1057
        if (
1,657✔
1058
            //has same name as stdlib
1059
            globalCallableMap.has(lowerVarName)
1060
        ) {
1061
            //local var function with same name as stdlib function
1062
            if (varIsFunction()) {
8✔
1063
                this.addMultiScopeDiagnostic({
1✔
1064
                    ...DiagnosticMessages.localVarFunctionShadowsParentFunction('stdlib'),
1065
                    location: util.createLocationFromFileRange(file, varDeclaration.nameRange)
1066
                });
1067
            }
1068
        } else if (callableContainerMap.has(lowerVarName) && !localVarIsInNamespace) {
1,649✔
1069
            const callable = callableContainerMap.get(lowerVarName);
3✔
1070
            //is same name as a callable
1071
            if (varIsFunction()) {
3✔
1072
                this.addMultiScopeDiagnostic({
1✔
1073
                    ...DiagnosticMessages.localVarFunctionShadowsParentFunction('scope'),
1074
                    location: util.createLocationFromFileRange(file, varDeclaration.nameRange),
1075
                    relatedInformation: [{
1076
                        message: 'Function declared here',
1077
                        location: util.createLocationFromFileRange(
1078
                            callable[0].callable.file,
1079
                            callable[0].callable.nameRange
1080
                        )
1081
                    }]
1082
                });
1083
            } else {
1084
                this.addMultiScopeDiagnostic({
2✔
1085
                    ...DiagnosticMessages.localVarShadowedByScopedFunction(),
1086
                    location: util.createLocationFromFileRange(file, varDeclaration.nameRange),
1087
                    relatedInformation: [{
1088
                        message: 'Function declared here',
1089
                        location: util.createLocationFromRange(
1090
                            util.pathToUri(callable[0].callable.file.srcPath),
1091
                            callable[0].callable.nameRange
1092
                        )
1093
                    }]
1094
                });
1095
            }
1096
            //has the same name as an in-scope class
1097
        } else if (!localVarIsInNamespace) {
1,646✔
1098
            const classStmtLink = this.event.scope.getClassFileLink(lowerVarName);
1,496✔
1099
            if (classStmtLink) {
1,496✔
1100
                this.addMultiScopeDiagnostic({
3✔
1101
                    ...DiagnosticMessages.localVarSameNameAsClass(classStmtLink?.item?.getName(ParseMode.BrighterScript)),
18!
1102
                    location: util.createLocationFromFileRange(file, varDeclaration.nameRange),
1103
                    relatedInformation: [{
1104
                        message: 'Class declared here',
1105
                        location: util.createLocationFromRange(
1106
                            util.pathToUri(classStmtLink.file.srcPath),
1107
                            classStmtLink?.item.tokens.name.location?.range
18!
1108
                        )
1109
                    }]
1110
                });
1111
            }
1112
        }
1113
    }
1114

1115
    private validateXmlInterface(scope: XmlScope) {
1116
        if (!scope.xmlFile.parser.ast?.componentElement?.interfaceElement) {
429!
1117
            return;
398✔
1118
        }
1119
        this.event.program.diagnostics.clearByFilter({ scope: this.event.scope, fileUri: util.pathToUri(scope.xmlFile?.srcPath), tag: ScopeValidatorDiagnosticTag.XMLInterface });
31!
1120

1121
        const iface = scope.xmlFile.parser.ast.componentElement.interfaceElement;
31✔
1122
        const callableContainerMap = scope.getCallableContainerMap();
31✔
1123
        //validate functions
1124
        for (const func of iface.functions) {
31✔
1125
            const name = func.name;
33✔
1126
            if (!name) {
33✔
1127
                this.addDiagnostic({
3✔
1128
                    ...DiagnosticMessages.xmlTagMissingAttribute(func.tokens.startTagName.text, 'name'),
1129
                    location: func.tokens.startTagName.location
1130
                }, ScopeValidatorDiagnosticTag.XMLInterface);
1131
            } else if (!callableContainerMap.has(name.toLowerCase())) {
30✔
1132
                this.addDiagnostic({
4✔
1133
                    ...DiagnosticMessages.xmlFunctionNotFound(name),
1134
                    location: func.getAttribute('name')?.tokens.value.location
12!
1135
                }, ScopeValidatorDiagnosticTag.XMLInterface);
1136
            }
1137
        }
1138
        //validate fields
1139
        for (const field of iface.fields) {
31✔
1140
            const { id, type, onChange } = field;
28✔
1141
            if (!id) {
28✔
1142
                this.addDiagnostic({
3✔
1143
                    ...DiagnosticMessages.xmlTagMissingAttribute(field.tokens.startTagName.text, 'id'),
1144
                    location: field.tokens.startTagName.location
1145
                }, ScopeValidatorDiagnosticTag.XMLInterface);
1146
            }
1147
            if (!type) {
28✔
1148
                if (!field.alias) {
3✔
1149
                    this.addDiagnostic({
2✔
1150
                        ...DiagnosticMessages.xmlTagMissingAttribute(field.tokens.startTagName.text, 'type'),
1151
                        location: field.tokens.startTagName.location
1152
                    }, ScopeValidatorDiagnosticTag.XMLInterface);
1153
                }
1154
            } else if (!SGFieldTypes.includes(type.toLowerCase())) {
25✔
1155
                this.addDiagnostic({
1✔
1156
                    ...DiagnosticMessages.xmlInvalidFieldType(type),
1157
                    location: field.getAttribute('type')?.tokens.value.location
3!
1158
                }, ScopeValidatorDiagnosticTag.XMLInterface);
1159
            }
1160
            if (onChange) {
28✔
1161
                if (!callableContainerMap.has(onChange.toLowerCase())) {
1!
1162
                    this.addDiagnostic({
1✔
1163
                        ...DiagnosticMessages.xmlFunctionNotFound(onChange),
1164
                        location: field.getAttribute('onchange')?.tokens.value.location
3!
1165
                    }, ScopeValidatorDiagnosticTag.XMLInterface);
1166
                }
1167
            }
1168
        }
1169
    }
1170

1171
    private validateDocComments(node: AstNode) {
1172
        const doc = brsDocParser.parseNode(node);
228✔
1173
        for (const docTag of doc.tags) {
228✔
1174
            const docTypeTag = docTag as BrsDocWithType;
24✔
1175
            if (!docTypeTag.type || !docTypeTag.location) {
24✔
1176
                continue;
1✔
1177
            }
1178
            const foundType = doc.getTypeFromContext(docTypeTag.type, node, { flags: SymbolTypeFlag.typetime });
23✔
1179
            if (!foundType?.isResolvable()) {
23✔
1180
                this.addMultiScopeDiagnostic({
8✔
1181
                    ...DiagnosticMessages.cannotFindTypeInCommentDoc(docTypeTag.type),
1182
                    location: docTypeTag.location
1183
                });
1184
            }
1185
        }
1186
    }
1187

1188
    /**
1189
     * Detect when a child has imported a script that an ancestor also imported
1190
     */
1191
    private diagnosticDetectDuplicateAncestorScriptImports(scope: XmlScope) {
1192
        this.event.program.diagnostics.clearByFilter({ scope: this.event.scope, fileUri: util.pathToUri(scope.xmlFile?.srcPath), tag: ScopeValidatorDiagnosticTag.XMLImports });
429!
1193
        if (scope.xmlFile.parentComponent) {
429✔
1194
            //build a lookup of pkg paths -> FileReference so we can more easily look up collisions
1195
            let parentScriptImports = scope.xmlFile.getAncestorScriptTagImports();
34✔
1196
            let lookup = {} as Record<string, FileReference>;
34✔
1197
            for (let parentScriptImport of parentScriptImports) {
34✔
1198
                //keep the first occurance of a pkgPath. Parent imports are first in the array
1199
                if (!lookup[parentScriptImport.destPath]) {
30!
1200
                    lookup[parentScriptImport.destPath] = parentScriptImport;
30✔
1201
                }
1202
            }
1203

1204
            //add warning for every script tag that this file shares with an ancestor
1205
            for (let scriptImport of scope.xmlFile.scriptTagImports) {
34✔
1206
                let ancestorScriptImport = lookup[scriptImport.destPath];
30✔
1207
                if (ancestorScriptImport) {
30✔
1208
                    let ancestorComponent = ancestorScriptImport.sourceFile as XmlFile;
21✔
1209
                    let ancestorComponentName = ancestorComponent.componentName?.text ?? ancestorComponent.destPath;
21!
1210
                    this.addDiagnostic({
21✔
1211
                        location: util.createLocationFromFileRange(scope.xmlFile, scriptImport.filePathRange),
1212
                        ...DiagnosticMessages.unnecessaryScriptImportInChildFromParent(ancestorComponentName)
1213
                    }, ScopeValidatorDiagnosticTag.XMLImports);
1214
                }
1215
            }
1216
        }
1217
    }
1218

1219
    /**
1220
     * Wraps the AstNode.getType() method, so that we can do extra processing on the result based on the current file
1221
     * In particular, since BrightScript does not support Unions, and there's no way to cast them to something else
1222
     * if the result of .getType() is a union, and we're in a .brs (brightScript) file, treat the result as Dynamic
1223
     *
1224
     * In most cases, this returns the result of node.getType()
1225
     *
1226
     * @param file the current file being processed
1227
     * @param node the node to get the type of
1228
     * @param getTypeOpts any options to pass to node.getType()
1229
     * @returns the processed result type
1230
     */
1231
    private getNodeTypeWrapper(file: BrsFile, node: AstNode, getTypeOpts: GetTypeOptions) {
1232
        const type = node?.getType(getTypeOpts);
7,873✔
1233

1234
        if (file.parseMode === ParseMode.BrightScript) {
7,873✔
1235
            // this is a brightscript file
1236
            const typeChain = getTypeOpts.typeChain;
944✔
1237
            if (typeChain) {
944✔
1238
                const hasUnion = typeChain.reduce((hasUnion, tce) => {
327✔
1239
                    return hasUnion || isUnionType(tce.type);
378✔
1240
                }, false);
1241
                if (hasUnion) {
327✔
1242
                    // there was a union somewhere in the typechain
1243
                    return DynamicType.instance;
6✔
1244
                }
1245
            }
1246
            if (isUnionType(type)) {
938✔
1247
                //this is a union
1248
                return DynamicType.instance;
4✔
1249
            }
1250
        }
1251

1252
        // by default return the result of node.getType()
1253
        return type;
7,863✔
1254
    }
1255

1256
    private getParentTypeDescriptor(typeChainResult: TypeChainProcessResult) {
1257
        if (typeChainResult.itemParentTypeKind === BscTypeKind.NamespaceType) {
231✔
1258
            return 'namespace';
117✔
1259
        }
1260
        return 'type';
114✔
1261
    }
1262

1263
    private addDiagnostic(diagnostic: BsDiagnostic, diagnosticTag?: string) {
1264
        diagnosticTag = diagnosticTag ?? (this.currentSegmentBeingValidated ? ScopeValidatorDiagnosticTag.Segment : ScopeValidatorDiagnosticTag.Default);
51!
1265
        this.event.program.diagnostics.register(diagnostic, {
51✔
1266
            tags: [diagnosticTag],
1267
            segment: this.currentSegmentBeingValidated
1268
        });
1269
    }
1270

1271
    /**
1272
     * Add a diagnostic (to the first scope) that will have `relatedInformation` for each affected scope
1273
     */
1274
    private addMultiScopeDiagnostic(diagnostic: BsDiagnostic, diagnosticTag?: string) {
1275
        diagnosticTag = diagnosticTag ?? (this.currentSegmentBeingValidated ? ScopeValidatorDiagnosticTag.Segment : ScopeValidatorDiagnosticTag.Default);
452✔
1276
        this.event.program.diagnostics.register(diagnostic, {
452✔
1277
            tags: [diagnosticTag],
1278
            segment: this.currentSegmentBeingValidated,
1279
            scope: this.event.scope
1280
        });
1281
    }
1282
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc