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

rokucommunity / brighterscript / #13111

30 Sep 2024 04:35PM UTC coverage: 86.842% (-1.4%) from 88.193%
#13111

push

web-flow
Merge 25fc06528 into 3a2dc7282

11525 of 14034 branches covered (82.12%)

Branch coverage included in aggregate %.

6990 of 7581 new or added lines in 100 files covered. (92.2%)

83 existing lines in 18 files now uncovered.

12691 of 13851 relevant lines covered (91.63%)

29449.4 hits per line

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

86.44
/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, isLibraryStatement, isLiteralExpression, isMethodStatement, isNamespaceStatement, isTypecastExpression, 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
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,602✔
24
    ) {
25
    }
26

27

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

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

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

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

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

59
        const visitor = createVisitor({
1,602✔
60
            MethodStatement: (node) => {
61
                //add the `super` symbol to class methods
62
                if (isClassStatement(node.parent) && node.parent.hasParentClass()) {
232✔
63
                    const data: ExtraSymbolData = {};
70✔
64
                    const parentClassType = node.parent.parentClassName.getType({ flags: SymbolTypeFlag.typetime, data: data });
70✔
65
                    node.func.body.getSymbolTable().addSymbol('super', { ...data, isInstance: true }, parentClassType, SymbolTypeFlag.runtime);
70✔
66
                }
67
            },
68
            CallfuncExpression: (node) => {
69
                if (node.args.length > 5) {
19✔
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));
133✔
78

79
                this.validateEnumDeclaration(node);
133✔
80

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

89
                //register this class
90
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime });
402✔
91
                node.getSymbolTable().addSymbol('m', { definingNode: node, isInstance: true }, nodeType, SymbolTypeFlag.runtime);
402✔
92
                // eslint-disable-next-line no-bitwise
93
                node.parent.getSymbolTable()?.addSymbol(node.tokens.name?.text, { definingNode: node }, nodeType, SymbolTypeFlag.typetime | SymbolTypeFlag.runtime);
402!
94

95
                if (node.findAncestor(isNamespaceStatement)) {
402✔
96
                    //add the transpiled name for namespaced constructors to the root symbol table
97
                    const transpiledClassConstructor = node.getName(ParseMode.BrightScript);
126✔
98

99
                    this.event.file.parser.ast.symbolTable.addSymbol(
126✔
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 = {};
612✔
110
                //register this variable
111
                const nodeType = node.getType({ flags: SymbolTypeFlag.runtime, data: data });
612✔
112
                node.parent.getSymbolTable()?.addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true, isFromDocComment: data.isFromDocComment }, nodeType, SymbolTypeFlag.runtime);
612!
113
            },
114
            DottedSetStatement: (node) => {
115
                this.validateNoOptionalChainingInVarSet(node, [node.obj]);
85✔
116
            },
117
            IndexedSetStatement: (node) => {
118
                this.validateNoOptionalChainingInVarSet(node, [node.obj]);
15✔
119
            },
120
            ForEachStatement: (node) => {
121
                //register the for loop variable
122
                const loopTargetType = node.target.getType({ flags: SymbolTypeFlag.runtime });
24✔
123
                let loopVarType = isArrayType(loopTargetType) ? loopTargetType.defaultType : DynamicType.instance;
24✔
124
                if (!loopTargetType.isResolvable()) {
24✔
125
                    loopVarType = new ArrayDefaultTypeReferenceType(loopTargetType);
1✔
126
                }
127
                node.parent.getSymbolTable()?.addSymbol(node.tokens.item.text, { definingNode: node, isInstance: true }, loopVarType, SymbolTypeFlag.runtime);
24!
128
            },
129
            NamespaceStatement: (node) => {
130
                this.validateDeclarationLocations(node, 'namespace', () => util.createBoundingRange(node.tokens.namespace, node.nameExpression));
563✔
131
                //Namespace Types are added at the Scope level - This is handled when the SymbolTables get linked
132
            },
133
            FunctionStatement: (node) => {
134
                this.validateDeclarationLocations(node, 'function', () => util.createBoundingRange(node.func.tokens.functionType, node.tokens.name));
1,570✔
135
                const funcType = node.getType({ flags: SymbolTypeFlag.typetime });
1,570✔
136

137
                if (node.tokens.name?.text) {
1,570!
138
                    node.parent.getSymbolTable().addSymbol(
1,570✔
139
                        node.tokens.name.text,
140
                        { definingNode: node },
141
                        funcType,
142
                        SymbolTypeFlag.runtime
143
                    );
144
                }
145

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

158
                    this.event.file.parser.ast.symbolTable.addSymbol(
371✔
159
                        transpiledNamespaceFunctionName,
160
                        { definingNode: node },
161
                        funcType,
162
                        // eslint-disable-next-line no-bitwise
163
                        SymbolTypeFlag.runtime | SymbolTypeFlag.postTranspile
164
                    );
165
                }
166
            },
167
            FunctionExpression: (node) => {
168
                const funcSymbolTable = node.getSymbolTable();
1,829✔
169
                const isInlineFunc = !(isFunctionStatement(node.parent) || isMethodStatement(node.parent));
1,829✔
170
                if (!funcSymbolTable?.hasSymbol('m', SymbolTypeFlag.runtime) || isInlineFunc) {
1,829!
171
                    if (!isTypecastStatement(node.body?.statements?.[0])) {
27!
172
                        funcSymbolTable?.addSymbol('m', { isInstance: true }, new AssociativeArrayType(), SymbolTypeFlag.runtime);
26!
173
                    }
174
                }
175
                this.validateFunctionParameterCount(node);
1,829✔
176
            },
177
            FunctionParameterExpression: (node) => {
178
                const paramName = node.tokens.name?.text;
969!
179
                const data: ExtraSymbolData = {};
969✔
180
                const nodeType = node.getType({ flags: SymbolTypeFlag.typetime, data: data });
969✔
181
                // add param symbol at expression level, so it can be used as default value in other params
182
                const funcExpr = node.findAncestor<FunctionExpression>(isFunctionExpression);
969✔
183
                const funcSymbolTable = funcExpr?.getSymbolTable();
969!
184
                funcSymbolTable?.addSymbol(paramName, { definingNode: node, isInstance: true, isFromDocComment: data.isFromDocComment }, nodeType, SymbolTypeFlag.runtime);
969!
185

186
                //also add param symbol at block level, as it may be redefined, and if so, should show a union
187
                funcExpr.body.getSymbolTable()?.addSymbol(paramName, { definingNode: node, isInstance: true, isFromDocComment: data.isFromDocComment }, nodeType, SymbolTypeFlag.runtime);
969!
188
            },
189
            InterfaceStatement: (node) => {
190
                this.validateDeclarationLocations(node, 'interface', () => util.createBoundingRange(node.tokens.interface, node.tokens.name));
122✔
191

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

215
                    //brighterscript allows a typecast expression here
NEW
216
                } else if (isBrighterscript && isTypecastExpression(node.exceptionVariableExpression) && isVariableExpression(node.exceptionVariableExpression.obj)) {
×
NEW
217
                    node.parent.getSymbolTable().addSymbol(
×
218
                        node.exceptionVariableExpression.obj.getName(),
219
                        { definingNode: node, isInstance: true },
220
                        node.exceptionVariableExpression.getType({ flags: SymbolTypeFlag.runtime }),
221
                        SymbolTypeFlag.runtime
222
                    );
223

224
                    //no other expressions are allowed here
225
                } else {
NEW
226
                    this.event.program.diagnostics.register({
×
227
                        ...DiagnosticMessages.expectedExceptionVarToFollowCatch(),
228
                        location: node.exceptionVariableExpression?.location ?? node.tokens.catch?.location
×
229
                    });
230
                }
231
            },
232
            DimStatement: (node) => {
233
                if (node.tokens.name) {
18!
234
                    node.parent.getSymbolTable().addSymbol(node.tokens.name.text, { definingNode: node, isInstance: true }, node.getType({ flags: SymbolTypeFlag.runtime }), SymbolTypeFlag.runtime);
18✔
235
                }
236
            },
237
            ContinueStatement: (node) => {
238
                this.validateContinueStatement(node);
8✔
239
            },
240
            TypecastStatement: (node) => {
241
                node.parent.getSymbolTable().addSymbol('m', { definingNode: node, doNotMerge: true, isInstance: true }, node.getType({ flags: SymbolTypeFlag.typetime }), SymbolTypeFlag.runtime);
19✔
242
            },
243
            ConditionalCompileConstStatement: (node) => {
244
                const assign = node.assignment;
10✔
245
                const constNameLower = assign.tokens.name?.text.toLowerCase();
10!
246
                const astBsConsts = this.event.file.ast.bsConsts;
10✔
247
                if (isLiteralExpression(assign.value)) {
10!
248
                    astBsConsts.set(constNameLower, assign.value.tokens.value.text.toLowerCase() === 'true');
10✔
NEW
249
                } else if (isVariableExpression(assign.value)) {
×
NEW
250
                    if (this.validateConditionalCompileConst(assign.value.tokens.name)) {
×
NEW
251
                        astBsConsts.set(constNameLower, astBsConsts.get(assign.value.tokens.name.text.toLowerCase()));
×
252
                    }
253
                }
254
            },
255
            ConditionalCompileStatement: (node) => {
256
                this.validateConditionalCompileConst(node.tokens.condition);
22✔
257
            },
258
            ConditionalCompileErrorStatement: (node) => {
259
                this.event.program.diagnostics.register({
1✔
260
                    ...DiagnosticMessages.hashError(node.tokens.message.text),
261
                    location: node.location
262
                });
263
            },
264
            AliasStatement: (node) => {
265
                // eslint-disable-next-line no-bitwise
266
                const targetType = node.value.getType({ flags: SymbolTypeFlag.typetime | SymbolTypeFlag.runtime });
30✔
267

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

271
            },
272
            AstNode: (node) => {
273
                //check for doc comments
274
                if (!node.leadingTrivia || node.leadingTrivia.length === 0) {
22,347✔
275
                    return;
3,947✔
276
                }
277
                const doc = brsDocParser.parseNode(node);
18,400✔
278
                if (doc.tags.length === 0) {
18,400✔
279
                    return;
18,364✔
280
                }
281

282
                let funcExpr = node.findAncestor<FunctionExpression>(isFunctionExpression);
36✔
283
                if (funcExpr) {
36✔
284
                    // handle comment tags inside a function expression
285
                    this.processDocTagsInFunction(doc, node, funcExpr);
8✔
286
                } else {
287
                    //handle comment tags outside of a function expression
288
                    this.processDocTagsAtTopLevel(doc, node);
28✔
289
                }
290
            }
291
        });
292

293
        this.event.file.ast.walk((node, parent) => {
1,602✔
294
            visitor(node, parent);
22,347✔
295
        }, {
296
            walkMode: WalkMode.visitAllRecursive
297
        });
298
    }
299

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

303
        // For example, declaring variable types:
304
        // const symbolTable = funcExpr.body.getSymbolTable();
305

306
        // for (const varTag of doc.getAllTags(BrsDocTagKind.Var)) {
307
        //     const varName = (varTag as BrsDocParamTag).name;
308
        //     const varTypeStr = (varTag as BrsDocParamTag).type;
309
        //     const data: ExtraSymbolData = {};
310
        //     const type = doc.getTypeFromContext(varTypeStr, node, { flags: SymbolTypeFlag.typetime, fullName: varTypeStr, data: data, tableProvider: () => symbolTable });
311
        //     if (type) {
312
        //         symbolTable.addSymbol(varName, { ...data, isFromDocComment: true }, type, SymbolTypeFlag.runtime);
313
        //     }
314
        // }
315
    }
316

317
    private processDocTagsAtTopLevel(doc: BrightScriptDoc, node: AstNode) {
318
        //TODO:
319
        // - handle import statements?
320
        // - handle library statements?
321
        // - handle typecast statements?
322
        // - handle alias statements?
323
        // - handle const statements?
324
        // - allow interface definitions?
325
    }
326

327
    /**
328
     * Validate that a statement is defined in one of these specific locations
329
     *  - the root of the AST
330
     *  - inside a namespace
331
     * This is applicable to things like FunctionStatement, ClassStatement, NamespaceStatement, EnumStatement, InterfaceStatement
332
     */
333
    private validateDeclarationLocations(statement: Statement, keyword: string, rangeFactory?: () => (Range | undefined)) {
334
        //if nested inside a namespace, or defined at the root of the AST (i.e. in a body that has no parent)
335
        const isOkDeclarationLocation = (parentNode) => {
2,930✔
336
            return isNamespaceStatement(parentNode?.parent) || (isBody(parentNode) && !parentNode?.parent);
2,935!
337
        };
338
        if (isOkDeclarationLocation(statement.parent)) {
2,930✔
339
            return;
2,912✔
340
        }
341

342
        // is this in a top levelconditional compile?
343
        if (isConditionalCompileStatement(statement.parent?.parent)) {
18!
344
            if (isOkDeclarationLocation(statement.parent.parent.parent)) {
5✔
345
                return;
4✔
346
            }
347
        }
348

349
        //the statement was defined in the wrong place. Flag it.
350
        this.event.program.diagnostics.register({
14✔
351
            ...DiagnosticMessages.keywordMustBeDeclaredAtNamespaceLevel(keyword),
352
            location: rangeFactory ? util.createLocationFromFileRange(this.event.file, rangeFactory()) : statement.location
14!
353
        });
354
    }
355

356
    private validateFunctionParameterCount(func: FunctionExpression) {
357
        if (func.parameters.length > CallExpression.MaximumArguments) {
1,829✔
358
            //flag every parameter over the limit
359
            for (let i = CallExpression.MaximumArguments; i < func.parameters.length; i++) {
2✔
360
                this.event.program.diagnostics.register({
3✔
361
                    ...DiagnosticMessages.tooManyCallableParameters(func.parameters.length, CallExpression.MaximumArguments),
362
                    location: func.parameters[i]?.tokens.name?.location ?? func.parameters[i]?.location ?? func.location
36!
363
                });
364
            }
365
        }
366
    }
367

368
    private validateEnumDeclaration(stmt: EnumStatement) {
369
        const members = stmt.getMembers();
133✔
370
        //the enum data type is based on the first member value
371
        const enumValueKind = (members.find(x => x.value)?.value as LiteralExpression)?.tokens?.value?.kind ?? TokenKind.IntegerLiteral;
187✔
372
        const memberNames = new Set<string>();
133✔
373
        for (const member of members) {
133✔
374
            const memberNameLower = member.name?.toLowerCase();
258!
375

376
            /**
377
             * flag duplicate member names
378
             */
379
            if (memberNames.has(memberNameLower)) {
258✔
380
                this.event.program.diagnostics.register({
1✔
381
                    ...DiagnosticMessages.duplicateIdentifier(member.name),
382
                    location: member.location
383
                });
384
            } else {
385
                memberNames.add(memberNameLower);
257✔
386
            }
387

388
            //Enforce all member values are the same type
389
            this.validateEnumValueTypes(member, enumValueKind);
258✔
390
        }
391
    }
392

393
    private validateEnumValueTypes(member: EnumMemberStatement, enumValueKind: TokenKind) {
394
        let memberValueKind: TokenKind;
395
        let memberValue: Expression;
396
        if (isUnaryExpression(member.value)) {
258✔
397
            memberValueKind = (member.value?.right as LiteralExpression)?.tokens?.value?.kind;
2!
398
            memberValue = member.value?.right;
2!
399
        } else {
400
            memberValueKind = (member.value as LiteralExpression)?.tokens?.value?.kind;
256✔
401
            memberValue = member.value;
256✔
402
        }
403
        const range = (memberValue ?? member)?.location?.range;
258!
404
        if (
258✔
405
            //is integer enum, has value, that value type is not integer
406
            (enumValueKind === TokenKind.IntegerLiteral && memberValueKind && memberValueKind !== enumValueKind) ||
859✔
407
            //has value, that value is not a literal
408
            (memberValue && !isLiteralExpression(memberValue))
409
        ) {
410
            this.event.program.diagnostics.register({
6✔
411
                ...DiagnosticMessages.enumValueMustBeType(
412
                    enumValueKind.replace(/literal$/i, '').toLowerCase()
413
                ),
414
                location: util.createLocationFromFileRange(this.event.file, range)
415
            });
416
        }
417

418
        //is non integer value
419
        if (enumValueKind !== TokenKind.IntegerLiteral) {
258✔
420
            //default value present
421
            if (memberValueKind) {
93✔
422
                //member value is same as enum
423
                if (memberValueKind !== enumValueKind) {
91✔
424
                    this.event.program.diagnostics.register({
1✔
425
                        ...DiagnosticMessages.enumValueMustBeType(
426
                            enumValueKind.replace(/literal$/i, '').toLowerCase()
427
                        ),
428
                        location: util.createLocationFromFileRange(this.event.file, range)
429
                    });
430
                }
431

432
                //default value missing
433
            } else {
434
                this.event.program.diagnostics.register({
2✔
435
                    ...DiagnosticMessages.enumValueIsRequired(
436
                        enumValueKind.replace(/literal$/i, '').toLowerCase()
437
                    ),
438
                    location: util.createLocationFromFileRange(this.event.file, range)
439
                });
440
            }
441
        }
442
    }
443

444

445
    private validateConditionalCompileConst(ccConst: Token) {
446
        const isBool = ccConst.kind === TokenKind.True || ccConst.kind === TokenKind.False;
22✔
447
        if (!isBool && !this.event.file.ast.bsConsts.has(ccConst.text.toLowerCase())) {
22✔
448
            this.event.program.diagnostics.register({
2✔
449
                ...DiagnosticMessages.referencedConstDoesNotExist(),
450
                location: ccConst.location
451
            });
452
            return false;
2✔
453
        }
454
        return true;
20✔
455
    }
456

457
    /**
458
     * Find statements defined at the top level (or inside a namespace body) that are not allowed to be there
459
     */
460
    private flagTopLevelStatements() {
461
        const statements = [...this.event.file.ast.statements];
1,602✔
462
        while (statements.length > 0) {
1,602✔
463
            const statement = statements.pop();
3,158✔
464
            if (isNamespaceStatement(statement)) {
3,158✔
465
                statements.push(...statement.body.statements);
558✔
466
            } else {
467
                //only allow these statement types
468
                if (
2,600✔
469
                    !isFunctionStatement(statement) &&
5,945✔
470
                    !isClassStatement(statement) &&
471
                    !isEnumStatement(statement) &&
472
                    !isInterfaceStatement(statement) &&
473
                    !isLibraryStatement(statement) &&
474
                    !isImportStatement(statement) &&
475
                    !isConstStatement(statement) &&
476
                    !isTypecastStatement(statement) &&
477
                    !isConditionalCompileConstStatement(statement) &&
478
                    !isConditionalCompileErrorStatement(statement) &&
479
                    !isConditionalCompileStatement(statement) &&
480
                    !isAliasStatement(statement)
481
                ) {
482
                    this.event.program.diagnostics.register({
7✔
483
                        ...DiagnosticMessages.unexpectedStatementOutsideFunction(),
484
                        location: statement.location
485
                    });
486
                }
487
            }
488
        }
489
    }
490

491
    private getTopOfFileStatements() {
492
        let topOfFileIncludeStatements = [] as Array<LibraryStatement | ImportStatement | TypecastStatement | AliasStatement>;
3,202✔
493
        for (let stmt of this.event.file.parser.ast.statements) {
3,202✔
494
            //if we found a non-library statement, this statement is not at the top of the file
495
            if (isLibraryStatement(stmt) || isImportStatement(stmt) || isTypecastStatement(stmt) || isAliasStatement(stmt)) {
3,524✔
496
                topOfFileIncludeStatements.push(stmt);
452✔
497
            } else {
498
                //break out of the loop, we found all of our library statements
499
                break;
3,072✔
500
            }
501
        }
502
        return topOfFileIncludeStatements;
3,202✔
503
    }
504

505
    private validateTopOfFileStatements() {
506
        let topOfFileStatements = this.getTopOfFileStatements();
1,601✔
507

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

540
    private validateTypecastStatements() {
541
        let topOfFileTypecastStatements = this.getTopOfFileStatements().filter(stmt => isTypecastStatement(stmt));
1,601✔
542

543
        //check only one `typecast` statement at "top" of file (eg. before non import/library statements)
544
        for (let i = 1; i < topOfFileTypecastStatements.length; i++) {
1,601✔
545
            const typecastStmt = topOfFileTypecastStatements[i];
1✔
546
            this.event.program.diagnostics.register({
1✔
547
                ...DiagnosticMessages.typecastStatementMustBeDeclaredAtStart(),
548
                location: typecastStmt.location
549
            });
550
        }
551

552
        // eslint-disable-next-line @typescript-eslint/dot-notation
553
        for (let result of this.event.file['_cachedLookups'].typecastStatements) {
1,601✔
554
            let isBadTypecastObj = false;
19✔
555
            if (!isVariableExpression(result.typecastExpression.obj)) {
19✔
556
                isBadTypecastObj = true;
1✔
557
            } else if (result.typecastExpression.obj.tokens.name.text.toLowerCase() !== 'm') {
18✔
558
                isBadTypecastObj = true;
1✔
559
            }
560
            if (isBadTypecastObj) {
19✔
561
                this.event.program.diagnostics.register({
2✔
562
                    ...DiagnosticMessages.invalidTypecastStatementApplication(util.getAllDottedGetPartsAsString(result.typecastExpression.obj)),
563
                    location: result.typecastExpression.obj.location
564
                });
565
            }
566

567
            if (topOfFileTypecastStatements.includes(result)) {
19✔
568
                // already validated
569
                continue;
7✔
570
            }
571

572
            const block = result.findAncestor<Body | Block>(node => (isBody(node) || isBlock(node)));
12✔
573
            const isFirst = block?.statements[0] === result;
12!
574
            const isAllowedBlock = (isBody(block) || isFunctionExpression(block.parent) || isNamespaceStatement(block.parent));
12!
575

576
            if (!isFirst || !isAllowedBlock) {
12✔
577
                this.event.program.diagnostics.register({
3✔
578
                    ...DiagnosticMessages.typecastStatementMustBeDeclaredAtStart(),
579
                    location: result.location
580
                });
581
            }
582
        }
583
    }
584

585
    private validateContinueStatement(statement: ContinueStatement) {
586
        const validateLoopTypeMatch = (expectedLoopType: TokenKind) => {
8✔
587
            //coerce ForEach to For
588
            expectedLoopType = expectedLoopType === TokenKind.ForEach ? TokenKind.For : expectedLoopType;
7✔
589
            const actualLoopType = statement.tokens.loopType;
7✔
590
            if (actualLoopType && expectedLoopType?.toLowerCase() !== actualLoopType.text?.toLowerCase()) {
7!
591
                this.event.program.diagnostics.register({
3✔
592
                    location: statement.tokens.loopType.location,
593
                    ...DiagnosticMessages.expectedToken(expectedLoopType)
594
                });
595
            }
596
        };
597

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

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

646
                this.event.program.diagnostics.register({
8✔
647
                    ...DiagnosticMessages.noOptionalChainingInLeftHandSideOfAssignment(),
648
                    location: util.createLocationFromFileRange(this.event.file, range)
649
                });
650
            }
651

652
            if (node === parent) {
200✔
653
                break;
100✔
654
            } else {
655
                nodes.push(node.parent);
100✔
656
            }
657
        }
658
    }
659
}
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

© 2025 Coveralls, Inc