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

rokucommunity / brighterscript / #14044

20 Mar 2025 07:09PM UTC coverage: 87.163% (-2.0%) from 89.117%
#14044

push

web-flow
Merge e33b1f944 into 0eceb0830

13257 of 16072 branches covered (82.49%)

Branch coverage included in aggregate %.

1163 of 1279 new or added lines in 24 files covered. (90.93%)

802 existing lines in 52 files now uncovered.

14323 of 15570 relevant lines covered (91.99%)

21312.85 hits per line

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

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

27

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

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

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

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

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

59
        const visitor = createVisitor({
1,844✔
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));
147✔
78

79
                this.validateEnumDeclaration(node);
147✔
80

81
                //register this enum declaration
82
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
147✔
83
                // eslint-disable-next-line no-bitwise
84
                node.parent.getSymbolTable()?.addSymbol(node.tokens.name.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime | SymbolTypeFlag.runtime);
147!
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 = {};
721✔
110
                //register this variable
111
                let nodeType = node.getType({ flags: SymbolTypeFlag.runtime, data: data });
721✔
112
                if (isInvalidType(nodeType) || isVoidType(nodeType)) {
721✔
113
                    nodeType = DynamicType.instance;
9✔
114
                }
115
                node.parent.getSymbolTable()?.addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true, isFromDocComment: data.isFromDocComment, isFromCallFunc: data.isFromCallFunc }, nodeType, SymbolTypeFlag.runtime);
721!
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));
597✔
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,840✔
139
                const funcType = node.getType({ flags: SymbolTypeFlag.typetime });
1,840✔
140

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

150
                const namespace = node.findAncestor(isNamespaceStatement);
1,840✔
151
                //this function is declared inside a namespace
152
                if (namespace) {
1,840✔
153
                    namespace.getSymbolTable().addSymbol(
404✔
154
                        node.tokens.name?.text,
1,212!
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);
404✔
161

162
                    this.event.file.parser.ast.symbolTable.addSymbol(
404✔
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,113✔
173
                const isInlineFunc = !(isFunctionStatement(node.parent) || isMethodStatement(node.parent));
2,113✔
174
                if (isInlineFunc) {
2,113✔
175
                    // symbol table should not include any symbols from parent func
176
                    funcSymbolTable.pushParentProvider(() => node.findAncestor<Body>(isBody).getSymbolTable());
119✔
177
                }
178
                if (!funcSymbolTable?.hasSymbol('m', SymbolTypeFlag.runtime) || isInlineFunc) {
2,113!
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,113✔
184
            },
185
            FunctionParameterExpression: (node) => {
186
                const paramName = node.tokens.name?.text;
1,074!
187
                const data: ExtraSymbolData = {};
1,074✔
188
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime, data: data });
1,074✔
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,074✔
191
                const funcSymbolTable = funcExpr?.getSymbolTable();
1,074!
192
                funcSymbolTable?.addSymbol(paramName, { definingNode: node, isInstance: true, isFromDocComment: data.isFromDocComment }, nodeType, SymbolTypeFlag.runtime);
1,074!
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,074!
196
            },
197
            InterfaceStatement: (node) => {
198
                this.validateDeclarationLocations(node, 'interface', () => util.createBoundingRange(node.tokens.interface, node.tokens.name));
141✔
199

200
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
141✔
201
                // eslint-disable-next-line no-bitwise
202
                node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime);
141✔
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
UNCOV
224
                } else if (isBrighterscript && isTypecastExpression(node.exceptionVariableExpression) && isVariableExpression(node.exceptionVariableExpression.obj)) {
×
UNCOV
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 {
UNCOV
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);
21✔
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✔
UNCOV
257
                } else if (isVariableExpression(assign.value)) {
×
UNCOV
258
                    if (this.validateConditionalCompileConst(assign.value.tokens.name)) {
×
UNCOV
259
                        astBsConsts.set(constNameLower, astBsConsts.get(assign.value.tokens.name.text.toLowerCase()));
×
260
                    }
261
                }
262
            },
263
            ConditionalCompileStatement: (node) => {
264
                this.validateConditionalCompileConst(node.tokens.condition);
22✔
265
            },
266
            ConditionalCompileErrorStatement: (node) => {
267
                this.event.program.diagnostics.register({
1✔
268
                    ...DiagnosticMessages.hashError(node.tokens.message.text),
269
                    location: node.location
270
                });
271
            },
272
            AliasStatement: (node) => {
273
                // eslint-disable-next-line no-bitwise
274
                const targetType = node.value.getType({ flags: SymbolTypeFlag.typetime | SymbolTypeFlag.runtime });
30✔
275

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

279
            },
280
            AstNode: (node) => {
281
                //check for doc comments
282
                if (!node.leadingTrivia || node.leadingTrivia.length === 0) {
25,684✔
283
                    return;
4,484✔
284
                }
285
                const doc = brsDocParser.parseNode(node);
21,200✔
286
                if (doc.tags.length === 0) {
21,200✔
287
                    return;
21,152✔
288
                }
289

290
                let funcExpr = node.findAncestor<FunctionExpression>(isFunctionExpression);
48✔
291
                if (funcExpr) {
48✔
292
                    // handle comment tags inside a function expression
293
                    this.processDocTagsInFunction(doc, node, funcExpr);
8✔
294
                } else {
295
                    //handle comment tags outside of a function expression
296
                    this.processDocTagsAtTopLevel(doc, node);
40✔
297
                }
298
            }
299
        });
300

301
        this.event.file.ast.walk((node, parent) => {
1,844✔
302
            visitor(node, parent);
25,684✔
303
        }, {
304
            walkMode: WalkMode.visitAllRecursive
305
        });
306
    }
307

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

311
        // For example, declaring variable types:
312
        // const symbolTable = funcExpr.body.getSymbolTable();
313

314
        // for (const varTag of doc.getAllTags(BrsDocTagKind.Var)) {
315
        //     const varName = (varTag as BrsDocParamTag).name;
316
        //     const varTypeStr = (varTag as BrsDocParamTag).type;
317
        //     const data: ExtraSymbolData = {};
318
        //     const type = doc.getTypeFromContext(varTypeStr, node, { flags: SymbolTypeFlag.typetime, fullName: varTypeStr, data: data, tableProvider: () => symbolTable });
319
        //     if (type) {
320
        //         symbolTable.addSymbol(varName, { ...data, isFromDocComment: true }, type, SymbolTypeFlag.runtime);
321
        //     }
322
        // }
323
    }
324

325
    private processDocTagsAtTopLevel(doc: BrightScriptDoc, node: AstNode) {
326
        //TODO:
327
        // - handle import statements?
328
        // - handle library statements?
329
        // - handle typecast statements?
330
        // - handle alias statements?
331
        // - handle const statements?
332
        // - allow interface definitions?
333
    }
334

335
    /**
336
     * Validate that a statement is defined in one of these specific locations
337
     *  - the root of the AST
338
     *  - inside a namespace
339
     * This is applicable to things like FunctionStatement, ClassStatement, NamespaceStatement, EnumStatement, InterfaceStatement
340
     */
341
    private validateDeclarationLocations(statement: Statement, keyword: string, rangeFactory?: () => (Range | undefined)) {
342
        //if nested inside a namespace, or defined at the root of the AST (i.e. in a body that has no parent)
343
        const isOkDeclarationLocation = (parentNode) => {
3,288✔
344
            return isNamespaceStatement(parentNode?.parent) || (isBody(parentNode) && !parentNode?.parent);
3,293!
345
        };
346
        if (isOkDeclarationLocation(statement.parent)) {
3,288✔
347
            return;
3,270✔
348
        }
349

350
        // is this in a top levelconditional compile?
351
        if (isConditionalCompileStatement(statement.parent?.parent)) {
18!
352
            if (isOkDeclarationLocation(statement.parent.parent.parent)) {
5✔
353
                return;
4✔
354
            }
355
        }
356

357
        //the statement was defined in the wrong place. Flag it.
358
        this.event.program.diagnostics.register({
14✔
359
            ...DiagnosticMessages.keywordMustBeDeclaredAtNamespaceLevel(keyword),
360
            location: rangeFactory ? util.createLocationFromFileRange(this.event.file, rangeFactory()) : statement.location
14!
361
        });
362
    }
363

364
    private validateFunctionParameterCount(func: FunctionExpression) {
365
        if (func.parameters.length > CallExpression.MaximumArguments) {
2,113✔
366
            //flag every parameter over the limit
367
            for (let i = CallExpression.MaximumArguments; i < func.parameters.length; i++) {
2✔
368
                this.event.program.diagnostics.register({
3✔
369
                    ...DiagnosticMessages.tooManyCallableParameters(func.parameters.length, CallExpression.MaximumArguments),
370
                    location: func.parameters[i]?.tokens.name?.location ?? func.parameters[i]?.location ?? func.location
36!
371
                });
372
            }
373
        }
374
    }
375

376
    private validateEnumDeclaration(stmt: EnumStatement) {
377
        const members = stmt.getMembers();
147✔
378
        //the enum data type is based on the first member value
379
        const enumValueKind = (members.find(x => x.value)?.value as LiteralExpression)?.tokens?.value?.kind ?? TokenKind.IntegerLiteral;
211✔
380
        const memberNames = new Set<string>();
147✔
381
        for (const member of members) {
147✔
382
            const memberNameLower = member.name?.toLowerCase();
297!
383

384
            /**
385
             * flag duplicate member names
386
             */
387
            if (memberNames.has(memberNameLower)) {
297✔
388
                this.event.program.diagnostics.register({
1✔
389
                    ...DiagnosticMessages.duplicateIdentifier(member.name),
390
                    location: member.location
391
                });
392
            } else {
393
                memberNames.add(memberNameLower);
296✔
394
            }
395

396
            //Enforce all member values are the same type
397
            this.validateEnumValueTypes(member, enumValueKind);
297✔
398
        }
399
    }
400

401
    private validateEnumValueTypes(member: EnumMemberStatement, enumValueKind: TokenKind) {
402
        let memberValueKind: TokenKind;
403
        let memberValue: Expression;
404
        if (isUnaryExpression(member.value)) {
297✔
405
            memberValueKind = (member.value?.right as LiteralExpression)?.tokens?.value?.kind;
2!
406
            memberValue = member.value?.right;
2!
407
        } else {
408
            memberValueKind = (member.value as LiteralExpression)?.tokens?.value?.kind;
295✔
409
            memberValue = member.value;
295✔
410
        }
411
        const range = (memberValue ?? member)?.location?.range;
297!
412
        if (
297✔
413
            //is integer enum, has value, that value type is not integer
414
            (enumValueKind === TokenKind.IntegerLiteral && memberValueKind && memberValueKind !== enumValueKind) ||
1,000✔
415
            //has value, that value is not a literal
416
            (memberValue && !isLiteralExpression(memberValue))
417
        ) {
418
            this.event.program.diagnostics.register({
6✔
419
                ...DiagnosticMessages.enumValueMustBeType(
420
                    enumValueKind.replace(/literal$/i, '').toLowerCase()
421
                ),
422
                location: util.createLocationFromFileRange(this.event.file, range)
423
            });
424
        }
425

426
        //is non integer value
427
        if (enumValueKind !== TokenKind.IntegerLiteral) {
297✔
428
            //default value present
429
            if (memberValueKind) {
102✔
430
                //member value is same as enum
431
                if (memberValueKind !== enumValueKind) {
100✔
432
                    this.event.program.diagnostics.register({
1✔
433
                        ...DiagnosticMessages.enumValueMustBeType(
434
                            enumValueKind.replace(/literal$/i, '').toLowerCase()
435
                        ),
436
                        location: util.createLocationFromFileRange(this.event.file, range)
437
                    });
438
                }
439

440
                //default value missing
441
            } else {
442
                this.event.program.diagnostics.register({
2✔
443
                    ...DiagnosticMessages.enumValueIsRequired(
444
                        enumValueKind.replace(/literal$/i, '').toLowerCase()
445
                    ),
446
                    location: util.createLocationFromFileRange(this.event.file, range)
447
                });
448
            }
449
        }
450
    }
451

452

453
    private validateConditionalCompileConst(ccConst: Token) {
454
        const isBool = ccConst.kind === TokenKind.True || ccConst.kind === TokenKind.False;
22✔
455
        if (!isBool && !this.event.file.ast.bsConsts.has(ccConst.text.toLowerCase())) {
22✔
456
            this.event.program.diagnostics.register({
2✔
457
                ...DiagnosticMessages.hashConstDoesNotExist(),
458
                location: ccConst.location
459
            });
460
            return false;
2✔
461
        }
462
        return true;
20✔
463
    }
464

465
    /**
466
     * Find statements defined at the top level (or inside a namespace body) that are not allowed to be there
467
     */
468
    private flagTopLevelStatements() {
469
        const statements = [...this.event.file.ast.statements];
1,844✔
470
        while (statements.length > 0) {
1,844✔
471
            const statement = statements.pop();
3,527✔
472
            if (isNamespaceStatement(statement)) {
3,527✔
473
                statements.push(...statement.body.statements);
592✔
474
            } else {
475
                //only allow these statement types
476
                if (
2,935✔
477
                    !isFunctionStatement(statement) &&
6,476✔
478
                    !isClassStatement(statement) &&
479
                    !isEnumStatement(statement) &&
480
                    !isInterfaceStatement(statement) &&
481
                    !isLibraryStatement(statement) &&
482
                    !isImportStatement(statement) &&
483
                    !isConstStatement(statement) &&
484
                    !isTypecastStatement(statement) &&
485
                    !isConditionalCompileConstStatement(statement) &&
486
                    !isConditionalCompileErrorStatement(statement) &&
487
                    !isConditionalCompileStatement(statement) &&
488
                    !isAliasStatement(statement)
489
                ) {
490
                    this.event.program.diagnostics.register({
8✔
491
                        ...DiagnosticMessages.unexpectedStatementOutsideFunction(),
492
                        location: statement.location
493
                    });
494
                }
495
            }
496
        }
497
    }
498

499
    private getTopOfFileStatements() {
500
        let topOfFileIncludeStatements = [] as Array<LibraryStatement | ImportStatement | TypecastStatement | AliasStatement>;
3,686✔
501
        for (let stmt of this.event.file.parser.ast.statements) {
3,686✔
502
            //if we found a non-library statement, this statement is not at the top of the file
503
            if (isLibraryStatement(stmt) || isImportStatement(stmt) || isTypecastStatement(stmt) || isAliasStatement(stmt)) {
4,002✔
504
                topOfFileIncludeStatements.push(stmt);
472✔
505
            } else {
506
                //break out of the loop, we found all of our library statements
507
                break;
3,530✔
508
            }
509
        }
510
        return topOfFileIncludeStatements;
3,686✔
511
    }
512

513
    private validateTopOfFileStatements() {
514
        let topOfFileStatements = this.getTopOfFileStatements();
1,843✔
515

516
        let statements = [
1,843✔
517
            // eslint-disable-next-line @typescript-eslint/dot-notation
518
            ...this.event.file['_cachedLookups'].libraryStatements,
519
            // eslint-disable-next-line @typescript-eslint/dot-notation
520
            ...this.event.file['_cachedLookups'].importStatements,
521
            // eslint-disable-next-line @typescript-eslint/dot-notation
522
            ...this.event.file['_cachedLookups'].aliasStatements
523
        ];
524
        for (let result of statements) {
1,843✔
525
            //if this statement is not one of the top-of-file statements,
526
            //then add a diagnostic explaining that it is invalid
527
            if (!topOfFileStatements.includes(result)) {
232✔
528
                if (isLibraryStatement(result)) {
5✔
529
                    this.event.program.diagnostics.register({
2✔
530
                        ...DiagnosticMessages.unexpectedStatementLocation('library', 'at the top of the file'),
531
                        location: result.location
532
                    });
533
                } else if (isImportStatement(result)) {
3✔
534
                    this.event.program.diagnostics.register({
1✔
535
                        ...DiagnosticMessages.unexpectedStatementLocation('import', 'at the top of the file'),
536
                        location: result.location
537
                    });
538
                } else if (isAliasStatement(result)) {
2!
539
                    this.event.program.diagnostics.register({
2✔
540
                        ...DiagnosticMessages.unexpectedStatementLocation('alias', 'at the top of the file'),
541
                        location: result.location
542
                    });
543
                }
544
            }
545
        }
546
    }
547

548
    private validateTypecastStatements() {
549
        let topOfFileTypecastStatements = this.getTopOfFileStatements().filter(stmt => isTypecastStatement(stmt));
1,843✔
550

551
        //check only one `typecast` statement at "top" of file (eg. before non import/library statements)
552
        for (let i = 1; i < topOfFileTypecastStatements.length; i++) {
1,843✔
553
            const typecastStmt = topOfFileTypecastStatements[i];
1✔
554
            this.event.program.diagnostics.register({
1✔
555
                ...DiagnosticMessages.unexpectedStatementLocation('typecast', 'at the top of the file or beginning of function or namespace'),
556
                location: typecastStmt.location
557
            });
558
        }
559

560
        // eslint-disable-next-line @typescript-eslint/dot-notation
561
        for (let result of this.event.file['_cachedLookups'].typecastStatements) {
1,843✔
562
            let isBadTypecastObj = false;
21✔
563
            if (!isVariableExpression(result.typecastExpression.obj)) {
21✔
564
                isBadTypecastObj = true;
1✔
565
            } else if (result.typecastExpression.obj.tokens.name.text.toLowerCase() !== 'm') {
20✔
566
                isBadTypecastObj = true;
1✔
567
            }
568
            if (isBadTypecastObj) {
21✔
569
                this.event.program.diagnostics.register({
2✔
570
                    ...DiagnosticMessages.invalidTypecastStatementApplication(util.getAllDottedGetPartsAsString(result.typecastExpression.obj)),
571
                    location: result.typecastExpression.obj.location
572
                });
573
            }
574

575
            if (topOfFileTypecastStatements.includes(result)) {
21✔
576
                // already validated
577
                continue;
9✔
578
            }
579

580
            const block = result.findAncestor<Body | Block>(node => (isBody(node) || isBlock(node)));
12✔
581
            const isFirst = block?.statements[0] === result;
12!
582
            const isAllowedBlock = (isBody(block) || isFunctionExpression(block.parent) || isNamespaceStatement(block.parent));
12!
583

584
            if (!isFirst || !isAllowedBlock) {
12✔
585
                this.event.program.diagnostics.register({
3✔
586
                    ...DiagnosticMessages.unexpectedStatementLocation('typecast', 'at the top of the file or beginning of function or namespace'),
587
                    location: result.location
588
                });
589
            }
590
        }
591
    }
592

593
    private validateContinueStatement(statement: ContinueStatement) {
594
        const validateLoopTypeMatch = (expectedLoopType: TokenKind) => {
8✔
595
            //coerce ForEach to For
596
            expectedLoopType = expectedLoopType === TokenKind.ForEach ? TokenKind.For : expectedLoopType;
7✔
597
            const actualLoopType = statement.tokens.loopType;
7✔
598
            if (actualLoopType && expectedLoopType?.toLowerCase() !== actualLoopType.text?.toLowerCase()) {
7!
599
                this.event.program.diagnostics.register({
3✔
600
                    location: statement.tokens.loopType.location,
601
                    ...DiagnosticMessages.expectedToken(expectedLoopType)
602
                });
603
            }
604
        };
605

606
        //find the parent loop statement
607
        const parent = statement.findAncestor<WhileStatement | ForStatement | ForEachStatement>((node) => {
8✔
608
            if (isWhileStatement(node)) {
18✔
609
                validateLoopTypeMatch(node.tokens.while.kind);
3✔
610
                return true;
3✔
611
            } else if (isForStatement(node)) {
15✔
612
                validateLoopTypeMatch(node.tokens.for.kind);
3✔
613
                return true;
3✔
614
            } else if (isForEachStatement(node)) {
12✔
615
                validateLoopTypeMatch(node.tokens.forEach.kind);
1✔
616
                return true;
1✔
617
            }
618
        });
619
        //flag continue statements found outside of a loop
620
        if (!parent) {
8✔
621
            this.event.program.diagnostics.register({
1✔
622
                location: statement.location,
623
                ...DiagnosticMessages.illegalContinueStatement()
624
            });
625
        }
626
    }
627

628
    /**
629
     * Validate that there are no optional chaining operators on the left-hand-side of an assignment, indexed set, or dotted get
630
     */
631
    private validateNoOptionalChainingInVarSet(parent: AstNode, children: AstNode[]) {
632
        const nodes = [...children, parent];
119✔
633
        //flag optional chaining anywhere in the left of this statement
634
        while (nodes.length > 0) {
119✔
635
            const node = nodes.shift();
238✔
636
            if (
238✔
637
                // a?.b = true or a.b?.c = true
638
                ((isDottedSetStatement(node) || isDottedGetExpression(node)) && node.tokens.dot?.kind === TokenKind.QuestionDot) ||
1,357!
639
                // a.b?[2] = true
640
                (isIndexedGetExpression(node) && (node?.tokens.questionDot?.kind === TokenKind.QuestionDot || node.tokens.openingSquare?.kind === TokenKind.QuestionLeftSquare)) ||
36!
641
                // a?[1] = true
642
                (isIndexedSetStatement(node) && node.tokens.openingSquare?.kind === TokenKind.QuestionLeftSquare)
57!
643
            ) {
644
                //try to highlight the entire left-hand-side expression if possible
645
                let range: Range;
646
                if (isDottedSetStatement(parent)) {
8✔
647
                    range = util.createBoundingRange(parent.obj?.location, parent.tokens.dot, parent.tokens.name);
5!
648
                } else if (isIndexedSetStatement(parent)) {
3!
649
                    range = util.createBoundingRange(parent.obj?.location, parent.tokens.openingSquare, ...parent.indexes, parent.tokens.closingSquare);
3!
650
                } else {
UNCOV
651
                    range = node.location?.range;
×
652
                }
653

654
                this.event.program.diagnostics.register({
8✔
655
                    ...DiagnosticMessages.noOptionalChainingInLeftHandSideOfAssignment(),
656
                    location: util.createLocationFromFileRange(this.event.file, range)
657
                });
658
            }
659

660
            if (node === parent) {
238✔
661
                break;
119✔
662
            } else {
663
                nodes.push(node.parent);
119✔
664
            }
665
        }
666
    }
667
}
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