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

rokucommunity / brighterscript / #14231

23 Apr 2025 04:25PM UTC coverage: 87.082% (-0.006%) from 87.088%
#14231

push

web-flow
Merge 965d70740 into 99ec33ad4

13478 of 16355 branches covered (82.41%)

Branch coverage included in aggregate %.

164 of 181 new or added lines in 10 files covered. (90.61%)

116 existing lines in 9 files now uncovered.

14525 of 15802 relevant lines covered (91.92%)

21149.27 hits per line

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

87.07
/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,878✔
24
    ) {
25
    }
26

27

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

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

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

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

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

59
        const visitor = createVisitor({
1,878✔
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 = {};
747✔
110
                //register this variable
111
                let nodeType = node.getType({ flags: SymbolTypeFlag.runtime, data: data });
747✔
112
                if (isInvalidType(nodeType) || isVoidType(nodeType)) {
747✔
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);
747!
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,874✔
139
                const funcType = node.getType({ flags: SymbolTypeFlag.typetime });
1,874✔
140

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

150
                const namespace = node.findAncestor(isNamespaceStatement);
1,874✔
151
                //this function is declared inside a namespace
152
                if (namespace) {
1,874✔
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,147✔
173
                const isInlineFunc = !(isFunctionStatement(node.parent) || isMethodStatement(node.parent));
2,147✔
174
                if (isInlineFunc) {
2,147✔
175
                    // symbol table should not include any symbols from parent func
176
                    funcSymbolTable.pushParentProvider(() => node.findAncestor<Body>(isBody).getSymbolTable());
121✔
177
                }
178
                if (!funcSymbolTable?.hasSymbol('m', SymbolTypeFlag.runtime) || isInlineFunc) {
2,147!
179
                    if (!isTypecastStatement(node.body?.statements?.[0])) {
31!
180
                        funcSymbolTable?.addSymbol('m', { isInstance: true }, new AssociativeArrayType(), SymbolTypeFlag.runtime);
30!
181
                    }
182
                }
183
                this.validateFunctionParameterCount(node);
2,147✔
184
            },
185
            FunctionParameterExpression: (node) => {
186
                const paramName = node.tokens.name?.text;
1,088!
187
                const data: ExtraSymbolData = {};
1,088✔
188
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime, data: data });
1,088✔
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,088✔
191
                const funcSymbolTable = funcExpr?.getSymbolTable();
1,088!
192
                funcSymbolTable?.addSymbol(paramName, { definingNode: node, isInstance: true, isFromDocComment: data.isFromDocComment }, nodeType, SymbolTypeFlag.runtime);
1,088!
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,088!
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
            ContinueStatement: (node) => {
246
                this.validateContinueStatement(node);
8✔
247
            },
248
            TypecastStatement: (node) => {
249
                node.parent.getSymbolTable().addSymbol('m', { definingNode: node, doNotMerge: true, isInstance: true }, node.getType({ flags: SymbolTypeFlag.typetime }), SymbolTypeFlag.runtime);
22✔
250
            },
251
            ConditionalCompileConstStatement: (node) => {
252
                const assign = node.assignment;
10✔
253
                const constNameLower = assign.tokens.name?.text.toLowerCase();
10!
254
                const astBsConsts = this.event.file.ast.bsConsts;
10✔
255
                if (isLiteralExpression(assign.value)) {
10!
256
                    astBsConsts.set(constNameLower, assign.value.tokens.value.text.toLowerCase() === 'true');
10✔
257
                } else if (isVariableExpression(assign.value)) {
×
258
                    if (this.validateConditionalCompileConst(assign.value.tokens.name)) {
×
259
                        astBsConsts.set(constNameLower, astBsConsts.get(assign.value.tokens.name.text.toLowerCase()));
×
260
                    }
261
                }
262
            },
263
            ConditionalCompileStatement: (node) => {
264
                this.setUpComplementSymbolTables(node, isConditionalCompileStatement);
24✔
265
                this.validateConditionalCompileConst(node.tokens.condition);
24✔
266
            },
267
            ConditionalCompileErrorStatement: (node) => {
268
                this.event.program.diagnostics.register({
1✔
269
                    ...DiagnosticMessages.hashError(node.tokens.message.text),
270
                    location: node.location
271
                });
272
            },
273
            AliasStatement: (node) => {
274
                // eslint-disable-next-line no-bitwise
275
                const targetType = node.value.getType({ flags: SymbolTypeFlag.typetime | SymbolTypeFlag.runtime });
30✔
276

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

280
            },
281
            IfStatement: (node) => {
282
                this.setUpComplementSymbolTables(node, isIfStatement);
135✔
283
            },
284
            Block: (node) => {
285
                const blockSymbolTable = node.symbolTable;
2,400✔
286
                if (node.findAncestor<Block>(isFunctionExpression)) {
2,400✔
287
                    // this block is in a function. order matters!
288
                    blockSymbolTable.isOrdered = true;
2,396✔
289
                }
290
                if (!isFunctionExpression(node.parent)) {
2,400✔
291
                    // we're a block inside another block (or body). This block is a pocket in the bigger block
292
                    node.parent.getSymbolTable().addPocketTable({ index: node.parent.statementIndex, table: node.symbolTable });
253✔
293
                }
294
            },
295
            AstNode: (node) => {
296
                //check for doc comments
297
                if (!node.leadingTrivia || node.leadingTrivia.length === 0) {
26,136✔
298
                    return;
4,572✔
299
                }
300
                const doc = brsDocParser.parseNode(node);
21,564✔
301
                if (doc.tags.length === 0) {
21,564✔
302
                    return;
21,516✔
303
                }
304

305
                let funcExpr = node.findAncestor<FunctionExpression>(isFunctionExpression);
48✔
306
                if (funcExpr) {
48✔
307
                    // handle comment tags inside a function expression
308
                    this.processDocTagsInFunction(doc, node, funcExpr);
8✔
309
                } else {
310
                    //handle comment tags outside of a function expression
311
                    this.processDocTagsAtTopLevel(doc, node);
40✔
312
                }
313
            }
314
        });
315

316
        this.event.file.ast.walk((node, parent) => {
1,878✔
317
            visitor(node, parent);
26,136✔
318
        }, {
319
            walkMode: WalkMode.visitAllRecursive
320
        });
321
    }
322

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

326
        // For example, declaring variable types:
327
        // const symbolTable = funcExpr.body.getSymbolTable();
328

329
        // for (const varTag of doc.getAllTags(BrsDocTagKind.Var)) {
330
        //     const varName = (varTag as BrsDocParamTag).name;
331
        //     const varTypeStr = (varTag as BrsDocParamTag).type;
332
        //     const data: ExtraSymbolData = {};
333
        //     const type = doc.getTypeFromContext(varTypeStr, node, { flags: SymbolTypeFlag.typetime, fullName: varTypeStr, data: data, tableProvider: () => symbolTable });
334
        //     if (type) {
335
        //         symbolTable.addSymbol(varName, { ...data, isFromDocComment: true }, type, SymbolTypeFlag.runtime);
336
        //     }
337
        // }
338
    }
339

340
    private processDocTagsAtTopLevel(doc: BrightScriptDoc, node: AstNode) {
341
        //TODO:
342
        // - handle import statements?
343
        // - handle library statements?
344
        // - handle typecast statements?
345
        // - handle alias statements?
346
        // - handle const statements?
347
        // - allow interface definitions?
348
    }
349

350
    /**
351
     * Validate that a statement is defined in one of these specific locations
352
     *  - the root of the AST
353
     *  - inside a namespace
354
     * This is applicable to things like FunctionStatement, ClassStatement, NamespaceStatement, EnumStatement, InterfaceStatement
355
     */
356
    private validateDeclarationLocations(statement: Statement, keyword: string, rangeFactory?: () => (Range | undefined)) {
357
        //if nested inside a namespace, or defined at the root of the AST (i.e. in a body that has no parent)
358
        const isOkDeclarationLocation = (parentNode) => {
3,332✔
359
            return isNamespaceStatement(parentNode?.parent) || (isBody(parentNode) && !parentNode?.parent);
3,337!
360
        };
361
        if (isOkDeclarationLocation(statement.parent)) {
3,332✔
362
            return;
3,314✔
363
        }
364

365
        // is this in a top levelconditional compile?
366
        if (isConditionalCompileStatement(statement.parent?.parent)) {
18!
367
            if (isOkDeclarationLocation(statement.parent.parent.parent)) {
5✔
368
                return;
4✔
369
            }
370
        }
371

372
        //the statement was defined in the wrong place. Flag it.
373
        this.event.program.diagnostics.register({
14✔
374
            ...DiagnosticMessages.keywordMustBeDeclaredAtNamespaceLevel(keyword),
375
            location: rangeFactory ? util.createLocationFromFileRange(this.event.file, rangeFactory()) : statement.location
14!
376
        });
377
    }
378

379
    private validateFunctionParameterCount(func: FunctionExpression) {
380
        if (func.parameters.length > CallExpression.MaximumArguments) {
2,147✔
381
            //flag every parameter over the limit
382
            for (let i = CallExpression.MaximumArguments; i < func.parameters.length; i++) {
2✔
383
                this.event.program.diagnostics.register({
3✔
384
                    ...DiagnosticMessages.tooManyCallableParameters(func.parameters.length, CallExpression.MaximumArguments),
385
                    location: func.parameters[i]?.tokens.name?.location ?? func.parameters[i]?.location ?? func.location
36!
386
                });
387
            }
388
        }
389
    }
390

391
    private validateEnumDeclaration(stmt: EnumStatement) {
392
        const members = stmt.getMembers();
150✔
393
        //the enum data type is based on the first member value
394
        const enumValueKind = (members.find(x => x.value)?.value as LiteralExpression)?.tokens?.value?.kind ?? TokenKind.IntegerLiteral;
211✔
395
        const memberNames = new Set<string>();
150✔
396
        for (const member of members) {
150✔
397
            const memberNameLower = member.name?.toLowerCase();
297!
398

399
            /**
400
             * flag duplicate member names
401
             */
402
            if (memberNames.has(memberNameLower)) {
297✔
403
                this.event.program.diagnostics.register({
1✔
404
                    ...DiagnosticMessages.duplicateIdentifier(member.name),
405
                    location: member.location
406
                });
407
            } else {
408
                memberNames.add(memberNameLower);
296✔
409
            }
410

411
            //Enforce all member values are the same type
412
            this.validateEnumValueTypes(member, enumValueKind);
297✔
413
        }
414
    }
415

416
    private validateEnumValueTypes(member: EnumMemberStatement, enumValueKind: TokenKind) {
417
        let memberValueKind: TokenKind;
418
        let memberValue: Expression;
419
        if (isUnaryExpression(member.value)) {
297✔
420
            memberValueKind = (member.value?.right as LiteralExpression)?.tokens?.value?.kind;
2!
421
            memberValue = member.value?.right;
2!
422
        } else {
423
            memberValueKind = (member.value as LiteralExpression)?.tokens?.value?.kind;
295✔
424
            memberValue = member.value;
295✔
425
        }
426
        const range = (memberValue ?? member)?.location?.range;
297!
427
        if (
297✔
428
            //is integer enum, has value, that value type is not integer
429
            (enumValueKind === TokenKind.IntegerLiteral && memberValueKind && memberValueKind !== enumValueKind) ||
1,000✔
430
            //has value, that value is not a literal
431
            (memberValue && !isLiteralExpression(memberValue))
432
        ) {
433
            this.event.program.diagnostics.register({
6✔
434
                ...DiagnosticMessages.enumValueMustBeType(
435
                    enumValueKind.replace(/literal$/i, '').toLowerCase()
436
                ),
437
                location: util.createLocationFromFileRange(this.event.file, range)
438
            });
439
        }
440

441
        //is non integer value
442
        if (enumValueKind !== TokenKind.IntegerLiteral) {
297✔
443
            //default value present
444
            if (memberValueKind) {
102✔
445
                //member value is same as enum
446
                if (memberValueKind !== enumValueKind) {
100✔
447
                    this.event.program.diagnostics.register({
1✔
448
                        ...DiagnosticMessages.enumValueMustBeType(
449
                            enumValueKind.replace(/literal$/i, '').toLowerCase()
450
                        ),
451
                        location: util.createLocationFromFileRange(this.event.file, range)
452
                    });
453
                }
454

455
                //default value missing
456
            } else {
457
                this.event.program.diagnostics.register({
2✔
458
                    ...DiagnosticMessages.enumValueIsRequired(
459
                        enumValueKind.replace(/literal$/i, '').toLowerCase()
460
                    ),
461
                    location: util.createLocationFromFileRange(this.event.file, range)
462
                });
463
            }
464
        }
465
    }
466

467

468
    private validateConditionalCompileConst(ccConst: Token) {
469
        const isBool = ccConst.kind === TokenKind.True || ccConst.kind === TokenKind.False;
24✔
470
        if (!isBool && !this.event.file.ast.bsConsts.has(ccConst.text.toLowerCase())) {
24✔
471
            this.event.program.diagnostics.register({
2✔
472
                ...DiagnosticMessages.hashConstDoesNotExist(),
473
                location: ccConst.location
474
            });
475
            return false;
2✔
476
        }
477
        return true;
22✔
478
    }
479

480
    /**
481
     * Find statements defined at the top level (or inside a namespace body) that are not allowed to be there
482
     */
483
    private flagTopLevelStatements() {
484
        const statements = [...this.event.file.ast.statements];
1,878✔
485
        while (statements.length > 0) {
1,878✔
486
            const statement = statements.pop();
3,572✔
487
            if (isNamespaceStatement(statement)) {
3,572✔
488
                statements.push(...statement.body.statements);
596✔
489
            } else {
490
                //only allow these statement types
491
                if (
2,976✔
492
                    !isFunctionStatement(statement) &&
6,539✔
493
                    !isClassStatement(statement) &&
494
                    !isEnumStatement(statement) &&
495
                    !isInterfaceStatement(statement) &&
496
                    !isLibraryStatement(statement) &&
497
                    !isImportStatement(statement) &&
498
                    !isConstStatement(statement) &&
499
                    !isTypecastStatement(statement) &&
500
                    !isConditionalCompileConstStatement(statement) &&
501
                    !isConditionalCompileErrorStatement(statement) &&
502
                    !isConditionalCompileStatement(statement) &&
503
                    !isAliasStatement(statement)
504
                ) {
505
                    this.event.program.diagnostics.register({
8✔
506
                        ...DiagnosticMessages.unexpectedStatementOutsideFunction(),
507
                        location: statement.location
508
                    });
509
                }
510
            }
511
        }
512
    }
513

514
    private getTopOfFileStatements() {
515
        let topOfFileIncludeStatements = [] as Array<LibraryStatement | ImportStatement | TypecastStatement | AliasStatement>;
3,754✔
516
        for (let stmt of this.event.file.parser.ast.statements) {
3,754✔
517
            //if we found a non-library statement, this statement is not at the top of the file
518
            if (isLibraryStatement(stmt) || isImportStatement(stmt) || isTypecastStatement(stmt) || isAliasStatement(stmt)) {
4,070✔
519
                topOfFileIncludeStatements.push(stmt);
474✔
520
            } else {
521
                //break out of the loop, we found all of our library statements
522
                break;
3,596✔
523
            }
524
        }
525
        return topOfFileIncludeStatements;
3,754✔
526
    }
527

528
    private validateTopOfFileStatements() {
529
        let topOfFileStatements = this.getTopOfFileStatements();
1,877✔
530

531
        let statements = [
1,877✔
532
            // eslint-disable-next-line @typescript-eslint/dot-notation
533
            ...this.event.file['_cachedLookups'].libraryStatements,
534
            // eslint-disable-next-line @typescript-eslint/dot-notation
535
            ...this.event.file['_cachedLookups'].importStatements,
536
            // eslint-disable-next-line @typescript-eslint/dot-notation
537
            ...this.event.file['_cachedLookups'].aliasStatements
538
        ];
539
        for (let result of statements) {
1,877✔
540
            //if this statement is not one of the top-of-file statements,
541
            //then add a diagnostic explaining that it is invalid
542
            if (!topOfFileStatements.includes(result)) {
232✔
543
                if (isLibraryStatement(result)) {
5✔
544
                    this.event.program.diagnostics.register({
2✔
545
                        ...DiagnosticMessages.unexpectedStatementLocation('library', 'at the top of the file'),
546
                        location: result.location
547
                    });
548
                } else if (isImportStatement(result)) {
3✔
549
                    this.event.program.diagnostics.register({
1✔
550
                        ...DiagnosticMessages.unexpectedStatementLocation('import', 'at the top of the file'),
551
                        location: result.location
552
                    });
553
                } else if (isAliasStatement(result)) {
2!
554
                    this.event.program.diagnostics.register({
2✔
555
                        ...DiagnosticMessages.unexpectedStatementLocation('alias', 'at the top of the file'),
556
                        location: result.location
557
                    });
558
                }
559
            }
560
        }
561
    }
562

563
    private validateTypecastStatements() {
564
        let topOfFileTypecastStatements = this.getTopOfFileStatements().filter(stmt => isTypecastStatement(stmt));
1,877✔
565

566
        //check only one `typecast` statement at "top" of file (eg. before non import/library statements)
567
        for (let i = 1; i < topOfFileTypecastStatements.length; i++) {
1,877✔
568
            const typecastStmt = topOfFileTypecastStatements[i];
1✔
569
            this.event.program.diagnostics.register({
1✔
570
                ...DiagnosticMessages.unexpectedStatementLocation('typecast', 'at the top of the file or beginning of function or namespace'),
571
                location: typecastStmt.location
572
            });
573
        }
574

575
        // eslint-disable-next-line @typescript-eslint/dot-notation
576
        for (let result of this.event.file['_cachedLookups'].typecastStatements) {
1,877✔
577
            let isBadTypecastObj = false;
22✔
578
            if (!isVariableExpression(result.typecastExpression.obj)) {
22✔
579
                isBadTypecastObj = true;
1✔
580
            } else if (result.typecastExpression.obj.tokens.name.text.toLowerCase() !== 'm') {
21✔
581
                isBadTypecastObj = true;
1✔
582
            }
583
            if (isBadTypecastObj) {
22✔
584
                this.event.program.diagnostics.register({
2✔
585
                    ...DiagnosticMessages.invalidTypecastStatementApplication(util.getAllDottedGetPartsAsString(result.typecastExpression.obj)),
586
                    location: result.typecastExpression.obj.location
587
                });
588
            }
589

590
            if (topOfFileTypecastStatements.includes(result)) {
22✔
591
                // already validated
592
                continue;
10✔
593
            }
594

595
            const block = result.findAncestor<Body | Block>(node => (isBody(node) || isBlock(node)));
12✔
596
            const isFirst = block?.statements[0] === result;
12!
597
            const isAllowedBlock = (isBody(block) || isFunctionExpression(block.parent) || isNamespaceStatement(block.parent));
12!
598

599
            if (!isFirst || !isAllowedBlock) {
12✔
600
                this.event.program.diagnostics.register({
3✔
601
                    ...DiagnosticMessages.unexpectedStatementLocation('typecast', 'at the top of the file or beginning of function or namespace'),
602
                    location: result.location
603
                });
604
            }
605
        }
606
    }
607

608
    private validateContinueStatement(statement: ContinueStatement) {
609
        const validateLoopTypeMatch = (expectedLoopType: TokenKind) => {
8✔
610
            //coerce ForEach to For
611
            expectedLoopType = expectedLoopType === TokenKind.ForEach ? TokenKind.For : expectedLoopType;
7✔
612
            const actualLoopType = statement.tokens.loopType;
7✔
613
            if (actualLoopType && expectedLoopType?.toLowerCase() !== actualLoopType.text?.toLowerCase()) {
7!
614
                this.event.program.diagnostics.register({
3✔
615
                    location: statement.tokens.loopType.location,
616
                    ...DiagnosticMessages.expectedToken(expectedLoopType)
617
                });
618
            }
619
        };
620

621
        //find the parent loop statement
622
        const parent = statement.findAncestor<WhileStatement | ForStatement | ForEachStatement>((node) => {
8✔
623
            if (isWhileStatement(node)) {
18✔
624
                validateLoopTypeMatch(node.tokens.while.kind);
3✔
625
                return true;
3✔
626
            } else if (isForStatement(node)) {
15✔
627
                validateLoopTypeMatch(node.tokens.for.kind);
3✔
628
                return true;
3✔
629
            } else if (isForEachStatement(node)) {
12✔
630
                validateLoopTypeMatch(node.tokens.forEach.kind);
1✔
631
                return true;
1✔
632
            }
633
        });
634
        //flag continue statements found outside of a loop
635
        if (!parent) {
8✔
636
            this.event.program.diagnostics.register({
1✔
637
                location: statement.location,
638
                ...DiagnosticMessages.illegalContinueStatement()
639
            });
640
        }
641
    }
642

643
    /**
644
     * Validate that there are no optional chaining operators on the left-hand-side of an assignment, indexed set, or dotted get
645
     */
646
    private validateNoOptionalChainingInVarSet(parent: AstNode, children: AstNode[]) {
647
        const nodes = [...children, parent];
119✔
648
        //flag optional chaining anywhere in the left of this statement
649
        while (nodes.length > 0) {
119✔
650
            const node = nodes.shift();
238✔
651
            if (
238✔
652
                // a?.b = true or a.b?.c = true
653
                ((isDottedSetStatement(node) || isDottedGetExpression(node)) && node.tokens.dot?.kind === TokenKind.QuestionDot) ||
1,357!
654
                // a.b?[2] = true
655
                (isIndexedGetExpression(node) && (node?.tokens.questionDot?.kind === TokenKind.QuestionDot || node.tokens.openingSquare?.kind === TokenKind.QuestionLeftSquare)) ||
36!
656
                // a?[1] = true
657
                (isIndexedSetStatement(node) && node.tokens.openingSquare?.kind === TokenKind.QuestionLeftSquare)
57!
658
            ) {
659
                //try to highlight the entire left-hand-side expression if possible
660
                let range: Range;
661
                if (isDottedSetStatement(parent)) {
8✔
662
                    range = util.createBoundingRange(parent.obj?.location, parent.tokens.dot, parent.tokens.name);
5!
663
                } else if (isIndexedSetStatement(parent)) {
3!
664
                    range = util.createBoundingRange(parent.obj?.location, parent.tokens.openingSquare, ...parent.indexes, parent.tokens.closingSquare);
3!
665
                } else {
UNCOV
666
                    range = node.location?.range;
×
667
                }
668

669
                this.event.program.diagnostics.register({
8✔
670
                    ...DiagnosticMessages.noOptionalChainingInLeftHandSideOfAssignment(),
671
                    location: util.createLocationFromFileRange(this.event.file, range)
672
                });
673
            }
674

675
            if (node === parent) {
238✔
676
                break;
119✔
677
            } else {
678
                nodes.push(node.parent);
119✔
679
            }
680
        }
681
    }
682

683
    private setUpComplementSymbolTables(node: IfStatement | ConditionalCompileStatement, predicate: (node: AstNode) => boolean) {
684
        if (isBlock(node.elseBranch)) {
159✔
685
            const elseTable = node.elseBranch.symbolTable;
25✔
686
            let currentNode = node;
25✔
687
            while (predicate(currentNode)) {
25✔
688
                const thenBranch = (currentNode as IfStatement | ConditionalCompileStatement).thenBranch;
37✔
689
                elseTable.complementOtherTable(thenBranch.symbolTable);
37✔
690
                currentNode = currentNode.parent as IfStatement | ConditionalCompileStatement;
37✔
691
            }
692
        }
693
    }
694
}
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