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

rokucommunity / brighterscript / #14428

23 May 2025 01:53PM UTC coverage: 86.994% (-0.006%) from 87.0%
#14428

push

web-flow
Merge 12c748f28 into ce167b8d3

13882 of 16865 branches covered (82.31%)

Branch coverage included in aggregate %.

18 of 19 new or added lines in 3 files covered. (94.74%)

39 existing lines in 4 files now uncovered.

14733 of 16028 relevant lines covered (91.92%)

21961.95 hits per line

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

86.89
/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, 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, OnFileValidateEvent } 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 { ArrayDefaultTypeReferenceType } from '../../types/ReferenceType';
1✔
13
import { AssociativeArrayType } from '../../types/AssociativeArrayType';
1✔
14
import { DynamicType } from '../../types/DynamicType';
1✔
15
import util from '../../util';
1✔
16
import type { Range } from 'vscode-languageserver';
17
import type { Token } from '../../lexer/Token';
18
import type { BrightScriptDoc } from '../../parser/BrightScriptDocParser';
19
import brsDocParser from '../../parser/BrightScriptDocParser';
1✔
20

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

27

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

31
        util.validateTooDeepFile(this.event.file);
1,934✔
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();
1,934✔
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());
1,934✔
40

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

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

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

59
        const visitor = createVisitor({
1,934✔
60
            MethodStatement: (node) => {
61
                //add the `super` symbol to class methods
62
                if (isClassStatement(node.parent) && node.parent.hasParentClass()) {
242✔
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) {
62✔
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));
150✔
78

79
                this.validateEnumDeclaration(node);
150✔
80

81
                //register this enum declaration
82
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
150✔
83
                // eslint-disable-next-line no-bitwise
84
                node.parent.getSymbolTable()?.addSymbol(node.tokens.name.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime | SymbolTypeFlag.runtime);
150!
85
            },
86
            ClassStatement: (node) => {
87
                this.validateDeclarationLocations(node, 'class', () => util.createBoundingRange(node.tokens.class, node.tokens.name));
418✔
88

89
                //register this class
90
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
418✔
91
                node.getSymbolTable().addSymbol('m', { definingNode: node, isInstance: true }, nodeType, SymbolTypeFlag.runtime);
418✔
92
                // eslint-disable-next-line no-bitwise
93
                node.parent.getSymbolTable()?.addSymbol(node.tokens.name?.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime | SymbolTypeFlag.runtime);
418!
94

95
                if (node.findAncestor(isNamespaceStatement)) {
418✔
96
                    //add the transpiled name for namespaced constructors to the root symbol table
97
                    const transpiledClassConstructor = node.getName(ParseMode.BrightScript);
129✔
98

99
                    this.event.file.parser.ast.symbolTable.addSymbol(
129✔
100
                        transpiledClassConstructor,
101
                        { definingNode: node },
102
                        node.getConstructorType(),
103
                        // eslint-disable-next-line no-bitwise
104
                        SymbolTypeFlag.runtime | SymbolTypeFlag.postTranspile
105
                    );
106
                }
107
            },
108
            AssignmentStatement: (node) => {
109
                const data: ExtraSymbolData = {};
765✔
110
                //register this variable
111
                let nodeType = node.getType({ flags: SymbolTypeFlag.runtime, data: data });
765✔
112
                if (isInvalidType(nodeType) || isVoidType(nodeType)) {
765✔
113
                    nodeType = DynamicType.instance;
11✔
114
                }
115
                node.parent.getSymbolTable()?.addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true, isFromDocComment: data.isFromDocComment, isFromCallFunc: data.isFromCallFunc }, nodeType, SymbolTypeFlag.runtime);
765!
116
            },
117
            DottedSetStatement: (node) => {
118
                this.validateNoOptionalChainingInVarSet(node, [node.obj]);
100✔
119
            },
120
            IndexedSetStatement: (node) => {
121
                this.validateNoOptionalChainingInVarSet(node, [node.obj]);
19✔
122
            },
123
            ForEachStatement: (node) => {
124
                //register the for loop variable
125
                const loopTargetType = node.target.getType({ flags: SymbolTypeFlag.runtime });
27✔
126
                const loopVarType = new ArrayDefaultTypeReferenceType(loopTargetType);
27✔
127

128
                node.parent.getSymbolTable()?.addSymbol(node.tokens.item.text, { definingNode: node, isInstance: true, canUseInDefinedAstNode: true }, loopVarType, SymbolTypeFlag.runtime);
27!
129
            },
130
            NamespaceStatement: (node) => {
131
                this.validateDeclarationLocations(node, 'namespace', () => util.createBoundingRange(node.tokens.namespace, node.nameExpression));
601✔
132
                //Namespace Types are added at the Scope level - This is handled when the SymbolTables get linked
133
            },
134
            FunctionStatement: (node) => {
135
                this.validateDeclarationLocations(node, 'function', () => util.createBoundingRange(node.func.tokens.functionType, node.tokens.name));
1,931✔
136
                const funcType = node.getType({ flags: SymbolTypeFlag.typetime });
1,931✔
137

138
                if (node.tokens.name?.text) {
1,931!
139
                    node.parent.getSymbolTable().addSymbol(
1,931✔
140
                        node.tokens.name.text,
141
                        { definingNode: node },
142
                        funcType,
143
                        SymbolTypeFlag.runtime
144
                    );
145
                }
146

147
                const namespace = node.findAncestor(isNamespaceStatement);
1,931✔
148
                //this function is declared inside a namespace
149
                if (namespace) {
1,931✔
150
                    namespace.getSymbolTable().addSymbol(
407✔
151
                        node.tokens.name?.text,
1,221!
152
                        { definingNode: node },
153
                        funcType,
154
                        SymbolTypeFlag.runtime
155
                    );
156
                    //add the transpiled name for namespaced functions to the root symbol table
157
                    const transpiledNamespaceFunctionName = node.getName(ParseMode.BrightScript);
407✔
158

159
                    this.event.file.parser.ast.symbolTable.addSymbol(
407✔
160
                        transpiledNamespaceFunctionName,
161
                        { definingNode: node },
162
                        funcType,
163
                        // eslint-disable-next-line no-bitwise
164
                        SymbolTypeFlag.runtime | SymbolTypeFlag.postTranspile
165
                    );
166
                }
167
            },
168
            FunctionExpression: (node) => {
169
                const funcSymbolTable = node.getSymbolTable();
2,210✔
170
                const isInlineFunc = !(isFunctionStatement(node.parent) || isMethodStatement(node.parent));
2,210✔
171
                if (isInlineFunc) {
2,210✔
172
                    // symbol table should not include any symbols from parent func
173
                    funcSymbolTable.pushParentProvider(() => node.findAncestor<Body>(isBody).getSymbolTable());
140✔
174
                }
175
                if (!funcSymbolTable?.hasSymbol('m', SymbolTypeFlag.runtime) || isInlineFunc) {
2,210!
176
                    if (!isTypecastStatement(node.body?.statements?.[0])) {
37!
177
                        funcSymbolTable?.addSymbol('m', { isInstance: true }, new AssociativeArrayType(), SymbolTypeFlag.runtime);
36!
178
                    }
179
                }
180
                this.validateFunctionParameterCount(node);
2,210✔
181
            },
182
            FunctionParameterExpression: (node) => {
183
                const paramName = node.tokens.name?.text;
1,119!
184
                const data: ExtraSymbolData = {};
1,119✔
185
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime, data: data });
1,119✔
186
                // add param symbol at expression level, so it can be used as default value in other params
187
                const funcExpr = node.findAncestor<FunctionExpression>(isFunctionExpression);
1,119✔
188
                const funcSymbolTable = funcExpr?.getSymbolTable();
1,119!
189
                funcSymbolTable?.addSymbol(paramName, { definingNode: node, isInstance: true, isFromDocComment: data.isFromDocComment }, nodeType, SymbolTypeFlag.runtime);
1,119!
190

191
                //also add param symbol at block level, as it may be redefined, and if so, should show a union
192
                funcExpr.body.getSymbolTable()?.addSymbol(paramName, { definingNode: node, isInstance: true, isFromDocComment: data.isFromDocComment }, nodeType, SymbolTypeFlag.runtime);
1,119!
193
            },
194
            InterfaceStatement: (node) => {
195
                this.validateDeclarationLocations(node, 'interface', () => util.createBoundingRange(node.tokens.interface, node.tokens.name));
153✔
196

197
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
153✔
198
                // eslint-disable-next-line no-bitwise
199
                node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime);
153✔
200
            },
201
            ConstStatement: (node) => {
202
                this.validateDeclarationLocations(node, 'const', () => util.createBoundingRange(node.tokens.const, node.tokens.name));
145✔
203
                const nodeType = node.getType({ flags: SymbolTypeFlag.runtime });
145✔
204
                node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true }, nodeType, SymbolTypeFlag.runtime);
145✔
205
            },
206
            CatchStatement: (node) => {
207
                //brs and bs both support variableExpression for the exception variable
208
                if (isVariableExpression(node.exceptionVariableExpression)) {
9✔
209
                    node.parent.getSymbolTable().addSymbol(
7✔
210
                        node.exceptionVariableExpression.getName(),
211
                        { definingNode: node, isInstance: true },
212
                        //TODO I think we can produce a slightly more specific type here (like an AA but with the known exception properties)
213
                        DynamicType.instance,
214
                        SymbolTypeFlag.runtime
215
                    );
216
                    //brighterscript allows catch without an exception variable
217
                } else if (isBrighterscript && !node.exceptionVariableExpression) {
2!
218
                    //this is fine
219

220
                    //brighterscript allows a typecast expression here
UNCOV
221
                } else if (isBrighterscript && isTypecastExpression(node.exceptionVariableExpression) && isVariableExpression(node.exceptionVariableExpression.obj)) {
×
UNCOV
222
                    node.parent.getSymbolTable().addSymbol(
×
223
                        node.exceptionVariableExpression.obj.getName(),
224
                        { definingNode: node, isInstance: true },
225
                        node.exceptionVariableExpression.getType({ flags: SymbolTypeFlag.runtime }),
226
                        SymbolTypeFlag.runtime
227
                    );
228

229
                    //no other expressions are allowed here
230
                } else {
UNCOV
231
                    this.event.program.diagnostics.register({
×
232
                        ...DiagnosticMessages.expectedExceptionVarToFollowCatch(),
233
                        location: node.exceptionVariableExpression?.location ?? node.tokens.catch?.location
×
234
                    });
235
                }
236
            },
237
            DimStatement: (node) => {
238
                if (node.tokens.name) {
18!
239
                    node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true }, node.getType({ flags: SymbolTypeFlag.runtime }), SymbolTypeFlag.runtime);
18✔
240
                }
241
            },
242
            ReturnStatement: (node) => {
243
                const func = node.findAncestor<FunctionExpression>(isFunctionExpression);
464✔
244
                //these situations cannot have a value next to `return`
245
                if (
464✔
246
                    //`function as void`, `sub as void`
247
                    (isVariableExpression(func?.returnTypeExpression?.expression) && func.returnTypeExpression.expression.tokens.name.text?.toLowerCase() === 'void') ||
4,922!
248
                    //`sub` <without return value>
249
                    (func.tokens.functionType?.kind === TokenKind.Sub && !func.returnTypeExpression)
1,353!
250
                ) {
251
                    //there may not be a return value
252
                    if (node.value) {
19✔
253
                        this.event.program.diagnostics.register({
11✔
254
                            ...DiagnosticMessages.voidFunctionMayNotReturnValue(func.tokens.functionType?.text),
33!
255
                            location: node.location
256
                        });
257
                    }
258

259
                } else {
260
                    //there MUST be a return value
261
                    if (!node.value) {
445✔
262
                        this.event.program.diagnostics.register({
11✔
263
                            ...DiagnosticMessages.nonVoidFunctionMustReturnValue(func?.tokens.functionType?.text),
66!
264
                            location: node.location
265
                        });
266
                    }
267
                }
268
            },
269
            ContinueStatement: (node) => {
270
                this.validateContinueStatement(node);
8✔
271
            },
272
            TypecastStatement: (node) => {
273
                node.parent.getSymbolTable().addSymbol('m', { definingNode: node, doNotMerge: true, isInstance: true }, node.getType({ flags: SymbolTypeFlag.typetime }), SymbolTypeFlag.runtime);
22✔
274
            },
275
            ConditionalCompileConstStatement: (node) => {
276
                const assign = node.assignment;
10✔
277
                const constNameLower = assign.tokens.name?.text.toLowerCase();
10!
278
                const astBsConsts = this.event.file.ast.bsConsts;
10✔
279
                if (isLiteralExpression(assign.value)) {
10!
280
                    astBsConsts.set(constNameLower, assign.value.tokens.value.text.toLowerCase() === 'true');
10✔
UNCOV
281
                } else if (isVariableExpression(assign.value)) {
×
UNCOV
282
                    if (this.validateConditionalCompileConst(assign.value.tokens.name)) {
×
UNCOV
283
                        astBsConsts.set(constNameLower, astBsConsts.get(assign.value.tokens.name.text.toLowerCase()));
×
284
                    }
285
                }
286
            },
287
            ConditionalCompileStatement: (node) => {
288
                this.validateConditionalCompileConst(node.tokens.condition);
24✔
289
            },
290
            ConditionalCompileErrorStatement: (node) => {
291
                this.event.program.diagnostics.register({
1✔
292
                    ...DiagnosticMessages.hashError(node.tokens.message.text),
293
                    location: node.location
294
                });
295
            },
296
            AliasStatement: (node) => {
297
                // eslint-disable-next-line no-bitwise
298
                const targetType = node.value.getType({ flags: SymbolTypeFlag.typetime | SymbolTypeFlag.runtime });
30✔
299

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

303
            },
304
            IfStatement: (node) => {
305
                this.setUpComplementSymbolTables(node, isIfStatement);
139✔
306
            },
307
            Block: (node) => {
308
                const blockSymbolTable = node.symbolTable;
2,470✔
309
                if (node.findAncestor<Block>(isFunctionExpression)) {
2,470✔
310
                    // this block is in a function. order matters!
311
                    blockSymbolTable.isOrdered = true;
2,466✔
312
                }
313
                if (!isFunctionExpression(node.parent)) {
2,470✔
314
                    // we're a block inside another block (or body). This block is a pocket in the bigger block
315
                    node.parent.getSymbolTable().addPocketTable({
260✔
316
                        index: node.parent.statementIndex,
317
                        table: node.symbolTable,
318
                        // code always flows through ConditionalCompiles, because we walk according to defined BSConsts
319
                        willAlwaysBeExecuted: isConditionalCompileStatement(node.parent)
320
                    });
321
                }
322
            },
323
            AstNode: (node) => {
324
                //check for doc comments
325
                if (!node.leadingTrivia || node.leadingTrivia.length === 0) {
26,805✔
326
                    return;
4,688✔
327
                }
328
                const doc = brsDocParser.parseNode(node);
22,117✔
329
                if (doc.tags.length === 0) {
22,117✔
330
                    return;
22,069✔
331
                }
332

333
                let funcExpr = node.findAncestor<FunctionExpression>(isFunctionExpression);
48✔
334
                if (funcExpr) {
48✔
335
                    // handle comment tags inside a function expression
336
                    this.processDocTagsInFunction(doc, node, funcExpr);
8✔
337
                } else {
338
                    //handle comment tags outside of a function expression
339
                    this.processDocTagsAtTopLevel(doc, node);
40✔
340
                }
341
            }
342
        });
343

344
        this.event.file.ast.walk((node, parent) => {
1,934✔
345
            visitor(node, parent);
26,805✔
346
        }, {
347
            walkMode: WalkMode.visitAllRecursive
348
        });
349
    }
350

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

354
        // For example, declaring variable types:
355
        // const symbolTable = funcExpr.body.getSymbolTable();
356

357
        // for (const varTag of doc.getAllTags(BrsDocTagKind.Var)) {
358
        //     const varName = (varTag as BrsDocParamTag).name;
359
        //     const varTypeStr = (varTag as BrsDocParamTag).type;
360
        //     const data: ExtraSymbolData = {};
361
        //     const type = doc.getTypeFromContext(varTypeStr, node, { flags: SymbolTypeFlag.typetime, fullName: varTypeStr, data: data, tableProvider: () => symbolTable });
362
        //     if (type) {
363
        //         symbolTable.addSymbol(varName, { ...data, isFromDocComment: true }, type, SymbolTypeFlag.runtime);
364
        //     }
365
        // }
366
    }
367

368
    private processDocTagsAtTopLevel(doc: BrightScriptDoc, node: AstNode) {
369
        //TODO:
370
        // - handle import statements?
371
        // - handle library statements?
372
        // - handle typecast statements?
373
        // - handle alias statements?
374
        // - handle const statements?
375
        // - allow interface definitions?
376
    }
377

378
    /**
379
     * Validate that a statement is defined in one of these specific locations
380
     *  - the root of the AST
381
     *  - inside a namespace
382
     * This is applicable to things like FunctionStatement, ClassStatement, NamespaceStatement, EnumStatement, InterfaceStatement
383
     */
384
    private validateDeclarationLocations(statement: Statement, keyword: string, rangeFactory?: () => (Range | undefined)) {
385
        //if nested inside a namespace, or defined at the root of the AST (i.e. in a body that has no parent)
386
        const isOkDeclarationLocation = (parentNode) => {
3,398✔
387
            return isNamespaceStatement(parentNode?.parent) || (isBody(parentNode) && !parentNode?.parent);
3,403!
388
        };
389
        if (isOkDeclarationLocation(statement.parent)) {
3,398✔
390
            return;
3,380✔
391
        }
392

393
        // is this in a top levelconditional compile?
394
        if (isConditionalCompileStatement(statement.parent?.parent)) {
18!
395
            if (isOkDeclarationLocation(statement.parent.parent.parent)) {
5✔
396
                return;
4✔
397
            }
398
        }
399

400
        //the statement was defined in the wrong place. Flag it.
401
        this.event.program.diagnostics.register({
14✔
402
            ...DiagnosticMessages.keywordMustBeDeclaredAtNamespaceLevel(keyword),
403
            location: rangeFactory ? util.createLocationFromFileRange(this.event.file, rangeFactory()) : statement.location
14!
404
        });
405
    }
406

407
    private validateFunctionParameterCount(func: FunctionExpression) {
408
        if (func.parameters.length > CallExpression.MaximumArguments) {
2,210✔
409
            //flag every parameter over the limit
410
            for (let i = CallExpression.MaximumArguments; i < func.parameters.length; i++) {
2✔
411
                this.event.program.diagnostics.register({
3✔
412
                    ...DiagnosticMessages.tooManyCallableParameters(func.parameters.length, CallExpression.MaximumArguments),
413
                    location: func.parameters[i]?.tokens.name?.location ?? func.parameters[i]?.location ?? func.location
36!
414
                });
415
            }
416
        }
417
    }
418

419
    private validateEnumDeclaration(stmt: EnumStatement) {
420
        const members = stmt.getMembers();
150✔
421
        //the enum data type is based on the first member value
422
        const enumValueKind = (members.find(x => x.value)?.value as LiteralExpression)?.tokens?.value?.kind ?? TokenKind.IntegerLiteral;
211✔
423
        const memberNames = new Set<string>();
150✔
424
        for (const member of members) {
150✔
425
            const memberNameLower = member.name?.toLowerCase();
297!
426

427
            /**
428
             * flag duplicate member names
429
             */
430
            if (memberNames.has(memberNameLower)) {
297✔
431
                this.event.program.diagnostics.register({
1✔
432
                    ...DiagnosticMessages.duplicateIdentifier(member.name),
433
                    location: member.location
434
                });
435
            } else {
436
                memberNames.add(memberNameLower);
296✔
437
            }
438

439
            //Enforce all member values are the same type
440
            this.validateEnumValueTypes(member, enumValueKind);
297✔
441
        }
442
    }
443

444
    private validateEnumValueTypes(member: EnumMemberStatement, enumValueKind: TokenKind) {
445
        let memberValueKind: TokenKind;
446
        let memberValue: Expression;
447
        if (isUnaryExpression(member.value)) {
297✔
448
            memberValueKind = (member.value?.right as LiteralExpression)?.tokens?.value?.kind;
2!
449
            memberValue = member.value?.right;
2!
450
        } else {
451
            memberValueKind = (member.value as LiteralExpression)?.tokens?.value?.kind;
295✔
452
            memberValue = member.value;
295✔
453
        }
454
        const range = (memberValue ?? member)?.location?.range;
297!
455
        if (
297✔
456
            //is integer enum, has value, that value type is not integer
457
            (enumValueKind === TokenKind.IntegerLiteral && memberValueKind && memberValueKind !== enumValueKind) ||
1,000✔
458
            //has value, that value is not a literal
459
            (memberValue && !isLiteralExpression(memberValue))
460
        ) {
461
            this.event.program.diagnostics.register({
6✔
462
                ...DiagnosticMessages.enumValueMustBeType(
463
                    enumValueKind.replace(/literal$/i, '').toLowerCase()
464
                ),
465
                location: util.createLocationFromFileRange(this.event.file, range)
466
            });
467
        }
468

469
        //is non integer value
470
        if (enumValueKind !== TokenKind.IntegerLiteral) {
297✔
471
            //default value present
472
            if (memberValueKind) {
102✔
473
                //member value is same as enum
474
                if (memberValueKind !== enumValueKind) {
100✔
475
                    this.event.program.diagnostics.register({
1✔
476
                        ...DiagnosticMessages.enumValueMustBeType(
477
                            enumValueKind.replace(/literal$/i, '').toLowerCase()
478
                        ),
479
                        location: util.createLocationFromFileRange(this.event.file, range)
480
                    });
481
                }
482

483
                //default value missing
484
            } else {
485
                this.event.program.diagnostics.register({
2✔
486
                    ...DiagnosticMessages.enumValueIsRequired(
487
                        enumValueKind.replace(/literal$/i, '').toLowerCase()
488
                    ),
489
                    location: util.createLocationFromFileRange(this.event.file, range)
490
                });
491
            }
492
        }
493
    }
494

495

496
    private validateConditionalCompileConst(ccConst: Token) {
497
        const isBool = ccConst.kind === TokenKind.True || ccConst.kind === TokenKind.False;
24✔
498
        if (!isBool && !this.event.file.ast.bsConsts.has(ccConst.text.toLowerCase())) {
24✔
499
            this.event.program.diagnostics.register({
2✔
500
                ...DiagnosticMessages.hashConstDoesNotExist(),
501
                location: ccConst.location
502
            });
503
            return false;
2✔
504
        }
505
        return true;
22✔
506
    }
507

508
    /**
509
     * Find statements defined at the top level (or inside a namespace body) that are not allowed to be there
510
     */
511
    private flagTopLevelStatements() {
512
        const statements = [...this.event.file.ast.statements];
1,934✔
513
        while (statements.length > 0) {
1,934✔
514
            const statement = statements.pop();
3,638✔
515
            if (isNamespaceStatement(statement)) {
3,638✔
516
                statements.push(...statement.body.statements);
596✔
517
            } else {
518
                //only allow these statement types
519
                if (
3,042✔
520
                    !isFunctionStatement(statement) &&
6,632✔
521
                    !isClassStatement(statement) &&
522
                    !isEnumStatement(statement) &&
523
                    !isInterfaceStatement(statement) &&
524
                    !isLibraryStatement(statement) &&
525
                    !isImportStatement(statement) &&
526
                    !isConstStatement(statement) &&
527
                    !isTypecastStatement(statement) &&
528
                    !isConditionalCompileConstStatement(statement) &&
529
                    !isConditionalCompileErrorStatement(statement) &&
530
                    !isConditionalCompileStatement(statement) &&
531
                    !isAliasStatement(statement)
532
                ) {
533
                    this.event.program.diagnostics.register({
8✔
534
                        ...DiagnosticMessages.unexpectedStatementOutsideFunction(),
535
                        location: statement.location
536
                    });
537
                }
538
            }
539
        }
540
    }
541

542
    private getTopOfFileStatements() {
543
        let topOfFileIncludeStatements = [] as Array<LibraryStatement | ImportStatement | TypecastStatement | AliasStatement>;
3,866✔
544
        for (let stmt of this.event.file.parser.ast.statements) {
3,866✔
545
            //if we found a non-library statement, this statement is not at the top of the file
546
            if (isLibraryStatement(stmt) || isImportStatement(stmt) || isTypecastStatement(stmt) || isAliasStatement(stmt)) {
4,182✔
547
                topOfFileIncludeStatements.push(stmt);
474✔
548
            } else {
549
                //break out of the loop, we found all of our library statements
550
                break;
3,708✔
551
            }
552
        }
553
        return topOfFileIncludeStatements;
3,866✔
554
    }
555

556
    private validateTopOfFileStatements() {
557
        let topOfFileStatements = this.getTopOfFileStatements();
1,933✔
558

559
        let statements = [
1,933✔
560
            // eslint-disable-next-line @typescript-eslint/dot-notation
561
            ...this.event.file['_cachedLookups'].libraryStatements,
562
            // eslint-disable-next-line @typescript-eslint/dot-notation
563
            ...this.event.file['_cachedLookups'].importStatements,
564
            // eslint-disable-next-line @typescript-eslint/dot-notation
565
            ...this.event.file['_cachedLookups'].aliasStatements
566
        ];
567
        for (let result of statements) {
1,933✔
568
            //if this statement is not one of the top-of-file statements,
569
            //then add a diagnostic explaining that it is invalid
570
            if (!topOfFileStatements.includes(result)) {
232✔
571
                if (isLibraryStatement(result)) {
5✔
572
                    this.event.program.diagnostics.register({
2✔
573
                        ...DiagnosticMessages.unexpectedStatementLocation('library', 'at the top of the file'),
574
                        location: result.location
575
                    });
576
                } else if (isImportStatement(result)) {
3✔
577
                    this.event.program.diagnostics.register({
1✔
578
                        ...DiagnosticMessages.unexpectedStatementLocation('import', 'at the top of the file'),
579
                        location: result.location
580
                    });
581
                } else if (isAliasStatement(result)) {
2!
582
                    this.event.program.diagnostics.register({
2✔
583
                        ...DiagnosticMessages.unexpectedStatementLocation('alias', 'at the top of the file'),
584
                        location: result.location
585
                    });
586
                }
587
            }
588
        }
589
    }
590

591
    private validateTypecastStatements() {
592
        let topOfFileTypecastStatements = this.getTopOfFileStatements().filter(stmt => isTypecastStatement(stmt));
1,933✔
593

594
        //check only one `typecast` statement at "top" of file (eg. before non import/library statements)
595
        for (let i = 1; i < topOfFileTypecastStatements.length; i++) {
1,933✔
596
            const typecastStmt = topOfFileTypecastStatements[i];
1✔
597
            this.event.program.diagnostics.register({
1✔
598
                ...DiagnosticMessages.unexpectedStatementLocation('typecast', 'at the top of the file or beginning of function or namespace'),
599
                location: typecastStmt.location
600
            });
601
        }
602

603
        // eslint-disable-next-line @typescript-eslint/dot-notation
604
        for (let result of this.event.file['_cachedLookups'].typecastStatements) {
1,933✔
605
            let isBadTypecastObj = false;
22✔
606
            if (!isVariableExpression(result.typecastExpression.obj)) {
22✔
607
                isBadTypecastObj = true;
1✔
608
            } else if (result.typecastExpression.obj.tokens.name.text.toLowerCase() !== 'm') {
21✔
609
                isBadTypecastObj = true;
1✔
610
            }
611
            if (isBadTypecastObj) {
22✔
612
                this.event.program.diagnostics.register({
2✔
613
                    ...DiagnosticMessages.invalidTypecastStatementApplication(util.getAllDottedGetPartsAsString(result.typecastExpression.obj)),
614
                    location: result.typecastExpression.obj.location
615
                });
616
            }
617

618
            if (topOfFileTypecastStatements.includes(result)) {
22✔
619
                // already validated
620
                continue;
10✔
621
            }
622

623
            const block = result.findAncestor<Body | Block>(node => (isBody(node) || isBlock(node)));
12✔
624
            const isFirst = block?.statements[0] === result;
12!
625
            const isAllowedBlock = (isBody(block) || isFunctionExpression(block.parent) || isNamespaceStatement(block.parent));
12!
626

627
            if (!isFirst || !isAllowedBlock) {
12✔
628
                this.event.program.diagnostics.register({
3✔
629
                    ...DiagnosticMessages.unexpectedStatementLocation('typecast', 'at the top of the file or beginning of function or namespace'),
630
                    location: result.location
631
                });
632
            }
633
        }
634
    }
635

636
    private validateContinueStatement(statement: ContinueStatement) {
637
        const validateLoopTypeMatch = (expectedLoopType: TokenKind) => {
8✔
638
            //coerce ForEach to For
639
            expectedLoopType = expectedLoopType === TokenKind.ForEach ? TokenKind.For : expectedLoopType;
7✔
640
            const actualLoopType = statement.tokens.loopType;
7✔
641
            if (actualLoopType && expectedLoopType?.toLowerCase() !== actualLoopType.text?.toLowerCase()) {
7!
642
                this.event.program.diagnostics.register({
3✔
643
                    location: statement.tokens.loopType.location,
644
                    ...DiagnosticMessages.expectedToken(expectedLoopType)
645
                });
646
            }
647
        };
648

649
        //find the parent loop statement
650
        const parent = statement.findAncestor<WhileStatement | ForStatement | ForEachStatement>((node) => {
8✔
651
            if (isWhileStatement(node)) {
18✔
652
                validateLoopTypeMatch(node.tokens.while.kind);
3✔
653
                return true;
3✔
654
            } else if (isForStatement(node)) {
15✔
655
                validateLoopTypeMatch(node.tokens.for.kind);
3✔
656
                return true;
3✔
657
            } else if (isForEachStatement(node)) {
12✔
658
                validateLoopTypeMatch(node.tokens.forEach.kind);
1✔
659
                return true;
1✔
660
            }
661
        });
662
        //flag continue statements found outside of a loop
663
        if (!parent) {
8✔
664
            this.event.program.diagnostics.register({
1✔
665
                location: statement.location,
666
                ...DiagnosticMessages.illegalContinueStatement()
667
            });
668
        }
669
    }
670

671
    /**
672
     * Validate that there are no optional chaining operators on the left-hand-side of an assignment, indexed set, or dotted get
673
     */
674
    private validateNoOptionalChainingInVarSet(parent: AstNode, children: AstNode[]) {
675
        const nodes = [...children, parent];
119✔
676
        //flag optional chaining anywhere in the left of this statement
677
        while (nodes.length > 0) {
119✔
678
            const node = nodes.shift();
238✔
679
            if (
238✔
680
                // a?.b = true or a.b?.c = true
681
                ((isDottedSetStatement(node) || isDottedGetExpression(node)) && node.tokens.dot?.kind === TokenKind.QuestionDot) ||
1,357!
682
                // a.b?[2] = true
683
                (isIndexedGetExpression(node) && (node?.tokens.questionDot?.kind === TokenKind.QuestionDot || node.tokens.openingSquare?.kind === TokenKind.QuestionLeftSquare)) ||
36!
684
                // a?[1] = true
685
                (isIndexedSetStatement(node) && node.tokens.openingSquare?.kind === TokenKind.QuestionLeftSquare)
57!
686
            ) {
687
                //try to highlight the entire left-hand-side expression if possible
688
                let range: Range;
689
                if (isDottedSetStatement(parent)) {
8✔
690
                    range = util.createBoundingRange(parent.obj?.location, parent.tokens.dot, parent.tokens.name);
5!
691
                } else if (isIndexedSetStatement(parent)) {
3!
692
                    range = util.createBoundingRange(parent.obj?.location, parent.tokens.openingSquare, ...parent.indexes, parent.tokens.closingSquare);
3!
693
                } else {
UNCOV
694
                    range = node.location?.range;
×
695
                }
696

697
                this.event.program.diagnostics.register({
8✔
698
                    ...DiagnosticMessages.noOptionalChainingInLeftHandSideOfAssignment(),
699
                    location: util.createLocationFromFileRange(this.event.file, range)
700
                });
701
            }
702

703
            if (node === parent) {
238✔
704
                break;
119✔
705
            } else {
706
                nodes.push(node.parent);
119✔
707
            }
708
        }
709
    }
710

711
    private setUpComplementSymbolTables(node: IfStatement | ConditionalCompileStatement, predicate: (node: AstNode) => boolean) {
712
        if (isBlock(node.elseBranch)) {
139✔
713
            const elseTable = node.elseBranch.symbolTable;
26✔
714
            let currentNode = node;
26✔
715
            while (predicate(currentNode)) {
26✔
716
                const thenBranch = (currentNode as IfStatement | ConditionalCompileStatement).thenBranch;
37✔
717
                elseTable.complementOtherTable(thenBranch.symbolTable);
37✔
718
                currentNode = currentNode.parent as IfStatement | ConditionalCompileStatement;
37✔
719
            }
720
        }
721
    }
722
}
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