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

rokucommunity / brighterscript / #14385

09 May 2025 11:44AM UTC coverage: 87.032% (-2.0%) from 89.017%
#14385

push

web-flow
Merge a194c3925 into 489231ac7

13732 of 16677 branches covered (82.34%)

Branch coverage included in aggregate %.

8175 of 8874 new or added lines in 103 files covered. (92.12%)

84 existing lines in 22 files now uncovered.

14604 of 15881 relevant lines covered (91.96%)

20324.31 hits per line

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

86.64
/src/bscPlugin/validation/BrsFileValidator.ts
1
import { isAliasStatement, isArrayType, isBlock, isBody, isClassStatement, isConditionalCompileConstStatement, isConditionalCompileErrorStatement, isConditionalCompileStatement, isConstStatement, isDottedGetExpression, isDottedSetStatement, isEnumStatement, isForEachStatement, isForStatement, isFunctionExpression, isFunctionStatement, 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 } 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,920✔
24
    ) {
25
    }
26

27

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

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

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

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

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

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

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

150
                const namespace = node.findAncestor(isNamespaceStatement);
1,919✔
151
                //this function is declared inside a namespace
152
                if (namespace) {
1,919✔
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,198✔
173
                const isInlineFunc = !(isFunctionStatement(node.parent) || isMethodStatement(node.parent));
2,198✔
174
                if (isInlineFunc) {
2,198✔
175
                    // symbol table should not include any symbols from parent func
176
                    funcSymbolTable.pushParentProvider(() => node.findAncestor<Body>(isBody).getSymbolTable());
135✔
177
                }
178
                if (!funcSymbolTable?.hasSymbol('m', SymbolTypeFlag.runtime) || isInlineFunc) {
2,198!
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,198✔
184
            },
185
            FunctionParameterExpression: (node) => {
186
                const paramName = node.tokens.name?.text;
1,112!
187
                const data: ExtraSymbolData = {};
1,112✔
188
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime, data: data });
1,112✔
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,112✔
191
                const funcSymbolTable = funcExpr?.getSymbolTable();
1,112!
192
                funcSymbolTable?.addSymbol(paramName, { definingNode: node, isInstance: true, isFromDocComment: data.isFromDocComment }, nodeType, SymbolTypeFlag.runtime);
1,112!
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,112!
196
            },
197
            InterfaceStatement: (node) => {
198
                this.validateDeclarationLocations(node, 'interface', () => util.createBoundingRange(node.tokens.interface, node.tokens.name));
149✔
199

200
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
149✔
201
                // eslint-disable-next-line no-bitwise
202
                node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime);
149✔
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
NEW
224
                } else if (isBrighterscript && isTypecastExpression(node.exceptionVariableExpression) && isVariableExpression(node.exceptionVariableExpression.obj)) {
×
NEW
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 {
NEW
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);
461✔
247
                //these situations cannot have a value next to `return`
248
                if (
461✔
249
                    //`function as void`, `sub as void`
250
                    (isVariableExpression(func?.returnTypeExpression?.expression) && func.returnTypeExpression.expression.tokens.name.text?.toLowerCase() === 'void') ||
4,890!
251
                    //`sub` <without return value>
252
                    (func.tokens.functionType?.kind === TokenKind.Sub && !func.returnTypeExpression)
1,344!
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) {
442✔
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✔
NEW
284
                } else if (isVariableExpression(assign.value)) {
×
NEW
285
                    if (this.validateConditionalCompileConst(assign.value.tokens.name)) {
×
NEW
286
                        astBsConsts.set(constNameLower, astBsConsts.get(assign.value.tokens.name.text.toLowerCase()));
×
287
                    }
288
                }
289
            },
290
            ConditionalCompileStatement: (node) => {
291
                this.validateConditionalCompileConst(node.tokens.condition);
22✔
292
            },
293
            ConditionalCompileErrorStatement: (node) => {
294
                this.event.program.diagnostics.register({
1✔
295
                    ...DiagnosticMessages.hashError(node.tokens.message.text),
296
                    location: node.location
297
                });
298
            },
299
            AliasStatement: (node) => {
300
                // eslint-disable-next-line no-bitwise
301
                const targetType = node.value.getType({ flags: SymbolTypeFlag.typetime | SymbolTypeFlag.runtime });
30✔
302

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

306
            },
307
            AstNode: (node) => {
308
                //check for doc comments
309
                if (!node.leadingTrivia || node.leadingTrivia.length === 0) {
26,528✔
310
                    return;
4,655✔
311
                }
312
                const doc = brsDocParser.parseNode(node);
21,873✔
313
                if (doc.tags.length === 0) {
21,873✔
314
                    return;
21,825✔
315
                }
316

317
                let funcExpr = node.findAncestor<FunctionExpression>(isFunctionExpression);
48✔
318
                if (funcExpr) {
48✔
319
                    // handle comment tags inside a function expression
320
                    this.processDocTagsInFunction(doc, node, funcExpr);
8✔
321
                } else {
322
                    //handle comment tags outside of a function expression
323
                    this.processDocTagsAtTopLevel(doc, node);
40✔
324
                }
325
            }
326
        });
327

328
        this.event.file.ast.walk((node, parent) => {
1,920✔
329
            visitor(node, parent);
26,528✔
330
        }, {
331
            walkMode: WalkMode.visitAllRecursive
332
        });
333
    }
334

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

338
        // For example, declaring variable types:
339
        // const symbolTable = funcExpr.body.getSymbolTable();
340

341
        // for (const varTag of doc.getAllTags(BrsDocTagKind.Var)) {
342
        //     const varName = (varTag as BrsDocParamTag).name;
343
        //     const varTypeStr = (varTag as BrsDocParamTag).type;
344
        //     const data: ExtraSymbolData = {};
345
        //     const type = doc.getTypeFromContext(varTypeStr, node, { flags: SymbolTypeFlag.typetime, fullName: varTypeStr, data: data, tableProvider: () => symbolTable });
346
        //     if (type) {
347
        //         symbolTable.addSymbol(varName, { ...data, isFromDocComment: true }, type, SymbolTypeFlag.runtime);
348
        //     }
349
        // }
350
    }
351

352
    private processDocTagsAtTopLevel(doc: BrightScriptDoc, node: AstNode) {
353
        //TODO:
354
        // - handle import statements?
355
        // - handle library statements?
356
        // - handle typecast statements?
357
        // - handle alias statements?
358
        // - handle const statements?
359
        // - allow interface definitions?
360
    }
361

362
    /**
363
     * Validate that a statement is defined in one of these specific locations
364
     *  - the root of the AST
365
     *  - inside a namespace
366
     * This is applicable to things like FunctionStatement, ClassStatement, NamespaceStatement, EnumStatement, InterfaceStatement
367
     */
368
    private validateDeclarationLocations(statement: Statement, keyword: string, rangeFactory?: () => (Range | undefined)) {
369
        //if nested inside a namespace, or defined at the root of the AST (i.e. in a body that has no parent)
370
        const isOkDeclarationLocation = (parentNode) => {
3,382✔
371
            return isNamespaceStatement(parentNode?.parent) || (isBody(parentNode) && !parentNode?.parent);
3,387!
372
        };
373
        if (isOkDeclarationLocation(statement.parent)) {
3,382✔
374
            return;
3,364✔
375
        }
376

377
        // is this in a top levelconditional compile?
378
        if (isConditionalCompileStatement(statement.parent?.parent)) {
18!
379
            if (isOkDeclarationLocation(statement.parent.parent.parent)) {
5✔
380
                return;
4✔
381
            }
382
        }
383

384
        //the statement was defined in the wrong place. Flag it.
385
        this.event.program.diagnostics.register({
14✔
386
            ...DiagnosticMessages.keywordMustBeDeclaredAtNamespaceLevel(keyword),
387
            location: rangeFactory ? util.createLocationFromFileRange(this.event.file, rangeFactory()) : statement.location
14!
388
        });
389
    }
390

391
    private validateFunctionParameterCount(func: FunctionExpression) {
392
        if (func.parameters.length > CallExpression.MaximumArguments) {
2,198✔
393
            //flag every parameter over the limit
394
            for (let i = CallExpression.MaximumArguments; i < func.parameters.length; i++) {
2✔
395
                this.event.program.diagnostics.register({
3✔
396
                    ...DiagnosticMessages.tooManyCallableParameters(func.parameters.length, CallExpression.MaximumArguments),
397
                    location: func.parameters[i]?.tokens.name?.location ?? func.parameters[i]?.location ?? func.location
36!
398
                });
399
            }
400
        }
401
    }
402

403
    private validateEnumDeclaration(stmt: EnumStatement) {
404
        const members = stmt.getMembers();
150✔
405
        //the enum data type is based on the first member value
406
        const enumValueKind = (members.find(x => x.value)?.value as LiteralExpression)?.tokens?.value?.kind ?? TokenKind.IntegerLiteral;
211✔
407
        const memberNames = new Set<string>();
150✔
408
        for (const member of members) {
150✔
409
            const memberNameLower = member.name?.toLowerCase();
297!
410

411
            /**
412
             * flag duplicate member names
413
             */
414
            if (memberNames.has(memberNameLower)) {
297✔
415
                this.event.program.diagnostics.register({
1✔
416
                    ...DiagnosticMessages.duplicateIdentifier(member.name),
417
                    location: member.location
418
                });
419
            } else {
420
                memberNames.add(memberNameLower);
296✔
421
            }
422

423
            //Enforce all member values are the same type
424
            this.validateEnumValueTypes(member, enumValueKind);
297✔
425
        }
426
    }
427

428
    private validateEnumValueTypes(member: EnumMemberStatement, enumValueKind: TokenKind) {
429
        let memberValueKind: TokenKind;
430
        let memberValue: Expression;
431
        if (isUnaryExpression(member.value)) {
297✔
432
            memberValueKind = (member.value?.right as LiteralExpression)?.tokens?.value?.kind;
2!
433
            memberValue = member.value?.right;
2!
434
        } else {
435
            memberValueKind = (member.value as LiteralExpression)?.tokens?.value?.kind;
295✔
436
            memberValue = member.value;
295✔
437
        }
438
        const range = (memberValue ?? member)?.location?.range;
297!
439
        if (
297✔
440
            //is integer enum, has value, that value type is not integer
441
            (enumValueKind === TokenKind.IntegerLiteral && memberValueKind && memberValueKind !== enumValueKind) ||
1,000✔
442
            //has value, that value is not a literal
443
            (memberValue && !isLiteralExpression(memberValue))
444
        ) {
445
            this.event.program.diagnostics.register({
6✔
446
                ...DiagnosticMessages.enumValueMustBeType(
447
                    enumValueKind.replace(/literal$/i, '').toLowerCase()
448
                ),
449
                location: util.createLocationFromFileRange(this.event.file, range)
450
            });
451
        }
452

453
        //is non integer value
454
        if (enumValueKind !== TokenKind.IntegerLiteral) {
297✔
455
            //default value present
456
            if (memberValueKind) {
102✔
457
                //member value is same as enum
458
                if (memberValueKind !== enumValueKind) {
100✔
459
                    this.event.program.diagnostics.register({
1✔
460
                        ...DiagnosticMessages.enumValueMustBeType(
461
                            enumValueKind.replace(/literal$/i, '').toLowerCase()
462
                        ),
463
                        location: util.createLocationFromFileRange(this.event.file, range)
464
                    });
465
                }
466

467
                //default value missing
468
            } else {
469
                this.event.program.diagnostics.register({
2✔
470
                    ...DiagnosticMessages.enumValueIsRequired(
471
                        enumValueKind.replace(/literal$/i, '').toLowerCase()
472
                    ),
473
                    location: util.createLocationFromFileRange(this.event.file, range)
474
                });
475
            }
476
        }
477
    }
478

479

480
    private validateConditionalCompileConst(ccConst: Token) {
481
        const isBool = ccConst.kind === TokenKind.True || ccConst.kind === TokenKind.False;
22✔
482
        if (!isBool && !this.event.file.ast.bsConsts.has(ccConst.text.toLowerCase())) {
22✔
483
            this.event.program.diagnostics.register({
2✔
484
                ...DiagnosticMessages.hashConstDoesNotExist(),
485
                location: ccConst.location
486
            });
487
            return false;
2✔
488
        }
489
        return true;
20✔
490
    }
491

492
    /**
493
     * Find statements defined at the top level (or inside a namespace body) that are not allowed to be there
494
     */
495
    private flagTopLevelStatements() {
496
        const statements = [...this.event.file.ast.statements];
1,920✔
497
        while (statements.length > 0) {
1,920✔
498
            const statement = statements.pop();
3,622✔
499
            if (isNamespaceStatement(statement)) {
3,622✔
500
                statements.push(...statement.body.statements);
596✔
501
            } else {
502
                //only allow these statement types
503
                if (
3,026✔
504
                    !isFunctionStatement(statement) &&
6,604✔
505
                    !isClassStatement(statement) &&
506
                    !isEnumStatement(statement) &&
507
                    !isInterfaceStatement(statement) &&
508
                    !isLibraryStatement(statement) &&
509
                    !isImportStatement(statement) &&
510
                    !isConstStatement(statement) &&
511
                    !isTypecastStatement(statement) &&
512
                    !isConditionalCompileConstStatement(statement) &&
513
                    !isConditionalCompileErrorStatement(statement) &&
514
                    !isConditionalCompileStatement(statement) &&
515
                    !isAliasStatement(statement)
516
                ) {
517
                    this.event.program.diagnostics.register({
8✔
518
                        ...DiagnosticMessages.unexpectedStatementOutsideFunction(),
519
                        location: statement.location
520
                    });
521
                }
522
            }
523
        }
524
    }
525

526
    private getTopOfFileStatements() {
527
        let topOfFileIncludeStatements = [] as Array<LibraryStatement | ImportStatement | TypecastStatement | AliasStatement>;
3,838✔
528
        for (let stmt of this.event.file.parser.ast.statements) {
3,838✔
529
            //if we found a non-library statement, this statement is not at the top of the file
530
            if (isLibraryStatement(stmt) || isImportStatement(stmt) || isTypecastStatement(stmt) || isAliasStatement(stmt)) {
4,154✔
531
                topOfFileIncludeStatements.push(stmt);
474✔
532
            } else {
533
                //break out of the loop, we found all of our library statements
534
                break;
3,680✔
535
            }
536
        }
537
        return topOfFileIncludeStatements;
3,838✔
538
    }
539

540
    private validateTopOfFileStatements() {
541
        let topOfFileStatements = this.getTopOfFileStatements();
1,919✔
542

543
        let statements = [
1,919✔
544
            // eslint-disable-next-line @typescript-eslint/dot-notation
545
            ...this.event.file['_cachedLookups'].libraryStatements,
546
            // eslint-disable-next-line @typescript-eslint/dot-notation
547
            ...this.event.file['_cachedLookups'].importStatements,
548
            // eslint-disable-next-line @typescript-eslint/dot-notation
549
            ...this.event.file['_cachedLookups'].aliasStatements
550
        ];
551
        for (let result of statements) {
1,919✔
552
            //if this statement is not one of the top-of-file statements,
553
            //then add a diagnostic explaining that it is invalid
554
            if (!topOfFileStatements.includes(result)) {
232✔
555
                if (isLibraryStatement(result)) {
5✔
556
                    this.event.program.diagnostics.register({
2✔
557
                        ...DiagnosticMessages.unexpectedStatementLocation('library', 'at the top of the file'),
558
                        location: result.location
559
                    });
560
                } else if (isImportStatement(result)) {
3✔
561
                    this.event.program.diagnostics.register({
1✔
562
                        ...DiagnosticMessages.unexpectedStatementLocation('import', 'at the top of the file'),
563
                        location: result.location
564
                    });
565
                } else if (isAliasStatement(result)) {
2!
566
                    this.event.program.diagnostics.register({
2✔
567
                        ...DiagnosticMessages.unexpectedStatementLocation('alias', 'at the top of the file'),
568
                        location: result.location
569
                    });
570
                }
571
            }
572
        }
573
    }
574

575
    private validateTypecastStatements() {
576
        let topOfFileTypecastStatements = this.getTopOfFileStatements().filter(stmt => isTypecastStatement(stmt));
1,919✔
577

578
        //check only one `typecast` statement at "top" of file (eg. before non import/library statements)
579
        for (let i = 1; i < topOfFileTypecastStatements.length; i++) {
1,919✔
580
            const typecastStmt = topOfFileTypecastStatements[i];
1✔
581
            this.event.program.diagnostics.register({
1✔
582
                ...DiagnosticMessages.unexpectedStatementLocation('typecast', 'at the top of the file or beginning of function or namespace'),
583
                location: typecastStmt.location
584
            });
585
        }
586

587
        // eslint-disable-next-line @typescript-eslint/dot-notation
588
        for (let result of this.event.file['_cachedLookups'].typecastStatements) {
1,919✔
589
            let isBadTypecastObj = false;
22✔
590
            if (!isVariableExpression(result.typecastExpression.obj)) {
22✔
591
                isBadTypecastObj = true;
1✔
592
            } else if (result.typecastExpression.obj.tokens.name.text.toLowerCase() !== 'm') {
21✔
593
                isBadTypecastObj = true;
1✔
594
            }
595
            if (isBadTypecastObj) {
22✔
596
                this.event.program.diagnostics.register({
2✔
597
                    ...DiagnosticMessages.invalidTypecastStatementApplication(util.getAllDottedGetPartsAsString(result.typecastExpression.obj)),
598
                    location: result.typecastExpression.obj.location
599
                });
600
            }
601

602
            if (topOfFileTypecastStatements.includes(result)) {
22✔
603
                // already validated
604
                continue;
10✔
605
            }
606

607
            const block = result.findAncestor<Body | Block>(node => (isBody(node) || isBlock(node)));
12✔
608
            const isFirst = block?.statements[0] === result;
12!
609
            const isAllowedBlock = (isBody(block) || isFunctionExpression(block.parent) || isNamespaceStatement(block.parent));
12!
610

611
            if (!isFirst || !isAllowedBlock) {
12✔
612
                this.event.program.diagnostics.register({
3✔
613
                    ...DiagnosticMessages.unexpectedStatementLocation('typecast', 'at the top of the file or beginning of function or namespace'),
614
                    location: result.location
615
                });
616
            }
617
        }
618
    }
619

620
    private validateContinueStatement(statement: ContinueStatement) {
621
        const validateLoopTypeMatch = (expectedLoopType: TokenKind) => {
8✔
622
            //coerce ForEach to For
623
            expectedLoopType = expectedLoopType === TokenKind.ForEach ? TokenKind.For : expectedLoopType;
7✔
624
            const actualLoopType = statement.tokens.loopType;
7✔
625
            if (actualLoopType && expectedLoopType?.toLowerCase() !== actualLoopType.text?.toLowerCase()) {
7!
626
                this.event.program.diagnostics.register({
3✔
627
                    location: statement.tokens.loopType.location,
628
                    ...DiagnosticMessages.expectedToken(expectedLoopType)
629
                });
630
            }
631
        };
632

633
        //find the parent loop statement
634
        const parent = statement.findAncestor<WhileStatement | ForStatement | ForEachStatement>((node) => {
8✔
635
            if (isWhileStatement(node)) {
18✔
636
                validateLoopTypeMatch(node.tokens.while.kind);
3✔
637
                return true;
3✔
638
            } else if (isForStatement(node)) {
15✔
639
                validateLoopTypeMatch(node.tokens.for.kind);
3✔
640
                return true;
3✔
641
            } else if (isForEachStatement(node)) {
12✔
642
                validateLoopTypeMatch(node.tokens.forEach.kind);
1✔
643
                return true;
1✔
644
            }
645
        });
646
        //flag continue statements found outside of a loop
647
        if (!parent) {
8✔
648
            this.event.program.diagnostics.register({
1✔
649
                location: statement.location,
650
                ...DiagnosticMessages.illegalContinueStatement()
651
            });
652
        }
653
    }
654

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

681
                this.event.program.diagnostics.register({
8✔
682
                    ...DiagnosticMessages.noOptionalChainingInLeftHandSideOfAssignment(),
683
                    location: util.createLocationFromFileRange(this.event.file, range)
684
                });
685
            }
686

687
            if (node === parent) {
238✔
688
                break;
119✔
689
            } else {
690
                nodes.push(node.parent);
119✔
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