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

rokucommunity / brighterscript / #15133

28 Jan 2026 04:30PM UTC coverage: 87.192% (-0.006%) from 87.198%
#15133

push

web-flow
Merge 3366e9429 into 610607efc

14642 of 17747 branches covered (82.5%)

Branch coverage included in aggregate %.

76 of 78 new or added lines in 11 files covered. (97.44%)

201 existing lines in 9 files now uncovered.

15401 of 16709 relevant lines covered (92.17%)

24803.9 hits per line

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

85.73
/src/bscPlugin/validation/BrsFileValidator.ts
1
import { isAliasStatement, isBlock, isBody, isClassStatement, isConditionalCompileConstStatement, isConditionalCompileErrorStatement, isConditionalCompileStatement, isConstStatement, isDottedGetExpression, isDottedSetStatement, isEnumStatement, isForEachStatement, isForStatement, isFunctionExpression, isFunctionStatement, isIfStatement, isImportStatement, isIndexedGetExpression, isIndexedSetStatement, isInterfaceStatement, isInvalidType, isLibraryStatement, isLiteralExpression, isMethodStatement, isNamespaceStatement, isTypecastExpression, isTypecastStatement, isTypeStatement, isUnaryExpression, isVariableExpression, isVoidType, isWhileStatement } from '../../astUtils/reflection';
1✔
2
import { createVisitor, WalkMode } from '../../astUtils/visitors';
1✔
3
import { DiagnosticMessages } from '../../DiagnosticMessages';
1✔
4
import type { BrsFile } from '../../files/BrsFile';
5
import type { ExtraSymbolData, ValidateFileEvent } from '../../interfaces';
6
import { TokenKind } from '../../lexer/TokenKind';
1✔
7
import type { AstNode, Expression, Statement } from '../../parser/AstNode';
8
import { CallExpression, type FunctionExpression, type LiteralExpression } from '../../parser/Expression';
1✔
9
import { ParseMode } from '../../parser/Parser';
1✔
10
import type { ContinueStatement, EnumMemberStatement, EnumStatement, ForEachStatement, ForStatement, ImportStatement, LibraryStatement, Body, WhileStatement, TypecastStatement, Block, AliasStatement, IfStatement, ConditionalCompileStatement } from '../../parser/Statement';
11
import { SymbolTypeFlag } from '../../SymbolTypeFlag';
1✔
12
import { AssociativeArrayType } from '../../types/AssociativeArrayType';
1✔
13
import { DynamicType } from '../../types/DynamicType';
1✔
14
import util from '../../util';
1✔
15
import type { Range } from 'vscode-languageserver';
16
import type { Token } from '../../lexer/Token';
17
import type { BrightScriptDoc } from '../../parser/BrightScriptDocParser';
18
import brsDocParser from '../../parser/BrightScriptDocParser';
1✔
19
import { TypeStatementType } from '../../types/TypeStatementType';
1✔
20

21
export class BrsFileValidator {
1✔
22
    constructor(
23
        public event: ValidateFileEvent<BrsFile>
2,100✔
24
    ) {
25
    }
26

27

28
    public process() {
29
        const unlinkGlobalSymbolTable = this.event.file.parser.symbolTable.pushParentProvider(() => this.event.program.globalScope.symbolTable);
9,624✔
30

31
        util.validateTooDeepFile(this.event.file);
2,100✔
32

33
        // Invalidate cache on this file
34
        // It could have potentially changed before this from plugins, after this, it will not change
35
        // eslint-disable-next-line @typescript-eslint/dot-notation
36
        this.event.file['_cachedLookups'].invalidate();
2,100✔
37

38
        // make a copy of the bsConsts, because they might be added to
39
        const bsConstsBackup = new Map<string, boolean>(this.event.file.ast.getBsConsts());
2,100✔
40

41
        this.walk();
2,100✔
42
        this.flagTopLevelStatements();
2,100✔
43
        //only validate the file if it was actually parsed (skip files containing typedefs)
44
        if (!this.event.file.hasTypedef) {
2,100✔
45
            this.validateTopOfFileStatements();
2,099✔
46
            this.validateTypecastStatements();
2,099✔
47
        }
48

49
        this.event.file.ast.bsConsts = bsConstsBackup;
2,100✔
50
        unlinkGlobalSymbolTable();
2,100✔
51
    }
52

53
    /**
54
     * Walk the full AST
55
     */
56
    private walk() {
57
        const isBrighterscript = this.event.file.parser.options.mode === ParseMode.BrighterScript;
2,100✔
58

59
        const visitor = createVisitor({
2,100✔
60
            MethodStatement: (node) => {
61
                //add the `super` symbol to class methods
62
                if (isClassStatement(node.parent) && node.parent.hasParentClass()) {
243✔
63
                    const data: ExtraSymbolData = {};
71✔
64
                    const parentClassType = node.parent.parentClassName.getType({ flags: SymbolTypeFlag.typetime, data: data });
71✔
65
                    node.func.body.getSymbolTable().addSymbol('super', { ...data, isInstance: true }, parentClassType, SymbolTypeFlag.runtime);
71✔
66
                }
67
            },
68
            CallfuncExpression: (node) => {
69
                if (node.args.length > 5) {
69✔
70
                    this.event.program.diagnostics.register({
1✔
71
                        ...DiagnosticMessages.callfuncHasToManyArgs(node.args.length),
72
                        location: node.tokens.methodName.location
73
                    });
74
                }
75
            },
76
            EnumStatement: (node) => {
77
                this.validateDeclarationLocations(node, 'enum', () => util.createBoundingRange(node.tokens.enum, node.tokens.name));
155✔
78

79
                this.validateEnumDeclaration(node);
155✔
80

81
                if (!node.tokens.name) {
155!
UNCOV
82
                    return;
×
83
                }
84
                //register this enum declaration
85
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
155✔
86
                // eslint-disable-next-line no-bitwise
87
                node.parent.getSymbolTable()?.addSymbol(node.tokens.name.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime | SymbolTypeFlag.runtime);
155!
88
            },
89
            ClassStatement: (node) => {
90
                if (!node?.tokens?.name) {
434!
91
                    return;
1✔
92
                }
93
                this.validateDeclarationLocations(node, 'class', () => util.createBoundingRange(node.tokens.class, node.tokens.name));
433✔
94

95
                //register this class
96
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
433✔
97
                node.getSymbolTable().addSymbol('m', { definingNode: node, isInstance: true }, nodeType, SymbolTypeFlag.runtime);
433✔
98
                // eslint-disable-next-line no-bitwise
99
                node.parent.getSymbolTable()?.addSymbol(node.tokens.name?.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime | SymbolTypeFlag.runtime);
433!
100

101
                if (node.findAncestor(isNamespaceStatement)) {
433✔
102
                    //add the transpiled name for namespaced constructors to the root symbol table
103
                    const transpiledClassConstructor = node.getName(ParseMode.BrightScript);
135✔
104

105
                    this.event.file.parser.ast.symbolTable.addSymbol(
135✔
106
                        transpiledClassConstructor,
107
                        { definingNode: node },
108
                        node.getConstructorType(),
109
                        // eslint-disable-next-line no-bitwise
110
                        SymbolTypeFlag.runtime | SymbolTypeFlag.postTranspile
111
                    );
112
                }
113
            },
114
            AssignmentStatement: (node) => {
115
                if (!node?.tokens?.name) {
856!
UNCOV
116
                    return;
×
117
                }
118
                if (isForStatement(node.parent) && node.parent.counterDeclaration === node) {
856✔
119
                    // for loop variable variable is added to the block symbol table elsewhere
120
                    return;
21✔
121
                }
122
                const data: ExtraSymbolData = {};
835✔
123
                //register this variable
124
                let nodeType = node.getType({ flags: SymbolTypeFlag.runtime, data: data });
835✔
125
                if (isInvalidType(nodeType) || isVoidType(nodeType)) {
835✔
126
                    nodeType = DynamicType.instance;
11✔
127
                }
128
                node.parent.getSymbolTable()?.addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true, isFromDocComment: data.isFromDocComment, isFromCallFunc: data.isFromCallFunc }, nodeType, SymbolTypeFlag.runtime);
835!
129
            },
130
            DottedSetStatement: (node) => {
131
                this.validateNoOptionalChainingInVarSet(node, [node.obj]);
102✔
132
            },
133
            IndexedSetStatement: (node) => {
134
                this.validateNoOptionalChainingInVarSet(node, [node.obj]);
19✔
135
            },
136
            ForEachStatement: (node) => {
137
                //register the for loop variable
138
            },
139
            NamespaceStatement: (node) => {
140
                if (!node?.nameExpression) {
625!
UNCOV
141
                    return;
×
142
                }
143
                this.validateDeclarationLocations(node, 'namespace', () => util.createBoundingRange(node.tokens.namespace, node.nameExpression));
625✔
144
                //Namespace Types are added at the Scope level - This is handled when the SymbolTables get linked
145
            },
146
            FunctionStatement: (node) => {
147
                this.validateDeclarationLocations(node, 'function', () => util.createBoundingRange(node.func.tokens.functionType, node.tokens.name));
2,108✔
148
                const funcType = node.getType({ flags: SymbolTypeFlag.typetime });
2,108✔
149

150
                if (node.tokens.name?.text) {
2,108!
151
                    node.parent.getSymbolTable().addSymbol(
2,108✔
152
                        node.tokens.name.text,
153
                        { definingNode: node },
154
                        funcType,
155
                        SymbolTypeFlag.runtime
156
                    );
157
                }
158

159
                const namespace = node.findAncestor(isNamespaceStatement);
2,108✔
160
                //this function is declared inside a namespace
161
                if (namespace) {
2,108✔
162
                    namespace.getSymbolTable().addSymbol(
411✔
163
                        node.tokens.name?.text,
1,233!
164
                        { definingNode: node },
165
                        funcType,
166
                        SymbolTypeFlag.runtime
167
                    );
168
                    if (!node.tokens?.name) {
411!
UNCOV
169
                        return;
×
170
                    }
171
                    //add the transpiled name for namespaced functions to the root symbol table
172
                    const transpiledNamespaceFunctionName = node.getName(ParseMode.BrightScript);
411✔
173

174
                    this.event.file.parser.ast.symbolTable.addSymbol(
411✔
175
                        transpiledNamespaceFunctionName,
176
                        { definingNode: node },
177
                        funcType,
178
                        // eslint-disable-next-line no-bitwise
179
                        SymbolTypeFlag.runtime | SymbolTypeFlag.postTranspile
180
                    );
181
                }
182
            },
183
            FunctionExpression: (node) => {
184
                const funcSymbolTable = node.getSymbolTable();
2,393✔
185
                const isInlineFunc = !(isFunctionStatement(node.parent) || isMethodStatement(node.parent));
2,393✔
186
                if (isInlineFunc) {
2,393✔
187
                    // symbol table should not include any symbols from parent func
188
                    funcSymbolTable.pushParentProvider(() => node.findAncestor<Body>(isBody).getSymbolTable());
187✔
189
                }
190
                if (!funcSymbolTable?.hasSymbol('m', SymbolTypeFlag.runtime) || isInlineFunc) {
2,393!
191
                    if (!isTypecastStatement(node.body?.statements?.[0])) {
42!
192
                        funcSymbolTable?.addSymbol('m', { isInstance: true }, new AssociativeArrayType(), SymbolTypeFlag.runtime);
41!
193
                    }
194
                }
195
                this.validateFunctionParameterCount(node);
2,393✔
196
            },
197
            FunctionParameterExpression: (node) => {
198
                const paramName = node.tokens?.name?.text;
1,245!
199
                if (!paramName) {
1,245!
UNCOV
200
                    return;
×
201
                }
202
                const data: ExtraSymbolData = {};
1,245✔
203
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime, data: data });
1,245✔
204
                // add param symbol at expression level, so it can be used as default value in other params
205
                const funcExpr = node.findAncestor<FunctionExpression>(isFunctionExpression);
1,245✔
206
                const funcSymbolTable = funcExpr?.getSymbolTable();
1,245!
207
                const extraSymbolData: ExtraSymbolData = {
1,245✔
208
                    definingNode: node,
209
                    isInstance: true,
210
                    isFromDocComment: data.isFromDocComment,
211
                    description: data.description
212
                };
213
                funcSymbolTable?.addSymbol(paramName, extraSymbolData, nodeType, SymbolTypeFlag.runtime);
1,245!
214

215
                //also add param symbol at block level, as it may be redefined, and if so, should show a union
216
                funcExpr.body.getSymbolTable()?.addSymbol(paramName, extraSymbolData, nodeType, SymbolTypeFlag.runtime);
1,245!
217
            },
218
            InterfaceStatement: (node) => {
219
                if (!node.tokens.name) {
191!
UNCOV
220
                    return;
×
221
                }
222
                this.validateDeclarationLocations(node, 'interface', () => util.createBoundingRange(node.tokens.interface, node.tokens.name));
191✔
223

224
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
191✔
225
                // eslint-disable-next-line no-bitwise
226
                node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime);
191✔
227
            },
228
            ConstStatement: (node) => {
229
                if (!node.tokens.name) {
177!
UNCOV
230
                    return;
×
231
                }
232
                this.validateDeclarationLocations(node, 'const', () => util.createBoundingRange(node.tokens.const, node.tokens.name));
177✔
233
                const nodeType = node.getType({ flags: SymbolTypeFlag.runtime });
177✔
234
                node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true }, nodeType, SymbolTypeFlag.runtime);
177✔
235
            },
236
            CatchStatement: (node) => {
237
                //brs and bs both support variableExpression for the exception variable
238
                if (isVariableExpression(node.exceptionVariableExpression)) {
15✔
239
                    node.parent.getSymbolTable().addSymbol(
13✔
240
                        node.exceptionVariableExpression.getName(),
241
                        { definingNode: node, isInstance: true },
242
                        //TODO I think we can produce a slightly more specific type here (like an AA but with the known exception properties)
243
                        DynamicType.instance,
244
                        SymbolTypeFlag.runtime
245
                    );
246
                    //brighterscript allows catch without an exception variable
247
                } else if (isBrighterscript && !node.exceptionVariableExpression) {
2!
248
                    //this is fine
249

250
                    //brighterscript allows a typecast expression here
251
                } else if (isBrighterscript && isTypecastExpression(node.exceptionVariableExpression) && isVariableExpression(node.exceptionVariableExpression.obj)) {
×
UNCOV
252
                    node.parent.getSymbolTable().addSymbol(
×
253
                        node.exceptionVariableExpression.obj.getName(),
254
                        { definingNode: node, isInstance: true },
255
                        node.exceptionVariableExpression.getType({ flags: SymbolTypeFlag.runtime }),
256
                        SymbolTypeFlag.runtime
257
                    );
258

259
                    //no other expressions are allowed here
260
                } else {
UNCOV
261
                    this.event.program.diagnostics.register({
×
262
                        ...DiagnosticMessages.expectedExceptionVarToFollowCatch(),
263
                        location: node.exceptionVariableExpression?.location ?? node.tokens.catch?.location
×
264
                    });
265
                }
266
            },
267
            DimStatement: (node) => {
268
                if (node.tokens.name) {
18!
269
                    node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true }, node.getType({ flags: SymbolTypeFlag.runtime }), SymbolTypeFlag.runtime);
18✔
270
                }
271
            },
272
            ReturnStatement: (node) => {
273
                const func = node.findAncestor<FunctionExpression>(isFunctionExpression);
518✔
274
                //these situations cannot have a value next to `return`
275
                if (
518✔
276
                    //`function as void`, `sub as void`
277
                    (isVariableExpression(func?.returnTypeExpression?.expression) && func.returnTypeExpression.expression.tokens.name.text?.toLowerCase() === 'void') ||
5,516!
278
                    //`sub` <without return value>
279
                    (func.tokens.functionType?.kind === TokenKind.Sub && !func.returnTypeExpression)
1,515!
280
                ) {
281
                    //there may not be a return value
282
                    if (node.value) {
19✔
283
                        this.event.program.diagnostics.register({
11✔
284
                            ...DiagnosticMessages.voidFunctionMayNotReturnValue(func.tokens.functionType?.text),
33!
285
                            location: node.location
286
                        });
287
                    }
288

289
                } else {
290
                    //there MUST be a return value
291
                    if (!node.value) {
499✔
292
                        this.event.program.diagnostics.register({
11✔
293
                            ...DiagnosticMessages.nonVoidFunctionMustReturnValue(func?.tokens.functionType?.text),
66!
294
                            location: node.location
295
                        });
296
                    }
297
                }
298
            },
299
            ContinueStatement: (node) => {
300
                this.validateContinueStatement(node);
8✔
301
            },
302
            TypecastStatement: (node) => {
303
                node.parent.getSymbolTable().addSymbol('m', { definingNode: node, doNotMerge: true, isInstance: true }, node.getType({ flags: SymbolTypeFlag.typetime }), SymbolTypeFlag.runtime);
22✔
304
            },
305
            ConditionalCompileConstStatement: (node) => {
306
                const assign = node.assignment;
10✔
307
                const constNameLower = assign.tokens.name?.text.toLowerCase();
10!
308
                const astBsConsts = this.event.file.ast.bsConsts;
10✔
309
                if (isLiteralExpression(assign.value)) {
10!
310
                    astBsConsts.set(constNameLower, assign.value.tokens.value.text.toLowerCase() === 'true');
10✔
311
                } else if (isVariableExpression(assign.value)) {
×
312
                    if (this.validateConditionalCompileConst(assign.value.tokens.name)) {
×
UNCOV
313
                        astBsConsts.set(constNameLower, astBsConsts.get(assign.value.tokens.name.text.toLowerCase()));
×
314
                    }
315
                }
316
            },
317
            ConditionalCompileStatement: (node) => {
318
                this.validateConditionalCompileConst(node.tokens.condition);
24✔
319
            },
320
            ConditionalCompileErrorStatement: (node) => {
321
                this.event.program.diagnostics.register({
1✔
322
                    ...DiagnosticMessages.hashError(node.tokens.message.text),
323
                    location: node.location
324
                });
325
            },
326
            AliasStatement: (node) => {
327
                // eslint-disable-next-line no-bitwise
328
                const targetType = node.value.getType({ flags: SymbolTypeFlag.typetime | SymbolTypeFlag.runtime });
30✔
329

330
                // eslint-disable-next-line no-bitwise
331
                node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node, doNotMerge: true, isAlias: true }, targetType, SymbolTypeFlag.runtime | SymbolTypeFlag.typetime);
30✔
332

333
            },
334
            TypeStatement: (node) => {
335
                this.validateDeclarationLocations(node, 'type', () => util.createBoundingRange(node.tokens.type, node.tokens.name));
22✔
336
                const wrappedNodeType = node.getType({ flags: SymbolTypeFlag.runtime });
22✔
337
                const typeStmtType = new TypeStatementType(node.tokens.name.text, wrappedNodeType);
22✔
338
                node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node, isFromTypeStatement: true }, typeStmtType, SymbolTypeFlag.typetime);
22✔
339

340
            },
341
            IfStatement: (node) => {
342
                this.setUpComplementSymbolTables(node, isIfStatement);
153✔
343
            },
344
            Block: (node) => {
345
                const blockSymbolTable = node.symbolTable;
2,708✔
346
                if (node.findAncestor<Block>(isFunctionExpression)) {
2,708✔
347
                    // this block is in a function. order matters!
348
                    blockSymbolTable.isOrdered = true;
2,704✔
349
                }
350
                if (!isFunctionExpression(node.parent) && node.parent) {
2,708✔
351
                    node.symbolTable.name = `Block-${node.parent.kind}@${node.location?.range?.start?.line}`;
315✔
352
                    // we're a block inside another block (or body). This block is a pocket in the bigger block
353
                    node.parent.getSymbolTable().addPocketTable({
315✔
354
                        index: node.parent.statementIndex,
355
                        table: blockSymbolTable,
356
                        // code always flows through ConditionalCompiles, because we walk according to defined BSConsts
357
                        willAlwaysBeExecuted: isConditionalCompileStatement(node.parent)
358
                    });
359

360
                    if (isForStatement(node.parent)) {
315✔
361
                        const counterDecl = node.parent.counterDeclaration;
21✔
362
                        const loopVar = counterDecl.tokens.name;
21✔
363
                        const loopVarType = counterDecl.getType({ flags: SymbolTypeFlag.runtime });
21✔
364
                        blockSymbolTable.addSymbol(loopVar.text, { isInstance: true }, loopVarType, SymbolTypeFlag.runtime);
21✔
365

366
                    } else if (isForEachStatement(node.parent)) {
294✔
367
                        const loopVarType = node.parent.getLoopVariableType({ flags: SymbolTypeFlag.runtime });
49✔
368
                        blockSymbolTable.addSymbol(node.parent.tokens.item.text, { isInstance: true }, loopVarType, SymbolTypeFlag.runtime);
49✔
369
                    }
370
                }
371
            },
372
            AstNode: (node) => {
373
                //check for doc comments
374
                if (!node.leadingTrivia || node.leadingTrivia.length === 0) {
29,718✔
375
                    return;
5,273✔
376
                }
377
                const doc = brsDocParser.parseNode(node);
24,445✔
378
                if (doc.tags.length === 0) {
24,445✔
379
                    return;
24,393✔
380
                }
381

382
                let funcExpr = node.findAncestor<FunctionExpression>(isFunctionExpression);
52✔
383
                if (funcExpr) {
52✔
384
                    // handle comment tags inside a function expression
385
                    this.processDocTagsInFunction(doc, node, funcExpr);
8✔
386
                } else {
387
                    //handle comment tags outside of a function expression
388
                    this.processDocTagsAtTopLevel(doc, node);
44✔
389
                }
390
            }
391
        });
392

393
        this.event.file.ast.walk((node, parent) => {
2,100✔
394
            visitor(node, parent);
29,718✔
395
        }, {
396
            walkMode: WalkMode.visitAllRecursive
397
        });
398
    }
399

400
    private processDocTagsInFunction(doc: BrightScriptDoc, node: AstNode, funcExpr: FunctionExpression) {
401
        //TODO: Handle doc tags that influence the function they're in
402

403
        // For example, declaring variable types:
404
        // const symbolTable = funcExpr.body.getSymbolTable();
405

406
        // for (const varTag of doc.getAllTags(BrsDocTagKind.Var)) {
407
        //     const varName = (varTag as BrsDocParamTag).name;
408
        //     const varTypeStr = (varTag as BrsDocParamTag).type;
409
        //     const data: ExtraSymbolData = {};
410
        //     const type = doc.getTypeFromContext(varTypeStr, node, { flags: SymbolTypeFlag.typetime, fullName: varTypeStr, data: data, tableProvider: () => symbolTable });
411
        //     if (type) {
412
        //         symbolTable.addSymbol(varName, { ...data, isFromDocComment: true }, type, SymbolTypeFlag.runtime);
413
        //     }
414
        // }
415
    }
416

417
    private processDocTagsAtTopLevel(doc: BrightScriptDoc, node: AstNode) {
418
        //TODO:
419
        // - handle import statements?
420
        // - handle library statements?
421
        // - handle typecast statements?
422
        // - handle alias statements?
423
        // - handle const statements?
424
        // - allow interface definitions?
425
    }
426

427
    /**
428
     * Validate that a statement is defined in one of these specific locations
429
     *  - the root of the AST
430
     *  - inside a namespace
431
     * This is applicable to things like FunctionStatement, ClassStatement, NamespaceStatement, EnumStatement, InterfaceStatement
432
     */
433
    private validateDeclarationLocations(statement: Statement, keyword: string, rangeFactory?: () => (Range | undefined)) {
434
        //if nested inside a namespace, or defined at the root of the AST (i.e. in a body that has no parent)
435
        const isOkDeclarationLocation = (parentNode) => {
3,711✔
436
            return isNamespaceStatement(parentNode?.parent) || (isBody(parentNode) && !parentNode?.parent);
3,716!
437
        };
438
        if (isOkDeclarationLocation(statement.parent)) {
3,711✔
439
            return;
3,692✔
440
        }
441

442
        // is this in a top levelconditional compile?
443
        if (isConditionalCompileStatement(statement.parent?.parent)) {
19!
444
            if (isOkDeclarationLocation(statement.parent.parent.parent)) {
5✔
445
                return;
4✔
446
            }
447
        }
448

449
        //the statement was defined in the wrong place. Flag it.
450
        this.event.program.diagnostics.register({
15✔
451
            ...DiagnosticMessages.keywordMustBeDeclaredAtNamespaceLevel(keyword),
452
            location: rangeFactory ? util.createLocationFromFileRange(this.event.file, rangeFactory()) : statement.location
15!
453
        });
454
    }
455

456
    private validateFunctionParameterCount(func: FunctionExpression) {
457
        if (func.parameters.length > CallExpression.MaximumArguments) {
2,393✔
458
            //flag every parameter over the limit
459
            for (let i = CallExpression.MaximumArguments; i < func.parameters.length; i++) {
2✔
460
                this.event.program.diagnostics.register({
3✔
461
                    ...DiagnosticMessages.tooManyCallableParameters(func.parameters.length, CallExpression.MaximumArguments),
462
                    location: func.parameters[i]?.tokens.name?.location ?? func.parameters[i]?.location ?? func.location
36!
463
                });
464
            }
465
        }
466
    }
467

468
    private validateEnumDeclaration(stmt: EnumStatement) {
469
        const members = stmt.getMembers();
155✔
470
        //the enum data type is based on the first member value
471
        const enumValueKind = (members.find(x => x.value)?.value as LiteralExpression)?.tokens?.value?.kind ?? TokenKind.IntegerLiteral;
216✔
472
        const memberNames = new Set<string>();
155✔
473
        for (const member of members) {
155✔
474
            const memberNameLower = member.name?.toLowerCase();
307!
475

476
            /**
477
             * flag duplicate member names
478
             */
479
            if (memberNames.has(memberNameLower)) {
307✔
480
                this.event.program.diagnostics.register({
1✔
481
                    ...DiagnosticMessages.duplicateIdentifier(member.name),
482
                    location: member.location
483
                });
484
            } else {
485
                memberNames.add(memberNameLower);
306✔
486
            }
487

488
            //Enforce all member values are the same type
489
            this.validateEnumValueTypes(member, enumValueKind);
307✔
490
        }
491
    }
492

493
    private validateEnumValueTypes(member: EnumMemberStatement, enumValueKind: TokenKind) {
494
        let memberValueKind: TokenKind;
495
        let memberValue: Expression;
496
        if (isUnaryExpression(member.value)) {
307✔
497
            memberValueKind = (member.value?.right as LiteralExpression)?.tokens?.value?.kind;
2!
498
            memberValue = member.value?.right;
2!
499
        } else {
500
            memberValueKind = (member.value as LiteralExpression)?.tokens?.value?.kind;
305✔
501
            memberValue = member.value;
305✔
502
        }
503
        const range = (memberValue ?? member)?.location?.range;
307!
504
        if (
307✔
505
            //is integer enum, has value, that value type is not integer
506
            (enumValueKind === TokenKind.IntegerLiteral && memberValueKind && memberValueKind !== enumValueKind) ||
1,030✔
507
            //has value, that value is not a literal
508
            (memberValue && !isLiteralExpression(memberValue))
509
        ) {
510
            this.event.program.diagnostics.register({
6✔
511
                ...DiagnosticMessages.enumValueMustBeType(
512
                    enumValueKind.replace(/literal$/i, '').toLowerCase()
513
                ),
514
                location: util.createLocationFromFileRange(this.event.file, range)
515
            });
516
        }
517

518
        //is non integer value
519
        if (enumValueKind !== TokenKind.IntegerLiteral) {
307✔
520
            //default value present
521
            if (memberValueKind) {
112✔
522
                //member value is same as enum
523
                if (memberValueKind !== enumValueKind) {
110✔
524
                    this.event.program.diagnostics.register({
1✔
525
                        ...DiagnosticMessages.enumValueMustBeType(
526
                            enumValueKind.replace(/literal$/i, '').toLowerCase()
527
                        ),
528
                        location: util.createLocationFromFileRange(this.event.file, range)
529
                    });
530
                }
531

532
                //default value missing
533
            } else {
534
                this.event.program.diagnostics.register({
2✔
535
                    ...DiagnosticMessages.enumValueIsRequired(
536
                        enumValueKind.replace(/literal$/i, '').toLowerCase()
537
                    ),
538
                    location: util.createLocationFromFileRange(this.event.file, range)
539
                });
540
            }
541
        }
542
    }
543

544

545
    private validateConditionalCompileConst(ccConst: Token) {
546
        const isBool = ccConst.kind === TokenKind.True || ccConst.kind === TokenKind.False;
24✔
547
        if (!isBool && !this.event.file.ast.bsConsts.has(ccConst.text.toLowerCase())) {
24✔
548
            this.event.program.diagnostics.register({
2✔
549
                ...DiagnosticMessages.hashConstDoesNotExist(),
550
                location: ccConst.location
551
            });
552
            return false;
2✔
553
        }
554
        return true;
22✔
555
    }
556

557
    /**
558
     * Find statements defined at the top level (or inside a namespace body) that are not allowed to be there
559
     */
560
    private flagTopLevelStatements() {
561
        const statements = [...this.event.file.ast.statements];
2,100✔
562
        while (statements.length > 0) {
2,100✔
563
            const statement = statements.pop();
3,957✔
564
            if (isNamespaceStatement(statement)) {
3,957✔
565
                statements.push(...statement.body.statements);
620✔
566
            } else {
567
                //only allow these statement types
568
                if (
3,337✔
569
                    !isFunctionStatement(statement) &&
7,563✔
570
                    !isClassStatement(statement) &&
571
                    !isEnumStatement(statement) &&
572
                    !isInterfaceStatement(statement) &&
573
                    !isLibraryStatement(statement) &&
574
                    !isImportStatement(statement) &&
575
                    !isConstStatement(statement) &&
576
                    !isTypecastStatement(statement) &&
577
                    !isConditionalCompileConstStatement(statement) &&
578
                    !isConditionalCompileErrorStatement(statement) &&
579
                    !isConditionalCompileStatement(statement) &&
580
                    !isAliasStatement(statement) &&
581
                    !isTypeStatement(statement)
582
                ) {
583
                    this.event.program.diagnostics.register({
10✔
584
                        ...DiagnosticMessages.unexpectedStatementOutsideFunction(),
585
                        location: statement.location
586
                    });
587
                }
588
            }
589
        }
590
    }
591

592
    private getTopOfFileStatements() {
593
        let topOfFileIncludeStatements = [] as Array<LibraryStatement | ImportStatement | TypecastStatement | AliasStatement>;
4,198✔
594
        for (let stmt of this.event.file.parser.ast.statements) {
4,198✔
595
            //if we found a non-library statement, this statement is not at the top of the file
596
            if (isLibraryStatement(stmt) || isImportStatement(stmt) || isTypecastStatement(stmt) || isAliasStatement(stmt)) {
4,504✔
597
                topOfFileIncludeStatements.push(stmt);
482✔
598
            } else {
599
                //break out of the loop, we found all of our library statements
600
                break;
4,022✔
601
            }
602
        }
603
        return topOfFileIncludeStatements;
4,198✔
604
    }
605

606
    private validateTopOfFileStatements() {
607
        let topOfFileStatements = this.getTopOfFileStatements();
2,099✔
608

609
        let statements = [
2,099✔
610
            // eslint-disable-next-line @typescript-eslint/dot-notation
611
            ...this.event.file['_cachedLookups'].libraryStatements,
612
            // eslint-disable-next-line @typescript-eslint/dot-notation
613
            ...this.event.file['_cachedLookups'].importStatements,
614
            // eslint-disable-next-line @typescript-eslint/dot-notation
615
            ...this.event.file['_cachedLookups'].aliasStatements
616
        ];
617
        for (let result of statements) {
2,099✔
618
            //if this statement is not one of the top-of-file statements,
619
            //then add a diagnostic explaining that it is invalid
620
            if (!topOfFileStatements.includes(result)) {
236✔
621
                if (isLibraryStatement(result)) {
5✔
622
                    this.event.program.diagnostics.register({
2✔
623
                        ...DiagnosticMessages.unexpectedStatementLocation('library', 'at the top of the file'),
624
                        location: result.location
625
                    });
626
                } else if (isImportStatement(result)) {
3✔
627
                    this.event.program.diagnostics.register({
1✔
628
                        ...DiagnosticMessages.unexpectedStatementLocation('import', 'at the top of the file'),
629
                        location: result.location
630
                    });
631
                } else if (isAliasStatement(result)) {
2!
632
                    this.event.program.diagnostics.register({
2✔
633
                        ...DiagnosticMessages.unexpectedStatementLocation('alias', 'at the top of the file'),
634
                        location: result.location
635
                    });
636
                }
637
            }
638
        }
639
    }
640

641
    private validateTypecastStatements() {
642
        let topOfFileTypecastStatements = this.getTopOfFileStatements().filter(stmt => isTypecastStatement(stmt));
2,099✔
643

644
        //check only one `typecast` statement at "top" of file (eg. before non import/library statements)
645
        for (let i = 1; i < topOfFileTypecastStatements.length; i++) {
2,099✔
646
            const typecastStmt = topOfFileTypecastStatements[i];
1✔
647
            this.event.program.diagnostics.register({
1✔
648
                ...DiagnosticMessages.unexpectedStatementLocation('typecast', 'at the top of the file or beginning of function or namespace'),
649
                location: typecastStmt.location
650
            });
651
        }
652

653
        // eslint-disable-next-line @typescript-eslint/dot-notation
654
        for (let result of this.event.file['_cachedLookups'].typecastStatements) {
2,099✔
655
            let isBadTypecastObj = false;
22✔
656
            if (!isVariableExpression(result.typecastExpression.obj)) {
22✔
657
                isBadTypecastObj = true;
1✔
658
            } else if (result.typecastExpression.obj.tokens.name.text.toLowerCase() !== 'm') {
21✔
659
                isBadTypecastObj = true;
1✔
660
            }
661
            if (isBadTypecastObj) {
22✔
662
                this.event.program.diagnostics.register({
2✔
663
                    ...DiagnosticMessages.invalidTypecastStatementApplication(util.getAllDottedGetPartsAsString(result.typecastExpression.obj)),
664
                    location: result.typecastExpression.obj.location
665
                });
666
            }
667

668
            if (topOfFileTypecastStatements.includes(result)) {
22✔
669
                // already validated
670
                continue;
10✔
671
            }
672

673
            const block = result.findAncestor<Body | Block>(node => (isBody(node) || isBlock(node)));
12✔
674
            const isFirst = block?.statements[0] === result;
12!
675
            const isAllowedBlock = (isBody(block) || isFunctionExpression(block.parent) || isNamespaceStatement(block.parent));
12!
676

677
            if (!isFirst || !isAllowedBlock) {
12✔
678
                this.event.program.diagnostics.register({
3✔
679
                    ...DiagnosticMessages.unexpectedStatementLocation('typecast', 'at the top of the file or beginning of function or namespace'),
680
                    location: result.location
681
                });
682
            }
683
        }
684
    }
685

686
    private validateContinueStatement(statement: ContinueStatement) {
687
        const validateLoopTypeMatch = (expectedLoopType: TokenKind) => {
8✔
688
            //coerce ForEach to For
689
            expectedLoopType = expectedLoopType === TokenKind.ForEach ? TokenKind.For : expectedLoopType;
7✔
690
            const actualLoopType = statement.tokens.loopType;
7✔
691
            if (actualLoopType && expectedLoopType?.toLowerCase() !== actualLoopType.text?.toLowerCase()) {
7!
692
                this.event.program.diagnostics.register({
3✔
693
                    location: statement.tokens.loopType.location,
694
                    ...DiagnosticMessages.expectedToken(expectedLoopType)
695
                });
696
            }
697
        };
698

699
        //find the parent loop statement
700
        const parent = statement.findAncestor<WhileStatement | ForStatement | ForEachStatement>((node) => {
8✔
701
            if (isWhileStatement(node)) {
18✔
702
                validateLoopTypeMatch(node.tokens.while.kind);
3✔
703
                return true;
3✔
704
            } else if (isForStatement(node)) {
15✔
705
                validateLoopTypeMatch(node.tokens.for.kind);
3✔
706
                return true;
3✔
707
            } else if (isForEachStatement(node)) {
12✔
708
                validateLoopTypeMatch(node.tokens.forEach.kind);
1✔
709
                return true;
1✔
710
            }
711
        });
712
        //flag continue statements found outside of a loop
713
        if (!parent) {
8✔
714
            this.event.program.diagnostics.register({
1✔
715
                location: statement.location,
716
                ...DiagnosticMessages.illegalContinueStatement()
717
            });
718
        }
719
    }
720

721
    /**
722
     * Validate that there are no optional chaining operators on the left-hand-side of an assignment, indexed set, or dotted get
723
     */
724
    private validateNoOptionalChainingInVarSet(parent: AstNode, children: AstNode[]) {
725
        const nodes = [...children, parent];
121✔
726
        //flag optional chaining anywhere in the left of this statement
727
        while (nodes.length > 0) {
121✔
728
            const node = nodes.shift();
242✔
729
            if (
242✔
730
                // a?.b = true or a.b?.c = true
731
                ((isDottedSetStatement(node) || isDottedGetExpression(node)) && node.tokens.dot?.kind === TokenKind.QuestionDot) ||
1,379!
732
                // a.b?[2] = true
733
                (isIndexedGetExpression(node) && (node?.tokens.questionDot?.kind === TokenKind.QuestionDot || node.tokens.openingSquare?.kind === TokenKind.QuestionLeftSquare)) ||
36!
734
                // a?[1] = true
735
                (isIndexedSetStatement(node) && node.tokens.openingSquare?.kind === TokenKind.QuestionLeftSquare)
57!
736
            ) {
737
                //try to highlight the entire left-hand-side expression if possible
738
                let range: Range;
739
                if (isDottedSetStatement(parent)) {
8✔
740
                    range = util.createBoundingRange(parent.obj?.location, parent.tokens.dot, parent.tokens.name);
5!
741
                } else if (isIndexedSetStatement(parent)) {
3!
742
                    range = util.createBoundingRange(parent.obj?.location, parent.tokens.openingSquare, ...parent.indexes, parent.tokens.closingSquare);
3!
743
                } else {
UNCOV
744
                    range = node.location?.range;
×
745
                }
746

747
                this.event.program.diagnostics.register({
8✔
748
                    ...DiagnosticMessages.noOptionalChainingInLeftHandSideOfAssignment(),
749
                    location: util.createLocationFromFileRange(this.event.file, range)
750
                });
751
            }
752

753
            if (node === parent) {
242✔
754
                break;
121✔
755
            } else {
756
                nodes.push(node.parent);
121✔
757
            }
758
        }
759
    }
760

761
    private setUpComplementSymbolTables(node: IfStatement | ConditionalCompileStatement, predicate: (node: AstNode) => boolean) {
762
        if (isBlock(node.elseBranch)) {
153✔
763
            const elseTable = node.elseBranch.symbolTable;
28✔
764
            let currentNode = node;
28✔
765
            while (predicate(currentNode)) {
28✔
766
                const thenBranch = (currentNode as IfStatement | ConditionalCompileStatement).thenBranch;
39✔
767
                elseTable.complementOtherTable(thenBranch.symbolTable);
39✔
768
                currentNode = currentNode.parent as IfStatement | ConditionalCompileStatement;
39✔
769
            }
770
        }
771
    }
772
}
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