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

rokucommunity / brighterscript / #13592

13 Jan 2025 02:40PM UTC coverage: 86.911%. Remained the same
#13592

push

web-flow
Merge 38702985d into 9d6ef67ba

12071 of 14663 branches covered (82.32%)

Branch coverage included in aggregate %.

90 of 94 new or added lines in 11 files covered. (95.74%)

93 existing lines in 8 files now uncovered.

13048 of 14239 relevant lines covered (91.64%)

31884.8 hits per line

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

91.37
/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, isReturnStatement, isStringType, isTypedFunctionType, isUnionType, isVariableExpression, isVoidType, 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, FunctionExpression, CallExpression } from '../../parser/Expression';
17
import { createVisitor, WalkMode } from '../../astUtils/visitors';
1✔
18
import type { BscType } from '../../types/BscType';
19
import type { BscFile } from '../../files/BscFile';
20
import { InsideSegmentWalkMode } from '../../AstValidationSegmenter';
1✔
21
import { TokenKind } from '../../lexer/TokenKind';
1✔
22
import { ParseMode } from '../../parser/Parser';
1✔
23
import { BsClassValidator } from '../../validators/ClassValidator';
1✔
24
import { globalCallableMap } from '../../globalCallables';
1✔
25
import type { XmlScope } from '../../XmlScope';
26
import type { XmlFile } from '../../files/XmlFile';
27
import { SGFieldTypes } from '../../parser/SGTypes';
1✔
28
import { DynamicType } from '../../types/DynamicType';
1✔
29
import { BscTypeKind } from '../../types/BscTypeKind';
1✔
30
import type { BrsDocWithType } from '../../parser/BrightScriptDocParser';
31
import brsDocParser from '../../parser/BrightScriptDocParser';
1✔
32
import { InvalidType } from '../../types/InvalidType';
1✔
33
import { VoidType } from '../../types/VoidType';
1✔
34

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

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

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

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

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

68

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

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

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

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

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

109
            const thisFileHasChanges = this.event.changedFiles.includes(file);
2,068✔
110

111
            if (thisFileHasChanges || this.doesFileProvideChangedSymbol(file, this.event.changedSymbols)) {
2,068✔
112
                this.diagnosticDetectFunctionCollisions(file);
1,925✔
113
            }
114
        });
115

116
        this.event.scope.enumerateOwnFiles((file) => {
1,686✔
117
            if (isBrsFile(file)) {
2,486✔
118

119
                const fileUri = util.pathToUri(file.srcPath);
2,058✔
120
                const thisFileHasChanges = this.event.changedFiles.includes(file);
2,058✔
121

122
                const hasUnvalidatedSegments = file.validationSegmenter.hasUnvalidatedSegments();
2,058✔
123

124
                if (hasChangeInfo && !hasUnvalidatedSegments) {
2,058✔
125
                    return;
401✔
126
                }
127

128
                const validationVisitor = createVisitor({
1,657✔
129
                    VariableExpression: (varExpr) => {
130
                        this.validateVariableAndDottedGetExpressions(file, varExpr);
3,600✔
131
                    },
132
                    DottedGetExpression: (dottedGet) => {
133
                        this.validateVariableAndDottedGetExpressions(file, dottedGet);
1,477✔
134
                    },
135
                    CallExpression: (functionCall) => {
136
                        this.validateFunctionCall(file, functionCall);
910✔
137
                        this.validateCreateObjectCall(file, functionCall);
910✔
138
                    },
139
                    ReturnStatement: (returnStatement) => {
140
                        this.validateReturnStatement(file, returnStatement);
332✔
141
                    },
142
                    DottedSetStatement: (dottedSetStmt) => {
143
                        this.validateDottedSetStatement(file, dottedSetStmt);
90✔
144
                    },
145
                    BinaryExpression: (binaryExpr) => {
146
                        this.validateBinaryExpression(file, binaryExpr);
253✔
147
                    },
148
                    UnaryExpression: (unaryExpr) => {
149
                        this.validateUnaryExpression(file, unaryExpr);
33✔
150
                    },
151
                    AssignmentStatement: (assignStmt) => {
152
                        this.validateAssignmentStatement(file, assignStmt);
645✔
153
                        // Note: this also includes For statements
154
                        this.detectShadowedLocalVar(file, {
645✔
155
                            expr: assignStmt,
156
                            name: assignStmt.tokens.name.text,
157
                            type: this.getNodeTypeWrapper(file, assignStmt, { flags: SymbolTypeFlag.runtime }),
158
                            nameRange: assignStmt.tokens.name.location?.range
1,935✔
159
                        });
160
                    },
161
                    AugmentedAssignmentStatement: (binaryExpr) => {
162
                        this.validateBinaryExpression(file, binaryExpr);
56✔
163
                    },
164
                    IncrementStatement: (stmt) => {
165
                        this.validateIncrementStatement(file, stmt);
9✔
166
                    },
167
                    NewExpression: (newExpr) => {
168
                        this.validateNewExpression(file, newExpr);
121✔
169
                    },
170
                    ForEachStatement: (forEachStmt) => {
171
                        this.detectShadowedLocalVar(file, {
24✔
172
                            expr: forEachStmt,
173
                            name: forEachStmt.tokens.item.text,
174
                            type: this.getNodeTypeWrapper(file, forEachStmt, { flags: SymbolTypeFlag.runtime }),
175
                            nameRange: forEachStmt.tokens.item.location?.range
72✔
176
                        });
177
                    },
178
                    FunctionParameterExpression: (funcParam) => {
179
                        this.detectShadowedLocalVar(file, {
1,071✔
180
                            expr: funcParam,
181
                            name: funcParam.tokens.name.text,
182
                            type: this.getNodeTypeWrapper(file, funcParam, { flags: SymbolTypeFlag.runtime }),
183
                            nameRange: funcParam.tokens.name.location?.range
3,213✔
184
                        });
185
                    },
186
                    FunctionExpression: (func) => {
187
                        this.validateFunctionExpressionForReturn(func);
2,007✔
188
                    },
189
                    AstNode: (node) => {
190
                        //check for doc comments
191
                        if (!node.leadingTrivia || node.leadingTrivia.filter(triviaToken => triviaToken.kind === TokenKind.Comment).length === 0) {
24,303✔
192
                            return;
18,554✔
193
                        }
194
                        this.validateDocComments(node);
242✔
195
                    }
196
                });
197
                // validate only what's needed in the file
198

199
                const segmentsToWalkForValidation = thisFileHasChanges
1,657✔
200
                    ? file.validationSegmenter.getAllUnvalidatedSegments()
1,657✔
201
                    : file.validationSegmenter.getSegmentsWithChangedSymbols(this.event.changedSymbols);
202

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

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

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

239
    private currentSegmentBeingValidated: AstNode;
240

241

242
    private isTypeKnown(exprType: BscType) {
243
        let isKnownType = exprType?.isResolvable();
3,703✔
244
        return isKnownType;
3,703✔
245
    }
246

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

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

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

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

332
            // Test for deprecation
333
            if (brightScriptComponent?.isDeprecated) {
31!
UNCOV
334
                this.addDiagnostic({
×
335
                    ...DiagnosticMessages.itemIsDeprecated(firstParamStringValue, brightScriptComponent.deprecatedDescription),
336
                    location: call.location
337
                });
338
            }
339
        }
340

341
    }
342

343
    /**
344
     * Detect calls to functions with the incorrect number of parameters, or wrong types of arguments
345
     */
346
    private validateFunctionCall(file: BrsFile, expression: CallExpression) {
347
        const getTypeOptions = { flags: SymbolTypeFlag.runtime, data: {} };
910✔
348
        let funcType = this.getNodeTypeWrapper(file, expression?.callee, getTypeOptions);
910!
349
        if (funcType?.isResolvable() && isClassType(funcType)) {
910✔
350
            // We're calling a class - get the constructor
351
            funcType = funcType.getMemberType('new', getTypeOptions);
130✔
352
        }
353
        if (funcType?.isResolvable() && isTypedFunctionType(funcType)) {
910✔
354
            //get min/max parameter count for callable
355
            const { minParams, maxParams } = funcType.getMinMaxParamCount();
648✔
356
            let expCallArgCount = expression.args.length;
648✔
357
            if (expCallArgCount > maxParams || expCallArgCount < minParams) {
648✔
358
                let minMaxParamsText = minParams === maxParams ? maxParams : `${minParams}-${maxParams}`;
32✔
359
                this.addMultiScopeDiagnostic({
32✔
360
                    ...DiagnosticMessages.mismatchArgumentCount(minMaxParamsText, expCallArgCount),
361
                    location: expression.callee.location
362
                });
363
            }
364
            let paramIndex = 0;
648✔
365
            for (let arg of expression.args) {
648✔
366
                const data = {} as ExtraSymbolData;
557✔
367
                let argType = this.getNodeTypeWrapper(file, arg, { flags: SymbolTypeFlag.runtime, data: data });
557✔
368

369
                let paramType = funcType.params[paramIndex]?.type;
557✔
370
                if (!paramType) {
557✔
371
                    // unable to find a paramType -- maybe there are more args than params
372
                    break;
16✔
373
                }
374

375
                if (isCallableType(paramType) && isClassType(argType) && isClassStatement(data.definingNode)) {
541✔
376
                    argType = data.definingNode?.getConstructorType();
2!
377
                }
378

379
                const compatibilityData: TypeCompatibilityData = {};
541✔
380
                const isAllowedArgConversion = this.checkAllowedArgConversions(paramType, argType);
541✔
381
                if (!isAllowedArgConversion && !paramType?.isTypeCompatible(argType, compatibilityData)) {
541!
382
                    this.addMultiScopeDiagnostic({
35✔
383
                        ...DiagnosticMessages.argumentTypeMismatch(argType.toString(), paramType.toString(), compatibilityData),
384
                        location: arg.location
385
                    });
386
                }
387
                paramIndex++;
541✔
388
            }
389

390
        }
391
    }
392

393
    private checkAllowedArgConversions(paramType: BscType, argType: BscType): boolean {
394
        if (isNumberType(argType) && isBooleanType(paramType)) {
541✔
395
            return true;
8✔
396
        }
397
        return false;
533✔
398
    }
399

400

401
    /**
402
     * Detect return statements with incompatible types vs. declared return type
403
     */
404
    private validateReturnStatement(file: BrsFile, returnStmt: ReturnStatement) {
405
        const data: ExtraSymbolData = {};
333✔
406
        const getTypeOptions = { flags: SymbolTypeFlag.runtime, data: data };
333✔
407
        let funcType = returnStmt.findAncestor(isFunctionExpression)?.getType({ flags: SymbolTypeFlag.typetime });
333✔
408
        if (isTypedFunctionType(funcType)) {
333✔
409
            let actualReturnType = returnStmt?.value
332!
410
                ? this.getNodeTypeWrapper(file, returnStmt?.value, getTypeOptions)
1,289!
411
                : VoidType.instance;
412
            const compatibilityData: TypeCompatibilityData = {};
332✔
413

414
            // `return` statement by itself in non-built-in function will actually result in `invalid`
415
            const valueReturnType = isVoidType(actualReturnType) ? InvalidType.instance : actualReturnType;
332✔
416

417
            if (funcType.returnType.isResolvable()) {
332✔
418
                if (!returnStmt?.value && isVoidType(funcType.returnType)) {
328!
419
                    // allow empty return when function is return `as void`
420
                    // eslint-disable-next-line no-useless-return
421
                    return;
9✔
422
                } else if (!funcType.returnType.isTypeCompatible(valueReturnType, compatibilityData)) {
319✔
423
                    this.addMultiScopeDiagnostic({
14✔
424
                        ...DiagnosticMessages.returnTypeMismatch(actualReturnType.toString(), funcType.returnType.toString(), compatibilityData),
425
                        location: returnStmt.value?.location ?? returnStmt.location
84✔
426
                    });
427
                }
428
            }
429
        }
430
    }
431

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

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

457
        let accessibilityIsOk = this.checkMemberAccessibility(file, dottedSetStmt, typeChainExpectedLHS);
46✔
458

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

468
        if (accessibilityIsOk && !expectedLHSType?.isTypeCompatible(actualRHSType, compatibilityData)) {
41!
469
            this.addMultiScopeDiagnostic({
8✔
470
                ...DiagnosticMessages.assignmentTypeMismatch(actualRHSType.toString(), expectedLHSType.toString(), compatibilityData),
471
                location: dottedSetStmt.location
472
            });
473
        }
474
    }
475

476
    /**
477
     * Detect when declared type does not match rhs type
478
     */
479
    private validateAssignmentStatement(file: BrsFile, assignStmt: AssignmentStatement) {
480
        if (!assignStmt?.typeExpression) {
645!
481
            // nothing to check
482
            return;
638✔
483
        }
484

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

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

506
        if (util.isInTypeExpression(binaryExpr)) {
309✔
507
            return;
13✔
508
        }
509

510
        let leftType = isBinaryExpression(binaryExpr)
296✔
511
            ? this.getNodeTypeWrapper(file, binaryExpr.left, getTypeOpts)
296✔
512
            : this.getNodeTypeWrapper(file, binaryExpr.item, getTypeOpts);
513
        let rightType = isBinaryExpression(binaryExpr)
296✔
514
            ? this.getNodeTypeWrapper(file, binaryExpr.right, getTypeOpts)
296✔
515
            : this.getNodeTypeWrapper(file, binaryExpr.value, getTypeOpts);
516

517
        if (!leftType.isResolvable() || !rightType.isResolvable()) {
296✔
518
            // Can not find the type. error handled elsewhere
519
            return;
13✔
520
        }
521

522
        let leftTypeToTest = leftType;
283✔
523
        let rightTypeToTest = rightType;
283✔
524

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

532
        if (isUnionType(leftType) || isUnionType(rightType)) {
283✔
533
            // TODO: it is possible to validate based on innerTypes, but more complicated
534
            // Because you need to verify each combination of types
535
            return;
1✔
536
        }
537
        const opResult = util.binaryOperatorResultType(leftTypeToTest, binaryExpr.tokens.operator, rightTypeToTest);
282✔
538

539
        if (!opResult) {
282✔
540
            // if the result was dynamic or void, that means there wasn't a valid operation
541
            this.addMultiScopeDiagnostic({
9✔
542
                ...DiagnosticMessages.operatorTypeMismatch(binaryExpr.tokens.operator.text, leftType.toString(), rightType.toString()),
543
                location: binaryExpr.location
544
            });
545
        }
546
    }
547

548
    /**
549
     * Detect invalid use of a Unary operator
550
     */
551
    private validateUnaryExpression(file: BrsFile, unaryExpr: UnaryExpression) {
552
        const getTypeOpts = { flags: SymbolTypeFlag.runtime };
33✔
553

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

556
        if (!rightType.isResolvable()) {
33!
557
            // Can not find the type. error handled elsewhere
UNCOV
558
            return;
×
559
        }
560
        let rightTypeToTest = rightType;
33✔
561
        if (isEnumMemberType(rightType)) {
33!
UNCOV
562
            rightTypeToTest = rightType.underlyingType;
×
563
        }
564

565
        if (isUnionType(rightTypeToTest)) {
33✔
566
            // TODO: it is possible to validate based on innerTypes, but more complicated
567
            // Because you need to verify each combination of types
568

569
        } else if (isDynamicType(rightTypeToTest) || isObjectType(rightTypeToTest)) {
32✔
570
            // operand is basically "any" type... ignore;
571

572
        } else if (isPrimitiveType(rightType)) {
29!
573
            const opResult = util.unaryOperatorResultType(unaryExpr.tokens.operator, rightTypeToTest);
29✔
574
            if (!opResult) {
29✔
575
                this.addMultiScopeDiagnostic({
1✔
576
                    ...DiagnosticMessages.operatorTypeMismatch(unaryExpr.tokens.operator.text, rightType.toString()),
577
                    location: unaryExpr.location
578
                });
579
            }
580
        } else {
581
            // rhs is not a primitive, so no binary operator is allowed
UNCOV
582
            this.addMultiScopeDiagnostic({
×
583
                ...DiagnosticMessages.operatorTypeMismatch(unaryExpr.tokens.operator.text, rightType.toString()),
584
                location: unaryExpr.location
585
            });
586
        }
587
    }
588

589
    private validateIncrementStatement(file: BrsFile, incStmt: IncrementStatement) {
590
        const getTypeOpts = { flags: SymbolTypeFlag.runtime };
9✔
591

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

594
        if (!rightType.isResolvable()) {
9!
595
            // Can not find the type. error handled elsewhere
UNCOV
596
            return;
×
597
        }
598

599
        if (isUnionType(rightType)) {
9!
600
            // TODO: it is possible to validate based on innerTypes, but more complicated
601
            // because you need to verify each combination of types
602
        } else if (isDynamicType(rightType) || isObjectType(rightType)) {
9✔
603
            // operand is basically "any" type... ignore
604
        } else if (isNumberType(rightType)) {
8✔
605
            // operand is a number.. this is ok
606
        } else {
607
            // rhs is not a number, so no increment operator is not allowed
608
            this.addMultiScopeDiagnostic({
1✔
609
                ...DiagnosticMessages.operatorTypeMismatch(incStmt.tokens.operator.text, rightType.toString()),
610
                location: incStmt.location
611
            });
612
        }
613
    }
614

615

616
    validateVariableAndDottedGetExpressions(file: BrsFile, expression: VariableExpression | DottedGetExpression) {
617
        if (isDottedGetExpression(expression.parent)) {
5,077✔
618
            // We validate dottedGetExpressions at the top-most level
619
            return;
1,371✔
620
        }
621
        if (isVariableExpression(expression)) {
3,706✔
622
            if (isAssignmentStatement(expression.parent) && expression.parent.tokens.name === expression.tokens.name) {
2,647!
623
                // Don't validate LHS of assignments
UNCOV
624
                return;
×
625
            } else if (isNamespaceStatement(expression.parent)) {
2,647✔
626
                return;
3✔
627
            }
628
        }
629

630
        let symbolType = SymbolTypeFlag.runtime;
3,703✔
631
        let oppositeSymbolType = SymbolTypeFlag.typetime;
3,703✔
632
        const isUsedAsType = util.isInTypeExpression(expression);
3,703✔
633
        if (isUsedAsType) {
3,703✔
634
            // This is used in a TypeExpression - only look up types from SymbolTable
635
            symbolType = SymbolTypeFlag.typetime;
1,149✔
636
            oppositeSymbolType = SymbolTypeFlag.runtime;
1,149✔
637
        }
638

639
        // Do a complete type check on all DottedGet and Variable expressions
640
        // this will create a diagnostic if an invalid member is accessed
641
        const typeChain: TypeChainEntry[] = [];
3,703✔
642
        const typeData = {} as ExtraSymbolData;
3,703✔
643
        let exprType = this.getNodeTypeWrapper(file, expression, {
3,703✔
644
            flags: symbolType,
645
            typeChain: typeChain,
646
            data: typeData
647
        });
648

649
        const hasValidDeclaration = this.hasValidDeclaration(expression, exprType, typeData?.definingNode);
3,703!
650

651
        //include a hint diagnostic if this type is marked as deprecated
652
        if (typeData.flags & SymbolTypeFlag.deprecated) { // eslint-disable-line no-bitwise
3,703✔
653
            this.addMultiScopeDiagnostic({
2✔
654
                ...DiagnosticMessages.itemIsDeprecated(),
655
                location: expression.tokens.name.location,
656
                tags: [DiagnosticTag.Deprecated]
657
            });
658
        }
659

660
        if (!this.isTypeKnown(exprType) && !hasValidDeclaration) {
3,703✔
661
            if (this.getNodeTypeWrapper(file, expression, { flags: oppositeSymbolType, isExistenceTest: true })?.isResolvable()) {
234!
662
                const oppoSiteTypeChain = [];
5✔
663
                const invalidlyUsedResolvedType = this.getNodeTypeWrapper(file, expression, { flags: oppositeSymbolType, typeChain: oppoSiteTypeChain, isExistenceTest: true });
5✔
664
                const typeChainScan = util.processTypeChain(oppoSiteTypeChain);
5✔
665
                if (isUsedAsType) {
5✔
666
                    this.addMultiScopeDiagnostic({
2✔
667
                        ...DiagnosticMessages.itemCannotBeUsedAsType(typeChainScan.fullChainName),
668
                        location: expression.location
669
                    });
670
                } else if (invalidlyUsedResolvedType && !isReferenceType(invalidlyUsedResolvedType)) {
3✔
671
                    if (!isAliasStatement(expression.parent)) {
1!
672
                        // alias rhs CAN be a type!
UNCOV
673
                        this.addMultiScopeDiagnostic({
×
674
                            ...DiagnosticMessages.itemCannotBeUsedAsVariable(invalidlyUsedResolvedType.toString()),
675
                            location: expression.location
676
                        });
677
                    }
678
                } else {
679
                    const typeChainScan = util.processTypeChain(typeChain);
2✔
680
                    //if this is a function call, provide a different diganostic code
681
                    if (isCallExpression(typeChainScan.astNode.parent) && typeChainScan.astNode.parent.callee === expression) {
2✔
682
                        this.addMultiScopeDiagnostic({
1✔
683
                            ...DiagnosticMessages.cannotFindFunction(typeChainScan.itemName, typeChainScan.fullNameOfItem, typeChainScan.itemParentTypeName, this.getParentTypeDescriptor(typeChainScan)),
684
                            location: typeChainScan?.location
3!
685
                        });
686
                    } else {
687
                        this.addMultiScopeDiagnostic({
1✔
688
                            ...DiagnosticMessages.cannotFindName(typeChainScan.itemName, typeChainScan.fullNameOfItem, typeChainScan.itemParentTypeName, this.getParentTypeDescriptor(typeChainScan)),
689
                            location: typeChainScan?.location
3!
690
                        });
691
                    }
692
                }
693

694
            } else if (!typeData?.isFromDocComment) {
229!
695
                // only show "cannot find... " errors if the type is not defined from a doc comment
696
                const typeChainScan = util.processTypeChain(typeChain);
227✔
697
                if (isCallExpression(typeChainScan.astNode.parent) && typeChainScan.astNode.parent.callee === expression) {
227✔
698
                    this.addMultiScopeDiagnostic({
26✔
699
                        ...DiagnosticMessages.cannotFindFunction(typeChainScan.itemName, typeChainScan.fullNameOfItem, typeChainScan.itemParentTypeName, this.getParentTypeDescriptor(typeChainScan)),
700
                        location: typeChainScan?.location
78!
701
                    });
702
                } else {
703
                    this.addMultiScopeDiagnostic({
201✔
704
                        ...DiagnosticMessages.cannotFindName(typeChainScan.itemName, typeChainScan.fullNameOfItem, typeChainScan.itemParentTypeName, this.getParentTypeDescriptor(typeChainScan)),
705
                        location: typeChainScan?.location
603!
706
                    });
707
                }
708

709
            }
710
        }
711
        if (isUsedAsType) {
3,703✔
712
            return;
1,149✔
713
        }
714

715
        const containingNamespace = expression.findAncestor<NamespaceStatement>(isNamespaceStatement);
2,554✔
716
        const containingNamespaceName = containingNamespace?.getName(ParseMode.BrighterScript);
2,554✔
717

718
        if (!(isCallExpression(expression.parent) && isNewExpression(expression.parent?.parent))) {
2,554!
719
            const classUsedAsVarEntry = this.checkTypeChainForClassUsedAsVar(typeChain, containingNamespaceName);
2,433✔
720
            const isClassInNamespace = containingNamespace?.getSymbolTable().hasSymbol(typeChain[0].name, SymbolTypeFlag.runtime);
2,433✔
721
            if (classUsedAsVarEntry && !isClassInNamespace) {
2,433!
722

UNCOV
723
                this.addMultiScopeDiagnostic({
×
724
                    ...DiagnosticMessages.itemCannotBeUsedAsVariable(classUsedAsVarEntry.toString()),
725
                    location: expression.location
726
                });
UNCOV
727
                return;
×
728
            }
729
        }
730

731
        const lastTypeInfo = typeChain[typeChain.length - 1];
2,554✔
732
        const parentTypeInfo = typeChain[typeChain.length - 2];
2,554✔
733

734
        this.checkMemberAccessibility(file, expression, typeChain);
2,554✔
735

736
        if (isNamespaceType(exprType) && !isAliasStatement(expression.parent)) {
2,554✔
737
            this.addMultiScopeDiagnostic({
24✔
738
                ...DiagnosticMessages.itemCannotBeUsedAsVariable('namespace'),
739
                location: expression.location
740
            });
741
        } else if (isEnumType(exprType) && !isAliasStatement(expression.parent)) {
2,530✔
742
            const enumStatement = this.event.scope.getEnum(util.getAllDottedGetPartsAsString(expression));
25✔
743
            if (enumStatement) {
25✔
744
                // there's an enum with this name
745
                this.addMultiScopeDiagnostic({
2✔
746
                    ...DiagnosticMessages.itemCannotBeUsedAsVariable('enum'),
747
                    location: expression.location
748
                });
749
            }
750
        } else if (isDynamicType(exprType) && isEnumType(parentTypeInfo?.type) && isDottedGetExpression(expression)) {
2,505✔
751
            const enumFileLink = this.event.scope.getEnumFileLink(util.getAllDottedGetPartsAsString(expression.obj));
9✔
752
            const typeChainScanForItem = util.processTypeChain(typeChain);
9✔
753
            const typeChainScanForParent = util.processTypeChain(typeChain.slice(0, -1));
9✔
754
            if (enumFileLink) {
9✔
755
                this.addMultiScopeDiagnostic({
5✔
756
                    ...DiagnosticMessages.cannotFindName(lastTypeInfo?.name, typeChainScanForItem.fullChainName, typeChainScanForParent.fullNameOfItem, 'enum'),
15!
757
                    location: lastTypeInfo?.location,
15!
758
                    relatedInformation: [{
759
                        message: 'Enum declared here',
760
                        location: util.createLocationFromRange(
761
                            util.pathToUri(enumFileLink?.file.srcPath),
15!
762
                            enumFileLink?.item?.tokens.name.location?.range
45!
763
                        )
764
                    }]
765
                });
766
            }
767
        }
768
    }
769

770
    private checkTypeChainForClassUsedAsVar(typeChain: TypeChainEntry[], containingNamespaceName: string) {
771
        const ignoreKinds = [AstNodeKind.TypecastExpression, AstNodeKind.NewExpression];
2,433✔
772
        let lowerNameSoFar = '';
2,433✔
773
        let classUsedAsVar;
774
        let isFirst = true;
2,433✔
775
        for (let i = 0; i < typeChain.length - 1; i++) { // do not look at final entry - we CAN use the constructor as a variable
2,433✔
776
            const tce = typeChain[i];
1,281✔
777
            lowerNameSoFar += `${lowerNameSoFar ? '.' : ''}${tce.name.toLowerCase()}`;
1,281✔
778
            if (!isNamespaceType(tce.type)) {
1,281✔
779
                if (isFirst && containingNamespaceName) {
611✔
780
                    lowerNameSoFar = `${containingNamespaceName.toLowerCase()}.${lowerNameSoFar}`;
75✔
781
                }
782
                if (!tce.astNode || ignoreKinds.includes(tce.astNode.kind)) {
611✔
783
                    break;
12✔
784
                } else if (isClassType(tce.type) && lowerNameSoFar.toLowerCase() === tce.type.name.toLowerCase()) {
599✔
785
                    classUsedAsVar = tce.type;
1✔
786
                }
787
                break;
599✔
788
            }
789
            isFirst = false;
670✔
790
        }
791

792
        return classUsedAsVar;
2,433✔
793
    }
794

795
    /**
796
     * Adds diagnostics for accibility mismatches
797
     *
798
     * @param file file
799
     * @param expression containing expression
800
     * @param typeChain type chain to check
801
     * @returns true if member accesiibility is okay
802
     */
803
    private checkMemberAccessibility(file: BscFile, expression: Expression, typeChain: TypeChainEntry[]) {
804
        for (let i = 0; i < typeChain.length - 1; i++) {
2,600✔
805
            const parentChainItem = typeChain[i];
1,434✔
806
            const childChainItem = typeChain[i + 1];
1,434✔
807
            if (isClassType(parentChainItem.type)) {
1,434✔
808
                const containingClassStmt = expression.findAncestor<ClassStatement>(isClassStatement);
158✔
809
                const classStmtThatDefinesChildMember = childChainItem.data?.definingNode?.findAncestor<ClassStatement>(isClassStatement);
158!
810
                if (classStmtThatDefinesChildMember) {
158✔
811
                    const definingClassName = classStmtThatDefinesChildMember.getName(ParseMode.BrighterScript);
156✔
812
                    const inMatchingClassStmt = containingClassStmt?.getName(ParseMode.BrighterScript).toLowerCase() === parentChainItem.type.name.toLowerCase();
156✔
813
                    // eslint-disable-next-line no-bitwise
814
                    if (childChainItem.data.flags & SymbolTypeFlag.private) {
156✔
815
                        if (!inMatchingClassStmt || childChainItem.data.memberOfAncestor) {
15✔
816
                            this.addMultiScopeDiagnostic({
4✔
817
                                ...DiagnosticMessages.memberAccessibilityMismatch(childChainItem.name, childChainItem.data.flags, definingClassName),
818
                                location: expression.location
819
                            });
820
                            // there's an error... don't worry about the rest of the chain
821
                            return false;
4✔
822
                        }
823
                    }
824

825
                    // eslint-disable-next-line no-bitwise
826
                    if (childChainItem.data.flags & SymbolTypeFlag.protected) {
152✔
827
                        const containingClassName = containingClassStmt?.getName(ParseMode.BrighterScript);
13✔
828
                        const containingNamespaceName = expression.findAncestor<NamespaceStatement>(isNamespaceStatement)?.getName(ParseMode.BrighterScript);
13✔
829
                        const ancestorClasses = this.event.scope.getClassHierarchy(containingClassName, containingNamespaceName).map(link => link.item);
13✔
830
                        const isSubClassOfDefiningClass = ancestorClasses.includes(classStmtThatDefinesChildMember);
13✔
831

832
                        if (!isSubClassOfDefiningClass) {
13✔
833
                            this.addMultiScopeDiagnostic({
5✔
834
                                ...DiagnosticMessages.memberAccessibilityMismatch(childChainItem.name, childChainItem.data.flags, definingClassName),
835
                                location: expression.location
836
                            });
837
                            // there's an error... don't worry about the rest of the chain
838
                            return false;
5✔
839
                        }
840
                    }
841
                }
842

843
            }
844
        }
845
        return true;
2,591✔
846
    }
847

848
    /**
849
     * Find all "new" statements in the program,
850
     * and make sure we can find a class with that name
851
     */
852
    private validateNewExpression(file: BrsFile, newExpression: NewExpression) {
853
        const newExprType = this.getNodeTypeWrapper(file, newExpression, { flags: SymbolTypeFlag.typetime });
121✔
854
        if (isClassType(newExprType)) {
121✔
855
            return;
113✔
856
        }
857

858
        let potentialClassName = newExpression.className.getName(ParseMode.BrighterScript);
8✔
859
        const namespaceName = newExpression.findAncestor<NamespaceStatement>(isNamespaceStatement)?.getName(ParseMode.BrighterScript);
8!
860
        let newableClass = this.event.scope.getClass(potentialClassName, namespaceName);
8✔
861

862
        if (!newableClass) {
8!
863
            //try and find functions with this name.
864
            let fullName = util.getFullyQualifiedClassName(potentialClassName, namespaceName);
8✔
865

866
            this.addMultiScopeDiagnostic({
8✔
867
                ...DiagnosticMessages.expressionIsNotConstructable(fullName),
868
                location: newExpression.className.location
869
            });
870

871
        }
872
    }
873

874
    private validateFunctionExpressionForReturn(func: FunctionExpression) {
875
        const returnType = func?.returnTypeExpression?.getType({ flags: SymbolTypeFlag.typetime });
2,007!
876

877
        if (!returnType || !returnType.isResolvable() || isVoidType(returnType) || isDynamicType(returnType)) {
2,007✔
878
            return;
1,803✔
879
        }
880
        const returns = func.body?.findChild<ReturnStatement>(isReturnStatement, { walkMode: WalkMode.visitAll });
204!
881
        if (!returns && isStringType(returnType)) {
204✔
882
            this.addMultiScopeDiagnostic({
5✔
883
                ...DiagnosticMessages.returnTypeCoercionMismatch(returnType.toString()),
884
                location: func.location
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,686✔
894

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

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

903

904
            for (let container of callableContainers) {
126,616✔
905
                if (container.scope === this.event.program.globalScope) {
133,394✔
906
                    globalCallables.push(container);
131,508✔
907
                } else {
908
                    nonGlobalCallables.push(container);
1,886✔
909
                    if (container.scope === this.event.scope) {
1,886✔
910
                        ownCallables.push(container);
1,856✔
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) {
126,616✔
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) {
126,616✔
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,686✔
975

976
        let scriptImports = this.event.scope.getOwnScriptImports();
1,686✔
977
        //verify every script import
978
        for (let scriptImport of scriptImports) {
1,686✔
979
            let referencedFile = this.event.scope.getFileByRelativePath(scriptImport.destPath);
495✔
980
            //if we can't find the file
981
            if (!referencedFile) {
495✔
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) {
16✔
984
                    continue;
2✔
985
                }
986
                let dInfo: DiagnosticInfo;
987
                if (scriptImport.text.trim().length === 0) {
14✔
988
                    dInfo = DiagnosticMessages.scriptSrcCannotBeEmpty();
1✔
989
                } else {
990
                    dInfo = DiagnosticMessages.referencedFileDoesNotExist();
13✔
991
                }
992

993
                this.addMultiScopeDiagnostic({
14✔
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,686✔
1012

1013
        let validator = new BsClassValidator(this.event.scope);
1,686✔
1014
        validator.validate();
1,686✔
1015
        for (const diagnostic of validator.diagnostics) {
1,686✔
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,925✔
1028
        this.event.program.diagnostics.clearByFilter({ scope: this.event.scope, fileUri: fileUri, tag: ScopeValidatorDiagnosticTag.FunctionCollisions });
1,925✔
1029
        for (let func of file.callables) {
1,925✔
1030
            const funcName = func.getName(ParseMode.BrighterScript);
1,725✔
1031
            const lowerFuncName = funcName?.toLowerCase();
1,725!
1032
            if (lowerFuncName) {
1,725!
1033

1034
                //find function declarations with the same name as a stdlib function
1035
                if (globalCallableMap.has(lowerFuncName)) {
1,725✔
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,740✔
1048
        const lowerVarName = varName.toLowerCase();
1,740✔
1049
        const callableContainerMap = this.event.scope.getCallableContainerMap();
1,740✔
1050
        const containingNamespace = varDeclaration.expr?.findAncestor<NamespaceStatement>(isNamespaceStatement);
1,740!
1051
        const localVarIsInNamespace = util.isVariableMemberOfNamespace(varDeclaration.name, varDeclaration.expr, containingNamespace);
1,740✔
1052

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

1057
        if (
1,740✔
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,732✔
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,729✔
1098
            const classStmtLink = this.event.scope.getClassFileLink(lowerVarName);
1,728✔
1099
            if (classStmtLink) {
1,728✔
1100
                this.addMultiScopeDiagnostic({
3✔
1101
                    ...DiagnosticMessages.localVarShadowedByScopedFunction(),
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) {
428!
1117
            return;
397✔
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);
242✔
1173
        for (const docTag of doc.tags) {
242✔
1174
            const docTypeTag = docTag as BrsDocWithType;
29✔
1175
            if (!docTypeTag.typeExpression || !docTypeTag.location) {
29✔
1176
                continue;
1✔
1177
            }
1178
            const foundType = docTypeTag.typeExpression?.getType({ flags: SymbolTypeFlag.typetime });
28!
1179
            if (!foundType?.isResolvable()) {
28!
1180
                this.addMultiScopeDiagnostic({
8✔
1181
                    ...DiagnosticMessages.cannotFindName(docTypeTag.typeString),
1182
                    location: brsDocParser.getTypeLocationFromToken(docTypeTag.token) ?? docTypeTag.location
24!
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 });
428!
1193
        if (scope.xmlFile.parentComponent) {
428✔
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
     * Also, for BrightScript parse-mode, if .getType() returns a node type, do not validate unknown members.
1225
     *
1226
     * In most cases, this returns the result of node.getType()
1227
     *
1228
     * @param file the current file being processed
1229
     * @param node the node to get the type of
1230
     * @param getTypeOpts any options to pass to node.getType()
1231
     * @returns the processed result type
1232
     */
1233
    private getNodeTypeWrapper(file: BrsFile, node: AstNode, getTypeOpts: GetTypeOptions) {
1234
        const type = node?.getType(getTypeOpts);
8,417!
1235

1236
        if (file.parseMode === ParseMode.BrightScript) {
8,417✔
1237
            // this is a brightscript file
1238
            const typeChain = getTypeOpts.typeChain;
946✔
1239
            if (typeChain) {
946✔
1240
                const hasUnion = typeChain.reduce((hasUnion, tce) => {
313✔
1241
                    return hasUnion || isUnionType(tce.type);
364✔
1242
                }, false);
1243
                if (hasUnion) {
313✔
1244
                    // there was a union somewhere in the typechain
1245
                    return DynamicType.instance;
6✔
1246
                }
1247
            }
1248
            if (isUnionType(type)) {
940✔
1249
                //this is a union
1250
                return DynamicType.instance;
4✔
1251
            }
1252

1253
            if (isComponentType(type)) {
936✔
1254
                // modify type to allow any member access for Node types
1255
                type.changeUnknownMemberToDynamic = true;
15✔
1256
            }
1257
        }
1258

1259
        // by default return the result of node.getType()
1260
        return type;
8,407✔
1261
    }
1262

1263
    private getParentTypeDescriptor(typeChainResult: TypeChainProcessResult) {
1264
        if (typeChainResult.itemParentTypeKind === BscTypeKind.NamespaceType) {
234✔
1265
            return 'namespace';
117✔
1266
        }
1267
        return 'type';
117✔
1268
    }
1269

1270
    private addDiagnostic(diagnostic: BsDiagnostic, diagnosticTag?: string) {
1271
        diagnosticTag = diagnosticTag ?? (this.currentSegmentBeingValidated ? ScopeValidatorDiagnosticTag.Segment : ScopeValidatorDiagnosticTag.Default);
51!
1272
        this.event.program.diagnostics.register(diagnostic, {
51✔
1273
            tags: [diagnosticTag],
1274
            segment: this.currentSegmentBeingValidated
1275
        });
1276
    }
1277

1278
    /**
1279
     * Add a diagnostic (to the first scope) that will have `relatedInformation` for each affected scope
1280
     */
1281
    private addMultiScopeDiagnostic(diagnostic: BsDiagnostic, diagnosticTag?: string) {
1282
        diagnosticTag = diagnosticTag ?? (this.currentSegmentBeingValidated ? ScopeValidatorDiagnosticTag.Segment : ScopeValidatorDiagnosticTag.Default);
470✔
1283
        this.event.program.diagnostics.register(diagnostic, {
470✔
1284
            tags: [diagnosticTag],
1285
            segment: this.currentSegmentBeingValidated,
1286
            scope: this.event.scope
1287
        });
1288
    }
1289
}
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