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

rokucommunity / brighterscript / #12850

25 Jul 2024 12:51PM UTC coverage: 86.205%. Remained the same
#12850

push

web-flow
Merge 0c17734d3 into 5f3ffa3fa

10601 of 13088 branches covered (81.0%)

Branch coverage included in aggregate %.

82 of 88 new or added lines in 15 files covered. (93.18%)

288 existing lines in 16 files now uncovered.

12302 of 13480 relevant lines covered (91.26%)

26605.93 hits per line

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

88.83
/src/bscPlugin/validation/BrsFileValidator.ts
1
import { isAALiteralExpression, isAliasStatement, isArrayType, isBlock, isBody, isClassStatement, isConditionalCompileConstStatement, isConditionalCompileErrorStatement, isConditionalCompileStatement, isConstStatement, isDottedGetExpression, isDottedSetStatement, isEnumStatement, isForEachStatement, isForStatement, isFunctionExpression, isFunctionStatement, isImportStatement, isIndexedGetExpression, isIndexedSetStatement, isInterfaceStatement, isLibraryStatement, isLiteralExpression, isNamespaceStatement, isTypecastStatement, isUnaryExpression, isVariableExpression, 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

19
export class BrsFileValidator {
1✔
20
    constructor(
21
        public event: OnFileValidateEvent<BrsFile>
1,534✔
22
    ) {
23
    }
24

25

26
    public process() {
27
        const unlinkGlobalSymbolTable = this.event.file.parser.symbolTable.pushParentProvider(() => this.event.program.globalScope.symbolTable);
4,622✔
28

29
        util.validateTooDeepFile(this.event.file);
1,534✔
30

31
        // Invalidate cache on this file
32
        // It could have potentially changed before this from plugins, after this, it will not change
33
        // eslint-disable-next-line @typescript-eslint/dot-notation
34
        this.event.file['_cachedLookups'].invalidate();
1,534✔
35

36
        // make a copy of the bsConsts, because they might be added to
37
        const bsConstsBackup = new Map<string, boolean>(this.event.file.ast.getBsConsts());
1,534✔
38

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

47
        this.event.file.ast.bsConsts = bsConstsBackup;
1,534✔
48
        unlinkGlobalSymbolTable();
1,534✔
49
    }
50

51
    /**
52
     * Walk the full AST
53
     */
54
    private walk() {
55

56

57
        const visitor = createVisitor({
1,534✔
58
            MethodStatement: (node) => {
59
                //add the `super` symbol to class methods
60
                if (isClassStatement(node.parent) && node.parent.hasParentClass()) {
226✔
61
                    const data: ExtraSymbolData = {};
69✔
62
                    const parentClassType = node.parent.parentClassName.getType({ flags: SymbolTypeFlag.typetime, data: data });
69✔
63
                    node.func.body.getSymbolTable().addSymbol('super', { ...data, isInstance: true }, parentClassType, SymbolTypeFlag.runtime);
69✔
64
                }
65
            },
66
            CallfuncExpression: (node) => {
67
                if (node.args.length > 5) {
19✔
68
                    this.event.program.diagnostics.register({
1✔
69
                        ...DiagnosticMessages.callfuncHasToManyArgs(node.args.length),
70
                        location: node.tokens.methodName.location
71
                    });
72
                }
73
            },
74
            EnumStatement: (node) => {
75
                this.validateDeclarationLocations(node, 'enum', () => util.createBoundingRange(node.tokens.enum, node.tokens.name));
131✔
76

77
                this.validateEnumDeclaration(node);
131✔
78

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

87
                //register this class
88
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
390✔
89
                node.getSymbolTable().addSymbol('m', { definingNode: node, isInstance: true }, nodeType, SymbolTypeFlag.runtime);
390✔
90
                // eslint-disable-next-line no-bitwise
91
                node.parent.getSymbolTable()?.addSymbol(node.tokens.name?.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime | SymbolTypeFlag.runtime);
390!
92
            },
93
            AssignmentStatement: (node) => {
94
                //register this variable
95
                const nodeType = node.getType({ flags: SymbolTypeFlag.runtime });
589✔
96
                node.parent.getSymbolTable()?.addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true }, nodeType, SymbolTypeFlag.runtime);
589!
97
            },
98
            DottedSetStatement: (node) => {
99
                this.validateNoOptionalChainingInVarSet(node, [node.obj]);
76✔
100
            },
101
            IndexedSetStatement: (node) => {
102
                this.validateNoOptionalChainingInVarSet(node, [node.obj]);
15✔
103
            },
104
            ForEachStatement: (node) => {
105
                //register the for loop variable
106
                const loopTargetType = node.target.getType({ flags: SymbolTypeFlag.runtime });
22✔
107
                let loopVarType = isArrayType(loopTargetType) ? loopTargetType.defaultType : DynamicType.instance;
22✔
108
                if (!loopTargetType.isResolvable()) {
22✔
109
                    loopVarType = new ArrayDefaultTypeReferenceType(loopTargetType);
1✔
110
                }
111
                node.parent.getSymbolTable()?.addSymbol(node.tokens.item.text, { definingNode: node, isInstance: true }, loopVarType, SymbolTypeFlag.runtime);
22!
112
            },
113
            NamespaceStatement: (node) => {
114
                this.validateDeclarationLocations(node, 'namespace', () => util.createBoundingRange(node.tokens.namespace, node.nameExpression));
534✔
115
                //Namespace Types are added at the Scope level - This is handled when the SymbolTables get linked
116
            },
117
            FunctionStatement: (node) => {
118
                this.validateDeclarationLocations(node, 'function', () => util.createBoundingRange(node.func.tokens.functionType, node.tokens.name));
1,504✔
119
                const funcType = node.getType({ flags: SymbolTypeFlag.typetime });
1,504✔
120

121
                if (node.tokens.name?.text) {
1,504!
122
                    node.parent.getSymbolTable().addSymbol(
1,504✔
123
                        node.tokens.name.text,
124
                        { definingNode: node },
125
                        funcType,
126
                        SymbolTypeFlag.runtime
127
                    );
128
                }
129

130
                const namespace = node.findAncestor(isNamespaceStatement);
1,504✔
131
                //this function is declared inside a namespace
132
                if (namespace) {
1,504✔
133
                    namespace.getSymbolTable().addSymbol(
346✔
134
                        node.tokens.name?.text,
1,038!
135
                        { definingNode: node },
136
                        funcType,
137
                        SymbolTypeFlag.runtime
138
                    );
139
                    //add the transpiled name for namespaced functions to the root symbol table
140
                    const transpiledNamespaceFunctionName = node.getName(ParseMode.BrightScript);
346✔
141

142
                    this.event.file.parser.ast.symbolTable.addSymbol(
346✔
143
                        transpiledNamespaceFunctionName,
144
                        { definingNode: node },
145
                        funcType,
146
                        // eslint-disable-next-line no-bitwise
147
                        SymbolTypeFlag.runtime | SymbolTypeFlag.postTranspile
148
                    );
149
                }
150
            },
151
            FunctionExpression: (node) => {
152
                const funcSymbolTable = node.getSymbolTable();
1,753✔
153
                if (!funcSymbolTable?.hasSymbol('m', SymbolTypeFlag.runtime) || node.findAncestor(isAALiteralExpression)) {
1,753!
154
                    if (!isTypecastStatement(node.body?.statements?.[0])) {
4!
155
                        funcSymbolTable?.addSymbol('m', { isInstance: true }, new AssociativeArrayType(), SymbolTypeFlag.runtime);
3!
156
                    }
157
                }
158
                this.validateFunctionParameterCount(node);
1,753✔
159
            },
160
            FunctionParameterExpression: (node) => {
161
                const paramName = node.tokens.name?.text;
950!
162
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
950✔
163
                // add param symbol at expression level, so it can be used as default value in other params
164
                const funcExpr = node.findAncestor<FunctionExpression>(isFunctionExpression);
950✔
165
                const funcSymbolTable = funcExpr?.getSymbolTable();
950!
166
                funcSymbolTable?.addSymbol(paramName, { definingNode: node, isInstance: true }, nodeType, SymbolTypeFlag.runtime);
950!
167

168
                //also add param symbol at block level, as it may be redefined, and if so, should show a union
169
                funcExpr.body.getSymbolTable()?.addSymbol(paramName, { definingNode: node, isInstance: true }, nodeType, SymbolTypeFlag.runtime);
950!
170
            },
171
            InterfaceStatement: (node) => {
172
                this.validateDeclarationLocations(node, 'interface', () => util.createBoundingRange(node.tokens.interface, node.tokens.name));
121✔
173

174
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
121✔
175
                // eslint-disable-next-line no-bitwise
176
                node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime);
121✔
177
            },
178
            ConstStatement: (node) => {
179
                this.validateDeclarationLocations(node, 'const', () => util.createBoundingRange(node.tokens.const, node.tokens.name));
134✔
180
                const nodeType = node.getType({ flags: SymbolTypeFlag.runtime });
134✔
181
                node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true }, nodeType, SymbolTypeFlag.runtime);
134✔
182
            },
183
            CatchStatement: (node) => {
184
                node.parent.getSymbolTable().addSymbol(node.tokens.exceptionVariable.text, { definingNode: node, isInstance: true }, DynamicType.instance, SymbolTypeFlag.runtime);
6✔
185
            },
186
            DimStatement: (node) => {
187
                if (node.tokens.name) {
18!
188
                    node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true }, node.getType({ flags: SymbolTypeFlag.runtime }), SymbolTypeFlag.runtime);
18✔
189
                }
190
            },
191
            ContinueStatement: (node) => {
192
                this.validateContinueStatement(node);
8✔
193
            },
194
            TypecastStatement: (node) => {
195
                node.parent.getSymbolTable().addSymbol('m', { definingNode: node, doNotMerge: true, isInstance: true }, node.getType({ flags: SymbolTypeFlag.typetime }), SymbolTypeFlag.runtime);
19✔
196
            },
197
            ConditionalCompileConstStatement: (node) => {
198
                const assign = node.assignment;
10✔
199
                const constNameLower = assign.tokens.name?.text.toLowerCase();
10!
200
                const astBsConsts = this.event.file.ast.bsConsts;
10✔
201
                if (isLiteralExpression(assign.value)) {
10!
202
                    astBsConsts.set(constNameLower, assign.value.tokens.value.text.toLowerCase() === 'true');
10✔
203
                } else if (isVariableExpression(assign.value)) {
×
204
                    if (this.validateConditionalCompileConst(assign.value.tokens.name)) {
×
UNCOV
205
                        astBsConsts.set(constNameLower, astBsConsts.get(assign.value.tokens.name.text.toLowerCase()));
×
206
                    }
207
                }
208
            },
209
            ConditionalCompileStatement: (node) => {
210
                this.validateConditionalCompileConst(node.tokens.condition);
17✔
211
            },
212
            ConditionalCompileErrorStatement: (node) => {
213
                this.event.program.diagnostics.register({
1✔
214
                    ...DiagnosticMessages.hashError(node.tokens.message.text),
215
                    location: node.location
216
                });
217
            },
218
            AliasStatement: (node) => {
219
                // eslint-disable-next-line no-bitwise
220
                const targetType = node.value.getType({ flags: SymbolTypeFlag.typetime | SymbolTypeFlag.runtime });
30✔
221

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

225
            }
226
        });
227

228
        this.event.file.ast.walk((node, parent) => {
1,534✔
229
            visitor(node, parent);
21,622✔
230
        }, {
231
            walkMode: WalkMode.visitAllRecursive
232
        });
233
    }
234

235
    /**
236
     * Validate that a statement is defined in one of these specific locations
237
     *  - the root of the AST
238
     *  - inside a namespace
239
     * This is applicable to things like FunctionStatement, ClassStatement, NamespaceStatement, EnumStatement, InterfaceStatement
240
     */
241
    private validateDeclarationLocations(statement: Statement, keyword: string, rangeFactory?: () => (Range | undefined)) {
242
        //if nested inside a namespace, or defined at the root of the AST (i.e. in a body that has no parent)
243
        const isOkDeclarationLocation = (parentNode) => {
2,814✔
244
            return isNamespaceStatement(parentNode?.parent) || (isBody(parentNode) && !parentNode?.parent);
2,816!
245
        };
246
        if (isOkDeclarationLocation(statement.parent)) {
2,814✔
247
            return;
2,799✔
248
        }
249

250
        // is this in a top levelconditional compile?
251
        if (isConditionalCompileStatement(statement.parent?.parent)) {
15!
252
            if (isOkDeclarationLocation(statement.parent.parent.parent)) {
2✔
253
                return;
1✔
254
            }
255
        }
256

257
        //the statement was defined in the wrong place. Flag it.
258
        this.event.program.diagnostics.register({
14✔
259
            ...DiagnosticMessages.keywordMustBeDeclaredAtNamespaceLevel(keyword),
260
            location: rangeFactory ? util.createLocationFromFileRange(this.event.file, rangeFactory()) : statement.location
14!
261
        });
262
    }
263

264
    private validateFunctionParameterCount(func: FunctionExpression) {
265
        if (func.parameters.length > CallExpression.MaximumArguments) {
1,753✔
266
            //flag every parameter over the limit
267
            for (let i = CallExpression.MaximumArguments; i < func.parameters.length; i++) {
2✔
268
                this.event.program.diagnostics.register({
3✔
269
                    ...DiagnosticMessages.tooManyCallableParameters(func.parameters.length, CallExpression.MaximumArguments),
270
                    location: func.parameters[i]?.tokens.name?.location ?? func.parameters[i]?.location ?? func.location
36!
271
                });
272
            }
273
        }
274
    }
275

276
    private validateEnumDeclaration(stmt: EnumStatement) {
277
        const members = stmt.getMembers();
131✔
278
        //the enum data type is based on the first member value
279
        const enumValueKind = (members.find(x => x.value)?.value as LiteralExpression)?.tokens?.value?.kind ?? TokenKind.IntegerLiteral;
184✔
280
        const memberNames = new Set<string>();
131✔
281
        for (const member of members) {
131✔
282
            const memberNameLower = member.name?.toLowerCase();
255!
283

284
            /**
285
             * flag duplicate member names
286
             */
287
            if (memberNames.has(memberNameLower)) {
255✔
288
                this.event.program.diagnostics.register({
1✔
289
                    ...DiagnosticMessages.duplicateIdentifier(member.name),
290
                    location: member.location
291
                });
292
            } else {
293
                memberNames.add(memberNameLower);
254✔
294
            }
295

296
            //Enforce all member values are the same type
297
            this.validateEnumValueTypes(member, enumValueKind);
255✔
298
        }
299
    }
300

301
    private validateEnumValueTypes(member: EnumMemberStatement, enumValueKind: TokenKind) {
302
        let memberValueKind: TokenKind;
303
        let memberValue: Expression;
304
        if (isUnaryExpression(member.value)) {
255✔
305
            memberValueKind = (member.value?.right as LiteralExpression)?.tokens?.value?.kind;
2!
306
            memberValue = member.value?.right;
2!
307
        } else {
308
            memberValueKind = (member.value as LiteralExpression)?.tokens?.value?.kind;
253✔
309
            memberValue = member.value;
253✔
310
        }
311
        const range = (memberValue ?? member)?.location?.range;
255!
312
        if (
255✔
313
            //is integer enum, has value, that value type is not integer
314
            (enumValueKind === TokenKind.IntegerLiteral && memberValueKind && memberValueKind !== enumValueKind) ||
850✔
315
            //has value, that value is not a literal
316
            (memberValue && !isLiteralExpression(memberValue))
317
        ) {
318
            this.event.program.diagnostics.register({
6✔
319
                ...DiagnosticMessages.enumValueMustBeType(
320
                    enumValueKind.replace(/literal$/i, '').toLowerCase()
321
                ),
322
                location: util.createLocationFromFileRange(this.event.file, range)
323
            });
324
        }
325

326
        //is non integer value
327
        if (enumValueKind !== TokenKind.IntegerLiteral) {
255✔
328
            //default value present
329
            if (memberValueKind) {
92✔
330
                //member value is same as enum
331
                if (memberValueKind !== enumValueKind) {
90✔
332
                    this.event.program.diagnostics.register({
1✔
333
                        ...DiagnosticMessages.enumValueMustBeType(
334
                            enumValueKind.replace(/literal$/i, '').toLowerCase()
335
                        ),
336
                        location: util.createLocationFromFileRange(this.event.file, range)
337
                    });
338
                }
339

340
                //default value missing
341
            } else {
342
                this.event.program.diagnostics.register({
2✔
343
                    ...DiagnosticMessages.enumValueIsRequired(
344
                        enumValueKind.replace(/literal$/i, '').toLowerCase()
345
                    ),
346
                    location: util.createLocationFromFileRange(this.event.file, range)
347
                });
348
            }
349
        }
350
    }
351

352

353
    private validateConditionalCompileConst(ccConst: Token) {
354
        const isBool = ccConst.kind === TokenKind.True || ccConst.kind === TokenKind.False;
17✔
355
        if (!isBool && !this.event.file.ast.bsConsts.has(ccConst.text.toLowerCase())) {
17✔
356
            this.event.program.diagnostics.register({
2✔
357
                ...DiagnosticMessages.referencedConstDoesNotExist(),
358
                location: ccConst.location
359
            });
360
            return false;
2✔
361
        }
362
        return true;
15✔
363
    }
364

365
    /**
366
     * Find statements defined at the top level (or inside a namespace body) that are not allowed to be there
367
     */
368
    private flagTopLevelStatements() {
369
        const statements = [...this.event.file.ast.statements];
1,534✔
370
        while (statements.length > 0) {
1,534✔
371
            const statement = statements.pop();
3,041✔
372
            if (isNamespaceStatement(statement)) {
3,041✔
373
                statements.push(...statement.body.statements);
530✔
374
            } else {
375
                //only allow these statement types
376
                if (
2,511✔
377
                    !isFunctionStatement(statement) &&
5,765✔
378
                    !isClassStatement(statement) &&
379
                    !isEnumStatement(statement) &&
380
                    !isInterfaceStatement(statement) &&
381
                    !isLibraryStatement(statement) &&
382
                    !isImportStatement(statement) &&
383
                    !isConstStatement(statement) &&
384
                    !isTypecastStatement(statement) &&
385
                    !isConditionalCompileConstStatement(statement) &&
386
                    !isConditionalCompileErrorStatement(statement) &&
387
                    !isConditionalCompileStatement(statement) &&
388
                    !isAliasStatement(statement)
389
                ) {
390
                    this.event.program.diagnostics.register({
7✔
391
                        ...DiagnosticMessages.unexpectedStatementOutsideFunction(),
392
                        location: statement.location
393
                    });
394
                }
395
            }
396
        }
397
    }
398

399
    private getTopOfFileStatements() {
400
        let topOfFileIncludeStatements = [] as Array<LibraryStatement | ImportStatement | TypecastStatement | AliasStatement>;
3,066✔
401
        for (let stmt of this.event.file.parser.ast.statements) {
3,066✔
402
            //if we found a non-library statement, this statement is not at the top of the file
403
            if (isLibraryStatement(stmt) || isImportStatement(stmt) || isTypecastStatement(stmt) || isAliasStatement(stmt)) {
3,388✔
404
                topOfFileIncludeStatements.push(stmt);
448✔
405
            } else {
406
                //break out of the loop, we found all of our library statements
407
                break;
2,940✔
408
            }
409
        }
410
        return topOfFileIncludeStatements;
3,066✔
411
    }
412

413
    private validateTopOfFileStatements() {
414
        let topOfFileStatements = this.getTopOfFileStatements();
1,533✔
415

416
        let statements = [
1,533✔
417
            // eslint-disable-next-line @typescript-eslint/dot-notation
418
            ...this.event.file['_cachedLookups'].libraryStatements,
419
            // eslint-disable-next-line @typescript-eslint/dot-notation
420
            ...this.event.file['_cachedLookups'].importStatements,
421
            // eslint-disable-next-line @typescript-eslint/dot-notation
422
            ...this.event.file['_cachedLookups'].aliasStatements
423
        ];
424
        for (let result of statements) {
1,533✔
425
            //if this statement is not one of the top-of-file statements,
426
            //then add a diagnostic explaining that it is invalid
427
            if (!topOfFileStatements.includes(result)) {
222✔
428
                if (isLibraryStatement(result)) {
5✔
429
                    this.event.program.diagnostics.register({
2✔
430
                        ...DiagnosticMessages.statementMustBeDeclaredAtTopOfFile('library'),
431
                        location: result.location
432
                    });
433
                } else if (isImportStatement(result)) {
3✔
434
                    this.event.program.diagnostics.register({
1✔
435
                        ...DiagnosticMessages.statementMustBeDeclaredAtTopOfFile('import'),
436
                        location: result.location
437
                    });
438
                } else if (isAliasStatement(result)) {
2!
439
                    this.event.program.diagnostics.register({
2✔
440
                        ...DiagnosticMessages.statementMustBeDeclaredAtTopOfFile('alias'),
441
                        location: result.location
442
                    });
443
                }
444
            }
445
        }
446
    }
447

448
    private validateTypecastStatements() {
449
        let topOfFileTypecastStatements = this.getTopOfFileStatements().filter(stmt => isTypecastStatement(stmt));
1,533✔
450

451
        //check only one `typecast` statement at "top" of file (eg. before non import/library statements)
452
        for (let i = 1; i < topOfFileTypecastStatements.length; i++) {
1,533✔
453
            const typecastStmt = topOfFileTypecastStatements[i];
1✔
454
            this.event.program.diagnostics.register({
1✔
455
                ...DiagnosticMessages.typecastStatementMustBeDeclaredAtStart(),
456
                location: typecastStmt.location
457
            });
458
        }
459

460
        // eslint-disable-next-line @typescript-eslint/dot-notation
461
        for (let result of this.event.file['_cachedLookups'].typecastStatements) {
1,533✔
462
            let isBadTypecastObj = false;
19✔
463
            if (!isVariableExpression(result.typecastExpression.obj)) {
19✔
464
                isBadTypecastObj = true;
1✔
465
            } else if (result.typecastExpression.obj.tokens.name.text.toLowerCase() !== 'm') {
18✔
466
                isBadTypecastObj = true;
1✔
467
            }
468
            if (isBadTypecastObj) {
19✔
469
                this.event.program.diagnostics.register({
2✔
470
                    ...DiagnosticMessages.invalidTypecastStatementApplication(util.getAllDottedGetPartsAsString(result.typecastExpression.obj)),
471
                    location: result.typecastExpression.obj.location
472
                });
473
            }
474

475
            if (topOfFileTypecastStatements.includes(result)) {
19✔
476
                // already validated
477
                continue;
7✔
478
            }
479

480
            const block = result.findAncestor<Body | Block>(node => (isBody(node) || isBlock(node)));
12✔
481
            const isFirst = block?.statements[0] === result;
12!
482
            const isAllowedBlock = (isBody(block) || isFunctionExpression(block.parent) || isNamespaceStatement(block.parent));
12!
483

484
            if (!isFirst || !isAllowedBlock) {
12✔
485
                this.event.program.diagnostics.register({
3✔
486
                    ...DiagnosticMessages.typecastStatementMustBeDeclaredAtStart(),
487
                    location: result.location
488
                });
489
            }
490
        }
491
    }
492

493
    private validateContinueStatement(statement: ContinueStatement) {
494
        const validateLoopTypeMatch = (expectedLoopType: TokenKind) => {
8✔
495
            //coerce ForEach to For
496
            expectedLoopType = expectedLoopType === TokenKind.ForEach ? TokenKind.For : expectedLoopType;
7✔
497
            const actualLoopType = statement.tokens.loopType;
7✔
498
            if (actualLoopType && expectedLoopType?.toLowerCase() !== actualLoopType.text?.toLowerCase()) {
7!
499
                this.event.program.diagnostics.register({
3✔
500
                    location: statement.tokens.loopType.location,
501
                    ...DiagnosticMessages.expectedToken(expectedLoopType)
502
                });
503
            }
504
        };
505

506
        //find the parent loop statement
507
        const parent = statement.findAncestor<WhileStatement | ForStatement | ForEachStatement>((node) => {
8✔
508
            if (isWhileStatement(node)) {
18✔
509
                validateLoopTypeMatch(node.tokens.while.kind);
3✔
510
                return true;
3✔
511
            } else if (isForStatement(node)) {
15✔
512
                validateLoopTypeMatch(node.tokens.for.kind);
3✔
513
                return true;
3✔
514
            } else if (isForEachStatement(node)) {
12✔
515
                validateLoopTypeMatch(node.tokens.forEach.kind);
1✔
516
                return true;
1✔
517
            }
518
        });
519
        //flag continue statements found outside of a loop
520
        if (!parent) {
8✔
521
            this.event.program.diagnostics.register({
1✔
522
                location: statement.location,
523
                ...DiagnosticMessages.illegalContinueStatement()
524
            });
525
        }
526
    }
527

528
    /**
529
     * Validate that there are no optional chaining operators on the left-hand-side of an assignment, indexed set, or dotted get
530
     */
531
    private validateNoOptionalChainingInVarSet(parent: AstNode, children: AstNode[]) {
532
        const nodes = [...children, parent];
91✔
533
        //flag optional chaining anywhere in the left of this statement
534
        while (nodes.length > 0) {
91✔
535
            const node = nodes.shift();
182✔
536
            if (
182✔
537
                // a?.b = true or a.b?.c = true
538
                ((isDottedSetStatement(node) || isDottedGetExpression(node)) && node.tokens.dot?.kind === TokenKind.QuestionDot) ||
1,041!
539
                // a.b?[2] = true
540
                (isIndexedGetExpression(node) && (node?.tokens.questionDot?.kind === TokenKind.QuestionDot || node.tokens.openingSquare?.kind === TokenKind.QuestionLeftSquare)) ||
36!
541
                // a?[1] = true
542
                (isIndexedSetStatement(node) && node.tokens.openingSquare?.kind === TokenKind.QuestionLeftSquare)
45!
543
            ) {
544
                //try to highlight the entire left-hand-side expression if possible
545
                let range: Range;
546
                if (isDottedSetStatement(parent)) {
8✔
547
                    range = util.createBoundingRange(parent.obj?.location, parent.tokens.dot, parent.tokens.name);
5!
548
                } else if (isIndexedSetStatement(parent)) {
3!
549
                    range = util.createBoundingRange(parent.obj?.location, parent.tokens.openingSquare, ...parent.indexes, parent.tokens.closingSquare);
3!
550
                } else {
UNCOV
551
                    range = node.location?.range;
×
552
                }
553

554
                this.event.program.diagnostics.register({
8✔
555
                    ...DiagnosticMessages.noOptionalChainingInLeftHandSideOfAssignment(),
556
                    location: util.createLocationFromFileRange(this.event.file, range)
557
                });
558
            }
559

560
            if (node === parent) {
182✔
561
                break;
91✔
562
            } else {
563
                nodes.push(node.parent);
91✔
564
            }
565
        }
566
    }
567
}
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