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

rokucommunity / brighterscript / #14306

24 Apr 2025 07:32PM UTC coverage: 87.078% (+0.006%) from 87.072%
#14306

push

web-flow
Merge 46929bd4f into 9f25468b6

13644 of 16562 branches covered (82.38%)

Branch coverage included in aggregate %.

169 of 186 new or added lines in 10 files covered. (90.86%)

115 existing lines in 8 files now uncovered.

14606 of 15880 relevant lines covered (91.98%)

21525.93 hits per line

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

87.03
/src/bscPlugin/validation/BrsFileValidator.ts
1
import { isAliasStatement, isArrayType, 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,901✔
24
    ) {
25
    }
26

27

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

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

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

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

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

59
        const visitor = createVisitor({
1,901✔
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) {
47✔
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 = {};
755✔
110
                //register this variable
111
                let nodeType = node.getType({ flags: SymbolTypeFlag.runtime, data: data });
755✔
112
                if (isInvalidType(nodeType) || isVoidType(nodeType)) {
755✔
113
                    nodeType = DynamicType.instance;
10✔
114
                }
115
                node.parent.getSymbolTable()?.addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true, isFromDocComment: data.isFromDocComment, isFromCallFunc: data.isFromCallFunc }, nodeType, SymbolTypeFlag.runtime);
755!
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 });
26✔
126
                let loopVarType = isArrayType(loopTargetType) ? loopTargetType.defaultType : DynamicType.instance;
26✔
127

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

141
                if (node.tokens.name?.text) {
1,899!
142
                    node.parent.getSymbolTable().addSymbol(
1,899✔
143
                        node.tokens.name.text,
144
                        { definingNode: node },
145
                        funcType,
146
                        SymbolTypeFlag.runtime
147
                    );
148
                }
149

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

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

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

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

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

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

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

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

307
            },
308
            IfStatement: (node) => {
309
                this.setUpComplementSymbolTables(node, isIfStatement);
135✔
310
            },
311
            Block: (node) => {
312
                const blockSymbolTable = node.symbolTable;
2,431✔
313
                if (node.findAncestor<Block>(isFunctionExpression)) {
2,431✔
314
                    // this block is in a function. order matters!
315
                    blockSymbolTable.isOrdered = true;
2,427✔
316
                }
317
                if (!isFunctionExpression(node.parent)) {
2,431✔
318
                    // we're a block inside another block (or body). This block is a pocket in the bigger block
319
                    node.parent.getSymbolTable().addPocketTable({ index: node.parent.statementIndex, table: node.symbolTable });
253✔
320
                }
321
            },
322
            AstNode: (node) => {
323
                //check for doc comments
324
                if (!node.leadingTrivia || node.leadingTrivia.length === 0) {
26,373✔
325
                    return;
4,617✔
326
                }
327
                const doc = brsDocParser.parseNode(node);
21,756✔
328
                if (doc.tags.length === 0) {
21,756✔
329
                    return;
21,708✔
330
                }
331

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

494

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

710
    private setUpComplementSymbolTables(node: IfStatement | ConditionalCompileStatement, predicate: (node: AstNode) => boolean) {
711
        if (isBlock(node.elseBranch)) {
159✔
712
            const elseTable = node.elseBranch.symbolTable;
25✔
713
            let currentNode = node;
25✔
714
            while (predicate(currentNode)) {
25✔
715
                const thenBranch = (currentNode as IfStatement | ConditionalCompileStatement).thenBranch;
37✔
716
                elseTable.complementOtherTable(thenBranch.symbolTable);
37✔
717
                currentNode = currentNode.parent as IfStatement | ConditionalCompileStatement;
37✔
718
            }
719
        }
720
    }
721
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc