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

rokucommunity / brighterscript / #14416

15 May 2025 01:00PM UTC coverage: 86.983% (-0.006%) from 86.989%
#14416

push

web-flow
Merge 6d205e1f4 into a194c3925

13887 of 16873 branches covered (82.3%)

Branch coverage included in aggregate %.

158 of 175 new or added lines in 11 files covered. (90.29%)

130 existing lines in 11 files now uncovered.

14733 of 16030 relevant lines covered (91.91%)

21929.67 hits per line

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

87.68
/src/parser/Statement.ts
1
/* eslint-disable no-bitwise */
2
import type { Token, Identifier } from '../lexer/Token';
3
import { TokenKind } from '../lexer/TokenKind';
1✔
4
import type { DottedGetExpression, FunctionParameterExpression, LiteralExpression, TypecastExpression, TypeExpression } from './Expression';
5
import { FunctionExpression } from './Expression';
1✔
6
import { CallExpression, VariableExpression } from './Expression';
1✔
7
import { util } from '../util';
1✔
8
import type { Location } from 'vscode-languageserver';
9
import type { BrsTranspileState } from './BrsTranspileState';
10
import { ParseMode } from './Parser';
1✔
11
import type { WalkVisitor, WalkOptions } from '../astUtils/visitors';
12
import { InternalWalkMode, walk, createVisitor, WalkMode, walkArray } from '../astUtils/visitors';
1✔
13
import { isCallExpression, isCatchStatement, isConditionalCompileStatement, isEnumMemberStatement, isExpressionStatement, isFieldStatement, isForEachStatement, isForStatement, isFunctionExpression, isFunctionStatement, isIfStatement, isInterfaceFieldStatement, isInterfaceMethodStatement, isInvalidType, isLiteralExpression, isMethodStatement, isNamespaceStatement, isPrintSeparatorExpression, isTryCatchStatement, isTypedefProvider, isUnaryExpression, isUninitializedType, isVoidType, isWhileStatement } from '../astUtils/reflection';
1✔
14
import type { GetTypeOptions } from '../interfaces';
15
import { TypeChainEntry, type TranspileResult, type TypedefProvider } from '../interfaces';
1✔
16
import { createIdentifier, createInvalidLiteral, createMethodStatement, createToken } from '../astUtils/creators';
1✔
17
import { DynamicType } from '../types/DynamicType';
1✔
18
import type { BscType } from '../types/BscType';
19
import { SymbolTable } from '../SymbolTable';
1✔
20
import type { Expression } from './AstNode';
21
import { AstNodeKind, Statement } from './AstNode';
1✔
22
import { ClassType } from '../types/ClassType';
1✔
23
import { EnumMemberType, EnumType } from '../types/EnumType';
1✔
24
import { NamespaceType } from '../types/NamespaceType';
1✔
25
import { InterfaceType } from '../types/InterfaceType';
1✔
26
import { VoidType } from '../types/VoidType';
1✔
27
import { TypedFunctionType } from '../types/TypedFunctionType';
1✔
28
import { ArrayType } from '../types/ArrayType';
1✔
29
import { SymbolTypeFlag } from '../SymbolTypeFlag';
1✔
30
import brsDocParser from './BrightScriptDocParser';
1✔
31
export class EmptyStatement extends Statement {
1✔
32
    constructor(options?: { range?: Location }
33
    ) {
34
        super();
6✔
35
        this.location = undefined;
6✔
36
    }
37
    /**
38
     * Create a negative range to indicate this is an interpolated location
39
     */
40
    public readonly location?: Location;
41

42
    public readonly kind = AstNodeKind.EmptyStatement;
6✔
43

44
    transpile(state: BrsTranspileState) {
45
        return [];
2✔
46
    }
47
    walk(visitor: WalkVisitor, options: WalkOptions) {
48
        //nothing to walk
49
    }
50

51
    public clone() {
52
        return this.finalizeClone(
1✔
53
            new EmptyStatement({
54
                range: util.cloneLocation(this.location)
55
            })
56
        );
57
    }
58
}
59

60
/**
61
 * This is a top-level statement. Consider this the root of the AST
62
 */
63
export class Body extends Statement implements TypedefProvider {
1✔
64
    constructor(options?: {
65
        statements?: Statement[];
66
    }) {
67
        super();
8,648✔
68
        this.statements = options?.statements ?? [];
8,648!
69
    }
70

71
    public readonly statements: Statement[] = [];
8,648✔
72
    public readonly kind = AstNodeKind.Body;
8,648✔
73

74
    public readonly symbolTable = new SymbolTable('Body', () => this.parent?.getSymbolTable());
32,577✔
75

76
    public get location() {
77
        if (!this._location) {
990✔
78
            //this needs to be a getter because the body has its statements pushed to it after being constructed
79
            this._location = util.createBoundingLocation(
804✔
80
                ...(this.statements ?? [])
2,412✔
81
            );
82
        }
83
        return this._location;
990✔
84
    }
85
    public set location(value) {
86
        this._location = value;
×
87
    }
88
    private _location: Location;
89

90
    transpile(state: BrsTranspileState) {
91
        let result: TranspileResult = state.transpileAnnotations(this);
771✔
92
        for (let i = 0; i < this.statements.length; i++) {
771✔
93
            let statement = this.statements[i];
1,681✔
94
            let previousStatement = this.statements[i - 1];
1,681✔
95
            let nextStatement = this.statements[i + 1];
1,681✔
96

97
            if (!previousStatement) {
1,681✔
98
                //this is the first statement. do nothing related to spacing and newlines
99

100
                //if comment is on same line as prior sibling
101
            } else if (util.hasLeadingComments(statement) && previousStatement && util.getLeadingComments(statement)?.[0]?.location?.range?.start.line === previousStatement.location?.range?.end.line) {
915!
102
                result.push(
8✔
103
                    ' '
104
                );
105
                //add double newline if this is a comment, and next is a function
106
            } else if (util.hasLeadingComments(statement) && nextStatement && isFunctionStatement(nextStatement)) {
907✔
107
                result.push(state.newline, state.newline);
367✔
108

109
                //add double newline if is function not preceeded by a comment
110
            } else if (isFunctionStatement(statement) && previousStatement && !util.hasLeadingComments(statement)) {
540✔
111
                result.push(state.newline, state.newline);
91✔
112
            } else {
113
                //separate statements by a single newline
114
                result.push(state.newline);
449✔
115
            }
116

117
            result.push(...statement.transpile(state));
1,681✔
118
        }
119
        return result;
771✔
120
    }
121

122
    getTypedef(state: BrsTranspileState): TranspileResult {
123
        let result = [] as TranspileResult;
41✔
124
        for (const statement of this.statements) {
41✔
125
            //if the current statement supports generating typedef, call it
126
            if (isTypedefProvider(statement)) {
75!
127
                result.push(
75✔
128
                    state.indent(),
129
                    ...statement.getTypedef(state),
130
                    state.newline
131
                );
132
            }
133
        }
134
        return result;
41✔
135
    }
136

137
    walk(visitor: WalkVisitor, options: WalkOptions) {
138
        if (options.walkMode & InternalWalkMode.walkStatements) {
17,337!
139
            walkArray(this.statements, visitor, options, this);
17,337✔
140
        }
141
    }
142

143
    public clone() {
144
        return this.finalizeClone(
136✔
145
            new Body({
146
                statements: this.statements?.map(s => s?.clone())
143✔
147
            }),
148
            ['statements']
149
        );
150
    }
151
}
152

153
export class AssignmentStatement extends Statement {
1✔
154
    constructor(options: {
155
        name: Identifier;
156
        equals?: Token;
157
        value: Expression;
158
        as?: Token;
159
        typeExpression?: TypeExpression;
160
    }) {
161
        super();
1,688✔
162
        this.value = options.value;
1,688✔
163
        this.tokens = {
1,688✔
164
            equals: options.equals,
165
            name: options.name,
166
            as: options.as
167
        };
168
        this.typeExpression = options.typeExpression;
1,688✔
169
        this.location = util.createBoundingLocation(util.createBoundingLocationFromTokens(this.tokens), this.value);
1,688✔
170
    }
171

172
    public readonly tokens: {
173
        readonly equals?: Token;
174
        readonly name: Identifier;
175
        readonly as?: Token;
176
    };
177

178
    public readonly value: Expression;
179

180
    public readonly typeExpression?: TypeExpression;
181

182
    public readonly kind = AstNodeKind.AssignmentStatement;
1,688✔
183

184
    public readonly location: Location | undefined;
185

186
    transpile(state: BrsTranspileState) {
187
        return [
628✔
188
            state.transpileToken(this.tokens.name),
189
            ' ',
190
            state.transpileToken(this.tokens.equals ?? createToken(TokenKind.Equal), '='),
1,884!
191
            ' ',
192
            ...this.value.transpile(state)
193
        ];
194
    }
195

196
    walk(visitor: WalkVisitor, options: WalkOptions) {
197
        if (options.walkMode & InternalWalkMode.walkExpressions) {
7,398✔
198
            walk(this, 'typeExpression', visitor, options);
7,257✔
199
            walk(this, 'value', visitor, options);
7,257✔
200
        }
201
    }
202

203
    getType(options: GetTypeOptions) {
204
        const variableTypeFromCode = this.typeExpression?.getType({ ...options, typeChain: undefined });
1,566✔
205
        const docs = brsDocParser.parseNode(this);
1,566✔
206
        const variableTypeFromDocs = docs?.getTypeTagBscType(options);
1,566!
207
        const variableType = util.chooseTypeFromCodeOrDocComment(variableTypeFromCode, variableTypeFromDocs, options) ?? this.value.getType({ ...options, typeChain: undefined });
1,566✔
208

209
        // Note: compound assignments (eg. +=) are internally dealt with via the RHS being a BinaryExpression
210
        // so this.value will be a BinaryExpression, and BinaryExpressions can figure out their own types
211
        options.typeChain?.push(new TypeChainEntry({ name: this.tokens.name.text, type: variableType, data: options.data, location: this.tokens.name?.location, astNode: this }));
1,566!
212
        return variableType;
1,566✔
213
    }
214

215
    get leadingTrivia(): Token[] {
216
        return this.tokens.name.leadingTrivia;
8,951✔
217
    }
218

219
    public clone() {
220
        return this.finalizeClone(
16✔
221
            new AssignmentStatement({
222
                name: util.cloneToken(this.tokens.name),
223
                value: this.value?.clone(),
48✔
224
                as: util.cloneToken(this.tokens.as),
225
                equals: util.cloneToken(this.tokens.equals),
226
                typeExpression: this.typeExpression?.clone()
48!
227
            }),
228
            ['value', 'typeExpression']
229
        );
230
    }
231
}
232

233
export class AugmentedAssignmentStatement extends Statement {
1✔
234
    constructor(options: {
235
        item: Expression;
236
        operator: Token;
237
        value: Expression;
238
    }) {
239
        super();
105✔
240
        this.value = options.value;
105✔
241
        this.tokens = {
105✔
242
            operator: options.operator
243
        };
244
        this.item = options.item;
105✔
245
        this.value = options.value;
105✔
246
        this.location = util.createBoundingLocation(this.item, util.createBoundingLocationFromTokens(this.tokens), this.value);
105✔
247
    }
248

249
    public readonly tokens: {
250
        readonly operator?: Token;
251
    };
252

253
    public readonly item: Expression;
254

255
    public readonly value: Expression;
256

257
    public readonly kind = AstNodeKind.AugmentedAssignmentStatement;
105✔
258

259
    public readonly location: Location | undefined;
260

261
    transpile(state: BrsTranspileState) {
262
        return [
35✔
263
            this.item.transpile(state),
264
            ' ',
265
            state.transpileToken(this.tokens.operator),
266
            ' ',
267
            this.value.transpile(state)
268
        ];
269
    }
270

271
    walk(visitor: WalkVisitor, options: WalkOptions) {
272
        if (options.walkMode & InternalWalkMode.walkExpressions) {
476✔
273
            walk(this, 'item', visitor, options);
467✔
274
            walk(this, 'value', visitor, options);
467✔
275
        }
276
    }
277

278
    getType(options: GetTypeOptions) {
279
        const variableType = util.binaryOperatorResultType(this.item.getType(options), this.tokens.operator, this.value.getType(options));
×
280

281
        //const variableType = this.typeExpression?.getType({ ...options, typeChain: undefined }) ?? this.value.getType({ ...options, typeChain: undefined });
282

283
        // Note: compound assignments (eg. +=) are internally dealt with via the RHS being a BinaryExpression
284
        // so this.value will be a BinaryExpression, and BinaryExpressions can figure out their own types
285
        // options.typeChain?.push(new TypeChainEntry({ name: this.tokens.name.text, type: variableType, data: options.data, range: this.tokens.name.range, astNode: this }));
286
        return variableType;
×
287
    }
288

289
    get leadingTrivia(): Token[] {
290
        return this.item.leadingTrivia;
464✔
291
    }
292

293
    public clone() {
294
        return this.finalizeClone(
2✔
295
            new AugmentedAssignmentStatement({
296
                item: this.item?.clone(),
6!
297
                operator: util.cloneToken(this.tokens.operator),
298
                value: this.value?.clone()
6!
299
            }),
300
            ['item', 'value']
301
        );
302
    }
303
}
304

305
export class Block extends Statement {
1✔
306
    constructor(options: {
307
        statements: Statement[];
308
    }) {
309
        super();
7,491✔
310
        this.statements = options.statements;
7,491✔
311
        this.symbolTable = new SymbolTable('Block', () => this.parent.getSymbolTable());
44,792✔
312
    }
313

314
    public readonly statements: Statement[];
315

316
    public readonly kind = AstNodeKind.Block;
7,491✔
317

318
    private buildLocation(): Location {
319
        if (this.statements?.length > 0) {
3,816✔
320
            return util.createBoundingLocation(...this.statements ?? []);
3,563!
321
        }
322
        let lastBitBefore: Location;
323
        let firstBitAfter: Location;
324

325
        if (isFunctionExpression(this.parent)) {
253✔
326
            lastBitBefore = util.createBoundingLocation(
128✔
327
                this.parent.tokens.functionType,
328
                this.parent.tokens.leftParen,
329
                ...(this.parent.parameters ?? []),
384!
330
                this.parent.tokens.rightParen,
331
                this.parent.tokens.as,
332
                this.parent.returnTypeExpression
333
            );
334
            firstBitAfter = this.parent.tokens.endFunctionType?.location;
128!
335
        } else if (isIfStatement(this.parent)) {
125✔
336
            if (this.parent.thenBranch === this) {
4!
337
                lastBitBefore = util.createBoundingLocation(
4✔
338
                    this.parent.tokens.then,
339
                    this.parent.condition
340
                );
341
                firstBitAfter = util.createBoundingLocation(
4✔
342
                    this.parent.tokens.else,
343
                    this.parent.elseBranch,
344
                    this.parent.tokens.endIf
345
                );
UNCOV
346
            } else if (this.parent.elseBranch === this) {
×
347
                lastBitBefore = this.parent.tokens.else?.location;
×
348
                firstBitAfter = this.parent.tokens.endIf?.location;
×
349
            }
350
        } else if (isConditionalCompileStatement(this.parent)) {
121!
UNCOV
351
            if (this.parent.thenBranch === this) {
×
352
                lastBitBefore = util.createBoundingLocation(
×
353
                    this.parent.tokens.condition,
354
                    this.parent.tokens.not,
355
                    this.parent.tokens.hashIf
356
                );
UNCOV
357
                firstBitAfter = util.createBoundingLocation(
×
358
                    this.parent.tokens.hashElse,
359
                    this.parent.elseBranch,
360
                    this.parent.tokens.hashEndIf
361
                );
UNCOV
362
            } else if (this.parent.elseBranch === this) {
×
363
                lastBitBefore = this.parent.tokens.hashElse?.location;
×
364
                firstBitAfter = this.parent.tokens.hashEndIf?.location;
×
365
            }
366
        } else if (isForStatement(this.parent)) {
121✔
367
            lastBitBefore = util.createBoundingLocation(
2✔
368
                this.parent.increment,
369
                this.parent.tokens.step,
370
                this.parent.finalValue,
371
                this.parent.tokens.to,
372
                this.parent.counterDeclaration,
373
                this.parent.tokens.for
374
            );
375
            firstBitAfter = this.parent.tokens.endFor?.location;
2!
376
        } else if (isForEachStatement(this.parent)) {
119✔
377
            lastBitBefore = util.createBoundingLocation(
2✔
378
                this.parent.target,
379
                this.parent.tokens.in,
380
                this.parent.tokens.item,
381
                this.parent.tokens.forEach
382
            );
383
            firstBitAfter = this.parent.tokens.endFor?.location;
2!
384
        } else if (isWhileStatement(this.parent)) {
117✔
385
            lastBitBefore = util.createBoundingLocation(
2✔
386
                this.parent.condition,
387
                this.parent.tokens.while
388
            );
389
            firstBitAfter = this.parent.tokens.endWhile?.location;
2!
390
        } else if (isTryCatchStatement(this.parent)) {
115✔
391
            lastBitBefore = util.createBoundingLocation(
1✔
392
                this.parent.tokens.try
393
            );
394
            firstBitAfter = util.createBoundingLocation(
1✔
395
                this.parent.tokens.endTry,
396
                this.parent.catchStatement
397
            );
398
        } else if (isCatchStatement(this.parent) && isTryCatchStatement(this.parent?.parent)) {
114!
399
            lastBitBefore = util.createBoundingLocation(
1✔
400
                this.parent.tokens.catch,
401
                this.parent.exceptionVariableExpression
402
            );
403
            firstBitAfter = this.parent.parent.tokens.endTry?.location;
1!
404
        }
405
        if (lastBitBefore?.range && firstBitAfter?.range) {
253✔
406
            return util.createLocation(
115✔
407
                lastBitBefore.range.end.line,
408
                lastBitBefore.range.end.character,
409
                firstBitAfter.range.start.line,
410
                firstBitAfter.range.start.character,
411
                lastBitBefore.uri ?? firstBitAfter.uri
345✔
412
            );
413
        }
414
    }
415

416
    public get location() {
417
        if (!this._location) {
5,107✔
418
            //this needs to be a getter because the body has its statements pushed to it after being constructed
419
            this._location = this.buildLocation();
3,816✔
420
        }
421
        return this._location;
5,107✔
422
    }
423
    public set location(value) {
424
        this._location = value;
21✔
425
    }
426
    private _location: Location;
427

428
    transpile(state: BrsTranspileState) {
429
        state.blockDepth++;
4,632✔
430
        let results = [] as TranspileResult;
4,632✔
431
        for (let i = 0; i < this.statements.length; i++) {
4,632✔
432
            let previousStatement = this.statements[i - 1];
5,596✔
433
            let statement = this.statements[i];
5,596✔
434
            //is not a comment
435
            //if comment is on same line as parent
436
            if (util.isLeadingCommentOnSameLine(state.lineage[0]?.location, statement) ||
5,596!
437
                util.isLeadingCommentOnSameLine(previousStatement?.location, statement)
16,740✔
438
            ) {
439
                results.push(' ');
50✔
440

441
                //is not a comment
442
            } else {
443
                //add a newline and indent
444
                results.push(
5,546✔
445
                    state.newline,
446
                    state.indent()
447
                );
448
            }
449

450
            //push block onto parent list
451
            state.lineage.unshift(this);
5,596✔
452
            results.push(
5,596✔
453
                ...statement.transpile(state)
454
            );
455
            state.lineage.shift();
5,596✔
456
        }
457
        state.blockDepth--;
4,632✔
458
        return results;
4,632✔
459
    }
460

461
    public get leadingTrivia(): Token[] {
462
        return this.statements[0]?.leadingTrivia ?? [];
11,853✔
463
    }
464

465
    walk(visitor: WalkVisitor, options: WalkOptions) {
466
        if (options.walkMode & InternalWalkMode.walkStatements) {
33,717✔
467
            walkArray(this.statements, visitor, options, this);
33,711✔
468
        }
469
    }
470

471
    public clone() {
472
        return this.finalizeClone(
127✔
473
            new Block({
474
                statements: this.statements?.map(s => s?.clone())
117✔
475
            }),
476
            ['statements']
477
        );
478
    }
479
}
480

481
export class ExpressionStatement extends Statement {
1✔
482
    constructor(options: {
483
        expression: Expression;
484
    }) {
485
        super();
958✔
486
        this.expression = options.expression;
958✔
487
        this.location = this.expression?.location;
958✔
488
    }
489
    public readonly expression: Expression;
490
    public readonly kind = AstNodeKind.ExpressionStatement;
958✔
491

492
    public readonly location: Location | undefined;
493

494
    transpile(state: BrsTranspileState) {
495
        return [
68✔
496
            state.transpileAnnotations(this),
497
            this.expression.transpile(state)
498
        ];
499
    }
500

501
    walk(visitor: WalkVisitor, options: WalkOptions) {
502
        if (options.walkMode & InternalWalkMode.walkExpressions) {
3,776✔
503
            walk(this, 'expression', visitor, options);
3,747✔
504
        }
505
    }
506

507
    get leadingTrivia(): Token[] {
508
        return this.expression.leadingTrivia;
3,956✔
509
    }
510

511
    public clone() {
512
        return this.finalizeClone(
14✔
513
            new ExpressionStatement({
514
                expression: this.expression?.clone()
42✔
515
            }),
516
            ['expression']
517
        );
518
    }
519
}
520

521
export class ExitStatement extends Statement {
1✔
522
    constructor(options?: {
523
        exit?: Token;
524
        loopType: Token;
525
    }) {
526
        super();
26✔
527
        this.tokens = {
26✔
528
            exit: options?.exit,
78!
529
            loopType: options.loopType
530
        };
531
        this.location = util.createBoundingLocation(
26✔
532
            this.tokens.exit,
533
            this.tokens.loopType
534
        );
535
    }
536

537
    public readonly tokens: {
538
        readonly exit: Token;
539
        readonly loopType?: Token;
540
    };
541

542
    public readonly kind = AstNodeKind.ExitStatement;
26✔
543

544
    public readonly location?: Location;
545

546
    transpile(state: BrsTranspileState) {
547
        return [
11✔
548
            state.transpileToken(this.tokens.exit, 'exit'),
549
            this.tokens.loopType?.leadingWhitespace ?? ' ',
66!
550
            state.transpileToken(this.tokens.loopType)
551
        ];
552
    }
553

554
    walk(visitor: WalkVisitor, options: WalkOptions) {
555
        //nothing to walk
556
    }
557

558
    get leadingTrivia(): Token[] {
559
        return this.tokens.exit?.leadingTrivia;
124!
560
    }
561

562
    public clone() {
563
        return this.finalizeClone(
2✔
564
            new ExitStatement({
565
                loopType: util.cloneToken(this.tokens.loopType),
566
                exit: util.cloneToken(this.tokens.exit)
567
            })
568
        );
569
    }
570
}
571

572
export class FunctionStatement extends Statement implements TypedefProvider {
1✔
573
    constructor(options: {
574
        name: Identifier;
575
        func: FunctionExpression;
576
    }) {
577
        super();
4,460✔
578
        this.tokens = {
4,460✔
579
            name: options.name
580
        };
581
        this.func = options.func;
4,460✔
582
        if (this.func) {
4,460✔
583
            this.func.symbolTable.name += `: '${this.tokens.name?.text}'`;
4,458!
584
        }
585

586
        this.location = this.func?.location;
4,460✔
587
    }
588

589
    public readonly tokens: {
590
        readonly name: Identifier;
591
    };
592
    public readonly func: FunctionExpression;
593

594
    public readonly kind = AstNodeKind.FunctionStatement as AstNodeKind;
4,460✔
595

596
    public readonly location: Location | undefined;
597

598
    /**
599
     * Get the name of this expression based on the parse mode
600
     */
601
    public getName(parseMode: ParseMode) {
602
        const namespace = this.findAncestor<NamespaceStatement>(isNamespaceStatement);
14,240✔
603
        if (namespace) {
14,240✔
604
            let delimiter = parseMode === ParseMode.BrighterScript ? '.' : '_';
3,215✔
605
            let namespaceName = namespace.getName(parseMode);
3,215✔
606
            return namespaceName + delimiter + this.tokens.name?.text;
3,215!
607
        } else {
608
            return this.tokens.name.text;
11,025✔
609
        }
610
    }
611

612
    public get leadingTrivia(): Token[] {
613
        return this.func.leadingTrivia;
18,781✔
614
    }
615

616
    transpile(state: BrsTranspileState): TranspileResult {
617
        //create a fake token using the full transpiled name
618
        let nameToken = {
1,462✔
619
            ...this.tokens.name,
620
            text: this.getName(ParseMode.BrightScript)
621
        };
622

623
        return [
1,462✔
624
            ...state.transpileAnnotations(this),
625
            ...this.func.transpile(state, nameToken)
626
        ];
627
    }
628

629
    getTypedef(state: BrsTranspileState) {
630
        let result: TranspileResult = [];
39✔
631
        for (let comment of util.getLeadingComments(this) ?? []) {
39!
632
            result.push(
154✔
633
                comment.text,
634
                state.newline,
635
                state.indent()
636
            );
637
        }
638
        for (let annotation of this.annotations ?? []) {
39✔
639
            result.push(
2✔
640
                ...annotation.getTypedef(state),
641
                state.newline,
642
                state.indent()
643
            );
644
        }
645

646
        result.push(
39✔
647
            ...this.func.getTypedef(state)
648
        );
649
        return result;
39✔
650
    }
651

652
    walk(visitor: WalkVisitor, options: WalkOptions) {
653
        if (options.walkMode & InternalWalkMode.walkExpressions) {
19,795✔
654
            walk(this, 'func', visitor, options);
17,722✔
655
        }
656
    }
657

658
    getType(options: GetTypeOptions) {
659
        const funcExprType = this.func.getType(options);
3,911✔
660
        funcExprType.setName(this.getName(ParseMode.BrighterScript));
3,911✔
661
        return funcExprType;
3,911✔
662
    }
663

664
    public clone() {
665
        return this.finalizeClone(
107✔
666
            new FunctionStatement({
667
                func: this.func?.clone(),
321✔
668
                name: util.cloneToken(this.tokens.name)
669
            }),
670
            ['func']
671
        );
672
    }
673
}
674

675
export class IfStatement extends Statement {
1✔
676
    constructor(options: {
677
        if?: Token;
678
        then?: Token;
679
        else?: Token;
680
        endIf?: Token;
681

682
        condition: Expression;
683
        thenBranch: Block;
684
        elseBranch?: IfStatement | Block;
685
    }) {
686
        super();
2,268✔
687
        this.condition = options.condition;
2,268✔
688
        this.thenBranch = options.thenBranch;
2,268✔
689
        this.elseBranch = options.elseBranch;
2,268✔
690

691
        this.tokens = {
2,268✔
692
            if: options.if,
693
            then: options.then,
694
            else: options.else,
695
            endIf: options.endIf
696
        };
697

698
        this.location = util.createBoundingLocation(
2,268✔
699
            util.createBoundingLocationFromTokens(this.tokens),
700
            this.condition,
701
            this.thenBranch,
702
            this.elseBranch
703
        );
704
    }
705

706
    readonly tokens: {
707
        readonly if?: Token;
708
        readonly then?: Token;
709
        readonly else?: Token;
710
        readonly endIf?: Token;
711
    };
712
    public readonly condition: Expression;
713
    public readonly thenBranch: Block;
714
    public readonly elseBranch?: IfStatement | Block;
715

716
    public readonly kind = AstNodeKind.IfStatement;
2,268✔
717

718
    public readonly location: Location | undefined;
719

720
    get isInline() {
721
        const allLeadingTrivia = [
12✔
722
            ...this.thenBranch.leadingTrivia,
723
            ...this.thenBranch.statements.map(s => s.leadingTrivia).flat(),
16✔
724
            ...(this.tokens.else?.leadingTrivia ?? []),
72✔
725
            ...(this.tokens.endIf?.leadingTrivia ?? [])
72✔
726
        ];
727

728
        const hasNewline = allLeadingTrivia.find(t => t.kind === TokenKind.Newline);
29✔
729
        return !hasNewline;
12✔
730
    }
731

732
    transpile(state: BrsTranspileState) {
733
        let results = [] as TranspileResult;
2,277✔
734
        //if   (already indented by block)
735
        results.push(state.transpileToken(this.tokens.if ?? createToken(TokenKind.If)));
2,277!
736
        results.push(' ');
2,277✔
737
        //conditions
738
        results.push(...this.condition.transpile(state));
2,277✔
739
        //then
740
        if (this.tokens.then) {
2,277✔
741
            results.push(' ');
1,899✔
742
            results.push(
1,899✔
743
                state.transpileToken(this.tokens.then, 'then')
744
            );
745
        }
746
        state.lineage.unshift(this);
2,277✔
747

748
        //if statement body
749
        let thenNodes = this.thenBranch.transpile(state);
2,277✔
750
        state.lineage.shift();
2,277✔
751
        if (thenNodes.length > 0) {
2,277✔
752
            results.push(thenNodes);
2,266✔
753
        }
754
        //else branch
755
        if (this.elseBranch) {
2,277✔
756
            //else
757
            results.push(...state.transpileEndBlockToken(this.thenBranch, this.tokens.else, 'else'));
1,891✔
758

759
            if (isIfStatement(this.elseBranch)) {
1,891✔
760
                //chained elseif
761
                state.lineage.unshift(this.elseBranch);
1,120✔
762
                let body = this.elseBranch.transpile(state);
1,120✔
763
                state.lineage.shift();
1,120✔
764

765
                if (body.length > 0) {
1,120!
766
                    //zero or more spaces between the `else` and the `if`
767
                    results.push(this.elseBranch.tokens.if.leadingWhitespace!);
1,120✔
768
                    results.push(...body);
1,120✔
769

770
                    // stop here because chained if will transpile the rest
771
                    return results;
1,120✔
772
                } else {
UNCOV
773
                    results.push('\n');
×
774
                }
775

776
            } else {
777
                //else body
778
                state.lineage.unshift(this.tokens.else!);
771✔
779
                let body = this.elseBranch.transpile(state);
771✔
780
                state.lineage.shift();
771✔
781

782
                if (body.length > 0) {
771✔
783
                    results.push(...body);
769✔
784
                }
785
            }
786
        }
787

788
        //end if
789
        results.push(...state.transpileEndBlockToken(this.elseBranch ?? this.thenBranch, this.tokens.endIf, 'end if'));
1,157✔
790

791
        return results;
1,157✔
792
    }
793

794
    walk(visitor: WalkVisitor, options: WalkOptions) {
795
        if (options.walkMode & InternalWalkMode.walkExpressions) {
9,528✔
796
            walk(this, 'condition', visitor, options);
9,511✔
797
        }
798
        if (options.walkMode & InternalWalkMode.walkStatements) {
9,528✔
799
            walk(this, 'thenBranch', visitor, options);
9,526✔
800
        }
801
        if (this.elseBranch && options.walkMode & InternalWalkMode.walkStatements) {
9,528✔
802
            walk(this, 'elseBranch', visitor, options);
7,504✔
803
        }
804
    }
805

806
    get leadingTrivia(): Token[] {
807
        return this.tokens.if?.leadingTrivia ?? [];
3,169!
808
    }
809

810
    get endTrivia(): Token[] {
811
        return this.tokens.endIf?.leadingTrivia ?? [];
1!
812
    }
813

814
    public clone() {
815
        return this.finalizeClone(
5✔
816
            new IfStatement({
817
                if: util.cloneToken(this.tokens.if),
818
                else: util.cloneToken(this.tokens.else),
819
                endIf: util.cloneToken(this.tokens.endIf),
820
                then: util.cloneToken(this.tokens.then),
821
                condition: this.condition?.clone(),
15✔
822
                thenBranch: this.thenBranch?.clone(),
15✔
823
                elseBranch: this.elseBranch?.clone()
15✔
824
            }),
825
            ['condition', 'thenBranch', 'elseBranch']
826
        );
827
    }
828
}
829

830
export class IncrementStatement extends Statement {
1✔
831
    constructor(options: {
832
        value: Expression;
833
        operator: Token;
834
    }) {
835
        super();
29✔
836
        this.value = options.value;
29✔
837
        this.tokens = {
29✔
838
            operator: options.operator
839
        };
840
        this.location = util.createBoundingLocation(
29✔
841
            this.value,
842
            this.tokens.operator
843
        );
844
    }
845

846
    public readonly value: Expression;
847
    public readonly tokens: {
848
        readonly operator: Token;
849
    };
850

851
    public readonly kind = AstNodeKind.IncrementStatement;
29✔
852

853
    public readonly location: Location | undefined;
854

855
    transpile(state: BrsTranspileState) {
856
        return [
6✔
857
            ...this.value.transpile(state),
858
            state.transpileToken(this.tokens.operator)
859
        ];
860
    }
861

862
    walk(visitor: WalkVisitor, options: WalkOptions) {
863
        if (options.walkMode & InternalWalkMode.walkExpressions) {
94✔
864
            walk(this, 'value', visitor, options);
93✔
865
        }
866
    }
867

868
    get leadingTrivia(): Token[] {
869
        return this.value?.leadingTrivia ?? [];
94!
870
    }
871

872
    public clone() {
873
        return this.finalizeClone(
2✔
874
            new IncrementStatement({
875
                value: this.value?.clone(),
6✔
876
                operator: util.cloneToken(this.tokens.operator)
877
            }),
878
            ['value']
879
        );
880
    }
881
}
882

883
/**
884
 * Represents a `print` statement within BrightScript.
885
 */
886
export class PrintStatement extends Statement {
1✔
887
    /**
888
     * Creates a new internal representation of a BrightScript `print` statement.
889
     * @param options the options for this statement
890
     * @param options.print a print token
891
     * @param options.expressions an array of expressions to be evaluated and printed. Wrap PrintSeparator tokens (`;` or `,`) in `PrintSeparatorExpression`
892
     */
893
    constructor(options: {
894
        print?: Token;
895
        expressions: Array<Expression>;
896
    }) {
897
        super();
1,362✔
898
        this.tokens = {
1,362✔
899
            print: options.print
900
        };
901
        this.expressions = options.expressions;
1,362✔
902
        this.location = util.createBoundingLocation(
1,362✔
903
            this.tokens.print,
904
            ...(this.expressions ?? [])
4,086✔
905
        );
906
    }
907

908
    public readonly tokens: {
909
        readonly print?: Token;
910
    };
911

912
    public readonly expressions: Array<Expression>;
913

914
    public readonly kind = AstNodeKind.PrintStatement;
1,362✔
915

916
    public readonly location: Location | undefined;
917

918
    transpile(state: BrsTranspileState) {
919
        let result = [
238✔
920
            state.transpileToken(this.tokens.print, 'print')
921
        ] as TranspileResult;
922

923
        //if the first expression has no leading whitespace, add a single space between the `print` and the expression
924
        if (this.expressions.length > 0 && !this.expressions[0].leadingTrivia.find(t => t.kind === TokenKind.Whitespace)) {
238✔
925
            result.push(' ');
10✔
926
        }
927

928
        // eslint-disable-next-line @typescript-eslint/prefer-for-of
929
        for (let i = 0; i < this.expressions.length; i++) {
238✔
930
            const expression = this.expressions[i];
302✔
931
            let leadingWhitespace = expression.leadingTrivia.find(t => t.kind === TokenKind.Whitespace)?.text;
302✔
932
            if (leadingWhitespace) {
302✔
933
                result.push(leadingWhitespace);
252✔
934
                //if the previous expression was NOT a separator, and this one is not also, add a space between them
935
            } else if (i > 0 && !isPrintSeparatorExpression(this.expressions[i - 1]) && !isPrintSeparatorExpression(expression) && !leadingWhitespace) {
50✔
936
                result.push(' ');
6✔
937
            }
938

939
            result.push(
302✔
940
                ...expression.transpile(state)
941
            );
942
        }
943
        return result;
238✔
944
    }
945

946
    walk(visitor: WalkVisitor, options: WalkOptions) {
947
        if (options.walkMode & InternalWalkMode.walkExpressions) {
6,443✔
948
            walkArray(this.expressions, visitor, options, this);
6,369✔
949
        }
950
    }
951

952
    get leadingTrivia(): Token[] {
953
        return this.tokens.print?.leadingTrivia ?? [];
8,080✔
954
    }
955

956
    public clone() {
957
        return this.finalizeClone(
49✔
958
            new PrintStatement({
959
                print: util.cloneToken(this.tokens.print),
960
                expressions: this.expressions?.map(e => e?.clone())
49✔
961
            }),
962
            ['expressions' as any]
963
        );
964
    }
965
}
966

967
export class DimStatement extends Statement {
1✔
968
    constructor(options: {
969
        dim?: Token;
970
        name: Identifier;
971
        openingSquare?: Token;
972
        dimensions: Expression[];
973
        closingSquare?: Token;
974
    }) {
975
        super();
46✔
976
        this.tokens = {
46✔
977
            dim: options?.dim,
138!
978
            name: options.name,
979
            openingSquare: options.openingSquare,
980
            closingSquare: options.closingSquare
981
        };
982
        this.dimensions = options.dimensions;
46✔
983
        this.location = util.createBoundingLocation(
46✔
984
            options.dim,
985
            options.name,
986
            options.openingSquare,
987
            ...(this.dimensions ?? []),
138✔
988
            options.closingSquare
989
        );
990
    }
991

992
    public readonly tokens: {
993
        readonly dim?: Token;
994
        readonly name: Identifier;
995
        readonly openingSquare?: Token;
996
        readonly closingSquare?: Token;
997
    };
998
    public readonly dimensions: Expression[];
999

1000
    public readonly kind = AstNodeKind.DimStatement;
46✔
1001

1002
    public readonly location: Location | undefined;
1003

1004
    public transpile(state: BrsTranspileState) {
1005
        let result: TranspileResult = [
15✔
1006
            state.transpileToken(this.tokens.dim, 'dim'),
1007
            ' ',
1008
            state.transpileToken(this.tokens.name),
1009
            state.transpileToken(this.tokens.openingSquare, '[')
1010
        ];
1011
        for (let i = 0; i < this.dimensions.length; i++) {
15✔
1012
            if (i > 0) {
32✔
1013
                result.push(', ');
17✔
1014
            }
1015
            result.push(
32✔
1016
                ...this.dimensions![i].transpile(state)
1017
            );
1018
        }
1019
        result.push(state.transpileToken(this.tokens.closingSquare, ']'));
15✔
1020
        return result;
15✔
1021
    }
1022

1023
    public walk(visitor: WalkVisitor, options: WalkOptions) {
1024
        if (this.dimensions?.length !== undefined && this.dimensions?.length > 0 && options.walkMode & InternalWalkMode.walkExpressions) {
148!
1025
            walkArray(this.dimensions, visitor, options, this);
133✔
1026

1027
        }
1028
    }
1029

1030
    public getType(options: GetTypeOptions): BscType {
1031
        const numDimensions = this.dimensions?.length ?? 1;
18!
1032
        let type = new ArrayType();
18✔
1033
        for (let i = 0; i < numDimensions - 1; i++) {
18✔
1034
            type = new ArrayType(type);
17✔
1035
        }
1036
        return type;
18✔
1037
    }
1038

1039
    get leadingTrivia(): Token[] {
1040
        return this.tokens.dim?.leadingTrivia ?? [];
137!
1041
    }
1042

1043
    public clone() {
1044
        return this.finalizeClone(
3✔
1045
            new DimStatement({
1046
                dim: util.cloneToken(this.tokens.dim),
1047
                name: util.cloneToken(this.tokens.name),
1048
                openingSquare: util.cloneToken(this.tokens.openingSquare),
1049
                dimensions: this.dimensions?.map(e => e?.clone()),
5✔
1050
                closingSquare: util.cloneToken(this.tokens.closingSquare)
1051
            }),
1052
            ['dimensions']
1053
        );
1054
    }
1055
}
1056

1057
export class GotoStatement extends Statement {
1✔
1058
    constructor(options: {
1059
        goto?: Token;
1060
        label: Token;
1061
    }) {
1062
        super();
13✔
1063
        this.tokens = {
13✔
1064
            goto: options.goto,
1065
            label: options.label
1066
        };
1067
        this.location = util.createBoundingLocation(
13✔
1068
            this.tokens.goto,
1069
            this.tokens.label
1070
        );
1071
    }
1072

1073
    public readonly tokens: {
1074
        readonly goto?: Token;
1075
        readonly label: Token;
1076
    };
1077

1078
    public readonly kind = AstNodeKind.GotoStatement;
13✔
1079

1080
    public readonly location: Location | undefined;
1081

1082
    transpile(state: BrsTranspileState) {
1083
        return [
2✔
1084
            state.transpileToken(this.tokens.goto, 'goto'),
1085
            ' ',
1086
            state.transpileToken(this.tokens.label)
1087
        ];
1088
    }
1089

1090
    walk(visitor: WalkVisitor, options: WalkOptions) {
1091
        //nothing to walk
1092
    }
1093

1094
    get leadingTrivia(): Token[] {
1095
        return this.tokens.goto?.leadingTrivia ?? [];
19!
1096
    }
1097

1098
    public clone() {
1099
        return this.finalizeClone(
1✔
1100
            new GotoStatement({
1101
                goto: util.cloneToken(this.tokens.goto),
1102
                label: util.cloneToken(this.tokens.label)
1103
            })
1104
        );
1105
    }
1106
}
1107

1108
export class LabelStatement extends Statement {
1✔
1109
    constructor(options: {
1110
        name: Token;
1111
        colon?: Token;
1112
    }) {
1113
        super();
13✔
1114
        this.tokens = {
13✔
1115
            name: options.name,
1116
            colon: options.colon
1117
        };
1118
        this.location = util.createBoundingLocation(
13✔
1119
            this.tokens.name,
1120
            this.tokens.colon
1121
        );
1122
    }
1123
    public readonly tokens: {
1124
        readonly name: Token;
1125
        readonly colon: Token;
1126
    };
1127
    public readonly kind = AstNodeKind.LabelStatement;
13✔
1128

1129
    public readonly location: Location | undefined;
1130

1131
    public get leadingTrivia(): Token[] {
1132
        return this.tokens.name.leadingTrivia;
29✔
1133
    }
1134

1135
    transpile(state: BrsTranspileState) {
1136
        return [
2✔
1137
            state.transpileToken(this.tokens.name),
1138
            state.transpileToken(this.tokens.colon, ':')
1139

1140
        ];
1141
    }
1142

1143
    walk(visitor: WalkVisitor, options: WalkOptions) {
1144
        //nothing to walk
1145
    }
1146

1147
    public clone() {
1148
        return this.finalizeClone(
1✔
1149
            new LabelStatement({
1150
                name: util.cloneToken(this.tokens.name),
1151
                colon: util.cloneToken(this.tokens.colon)
1152
            })
1153
        );
1154
    }
1155
}
1156

1157
export class ReturnStatement extends Statement {
1✔
1158
    constructor(options?: {
1159
        return?: Token;
1160
        value?: Expression;
1161
    }) {
1162
        super();
3,524✔
1163
        this.tokens = {
3,524✔
1164
            return: options?.return
10,572!
1165
        };
1166
        this.value = options?.value;
3,524!
1167
        this.location = util.createBoundingLocation(
3,524✔
1168
            this.tokens.return,
1169
            this.value
1170
        );
1171
    }
1172

1173
    public readonly tokens: {
1174
        readonly return?: Token;
1175
    };
1176
    public readonly value?: Expression;
1177
    public readonly kind = AstNodeKind.ReturnStatement;
3,524✔
1178

1179
    public readonly location: Location | undefined;
1180

1181
    transpile(state: BrsTranspileState) {
1182
        let result = [] as TranspileResult;
3,363✔
1183
        result.push(
3,363✔
1184
            state.transpileToken(this.tokens.return, 'return')
1185
        );
1186
        if (this.value) {
3,363✔
1187
            result.push(' ');
3,358✔
1188
            result.push(...this.value.transpile(state));
3,358✔
1189
        }
1190
        return result;
3,363✔
1191
    }
1192

1193
    walk(visitor: WalkVisitor, options: WalkOptions) {
1194
        if (options.walkMode & InternalWalkMode.walkExpressions) {
15,551✔
1195
            walk(this, 'value', visitor, options);
15,528✔
1196
        }
1197
    }
1198

1199
    get leadingTrivia(): Token[] {
1200
        return this.tokens.return?.leadingTrivia ?? [];
10,785!
1201
    }
1202

1203
    public clone() {
1204
        return this.finalizeClone(
3✔
1205
            new ReturnStatement({
1206
                return: util.cloneToken(this.tokens.return),
1207
                value: this.value?.clone()
9✔
1208
            }),
1209
            ['value']
1210
        );
1211
    }
1212
}
1213

1214
export class EndStatement extends Statement {
1✔
1215
    constructor(options?: {
1216
        end?: Token;
1217
    }) {
1218
        super();
11✔
1219
        this.tokens = {
11✔
1220
            end: options?.end
33!
1221
        };
1222
        this.location = this.tokens.end?.location;
11!
1223
    }
1224
    public readonly tokens: {
1225
        readonly end?: Token;
1226
    };
1227
    public readonly kind = AstNodeKind.EndStatement;
11✔
1228

1229
    public readonly location: Location;
1230

1231
    transpile(state: BrsTranspileState) {
1232
        return [
2✔
1233
            state.transpileToken(this.tokens.end, 'end')
1234
        ];
1235
    }
1236

1237
    walk(visitor: WalkVisitor, options: WalkOptions) {
1238
        //nothing to walk
1239
    }
1240

1241
    get leadingTrivia(): Token[] {
1242
        return this.tokens.end?.leadingTrivia ?? [];
19!
1243
    }
1244

1245
    public clone() {
1246
        return this.finalizeClone(
1✔
1247
            new EndStatement({
1248
                end: util.cloneToken(this.tokens.end)
1249
            })
1250
        );
1251
    }
1252
}
1253

1254
export class StopStatement extends Statement {
1✔
1255
    constructor(options?: {
1256
        stop?: Token;
1257
    }) {
1258
        super();
19✔
1259
        this.tokens = { stop: options?.stop };
19!
1260
        this.location = this.tokens?.stop?.location;
19!
1261
    }
1262
    public readonly tokens: {
1263
        readonly stop?: Token;
1264
    };
1265

1266
    public readonly kind = AstNodeKind.StopStatement;
19✔
1267

1268
    public readonly location: Location;
1269

1270
    transpile(state: BrsTranspileState) {
1271
        return [
2✔
1272
            state.transpileToken(this.tokens.stop, 'stop')
1273
        ];
1274
    }
1275

1276
    walk(visitor: WalkVisitor, options: WalkOptions) {
1277
        //nothing to walk
1278
    }
1279

1280
    get leadingTrivia(): Token[] {
1281
        return this.tokens.stop?.leadingTrivia ?? [];
29!
1282
    }
1283

1284
    public clone() {
1285
        return this.finalizeClone(
1✔
1286
            new StopStatement({
1287
                stop: util.cloneToken(this.tokens.stop)
1288
            })
1289
        );
1290
    }
1291
}
1292

1293
export class ForStatement extends Statement {
1✔
1294
    constructor(options: {
1295
        for?: Token;
1296
        counterDeclaration: AssignmentStatement;
1297
        to?: Token;
1298
        finalValue: Expression;
1299
        body: Block;
1300
        endFor?: Token;
1301
        step?: Token;
1302
        increment?: Expression;
1303
    }) {
1304
        super();
47✔
1305
        this.tokens = {
47✔
1306
            for: options.for,
1307
            to: options.to,
1308
            endFor: options.endFor,
1309
            step: options.step
1310
        };
1311
        this.counterDeclaration = options.counterDeclaration;
47✔
1312
        this.finalValue = options.finalValue;
47✔
1313
        this.body = options.body;
47✔
1314
        this.increment = options.increment;
47✔
1315

1316
        this.location = util.createBoundingLocation(
47✔
1317
            this.tokens.for,
1318
            this.counterDeclaration,
1319
            this.tokens.to,
1320
            this.finalValue,
1321
            this.tokens.step,
1322
            this.increment,
1323
            this.body,
1324
            this.tokens.endFor
1325
        );
1326
    }
1327

1328
    public readonly tokens: {
1329
        readonly for?: Token;
1330
        readonly to?: Token;
1331
        readonly endFor?: Token;
1332
        readonly step?: Token;
1333
    };
1334

1335
    public readonly counterDeclaration: AssignmentStatement;
1336
    public readonly finalValue: Expression;
1337
    public readonly body: Block;
1338
    public readonly increment?: Expression;
1339

1340
    public readonly kind = AstNodeKind.ForStatement;
47✔
1341

1342
    public readonly location: Location | undefined;
1343

1344
    transpile(state: BrsTranspileState) {
1345
        let result = [] as TranspileResult;
11✔
1346
        //for
1347
        result.push(
11✔
1348
            state.transpileToken(this.tokens.for, 'for'),
1349
            ' '
1350
        );
1351
        //i=1
1352
        result.push(
11✔
1353
            ...this.counterDeclaration.transpile(state),
1354
            ' '
1355
        );
1356
        //to
1357
        result.push(
11✔
1358
            state.transpileToken(this.tokens.to, 'to'),
1359
            ' '
1360
        );
1361
        //final value
1362
        result.push(this.finalValue.transpile(state));
11✔
1363
        //step
1364
        if (this.increment) {
11✔
1365
            result.push(
4✔
1366
                ' ',
1367
                state.transpileToken(this.tokens.step, 'step'),
1368
                ' ',
1369
                this.increment!.transpile(state)
1370
            );
1371
        }
1372
        //loop body
1373
        state.lineage.unshift(this);
11✔
1374
        result.push(...this.body.transpile(state));
11✔
1375
        state.lineage.shift();
11✔
1376

1377
        //end for
1378
        result.push(...state.transpileEndBlockToken(this.body, this.tokens.endFor, 'end for'));
11✔
1379

1380
        return result;
11✔
1381
    }
1382

1383
    walk(visitor: WalkVisitor, options: WalkOptions) {
1384
        if (options.walkMode & InternalWalkMode.walkStatements) {
152✔
1385
            walk(this, 'counterDeclaration', visitor, options);
151✔
1386
        }
1387
        if (options.walkMode & InternalWalkMode.walkExpressions) {
152✔
1388
            walk(this, 'finalValue', visitor, options);
148✔
1389
            walk(this, 'increment', visitor, options);
148✔
1390
        }
1391
        if (options.walkMode & InternalWalkMode.walkStatements) {
152✔
1392
            walk(this, 'body', visitor, options);
151✔
1393
        }
1394
    }
1395

1396
    get leadingTrivia(): Token[] {
1397
        return this.tokens.for?.leadingTrivia ?? [];
152!
1398
    }
1399

1400
    public get endTrivia(): Token[] {
UNCOV
1401
        return this.tokens.endFor?.leadingTrivia ?? [];
×
1402
    }
1403

1404
    public clone() {
1405
        return this.finalizeClone(
5✔
1406
            new ForStatement({
1407
                for: util.cloneToken(this.tokens.for),
1408
                counterDeclaration: this.counterDeclaration?.clone(),
15✔
1409
                to: util.cloneToken(this.tokens.to),
1410
                finalValue: this.finalValue?.clone(),
15✔
1411
                body: this.body?.clone(),
15✔
1412
                endFor: util.cloneToken(this.tokens.endFor),
1413
                step: util.cloneToken(this.tokens.step),
1414
                increment: this.increment?.clone()
15✔
1415
            }),
1416
            ['counterDeclaration', 'finalValue', 'body', 'increment']
1417
        );
1418
    }
1419
}
1420

1421
export class ForEachStatement extends Statement {
1✔
1422
    constructor(options: {
1423
        forEach?: Token;
1424
        item: Token;
1425
        in?: Token;
1426
        target: Expression;
1427
        body: Block;
1428
        endFor?: Token;
1429
    }) {
1430
        super();
43✔
1431
        this.tokens = {
43✔
1432
            forEach: options.forEach,
1433
            item: options.item,
1434
            in: options.in,
1435
            endFor: options.endFor
1436
        };
1437
        this.body = options.body;
43✔
1438
        this.target = options.target;
43✔
1439

1440
        this.location = util.createBoundingLocation(
43✔
1441
            this.tokens.forEach,
1442
            this.tokens.item,
1443
            this.tokens.in,
1444
            this.target,
1445
            this.body,
1446
            this.tokens.endFor
1447
        );
1448
    }
1449

1450
    public readonly tokens: {
1451
        readonly forEach?: Token;
1452
        readonly item: Token;
1453
        readonly in?: Token;
1454
        readonly endFor?: Token;
1455
    };
1456
    public readonly body: Block;
1457
    public readonly target: Expression;
1458

1459
    public readonly kind = AstNodeKind.ForEachStatement;
43✔
1460

1461
    public readonly location: Location | undefined;
1462

1463
    transpile(state: BrsTranspileState) {
1464
        let result = [] as TranspileResult;
5✔
1465
        //for each
1466
        result.push(
5✔
1467
            state.transpileToken(this.tokens.forEach, 'for each'),
1468
            ' '
1469
        );
1470
        //item
1471
        result.push(
5✔
1472
            state.transpileToken(this.tokens.item),
1473
            ' '
1474
        );
1475
        //in
1476
        result.push(
5✔
1477
            state.transpileToken(this.tokens.in, 'in'),
1478
            ' '
1479
        );
1480
        //target
1481
        result.push(...this.target.transpile(state));
5✔
1482
        //body
1483
        state.lineage.unshift(this);
5✔
1484
        result.push(...this.body.transpile(state));
5✔
1485
        state.lineage.shift();
5✔
1486

1487
        //end for
1488
        result.push(...state.transpileEndBlockToken(this.body, this.tokens.endFor, 'end for'));
5✔
1489

1490
        return result;
5✔
1491
    }
1492

1493
    walk(visitor: WalkVisitor, options: WalkOptions) {
1494
        if (options.walkMode & InternalWalkMode.walkExpressions) {
197✔
1495
            walk(this, 'target', visitor, options);
190✔
1496
        }
1497
        if (options.walkMode & InternalWalkMode.walkStatements) {
197✔
1498
            walk(this, 'body', visitor, options);
196✔
1499
        }
1500
    }
1501

1502
    getType(options: GetTypeOptions): BscType {
1503
        return this.getSymbolTable().getSymbolType(this.tokens.item.text, { ...options, statementIndex: this.statementIndex });
31✔
1504
    }
1505

1506
    get leadingTrivia(): Token[] {
1507
        return this.tokens.forEach?.leadingTrivia ?? [];
197!
1508
    }
1509

1510
    public get endTrivia(): Token[] {
1511
        return this.tokens.endFor?.leadingTrivia ?? [];
1!
1512
    }
1513

1514
    public clone() {
1515
        return this.finalizeClone(
2✔
1516
            new ForEachStatement({
1517
                forEach: util.cloneToken(this.tokens.forEach),
1518
                in: util.cloneToken(this.tokens.in),
1519
                endFor: util.cloneToken(this.tokens.endFor),
1520
                item: util.cloneToken(this.tokens.item),
1521
                target: this.target?.clone(),
6✔
1522
                body: this.body?.clone()
6✔
1523
            }),
1524
            ['target', 'body']
1525
        );
1526
    }
1527
}
1528

1529
export class WhileStatement extends Statement {
1✔
1530
    constructor(options: {
1531
        while?: Token;
1532
        endWhile?: Token;
1533
        condition: Expression;
1534
        body: Block;
1535
    }) {
1536
        super();
38✔
1537
        this.tokens = {
38✔
1538
            while: options.while,
1539
            endWhile: options.endWhile
1540
        };
1541
        this.body = options.body;
38✔
1542
        this.condition = options.condition;
38✔
1543
        this.location = util.createBoundingLocation(
38✔
1544
            this.tokens.while,
1545
            this.condition,
1546
            this.body,
1547
            this.tokens.endWhile
1548
        );
1549
    }
1550

1551
    public readonly tokens: {
1552
        readonly while?: Token;
1553
        readonly endWhile?: Token;
1554
    };
1555
    public readonly condition: Expression;
1556
    public readonly body: Block;
1557

1558
    public readonly kind = AstNodeKind.WhileStatement;
38✔
1559

1560
    public readonly location: Location | undefined;
1561

1562
    transpile(state: BrsTranspileState) {
1563
        let result = [] as TranspileResult;
8✔
1564
        //while
1565
        result.push(
8✔
1566
            state.transpileToken(this.tokens.while, 'while'),
1567
            ' '
1568
        );
1569
        //condition
1570
        result.push(
8✔
1571
            ...this.condition.transpile(state)
1572
        );
1573
        state.lineage.unshift(this);
8✔
1574
        //body
1575
        result.push(...this.body.transpile(state));
8✔
1576
        state.lineage.shift();
8✔
1577

1578
        //end while
1579
        result.push(...state.transpileEndBlockToken(this.body, this.tokens.endWhile, 'end while'));
8✔
1580

1581
        return result;
8✔
1582
    }
1583

1584
    walk(visitor: WalkVisitor, options: WalkOptions) {
1585
        if (options.walkMode & InternalWalkMode.walkExpressions) {
128✔
1586
            walk(this, 'condition', visitor, options);
125✔
1587
        }
1588
        if (options.walkMode & InternalWalkMode.walkStatements) {
128✔
1589
            walk(this, 'body', visitor, options);
127✔
1590
        }
1591
    }
1592

1593
    get leadingTrivia(): Token[] {
1594
        return this.tokens.while?.leadingTrivia ?? [];
113!
1595
    }
1596

1597
    public get endTrivia(): Token[] {
1598
        return this.tokens.endWhile?.leadingTrivia ?? [];
1!
1599
    }
1600

1601
    public clone() {
1602
        return this.finalizeClone(
4✔
1603
            new WhileStatement({
1604
                while: util.cloneToken(this.tokens.while),
1605
                endWhile: util.cloneToken(this.tokens.endWhile),
1606
                condition: this.condition?.clone(),
12✔
1607
                body: this.body?.clone()
12✔
1608
            }),
1609
            ['condition', 'body']
1610
        );
1611
    }
1612
}
1613

1614
export class DottedSetStatement extends Statement {
1✔
1615
    constructor(options: {
1616
        obj: Expression;
1617
        name: Identifier;
1618
        value: Expression;
1619
        dot?: Token;
1620
        equals?: Token;
1621
    }) {
1622
        super();
318✔
1623
        this.tokens = {
318✔
1624
            name: options.name,
1625
            dot: options.dot,
1626
            equals: options.equals
1627
        };
1628
        this.obj = options.obj;
318✔
1629
        this.value = options.value;
318✔
1630
        this.location = util.createBoundingLocation(
318✔
1631
            this.obj,
1632
            this.tokens.dot,
1633
            this.tokens.equals,
1634
            this.tokens.name,
1635
            this.value
1636
        );
1637
    }
1638
    public readonly tokens: {
1639
        readonly name: Identifier;
1640
        readonly equals?: Token;
1641
        readonly dot?: Token;
1642
    };
1643

1644
    public readonly obj: Expression;
1645
    public readonly value: Expression;
1646

1647
    public readonly kind = AstNodeKind.DottedSetStatement;
318✔
1648

1649
    public readonly location: Location | undefined;
1650

1651
    transpile(state: BrsTranspileState) {
1652
        //if the value is a compound assignment, don't add the obj, dot, name, or operator...the expression will handle that
1653
        return [
15✔
1654
            //object
1655
            ...this.obj.transpile(state),
1656
            this.tokens.dot ? state.tokenToSourceNode(this.tokens.dot) : '.',
15✔
1657
            //name
1658
            state.transpileToken(this.tokens.name),
1659
            ' ',
1660
            state.transpileToken(this.tokens.equals, '='),
1661
            ' ',
1662
            //right-hand-side of assignment
1663
            ...this.value.transpile(state)
1664
        ];
1665

1666
    }
1667

1668
    walk(visitor: WalkVisitor, options: WalkOptions) {
1669
        if (options.walkMode & InternalWalkMode.walkExpressions) {
863✔
1670
            walk(this, 'obj', visitor, options);
861✔
1671
            walk(this, 'value', visitor, options);
861✔
1672
        }
1673
    }
1674

1675
    getType(options: GetTypeOptions) {
1676
        const objType = this.obj?.getType(options);
103!
1677
        const result = objType?.getMemberType(this.tokens.name?.text, options);
103!
1678
        options.typeChain?.push(new TypeChainEntry({
103✔
1679
            name: this.tokens.name?.text,
306!
1680
            type: result, data: options.data,
1681
            location: this.tokens.name?.location,
306!
1682
            astNode: this
1683
        }));
1684
        return result;
103✔
1685
    }
1686

1687
    get leadingTrivia(): Token[] {
1688
        return this.obj.leadingTrivia;
892✔
1689
    }
1690

1691
    public clone() {
1692
        return this.finalizeClone(
2✔
1693
            new DottedSetStatement({
1694
                obj: this.obj?.clone(),
6✔
1695
                dot: util.cloneToken(this.tokens.dot),
1696
                name: util.cloneToken(this.tokens.name),
1697
                equals: util.cloneToken(this.tokens.equals),
1698
                value: this.value?.clone()
6✔
1699
            }),
1700
            ['obj', 'value']
1701
        );
1702
    }
1703
}
1704

1705
export class IndexedSetStatement extends Statement {
1✔
1706
    constructor(options: {
1707
        obj: Expression;
1708
        indexes: Expression[];
1709
        value: Expression;
1710
        openingSquare?: Token;
1711
        closingSquare?: Token;
1712
        equals?: Token;
1713
    }) {
1714
        super();
47✔
1715
        this.tokens = {
47✔
1716
            openingSquare: options.openingSquare,
1717
            closingSquare: options.closingSquare,
1718
            equals: options.equals
1719
        };
1720
        this.obj = options.obj;
47✔
1721
        this.indexes = options.indexes ?? [];
47✔
1722
        this.value = options.value;
47✔
1723
        this.location = util.createBoundingLocation(
47✔
1724
            this.obj,
1725
            this.tokens.openingSquare,
1726
            ...this.indexes,
1727
            this.tokens.closingSquare,
1728
            this.value
1729
        );
1730
    }
1731

1732
    public readonly tokens: {
1733
        readonly openingSquare?: Token;
1734
        readonly closingSquare?: Token;
1735
        readonly equals?: Token;
1736
    };
1737
    public readonly obj: Expression;
1738
    public readonly indexes: Expression[];
1739
    public readonly value: Expression;
1740

1741
    public readonly kind = AstNodeKind.IndexedSetStatement;
47✔
1742

1743
    public readonly location: Location | undefined;
1744

1745
    transpile(state: BrsTranspileState) {
1746
        const result = [];
17✔
1747
        result.push(
17✔
1748
            //obj
1749
            ...this.obj.transpile(state),
1750
            //   [
1751
            state.transpileToken(this.tokens.openingSquare, '[')
1752
        );
1753
        for (let i = 0; i < this.indexes.length; i++) {
17✔
1754
            //add comma between indexes
1755
            if (i > 0) {
18✔
1756
                result.push(', ');
1✔
1757
            }
1758
            let index = this.indexes[i];
18✔
1759
            result.push(
18✔
1760
                ...(index?.transpile(state) ?? [])
108!
1761
            );
1762
        }
1763
        result.push(
17✔
1764
            state.transpileToken(this.tokens.closingSquare, ']'),
1765
            ' ',
1766
            state.transpileToken(this.tokens.equals, '='),
1767
            ' ',
1768
            ...this.value.transpile(state)
1769
        );
1770
        return result;
17✔
1771

1772
    }
1773

1774
    walk(visitor: WalkVisitor, options: WalkOptions) {
1775
        if (options.walkMode & InternalWalkMode.walkExpressions) {
166✔
1776
            walk(this, 'obj', visitor, options);
165✔
1777
            walkArray(this.indexes, visitor, options, this);
165✔
1778
            walk(this, 'value', visitor, options);
165✔
1779
        }
1780
    }
1781

1782
    get leadingTrivia(): Token[] {
1783
        return this.obj.leadingTrivia;
175✔
1784
    }
1785

1786
    public clone() {
1787
        return this.finalizeClone(
6✔
1788
            new IndexedSetStatement({
1789
                obj: this.obj?.clone(),
18✔
1790
                openingSquare: util.cloneToken(this.tokens.openingSquare),
1791
                indexes: this.indexes?.map(x => x?.clone()),
7✔
1792
                closingSquare: util.cloneToken(this.tokens.closingSquare),
1793
                equals: util.cloneToken(this.tokens.equals),
1794
                value: this.value?.clone()
18✔
1795
            }),
1796
            ['obj', 'indexes', 'value']
1797
        );
1798
    }
1799
}
1800

1801
export class LibraryStatement extends Statement implements TypedefProvider {
1✔
1802
    constructor(options: {
1803
        library: Token;
1804
        filePath?: Token;
1805
    }) {
1806
        super();
16✔
1807
        this.tokens = {
16✔
1808
            library: options?.library,
48!
1809
            filePath: options?.filePath
48!
1810
        };
1811
        this.location = util.createBoundingLocation(
16✔
1812
            this.tokens.library,
1813
            this.tokens.filePath
1814
        );
1815
    }
1816
    public readonly tokens: {
1817
        readonly library: Token;
1818
        readonly filePath?: Token;
1819
    };
1820

1821
    public readonly kind = AstNodeKind.LibraryStatement;
16✔
1822

1823
    public readonly location: Location | undefined;
1824

1825
    transpile(state: BrsTranspileState) {
1826
        let result = [] as TranspileResult;
2✔
1827
        result.push(
2✔
1828
            state.transpileToken(this.tokens.library)
1829
        );
1830
        //there will be a parse error if file path is missing, but let's prevent a runtime error just in case
1831
        if (this.tokens.filePath) {
2!
1832
            result.push(
2✔
1833
                ' ',
1834
                state.transpileToken(this.tokens.filePath)
1835
            );
1836
        }
1837
        return result;
2✔
1838
    }
1839

1840
    getTypedef(state: BrsTranspileState) {
UNCOV
1841
        return this.transpile(state);
×
1842
    }
1843

1844
    walk(visitor: WalkVisitor, options: WalkOptions) {
1845
        //nothing to walk
1846
    }
1847

1848
    get leadingTrivia(): Token[] {
1849
        return this.tokens.library?.leadingTrivia ?? [];
26!
1850
    }
1851

1852
    public clone() {
1853
        return this.finalizeClone(
1✔
1854
            new LibraryStatement({
1855
                library: util.cloneToken(this.tokens?.library),
3!
1856
                filePath: util.cloneToken(this.tokens?.filePath)
3!
1857
            })
1858
        );
1859
    }
1860
}
1861

1862
export class NamespaceStatement extends Statement implements TypedefProvider {
1✔
1863
    constructor(options: {
1864
        namespace?: Token;
1865
        nameExpression: VariableExpression | DottedGetExpression;
1866
        body: Body;
1867
        endNamespace?: Token;
1868
    }) {
1869
        super();
652✔
1870
        this.tokens = {
652✔
1871
            namespace: options.namespace,
1872
            endNamespace: options.endNamespace
1873
        };
1874
        this.nameExpression = options.nameExpression;
652✔
1875
        this.body = options.body;
652✔
1876
        this.symbolTable = new SymbolTable(`NamespaceStatement: '${this.name}'`, () => this.getRoot()?.getSymbolTable());
6,317!
1877
    }
1878

1879
    public readonly tokens: {
1880
        readonly namespace?: Token;
1881
        readonly endNamespace?: Token;
1882
    };
1883

1884
    public readonly nameExpression: VariableExpression | DottedGetExpression;
1885
    public readonly body: Body;
1886

1887
    public readonly kind = AstNodeKind.NamespaceStatement;
652✔
1888

1889
    /**
1890
     * The string name for this namespace
1891
     */
1892
    public get name(): string {
1893
        return this.getName(ParseMode.BrighterScript);
2,447✔
1894
    }
1895

1896
    public get location() {
1897
        return this.cacheLocation();
530✔
1898
    }
1899
    private _location: Location | undefined;
1900

1901
    public cacheLocation() {
1902
        if (!this._location) {
1,180✔
1903
            this._location = util.createBoundingLocation(
652✔
1904
                this.tokens.namespace,
1905
                this.nameExpression,
1906
                this.body,
1907
                this.tokens.endNamespace
1908
            );
1909
        }
1910
        return this._location;
1,180✔
1911
    }
1912

1913
    public getName(parseMode: ParseMode) {
1914
        const sep = parseMode === ParseMode.BrighterScript ? '.' : '_';
8,784✔
1915
        let name = util.getAllDottedGetPartsAsString(this.nameExpression, parseMode);
8,784✔
1916
        if ((this.parent as Body)?.parent?.kind === AstNodeKind.NamespaceStatement) {
8,784✔
1917
            name = (this.parent.parent as NamespaceStatement).getName(parseMode) + sep + name;
358✔
1918
        }
1919
        return name;
8,784✔
1920
    }
1921

1922
    public get leadingTrivia(): Token[] {
1923
        return this.tokens.namespace?.leadingTrivia;
1,897!
1924
    }
1925

1926
    public get endTrivia(): Token[] {
UNCOV
1927
        return this.tokens.endNamespace?.leadingTrivia;
×
1928
    }
1929

1930
    public getNameParts() {
1931
        let parts = util.getAllDottedGetParts(this.nameExpression);
1,466✔
1932

1933
        if ((this.parent as Body)?.parent?.kind === AstNodeKind.NamespaceStatement) {
1,466!
1934
            parts = (this.parent.parent as NamespaceStatement).getNameParts().concat(parts);
67✔
1935
        }
1936
        return parts;
1,466✔
1937
    }
1938

1939
    transpile(state: BrsTranspileState) {
1940
        //namespaces don't actually have any real content, so just transpile their bodies
1941
        return [
63✔
1942
            state.transpileAnnotations(this),
1943
            state.transpileLeadingComments(this.tokens.namespace),
1944
            this.body.transpile(state),
1945
            state.transpileLeadingComments(this.tokens.endNamespace)
1946
        ];
1947
    }
1948

1949
    getTypedef(state: BrsTranspileState) {
1950
        let result: TranspileResult = [];
7✔
1951
        for (let comment of util.getLeadingComments(this) ?? []) {
7!
UNCOV
1952
            result.push(
×
1953
                comment.text,
1954
                state.newline,
1955
                state.indent()
1956
            );
1957
        }
1958

1959
        result.push('namespace ',
7✔
1960
            ...this.getName(ParseMode.BrighterScript),
1961
            state.newline
1962
        );
1963
        state.blockDepth++;
7✔
1964
        result.push(
7✔
1965
            ...this.body.getTypedef(state)
1966
        );
1967
        state.blockDepth--;
7✔
1968

1969
        result.push(
7✔
1970
            state.indent(),
1971
            'end namespace'
1972
        );
1973
        return result;
7✔
1974
    }
1975

1976
    walk(visitor: WalkVisitor, options: WalkOptions) {
1977
        if (options.walkMode & InternalWalkMode.walkExpressions) {
3,316✔
1978
            walk(this, 'nameExpression', visitor, options);
2,717✔
1979
        }
1980

1981
        if (this.body.statements.length > 0 && options.walkMode & InternalWalkMode.walkStatements) {
3,316✔
1982
            walk(this, 'body', visitor, options);
3,113✔
1983
        }
1984
    }
1985

1986
    getType(options: GetTypeOptions) {
1987
        const resultType = new NamespaceType(this.name);
1,141✔
1988
        return resultType;
1,141✔
1989
    }
1990

1991
    public clone() {
1992
        const clone = this.finalizeClone(
3✔
1993
            new NamespaceStatement({
1994
                namespace: util.cloneToken(this.tokens.namespace),
1995
                nameExpression: this.nameExpression?.clone(),
9✔
1996
                body: this.body?.clone(),
9✔
1997
                endNamespace: util.cloneToken(this.tokens.endNamespace)
1998
            }),
1999
            ['nameExpression', 'body']
2000
        );
2001
        clone.cacheLocation();
3✔
2002
        return clone;
3✔
2003
    }
2004
}
2005

2006
export class ImportStatement extends Statement implements TypedefProvider {
1✔
2007
    constructor(options: {
2008
        import?: Token;
2009
        path?: Token;
2010
    }) {
2011
        super();
215✔
2012
        this.tokens = {
215✔
2013
            import: options.import,
2014
            path: options.path
2015
        };
2016
        this.location = util.createBoundingLocation(
215✔
2017
            this.tokens.import,
2018
            this.tokens.path
2019
        );
2020
        if (this.tokens.path) {
215✔
2021
            //remove quotes
2022
            this.filePath = this.tokens.path.text.replace(/"/g, '');
213✔
2023
            if (this.tokens.path?.location?.range) {
213!
2024
                //adjust the range to exclude the quotes
2025
                this.tokens.path.location = util.createLocation(
209✔
2026
                    this.tokens.path.location.range.start.line,
2027
                    this.tokens.path.location.range.start.character + 1,
2028
                    this.tokens.path.location.range.end.line,
2029
                    this.tokens.path.location.range.end.character - 1,
2030
                    this.tokens.path.location.uri
2031
                );
2032
            }
2033
        }
2034
    }
2035

2036
    public readonly tokens: {
2037
        readonly import?: Token;
2038
        readonly path: Token;
2039
    };
2040

2041
    public readonly kind = AstNodeKind.ImportStatement;
215✔
2042

2043
    public readonly location: Location;
2044

2045
    public readonly filePath: string;
2046

2047
    transpile(state: BrsTranspileState) {
2048
        //The xml files are responsible for adding the additional script imports, but
2049
        //add the import statement as a comment just for debugging purposes
2050
        return [
13✔
2051
            state.transpileToken(this.tokens.import, 'import', true),
2052
            ' ',
2053
            state.transpileToken(this.tokens.path)
2054
        ];
2055
    }
2056

2057
    /**
2058
     * Get the typedef for this statement
2059
     */
2060
    public getTypedef(state: BrsTranspileState) {
2061
        return [
3✔
2062
            this.tokens.import?.text ?? 'import',
18!
2063
            ' ',
2064
            //replace any `.bs` extension with `.brs`
2065
            this.tokens.path.text.replace(/\.bs"?$/i, '.brs"')
2066
        ];
2067
    }
2068

2069
    walk(visitor: WalkVisitor, options: WalkOptions) {
2070
        //nothing to walk
2071
    }
2072

2073
    get leadingTrivia(): Token[] {
2074
        return this.tokens.import?.leadingTrivia ?? [];
600!
2075
    }
2076

2077
    public clone() {
2078
        return this.finalizeClone(
1✔
2079
            new ImportStatement({
2080
                import: util.cloneToken(this.tokens.import),
2081
                path: util.cloneToken(this.tokens.path)
2082
            })
2083
        );
2084
    }
2085
}
2086

2087
export class InterfaceStatement extends Statement implements TypedefProvider {
1✔
2088
    constructor(options: {
2089
        interface: Token;
2090
        name: Identifier;
2091
        extends?: Token;
2092
        parentInterfaceName?: TypeExpression;
2093
        body: Statement[];
2094
        endInterface?: Token;
2095
    }) {
2096
        super();
190✔
2097
        this.tokens = {
190✔
2098
            interface: options.interface,
2099
            name: options.name,
2100
            extends: options.extends,
2101
            endInterface: options.endInterface
2102
        };
2103
        this.parentInterfaceName = options.parentInterfaceName;
190✔
2104
        this.body = options.body;
190✔
2105
        this.location = util.createBoundingLocation(
190✔
2106
            this.tokens.interface,
2107
            this.tokens.name,
2108
            this.tokens.extends,
2109
            this.parentInterfaceName,
2110
            ...this.body ?? [],
570✔
2111
            this.tokens.endInterface
2112
        );
2113
    }
2114
    public readonly parentInterfaceName?: TypeExpression;
2115
    public readonly body: Statement[];
2116

2117
    public readonly kind = AstNodeKind.InterfaceStatement;
190✔
2118

2119
    public readonly tokens = {} as {
190✔
2120
        readonly interface?: Token;
2121
        readonly name: Identifier;
2122
        readonly extends?: Token;
2123
        readonly endInterface?: Token;
2124
    };
2125

2126
    public readonly location: Location | undefined;
2127

2128
    public get fields(): InterfaceFieldStatement[] {
2129
        return this.body.filter(x => isInterfaceFieldStatement(x)) as InterfaceFieldStatement[];
240✔
2130
    }
2131

2132
    public get methods(): InterfaceMethodStatement[] {
2133
        return this.body.filter(x => isInterfaceMethodStatement(x)) as InterfaceMethodStatement[];
235✔
2134
    }
2135

2136

2137
    public hasParentInterface() {
UNCOV
2138
        return !!this.parentInterfaceName;
×
2139
    }
2140

2141
    public get leadingTrivia(): Token[] {
2142
        return this.tokens.interface?.leadingTrivia;
491!
2143
    }
2144

2145
    public get endTrivia(): Token[] {
UNCOV
2146
        return this.tokens.endInterface?.leadingTrivia;
×
2147
    }
2148

2149

2150
    /**
2151
     * The name of the interface WITH its leading namespace (if applicable)
2152
     */
2153
    public get fullName() {
UNCOV
2154
        const name = this.tokens.name?.text;
×
2155
        if (name) {
×
2156
            const namespace = this.findAncestor<NamespaceStatement>(isNamespaceStatement);
×
2157
            if (namespace) {
×
2158
                let namespaceName = namespace.getName(ParseMode.BrighterScript);
×
2159
                return `${namespaceName}.${name}`;
×
2160
            } else {
UNCOV
2161
                return name;
×
2162
            }
2163
        } else {
2164
            //return undefined which will allow outside callers to know that this interface doesn't have a name
UNCOV
2165
            return undefined;
×
2166
        }
2167
    }
2168

2169
    /**
2170
     * The name of the interface (without the namespace prefix)
2171
     */
2172
    public get name() {
2173
        return this.tokens.name?.text;
169!
2174
    }
2175

2176
    /**
2177
     * Get the name of this expression based on the parse mode
2178
     */
2179
    public getName(parseMode: ParseMode) {
2180
        const namespace = this.findAncestor<NamespaceStatement>(isNamespaceStatement);
169✔
2181
        if (namespace) {
169✔
2182
            let delimiter = parseMode === ParseMode.BrighterScript ? '.' : '_';
24!
2183
            let namespaceName = namespace.getName(parseMode);
24✔
2184
            return namespaceName + delimiter + this.name;
24✔
2185
        } else {
2186
            return this.name;
145✔
2187
        }
2188
    }
2189

2190
    public transpile(state: BrsTranspileState): TranspileResult {
2191
        //interfaces should completely disappear at runtime
2192
        return [
14✔
2193
            state.transpileLeadingComments(this.tokens.interface)
2194
        ];
2195
    }
2196

2197
    getTypedef(state: BrsTranspileState) {
2198
        const result = [] as TranspileResult;
7✔
2199
        for (let comment of util.getLeadingComments(this) ?? []) {
7!
UNCOV
2200
            result.push(
×
2201
                comment.text,
2202
                state.newline,
2203
                state.indent()
2204
            );
2205
        }
2206
        for (let annotation of this.annotations ?? []) {
7✔
2207
            result.push(
1✔
2208
                ...annotation.getTypedef(state),
2209
                state.newline,
2210
                state.indent()
2211
            );
2212
        }
2213
        result.push(
7✔
2214
            this.tokens.interface.text,
2215
            ' ',
2216
            this.tokens.name.text
2217
        );
2218
        const parentInterfaceName = this.parentInterfaceName?.getName();
7!
2219
        if (parentInterfaceName) {
7!
UNCOV
2220
            result.push(
×
2221
                ' extends ',
2222
                parentInterfaceName
2223
            );
2224
        }
2225
        const body = this.body ?? [];
7!
2226
        if (body.length > 0) {
7!
2227
            state.blockDepth++;
7✔
2228
        }
2229
        for (const statement of body) {
7✔
2230
            if (isInterfaceMethodStatement(statement) || isInterfaceFieldStatement(statement)) {
22!
2231
                result.push(
22✔
2232
                    state.newline,
2233
                    state.indent(),
2234
                    ...statement.getTypedef(state)
2235
                );
2236
            } else {
UNCOV
2237
                result.push(
×
2238
                    state.newline,
2239
                    state.indent(),
2240
                    ...statement.transpile(state)
2241
                );
2242
            }
2243
        }
2244
        if (body.length > 0) {
7!
2245
            state.blockDepth--;
7✔
2246
        }
2247
        result.push(
7✔
2248
            state.newline,
2249
            state.indent(),
2250
            'end interface',
2251
            state.newline
2252
        );
2253
        return result;
7✔
2254
    }
2255

2256
    walk(visitor: WalkVisitor, options: WalkOptions) {
2257
        //visitor-less walk function to do parent linking
2258
        walk(this, 'parentInterfaceName', null, options);
844✔
2259

2260
        if (options.walkMode & InternalWalkMode.walkStatements) {
844!
2261
            walkArray(this.body, visitor, options, this);
844✔
2262
        }
2263
    }
2264

2265
    getType(options: GetTypeOptions) {
2266
        const superIface = this.parentInterfaceName?.getType(options) as InterfaceType;
160✔
2267

2268
        const resultType = new InterfaceType(this.getName(ParseMode.BrighterScript), superIface);
160✔
2269
        for (const statement of this.methods) {
160✔
2270
            const memberType = statement?.getType({ ...options, typeChain: undefined }); // no typechain info needed
30!
2271
            const flag = statement.isOptional ? SymbolTypeFlag.runtime | SymbolTypeFlag.optional : SymbolTypeFlag.runtime;
30✔
2272
            resultType.addMember(statement?.tokens.name?.text, { definingNode: statement }, memberType, flag);
30!
2273
        }
2274
        for (const statement of this.fields) {
160✔
2275
            const memberType = statement?.getType({ ...options, typeChain: undefined }); // no typechain info needed
200!
2276
            const flag = statement.isOptional ? SymbolTypeFlag.runtime | SymbolTypeFlag.optional : SymbolTypeFlag.runtime;
200✔
2277
            resultType.addMember(statement?.tokens.name?.text, { definingNode: statement, isInstance: true }, memberType, flag);
200!
2278
        }
2279
        options.typeChain?.push(new TypeChainEntry({
160✔
2280
            name: this.getName(ParseMode.BrighterScript),
2281
            type: resultType,
2282
            data: options.data,
2283
            astNode: this
2284
        }));
2285
        return resultType;
160✔
2286
    }
2287

2288
    public clone() {
2289
        return this.finalizeClone(
8✔
2290
            new InterfaceStatement({
2291
                interface: util.cloneToken(this.tokens.interface),
2292
                name: util.cloneToken(this.tokens.name),
2293
                extends: util.cloneToken(this.tokens.extends),
2294
                parentInterfaceName: this.parentInterfaceName?.clone(),
24✔
2295
                body: this.body?.map(x => x?.clone()),
9✔
2296
                endInterface: util.cloneToken(this.tokens.endInterface)
2297
            }),
2298
            ['parentInterfaceName', 'body']
2299
        );
2300
    }
2301
}
2302

2303
export class InterfaceFieldStatement extends Statement implements TypedefProvider {
1✔
2304
    public transpile(state: BrsTranspileState): TranspileResult {
UNCOV
2305
        throw new Error('Method not implemented.');
×
2306
    }
2307
    constructor(options: {
2308
        name: Identifier;
2309
        as?: Token;
2310
        typeExpression?: TypeExpression;
2311
        optional?: Token;
2312
    }) {
2313
        super();
219✔
2314
        this.tokens = {
219✔
2315
            optional: options.optional,
2316
            name: options.name,
2317
            as: options.as
2318
        };
2319
        this.typeExpression = options.typeExpression;
219✔
2320
        this.location = util.createBoundingLocation(
219✔
2321
            this.tokens.optional,
2322
            this.tokens.name,
2323
            this.tokens.as,
2324
            this.typeExpression
2325
        );
2326
    }
2327

2328
    public readonly kind = AstNodeKind.InterfaceFieldStatement;
219✔
2329

2330
    public readonly typeExpression?: TypeExpression;
2331

2332
    public readonly location: Location | undefined;
2333

2334
    public readonly tokens: {
2335
        readonly name: Identifier;
2336
        readonly as: Token;
2337
        readonly optional?: Token;
2338
    };
2339

2340
    public get leadingTrivia(): Token[] {
2341
        return this.tokens.optional?.leadingTrivia ?? this.tokens.name.leadingTrivia;
593✔
2342
    }
2343

2344
    public get name() {
UNCOV
2345
        return this.tokens.name.text;
×
2346
    }
2347

2348
    public get isOptional() {
2349
        return !!this.tokens.optional;
220✔
2350
    }
2351

2352
    walk(visitor: WalkVisitor, options: WalkOptions) {
2353
        if (options.walkMode & InternalWalkMode.walkExpressions) {
1,415✔
2354
            walk(this, 'typeExpression', visitor, options);
1,228✔
2355
        }
2356
    }
2357

2358
    getTypedef(state: BrsTranspileState): TranspileResult {
2359
        const result = [] as TranspileResult;
12✔
2360
        for (let comment of util.getLeadingComments(this) ?? []) {
12!
UNCOV
2361
            result.push(
×
2362
                comment.text,
2363
                state.newline,
2364
                state.indent()
2365
            );
2366
        }
2367
        for (let annotation of this.annotations ?? []) {
12✔
2368
            result.push(
1✔
2369
                ...annotation.getTypedef(state),
2370
                state.newline,
2371
                state.indent()
2372
            );
2373
        }
2374
        if (this.isOptional) {
12✔
2375
            result.push(
1✔
2376
                this.tokens.optional!.text,
2377
                ' '
2378
            );
2379
        }
2380
        result.push(
12✔
2381
            this.tokens.name.text
2382
        );
2383

2384
        if (this.typeExpression) {
12!
2385
            result.push(
12✔
2386
                ' as ',
2387
                ...this.typeExpression.getTypedef(state)
2388
            );
2389
        }
2390
        return result;
12✔
2391
    }
2392

2393
    public getType(options: GetTypeOptions): BscType {
2394
        return this.typeExpression?.getType(options) ?? DynamicType.instance;
211✔
2395
    }
2396

2397
    public clone() {
2398
        return this.finalizeClone(
4✔
2399
            new InterfaceFieldStatement({
2400
                name: util.cloneToken(this.tokens.name),
2401
                as: util.cloneToken(this.tokens.as),
2402
                typeExpression: this.typeExpression?.clone(),
12✔
2403
                optional: util.cloneToken(this.tokens.optional)
2404
            })
2405
        );
2406
    }
2407

2408
}
2409

2410
//TODO: there is much that is similar with this and FunctionExpression.
2411
//It would be nice to refactor this so there is less duplicated code
2412
export class InterfaceMethodStatement extends Statement implements TypedefProvider {
1✔
2413
    public transpile(state: BrsTranspileState): TranspileResult {
UNCOV
2414
        throw new Error('Method not implemented.');
×
2415
    }
2416
    constructor(options: {
2417
        functionType?: Token;
2418
        name: Identifier;
2419
        leftParen?: Token;
2420
        params?: FunctionParameterExpression[];
2421
        rightParen?: Token;
2422
        as?: Token;
2423
        returnTypeExpression?: TypeExpression;
2424
        optional?: Token;
2425
    }) {
2426
        super();
48✔
2427
        this.tokens = {
48✔
2428
            optional: options.optional,
2429
            functionType: options.functionType,
2430
            name: options.name,
2431
            leftParen: options.leftParen,
2432
            rightParen: options.rightParen,
2433
            as: options.as
2434
        };
2435
        this.params = options.params ?? [];
48✔
2436
        this.returnTypeExpression = options.returnTypeExpression;
48✔
2437
    }
2438

2439
    public readonly kind = AstNodeKind.InterfaceMethodStatement;
48✔
2440

2441
    public get location() {
2442
        return util.createBoundingLocation(
78✔
2443
            this.tokens.optional,
2444
            this.tokens.functionType,
2445
            this.tokens.name,
2446
            this.tokens.leftParen,
2447
            ...(this.params ?? []),
234!
2448
            this.tokens.rightParen,
2449
            this.tokens.as,
2450
            this.returnTypeExpression
2451
        );
2452
    }
2453
    /**
2454
     * Get the name of this method.
2455
     */
2456
    public getName(parseMode: ParseMode) {
2457
        return this.tokens.name.text;
30✔
2458
    }
2459

2460
    public readonly tokens: {
2461
        readonly optional?: Token;
2462
        readonly functionType: Token;
2463
        readonly name: Identifier;
2464
        readonly leftParen?: Token;
2465
        readonly rightParen?: Token;
2466
        readonly as?: Token;
2467
    };
2468

2469
    public readonly params: FunctionParameterExpression[];
2470
    public readonly returnTypeExpression?: TypeExpression;
2471

2472
    public get isOptional() {
2473
        return !!this.tokens.optional;
43✔
2474
    }
2475

2476
    public get leadingTrivia(): Token[] {
2477
        return this.tokens.optional?.leadingTrivia ?? this.tokens.functionType.leadingTrivia;
94✔
2478
    }
2479

2480
    walk(visitor: WalkVisitor, options: WalkOptions) {
2481
        if (options.walkMode & InternalWalkMode.walkExpressions) {
229✔
2482
            walk(this, 'returnTypeExpression', visitor, options);
202✔
2483
        }
2484
    }
2485

2486
    getTypedef(state: BrsTranspileState) {
2487
        const result = [] as TranspileResult;
10✔
2488
        for (let comment of util.getLeadingComments(this) ?? []) {
10!
2489
            result.push(
1✔
2490
                comment.text,
2491
                state.newline,
2492
                state.indent()
2493
            );
2494
        }
2495
        for (let annotation of this.annotations ?? []) {
10✔
2496
            result.push(
1✔
2497
                ...annotation.getTypedef(state),
2498
                state.newline,
2499
                state.indent()
2500
            );
2501
        }
2502
        if (this.isOptional) {
10!
UNCOV
2503
            result.push(
×
2504
                this.tokens.optional!.text,
2505
                ' '
2506
            );
2507
        }
2508
        result.push(
10✔
2509
            this.tokens.functionType?.text ?? 'function',
60!
2510
            ' ',
2511
            this.tokens.name.text,
2512
            '('
2513
        );
2514
        const params = this.params ?? [];
10!
2515
        for (let i = 0; i < params.length; i++) {
10✔
2516
            if (i > 0) {
2✔
2517
                result.push(', ');
1✔
2518
            }
2519
            const param = params[i];
2✔
2520
            result.push(param.tokens.name.text);
2✔
2521
            if (param.typeExpression) {
2!
2522
                result.push(
2✔
2523
                    ' as ',
2524
                    ...param.typeExpression.getTypedef(state)
2525
                );
2526
            }
2527
        }
2528
        result.push(
10✔
2529
            ')'
2530
        );
2531
        if (this.returnTypeExpression) {
10!
2532
            result.push(
10✔
2533
                ' as ',
2534
                ...this.returnTypeExpression.getTypedef(state)
2535
            );
2536
        }
2537
        return result;
10✔
2538
    }
2539

2540
    public getType(options: GetTypeOptions): TypedFunctionType {
2541
        //if there's a defined return type, use that
2542
        let returnType = this.returnTypeExpression?.getType(options);
30✔
2543
        const isSub = this.tokens.functionType?.kind === TokenKind.Sub || !returnType;
30!
2544
        //if we don't have a return type and this is a sub, set the return type to `void`. else use `dynamic`
2545
        if (!returnType) {
30✔
2546
            returnType = isSub ? VoidType.instance : DynamicType.instance;
10!
2547
        }
2548
        const resultType = new TypedFunctionType(returnType);
30✔
2549
        resultType.isSub = isSub;
30✔
2550
        for (let param of this.params) {
30✔
2551
            resultType.addParameter(param.tokens.name.text, param.getType(options), !!param.defaultValue);
7✔
2552
        }
2553
        if (options.typeChain) {
30!
2554
            // need Interface type for type chain
UNCOV
2555
            this.parent?.getType(options);
×
2556
        }
2557
        let funcName = this.getName(ParseMode.BrighterScript);
30✔
2558
        resultType.setName(funcName);
30✔
2559
        options.typeChain?.push(new TypeChainEntry({ name: resultType.name, type: resultType, data: options.data, astNode: this }));
30!
2560
        return resultType;
30✔
2561
    }
2562

2563
    public clone() {
2564
        return this.finalizeClone(
4✔
2565
            new InterfaceMethodStatement({
2566
                optional: util.cloneToken(this.tokens.optional),
2567
                functionType: util.cloneToken(this.tokens.functionType),
2568
                name: util.cloneToken(this.tokens.name),
2569
                leftParen: util.cloneToken(this.tokens.leftParen),
2570
                params: this.params?.map(p => p?.clone()),
3✔
2571
                rightParen: util.cloneToken(this.tokens.rightParen),
2572
                as: util.cloneToken(this.tokens.as),
2573
                returnTypeExpression: this.returnTypeExpression?.clone()
12✔
2574
            }),
2575
            ['params']
2576
        );
2577
    }
2578
}
2579

2580
export class ClassStatement extends Statement implements TypedefProvider {
1✔
2581
    constructor(options: {
2582
        class?: Token;
2583
        /**
2584
         * The name of the class (without namespace prefix)
2585
         */
2586
        name: Identifier;
2587
        body: Statement[];
2588
        endClass?: Token;
2589
        extends?: Token;
2590
        parentClassName?: TypeExpression;
2591
    }) {
2592
        super();
708✔
2593
        this.body = options.body ?? [];
708✔
2594
        this.tokens = {
708✔
2595
            name: options.name,
2596
            class: options.class,
2597
            endClass: options.endClass,
2598
            extends: options.extends
2599
        };
2600
        this.parentClassName = options.parentClassName;
708✔
2601
        this.symbolTable = new SymbolTable(`ClassStatement: '${this.tokens.name?.text}'`, () => this.parent?.getSymbolTable());
1,851!
2602

2603
        for (let statement of this.body) {
708✔
2604
            if (isMethodStatement(statement)) {
718✔
2605
                this.methods.push(statement);
373✔
2606
                this.memberMap[statement?.tokens.name?.text.toLowerCase()] = statement;
373!
2607
            } else if (isFieldStatement(statement)) {
345✔
2608
                this.fields.push(statement);
344✔
2609
                this.memberMap[statement?.tokens.name?.text.toLowerCase()] = statement;
344!
2610
            }
2611
        }
2612

2613
        this.location = util.createBoundingLocation(
708✔
2614
            this.parentClassName,
2615
            ...(this.body ?? []),
2,124!
2616
            util.createBoundingLocationFromTokens(this.tokens)
2617
        );
2618
    }
2619

2620
    public readonly kind = AstNodeKind.ClassStatement;
708✔
2621

2622

2623
    public readonly tokens: {
2624
        readonly class?: Token;
2625
        /**
2626
         * The name of the class (without namespace prefix)
2627
         */
2628
        readonly name: Identifier;
2629
        readonly endClass?: Token;
2630
        readonly extends?: Token;
2631
    };
2632
    public readonly body: Statement[];
2633
    public readonly parentClassName: TypeExpression;
2634

2635

2636
    public getName(parseMode: ParseMode) {
2637
        const name = this.tokens.name?.text;
2,394✔
2638
        if (name) {
2,394✔
2639
            const namespace = this.findAncestor<NamespaceStatement>(isNamespaceStatement);
2,392✔
2640
            if (namespace) {
2,392✔
2641
                let namespaceName = namespace.getName(parseMode);
885✔
2642
                let separator = parseMode === ParseMode.BrighterScript ? '.' : '_';
885✔
2643
                return namespaceName + separator + name;
885✔
2644
            } else {
2645
                return name;
1,507✔
2646
            }
2647
        } else {
2648
            //return undefined which will allow outside callers to know that this class doesn't have a name
2649
            return undefined;
2✔
2650
        }
2651
    }
2652

2653
    public get leadingTrivia(): Token[] {
2654
        return this.tokens.class?.leadingTrivia;
1,355!
2655
    }
2656

2657
    public get endTrivia(): Token[] {
UNCOV
2658
        return this.tokens.endClass?.leadingTrivia ?? [];
×
2659
    }
2660

2661
    public readonly memberMap = {} as Record<string, MemberStatement>;
708✔
2662
    public readonly methods = [] as MethodStatement[];
708✔
2663
    public readonly fields = [] as FieldStatement[];
708✔
2664

2665
    public readonly location: Location | undefined;
2666

2667
    transpile(state: BrsTranspileState) {
2668
        let result = [] as TranspileResult;
54✔
2669
        //make the builder
2670
        result.push(...this.getTranspiledBuilder(state));
54✔
2671
        result.push(
54✔
2672
            '\n',
2673
            state.indent()
2674
        );
2675
        //make the class assembler (i.e. the public-facing class creator method)
2676
        result.push(...this.getTranspiledClassFunction(state));
54✔
2677
        return result;
54✔
2678
    }
2679

2680
    getTypedef(state: BrsTranspileState) {
2681
        const result = [] as TranspileResult;
15✔
2682
        for (let comment of util.getLeadingComments(this) ?? []) {
15!
UNCOV
2683
            result.push(
×
2684
                comment.text,
2685
                state.newline,
2686
                state.indent()
2687
            );
2688
        }
2689
        for (let annotation of this.annotations ?? []) {
15!
UNCOV
2690
            result.push(
×
2691
                ...annotation.getTypedef(state),
2692
                state.newline,
2693
                state.indent()
2694
            );
2695
        }
2696
        result.push(
15✔
2697
            'class ',
2698
            this.tokens.name.text
2699
        );
2700
        if (this.parentClassName) {
15✔
2701
            const namespace = this.findAncestor<NamespaceStatement>(isNamespaceStatement);
4✔
2702
            const fqName = util.getFullyQualifiedClassName(
4✔
2703
                this.parentClassName.getName(),
2704
                namespace?.getName(ParseMode.BrighterScript)
12✔
2705
            );
2706
            result.push(
4✔
2707
                ` extends ${fqName}`
2708
            );
2709
        }
2710
        result.push(state.newline);
15✔
2711
        state.blockDepth++;
15✔
2712

2713
        let body = this.body;
15✔
2714
        //inject an empty "new" method if missing
2715
        if (!this.getConstructorFunction()) {
15✔
2716
            const constructor = createMethodStatement('new', TokenKind.Sub);
11✔
2717
            constructor.parent = this;
11✔
2718
            //walk the constructor to set up parent links
2719
            constructor.link();
11✔
2720
            body = [
11✔
2721
                constructor,
2722
                ...this.body
2723
            ];
2724
        }
2725

2726
        for (const member of body) {
15✔
2727
            if (isTypedefProvider(member)) {
35!
2728
                result.push(
35✔
2729
                    state.indent(),
2730
                    ...member.getTypedef(state),
2731
                    state.newline
2732
                );
2733
            }
2734
        }
2735
        state.blockDepth--;
15✔
2736
        result.push(
15✔
2737
            state.indent(),
2738
            'end class'
2739
        );
2740
        return result;
15✔
2741
    }
2742

2743
    /**
2744
     * Find the parent index for this class's parent.
2745
     * For class inheritance, every class is given an index.
2746
     * The base class is index 0, its child is index 1, and so on.
2747
     */
2748
    public getParentClassIndex(state: BrsTranspileState) {
2749
        let myIndex = 0;
124✔
2750
        let stmt = this as ClassStatement;
124✔
2751
        while (stmt) {
124✔
2752
            if (stmt.parentClassName) {
185✔
2753
                const namespace = stmt.findAncestor<NamespaceStatement>(isNamespaceStatement);
62✔
2754
                //find the parent class
2755
                stmt = state.file.getClassFileLink(
62✔
2756
                    stmt.parentClassName.getName(),
2757
                    namespace?.getName(ParseMode.BrighterScript)
186✔
2758
                )?.item;
62✔
2759
                myIndex++;
62✔
2760
            } else {
2761
                break;
123✔
2762
            }
2763
        }
2764
        const result = myIndex - 1;
124✔
2765
        if (result >= 0) {
124✔
2766
            return result;
49✔
2767
        } else {
2768
            return null;
75✔
2769
        }
2770
    }
2771

2772
    public hasParentClass() {
2773
        return !!this.parentClassName;
296✔
2774
    }
2775

2776
    /**
2777
     * Get all ancestor classes, in closest-to-furthest order (i.e. 0 is parent, 1 is grandparent, etc...).
2778
     * This will return an empty array if no ancestors were found
2779
     */
2780
    public getAncestors(state: BrsTranspileState) {
2781
        let ancestors = [] as ClassStatement[];
139✔
2782
        let stmt = this as ClassStatement;
139✔
2783
        while (stmt) {
139✔
2784
            if (stmt.parentClassName) {
209✔
2785
                const namespace = stmt.findAncestor<NamespaceStatement>(isNamespaceStatement);
70✔
2786
                stmt = state.file.getClassFileLink(
70✔
2787
                    stmt.parentClassName.getName(),
2788
                    namespace?.getName(ParseMode.BrighterScript)
210✔
2789
                )?.item;
70!
2790
                ancestors.push(stmt);
70✔
2791
            } else {
2792
                break;
139✔
2793
            }
2794
        }
2795
        return ancestors;
139✔
2796
    }
2797

2798
    private getBuilderName(name: string) {
2799
        if (name.includes('.')) {
129✔
2800
            name = name.replace(/\./gi, '_');
3✔
2801
        }
2802
        return `__${name}_builder`;
129✔
2803
    }
2804

2805
    public getConstructorType() {
2806
        const constructorType = this.getConstructorFunction()?.getType({ flags: SymbolTypeFlag.runtime }) ?? new TypedFunctionType(null);
131✔
2807
        constructorType.returnType = this.getType({ flags: SymbolTypeFlag.runtime });
131✔
2808
        return constructorType;
131✔
2809
    }
2810

2811
    /**
2812
     * Get the constructor function for this class (if exists), or undefined if not exist
2813
     */
2814
    private getConstructorFunction() {
2815
        return this.body.find((stmt) => {
282✔
2816
            return (stmt as MethodStatement)?.tokens.name?.text?.toLowerCase() === 'new';
247!
2817
        }) as MethodStatement;
2818
    }
2819

2820
    /**
2821
     * Return the parameters for the first constructor function for this class
2822
     * @param ancestors The list of ancestors for this class
2823
     * @returns The parameters for the first constructor function for this class
2824
     */
2825
    private getConstructorParams(ancestors: ClassStatement[]) {
2826
        for (let ancestor of ancestors) {
43✔
2827
            const ctor = ancestor?.getConstructorFunction();
28!
2828
            if (ctor) {
28✔
2829
                return ctor.func.parameters;
10✔
2830
            }
2831
        }
2832
        return [];
33✔
2833
    }
2834

2835
    /**
2836
     * Determine if the specified field was declared in one of the ancestor classes
2837
     */
2838
    public isFieldDeclaredByAncestor(fieldName: string, ancestors: ClassStatement[]) {
UNCOV
2839
        let lowerFieldName = fieldName.toLowerCase();
×
2840
        for (let ancestor of ancestors) {
×
2841
            if (ancestor.memberMap[lowerFieldName]) {
×
2842
                return true;
×
2843
            }
2844
        }
UNCOV
2845
        return false;
×
2846
    }
2847

2848
    /**
2849
     * The builder is a function that assigns all of the methods and property names to a class instance.
2850
     * This needs to be a separate function so that child classes can call the builder from their parent
2851
     * without instantiating the parent constructor at that point in time.
2852
     */
2853
    private getTranspiledBuilder(state: BrsTranspileState) {
2854
        let result = [] as TranspileResult;
54✔
2855
        result.push(`function ${this.getBuilderName(this.getName(ParseMode.BrightScript)!)}()\n`);
54✔
2856
        state.blockDepth++;
54✔
2857
        //indent
2858
        result.push(state.indent());
54✔
2859

2860
        /**
2861
         * The lineage of this class. index 0 is a direct parent, index 1 is index 0's parent, etc...
2862
         */
2863
        let ancestors = this.getAncestors(state);
54✔
2864

2865
        //construct parent class or empty object
2866
        if (ancestors[0]) {
54✔
2867
            const ancestorNamespace = ancestors[0].findAncestor<NamespaceStatement>(isNamespaceStatement);
21✔
2868
            let fullyQualifiedClassName = util.getFullyQualifiedClassName(
21✔
2869
                ancestors[0].getName(ParseMode.BrighterScript)!,
2870
                ancestorNamespace?.getName(ParseMode.BrighterScript)
63✔
2871
            );
2872
            result.push(
21✔
2873
                'instance = ',
2874
                this.getBuilderName(fullyQualifiedClassName), '()');
2875
        } else {
2876
            //use an empty object.
2877
            result.push('instance = {}');
33✔
2878
        }
2879
        result.push(
54✔
2880
            state.newline,
2881
            state.indent()
2882
        );
2883
        let parentClassIndex = this.getParentClassIndex(state);
54✔
2884

2885
        let body = this.body;
54✔
2886
        //inject an empty "new" method if missing
2887
        if (!this.getConstructorFunction()) {
54✔
2888
            if (ancestors.length === 0) {
31✔
2889
                body = [
19✔
2890
                    createMethodStatement('new', TokenKind.Sub),
2891
                    ...this.body
2892
                ];
2893
            } else {
2894
                const params = this.getConstructorParams(ancestors);
12✔
2895
                const call = new ExpressionStatement({
12✔
2896
                    expression: new CallExpression({
2897
                        callee: new VariableExpression({
2898
                            name: createToken(TokenKind.Identifier, 'super')
2899
                        }),
2900
                        openingParen: createToken(TokenKind.LeftParen),
2901
                        args: params.map(x => new VariableExpression({
6✔
2902
                            name: util.cloneToken(x.tokens.name)
2903
                        })),
2904
                        closingParen: createToken(TokenKind.RightParen)
2905
                    })
2906
                });
2907
                body = [
12✔
2908
                    new MethodStatement({
2909
                        name: createIdentifier('new'),
2910
                        func: new FunctionExpression({
2911
                            parameters: params.map(x => x.clone()),
6✔
2912
                            body: new Block({
2913
                                statements: [call]
2914
                            }),
2915
                            functionType: createToken(TokenKind.Sub),
2916
                            endFunctionType: createToken(TokenKind.EndSub),
2917
                            leftParen: createToken(TokenKind.LeftParen),
2918
                            rightParen: createToken(TokenKind.RightParen)
2919
                        })
2920
                    }),
2921
                    ...this.body
2922
                ];
2923
            }
2924
        }
2925

2926
        for (let statement of body) {
54✔
2927
            //is field statement
2928
            if (isFieldStatement(statement)) {
84✔
2929
                //do nothing with class fields in this situation, they are handled elsewhere
2930
                continue;
15✔
2931

2932
                //methods
2933
            } else if (isMethodStatement(statement)) {
69!
2934

2935
                //store overridden parent methods as super{parentIndex}_{methodName}
2936
                if (
69✔
2937
                    //is override method
2938
                    statement.tokens.override ||
188✔
2939
                    //is constructor function in child class
2940
                    (statement.tokens.name.text.toLowerCase() === 'new' && ancestors[0])
2941
                ) {
2942
                    result.push(
25✔
2943
                        `instance.super${parentClassIndex}_${statement.tokens.name.text} = instance.${statement.tokens.name.text}`,
2944
                        state.newline,
2945
                        state.indent()
2946
                    );
2947
                }
2948

2949
                state.classStatement = this;
69✔
2950
                state.skipLeadingComments = true;
69✔
2951
                //add leading comments
2952
                if (statement.leadingTrivia.filter(token => token.kind === TokenKind.Comment).length > 0) {
82✔
2953
                    result.push(
2✔
2954
                        ...state.transpileComments(statement.leadingTrivia),
2955
                        state.indent()
2956
                    );
2957
                }
2958
                result.push(
69✔
2959
                    'instance.',
2960
                    state.transpileToken(statement.tokens.name),
2961
                    ' = ',
2962
                    ...statement.transpile(state),
2963
                    state.newline,
2964
                    state.indent()
2965
                );
2966
                state.skipLeadingComments = false;
69✔
2967
                delete state.classStatement;
69✔
2968
            } else {
2969
                //other random statements (probably just comments)
UNCOV
2970
                result.push(
×
2971
                    ...statement.transpile(state),
2972
                    state.newline,
2973
                    state.indent()
2974
                );
2975
            }
2976
        }
2977
        //return the instance
2978
        result.push('return instance\n');
54✔
2979
        state.blockDepth--;
54✔
2980
        result.push(state.indent());
54✔
2981
        result.push(`end function`);
54✔
2982
        return result;
54✔
2983
    }
2984

2985
    /**
2986
     * The class function is the function with the same name as the class. This is the function that
2987
     * consumers should call to create a new instance of that class.
2988
     * This invokes the builder, gets an instance of the class, then invokes the "new" function on that class.
2989
     */
2990
    private getTranspiledClassFunction(state: BrsTranspileState) {
2991
        let result: TranspileResult = state.transpileAnnotations(this);
54✔
2992
        const constructorFunction = this.getConstructorFunction();
54✔
2993
        let constructorParams = [];
54✔
2994
        if (constructorFunction) {
54✔
2995
            constructorParams = constructorFunction.func.parameters;
23✔
2996
        } else {
2997
            constructorParams = this.getConstructorParams(this.getAncestors(state));
31✔
2998
        }
2999

3000
        result.push(
54✔
3001
            state.transpileLeadingComments(this.tokens.class),
3002
            state.sourceNode(this.tokens.class, 'function'),
3003
            state.sourceNode(this.tokens.class, ' '),
3004
            state.sourceNode(this.tokens.name, this.getName(ParseMode.BrightScript)),
3005
            `(`
3006
        );
3007
        let i = 0;
54✔
3008
        for (let param of constructorParams) {
54✔
3009
            if (i > 0) {
17✔
3010
                result.push(', ');
4✔
3011
            }
3012
            result.push(
17✔
3013
                param.transpile(state)
3014
            );
3015
            i++;
17✔
3016
        }
3017
        result.push(
54✔
3018
            ')',
3019
            '\n'
3020
        );
3021

3022
        state.blockDepth++;
54✔
3023
        result.push(state.indent());
54✔
3024
        result.push(`instance = ${this.getBuilderName(this.getName(ParseMode.BrightScript)!)}()\n`);
54✔
3025

3026
        result.push(state.indent());
54✔
3027
        result.push(`instance.new(`);
54✔
3028

3029
        //append constructor arguments
3030
        i = 0;
54✔
3031
        for (let param of constructorParams) {
54✔
3032
            if (i > 0) {
17✔
3033
                result.push(', ');
4✔
3034
            }
3035
            result.push(
17✔
3036
                state.transpileToken(param.tokens.name)
3037
            );
3038
            i++;
17✔
3039
        }
3040
        result.push(
54✔
3041
            ')',
3042
            '\n'
3043
        );
3044

3045
        result.push(state.indent());
54✔
3046
        result.push(`return instance\n`);
54✔
3047

3048
        state.blockDepth--;
54✔
3049
        result.push(state.indent());
54✔
3050
        result.push(`end function`);
54✔
3051
        return result;
54✔
3052
    }
3053

3054
    walk(visitor: WalkVisitor, options: WalkOptions) {
3055
        //visitor-less walk function to do parent linking
3056
        walk(this, 'parentClassName', null, options);
2,772✔
3057

3058
        if (options.walkMode & InternalWalkMode.walkStatements) {
2,772!
3059
            walkArray(this.body, visitor, options, this);
2,772✔
3060
        }
3061
    }
3062

3063
    getType(options: GetTypeOptions) {
3064
        const superClass = this.parentClassName?.getType(options) as ClassType;
561✔
3065

3066
        const resultType = new ClassType(this.getName(ParseMode.BrighterScript), superClass);
561✔
3067

3068
        for (const statement of this.methods) {
561✔
3069
            const funcType = statement?.func.getType({ ...options, typeChain: undefined }); //no typechain needed
297!
3070
            let flag = SymbolTypeFlag.runtime;
297✔
3071
            if (statement.accessModifier?.kind === TokenKind.Private) {
297✔
3072
                flag |= SymbolTypeFlag.private;
9✔
3073
            }
3074
            if (statement.accessModifier?.kind === TokenKind.Protected) {
297✔
3075
                flag |= SymbolTypeFlag.protected;
8✔
3076
            }
3077
            resultType.addMember(statement?.tokens.name?.text, { definingNode: statement }, funcType, flag);
297!
3078
        }
3079
        for (const statement of this.fields) {
561✔
3080
            const fieldType = statement.getType({ ...options, typeChain: undefined }); //no typechain needed
283✔
3081
            let flag = SymbolTypeFlag.runtime;
283✔
3082
            if (statement.isOptional) {
283✔
3083
                flag |= SymbolTypeFlag.optional;
7✔
3084
            }
3085
            if (statement.tokens.accessModifier?.kind === TokenKind.Private) {
283✔
3086
                flag |= SymbolTypeFlag.private;
20✔
3087
            }
3088
            if (statement.tokens.accessModifier?.kind === TokenKind.Protected) {
283✔
3089
                flag |= SymbolTypeFlag.protected;
9✔
3090
            }
3091
            resultType.addMember(statement?.tokens.name?.text, { definingNode: statement, isInstance: true }, fieldType, flag);
283!
3092
        }
3093
        options.typeChain?.push(new TypeChainEntry({ name: resultType.name, type: resultType, data: options.data, astNode: this }));
561✔
3094
        return resultType;
561✔
3095
    }
3096

3097
    public clone() {
3098
        return this.finalizeClone(
11✔
3099
            new ClassStatement({
3100
                class: util.cloneToken(this.tokens.class),
3101
                name: util.cloneToken(this.tokens.name),
3102
                body: this.body?.map(x => x?.clone()),
11✔
3103
                endClass: util.cloneToken(this.tokens.endClass),
3104
                extends: util.cloneToken(this.tokens.extends),
3105
                parentClassName: this.parentClassName?.clone()
33✔
3106
            }),
3107
            ['body', 'parentClassName']
3108
        );
3109
    }
3110
}
3111

3112
const accessModifiers = [
1✔
3113
    TokenKind.Public,
3114
    TokenKind.Protected,
3115
    TokenKind.Private
3116
];
3117
export class MethodStatement extends FunctionStatement {
1✔
3118
    constructor(
3119
        options: {
3120
            modifiers?: Token | Token[];
3121
            name: Identifier;
3122
            func: FunctionExpression;
3123
            override?: Token;
3124
        }
3125
    ) {
3126
        super(options);
415✔
3127
        if (options.modifiers) {
415✔
3128
            if (Array.isArray(options.modifiers)) {
40✔
3129
                this.modifiers.push(...options.modifiers);
4✔
3130
            } else {
3131
                this.modifiers.push(options.modifiers);
36✔
3132
            }
3133
        }
3134
        this.tokens = {
415✔
3135
            ...this.tokens,
3136
            override: options.override
3137
        };
3138
        this.location = util.createBoundingLocation(
415✔
3139
            ...(this.modifiers),
3140
            util.createBoundingLocationFromTokens(this.tokens),
3141
            this.func
3142
        );
3143
    }
3144

3145
    public readonly kind = AstNodeKind.MethodStatement as AstNodeKind;
415✔
3146

3147
    public readonly modifiers: Token[] = [];
415✔
3148

3149
    public readonly tokens: {
3150
        readonly name: Identifier;
3151
        readonly override?: Token;
3152
    };
3153

3154
    public get accessModifier() {
3155
        return this.modifiers.find(x => accessModifiers.includes(x.kind));
704✔
3156
    }
3157

3158
    public readonly location: Location | undefined;
3159

3160
    /**
3161
     * Get the name of this method.
3162
     */
3163
    public getName(parseMode: ParseMode) {
3164
        return this.tokens.name.text;
376✔
3165
    }
3166

3167
    public get leadingTrivia(): Token[] {
3168
        return this.func.leadingTrivia;
834✔
3169
    }
3170

3171
    transpile(state: BrsTranspileState) {
3172
        if (this.tokens.name.text.toLowerCase() === 'new') {
69✔
3173
            this.ensureSuperConstructorCall(state);
54✔
3174
            //TODO we need to undo this at the bottom of this method
3175
            this.injectFieldInitializersForConstructor(state);
54✔
3176
        }
3177
        //TODO - remove type information from these methods because that doesn't work
3178
        //convert the `super` calls into the proper methods
3179
        const parentClassIndex = state.classStatement.getParentClassIndex(state);
69✔
3180
        const visitor = createVisitor({
69✔
3181
            VariableExpression: e => {
3182
                if (e.tokens.name.text.toLocaleLowerCase() === 'super') {
73✔
3183
                    state.editor.setProperty(e.tokens.name, 'text', `m.super${parentClassIndex}_new`);
21✔
3184
                }
3185
            },
3186
            DottedGetExpression: e => {
3187
                const beginningVariable = util.findBeginningVariableExpression(e);
30✔
3188
                const lowerName = beginningVariable?.getName(ParseMode.BrighterScript).toLowerCase();
30!
3189
                if (lowerName === 'super') {
30✔
3190
                    state.editor.setProperty(beginningVariable.tokens.name, 'text', 'm');
7✔
3191
                    state.editor.setProperty(e.tokens.name, 'text', `super${parentClassIndex}_${e.tokens.name.text}`);
7✔
3192
                }
3193
            }
3194
        });
3195
        const walkOptions: WalkOptions = { walkMode: WalkMode.visitExpressions };
69✔
3196
        for (const statement of this.func.body.statements) {
69✔
3197
            visitor(statement, undefined);
67✔
3198
            statement.walk(visitor, walkOptions);
67✔
3199
        }
3200
        return this.func.transpile(state);
69✔
3201
    }
3202

3203
    getTypedef(state: BrsTranspileState) {
3204
        const result: TranspileResult = [];
23✔
3205
        for (let comment of util.getLeadingComments(this) ?? []) {
23!
UNCOV
3206
            result.push(
×
3207
                comment.text,
3208
                state.newline,
3209
                state.indent()
3210
            );
3211
        }
3212
        for (let annotation of this.annotations ?? []) {
23✔
3213
            result.push(
2✔
3214
                ...annotation.getTypedef(state),
3215
                state.newline,
3216
                state.indent()
3217
            );
3218
        }
3219
        if (this.accessModifier) {
23✔
3220
            result.push(
8✔
3221
                this.accessModifier.text,
3222
                ' '
3223
            );
3224
        }
3225
        if (this.tokens.override) {
23✔
3226
            result.push('override ');
1✔
3227
        }
3228
        result.push(
23✔
3229
            ...this.func.getTypedef(state)
3230
        );
3231
        return result;
23✔
3232
    }
3233

3234
    /**
3235
     * All child classes must call the parent constructor. The type checker will warn users when they don't call it in their own class,
3236
     * but we still need to call it even if they have omitted it. This injects the super call if it's missing
3237
     */
3238
    private ensureSuperConstructorCall(state: BrsTranspileState) {
3239
        //if this class doesn't extend another class, quit here
3240
        if (state.classStatement!.getAncestors(state).length === 0) {
54✔
3241
            return;
33✔
3242
        }
3243

3244
        //check whether any calls to super exist
3245
        let containsSuperCall =
3246
            this.func.body.statements.findIndex((x) => {
21✔
3247
                //is a call statement
3248
                return isExpressionStatement(x) && isCallExpression(x.expression) &&
21✔
3249
                    //is a call to super
3250
                    util.findBeginningVariableExpression(x.expression.callee as any).tokens.name?.text.toLowerCase() === 'super';
60!
3251
            }) !== -1;
3252

3253
        //if a call to super exists, quit here
3254
        if (containsSuperCall) {
21✔
3255
            return;
20✔
3256
        }
3257

3258
        //this is a child class, and the constructor doesn't contain a call to super. Inject one
3259
        const superCall = new ExpressionStatement({
1✔
3260
            expression: new CallExpression({
3261
                callee: new VariableExpression({
3262
                    name: {
3263
                        kind: TokenKind.Identifier,
3264
                        text: 'super',
3265
                        isReserved: false,
3266
                        location: state.classStatement.tokens.name.location,
3267
                        leadingWhitespace: '',
3268
                        leadingTrivia: []
3269
                    }
3270
                }),
3271
                openingParen: {
3272
                    kind: TokenKind.LeftParen,
3273
                    text: '(',
3274
                    isReserved: false,
3275
                    location: state.classStatement.tokens.name.location,
3276
                    leadingWhitespace: '',
3277
                    leadingTrivia: []
3278
                },
3279
                closingParen: {
3280
                    kind: TokenKind.RightParen,
3281
                    text: ')',
3282
                    isReserved: false,
3283
                    location: state.classStatement.tokens.name.location,
3284
                    leadingWhitespace: '',
3285
                    leadingTrivia: []
3286
                },
3287
                args: []
3288
            })
3289
        });
3290
        state.editor.arrayUnshift(this.func.body.statements, superCall);
1✔
3291
    }
3292

3293
    /**
3294
     * Inject field initializers at the top of the `new` function (after any present `super()` call)
3295
     */
3296
    private injectFieldInitializersForConstructor(state: BrsTranspileState) {
3297
        let startingIndex = state.classStatement!.hasParentClass() ? 1 : 0;
54✔
3298

3299
        let newStatements = [] as Statement[];
54✔
3300
        //insert the field initializers in order
3301
        for (let field of state.classStatement!.fields) {
54✔
3302
            let thisQualifiedName = { ...field.tokens.name };
15✔
3303
            thisQualifiedName.text = 'm.' + field.tokens.name?.text;
15!
3304
            const fieldAssignment = field.initialValue
15✔
3305
                ? new AssignmentStatement({
15✔
3306
                    equals: field.tokens.equals,
3307
                    name: thisQualifiedName,
3308
                    value: field.initialValue
3309
                })
3310
                : new AssignmentStatement({
3311
                    equals: createToken(TokenKind.Equal, '=', field.tokens.name.location),
3312
                    name: thisQualifiedName,
3313
                    //if there is no initial value, set the initial value to `invalid`
3314
                    value: createInvalidLiteral('invalid', field.tokens.name.location)
3315
                });
3316
            // Add parent so namespace lookups work
3317
            fieldAssignment.parent = state.classStatement;
15✔
3318
            newStatements.push(fieldAssignment);
15✔
3319
        }
3320
        state.editor.arraySplice(this.func.body.statements, startingIndex, 0, ...newStatements);
54✔
3321
    }
3322

3323
    walk(visitor: WalkVisitor, options: WalkOptions) {
3324
        if (options.walkMode & InternalWalkMode.walkExpressions) {
2,270✔
3325
            walk(this, 'func', visitor, options);
1,819✔
3326
        }
3327
    }
3328

3329
    public clone() {
3330
        return this.finalizeClone(
5✔
3331
            new MethodStatement({
3332
                modifiers: this.modifiers?.map(m => util.cloneToken(m)),
1✔
3333
                name: util.cloneToken(this.tokens.name),
3334
                func: this.func?.clone(),
15✔
3335
                override: util.cloneToken(this.tokens.override)
3336
            }),
3337
            ['func']
3338
        );
3339
    }
3340
}
3341

3342
export class FieldStatement extends Statement implements TypedefProvider {
1✔
3343
    constructor(options: {
3344
        accessModifier?: Token;
3345
        name: Identifier;
3346
        as?: Token;
3347
        typeExpression?: TypeExpression;
3348
        equals?: Token;
3349
        initialValue?: Expression;
3350
        optional?: Token;
3351
    }) {
3352
        super();
344✔
3353
        this.tokens = {
344✔
3354
            accessModifier: options.accessModifier,
3355
            name: options.name,
3356
            as: options.as,
3357
            equals: options.equals,
3358
            optional: options.optional
3359
        };
3360
        this.typeExpression = options.typeExpression;
344✔
3361
        this.initialValue = options.initialValue;
344✔
3362

3363
        this.location = util.createBoundingLocation(
344✔
3364
            util.createBoundingLocationFromTokens(this.tokens),
3365
            this.typeExpression,
3366
            this.initialValue
3367
        );
3368
    }
3369

3370
    public readonly tokens: {
3371
        readonly accessModifier?: Token;
3372
        readonly name: Identifier;
3373
        readonly as?: Token;
3374
        readonly equals?: Token;
3375
        readonly optional?: Token;
3376
    };
3377

3378
    public readonly typeExpression?: TypeExpression;
3379
    public readonly initialValue?: Expression;
3380

3381
    public readonly kind = AstNodeKind.FieldStatement;
344✔
3382

3383
    /**
3384
     * Derive a ValueKind from the type token, or the initial value.
3385
     * Defaults to `DynamicType`
3386
     */
3387
    getType(options: GetTypeOptions) {
3388
        let initialValueType = this.initialValue?.getType({ ...options, flags: SymbolTypeFlag.runtime });
333✔
3389

3390
        if (isInvalidType(initialValueType) || isVoidType(initialValueType) || isUninitializedType(initialValueType)) {
333✔
3391
            initialValueType = undefined;
4✔
3392
        }
3393

3394
        return this.typeExpression?.getType({ ...options, flags: SymbolTypeFlag.typetime }) ??
333✔
3395
            util.getDefaultTypeFromValueType(initialValueType) ??
333✔
3396
            DynamicType.instance;
3397
    }
3398

3399
    public readonly location: Location | undefined;
3400

3401
    public get leadingTrivia(): Token[] {
3402
        return this.tokens.accessModifier?.leadingTrivia ?? this.tokens.optional?.leadingTrivia ?? this.tokens.name.leadingTrivia;
671✔
3403
    }
3404

3405
    public get isOptional() {
3406
        return !!this.tokens.optional;
302✔
3407
    }
3408

3409
    transpile(state: BrsTranspileState): TranspileResult {
UNCOV
3410
        throw new Error('transpile not implemented for ' + Object.getPrototypeOf(this).constructor.name);
×
3411
    }
3412

3413
    getTypedef(state: BrsTranspileState) {
3414
        const result = [];
12✔
3415
        if (this.tokens.name) {
12!
3416
            for (let comment of util.getLeadingComments(this) ?? []) {
12!
UNCOV
3417
                result.push(
×
3418
                    comment.text,
3419
                    state.newline,
3420
                    state.indent()
3421
                );
3422
            }
3423
            for (let annotation of this.annotations ?? []) {
12✔
3424
                result.push(
2✔
3425
                    ...annotation.getTypedef(state),
3426
                    state.newline,
3427
                    state.indent()
3428
                );
3429
            }
3430

3431
            let type = this.getType({ flags: SymbolTypeFlag.typetime });
12✔
3432
            if (isInvalidType(type) || isVoidType(type) || isUninitializedType(type)) {
12!
UNCOV
3433
                type = DynamicType.instance;
×
3434
            }
3435

3436
            result.push(
12✔
3437
                this.tokens.accessModifier?.text ?? 'public',
72✔
3438
                ' '
3439
            );
3440
            if (this.isOptional) {
12!
UNCOV
3441
                result.push(this.tokens.optional.text, ' ');
×
3442
            }
3443
            result.push(this.tokens.name?.text,
12!
3444
                ' as ',
3445
                type.toTypeString()
3446
            );
3447
        }
3448
        return result;
12✔
3449
    }
3450

3451
    walk(visitor: WalkVisitor, options: WalkOptions) {
3452
        if (options.walkMode & InternalWalkMode.walkExpressions) {
1,687✔
3453
            walk(this, 'typeExpression', visitor, options);
1,473✔
3454
            walk(this, 'initialValue', visitor, options);
1,473✔
3455
        }
3456
    }
3457

3458
    public clone() {
3459
        return this.finalizeClone(
5✔
3460
            new FieldStatement({
3461
                accessModifier: util.cloneToken(this.tokens.accessModifier),
3462
                name: util.cloneToken(this.tokens.name),
3463
                as: util.cloneToken(this.tokens.as),
3464
                typeExpression: this.typeExpression?.clone(),
15✔
3465
                equals: util.cloneToken(this.tokens.equals),
3466
                initialValue: this.initialValue?.clone(),
15✔
3467
                optional: util.cloneToken(this.tokens.optional)
3468
            }),
3469
            ['initialValue']
3470
        );
3471
    }
3472
}
3473

3474
export type MemberStatement = FieldStatement | MethodStatement;
3475

3476
export class TryCatchStatement extends Statement {
1✔
3477
    constructor(options?: {
3478
        try?: Token;
3479
        endTry?: Token;
3480
        tryBranch?: Block;
3481
        catchStatement?: CatchStatement;
3482
    }) {
3483
        super();
40✔
3484
        this.tokens = {
40✔
3485
            try: options.try,
3486
            endTry: options.endTry
3487
        };
3488
        this.tryBranch = options.tryBranch;
40✔
3489
        this.catchStatement = options.catchStatement;
40✔
3490
        this.location = util.createBoundingLocation(
40✔
3491
            this.tokens.try,
3492
            this.tryBranch,
3493
            this.catchStatement,
3494
            this.tokens.endTry
3495
        );
3496
    }
3497

3498
    public readonly tokens: {
3499
        readonly try?: Token;
3500
        readonly endTry?: Token;
3501
    };
3502

3503
    public readonly tryBranch: Block;
3504
    public readonly catchStatement: CatchStatement;
3505

3506
    public readonly kind = AstNodeKind.TryCatchStatement;
40✔
3507

3508
    public readonly location: Location | undefined;
3509

3510
    public transpile(state: BrsTranspileState): TranspileResult {
3511
        return [
7✔
3512
            state.transpileToken(this.tokens.try, 'try'),
3513
            ...this.tryBranch.transpile(state),
3514
            state.newline,
3515
            state.indent(),
3516
            ...(this.catchStatement?.transpile(state) ?? ['catch']),
42!
3517
            state.newline,
3518
            state.indent(),
3519
            state.transpileToken(this.tokens.endTry!, 'end try')
3520
        ];
3521
    }
3522

3523
    public walk(visitor: WalkVisitor, options: WalkOptions) {
3524
        if (this.tryBranch && options.walkMode & InternalWalkMode.walkStatements) {
93!
3525
            walk(this, 'tryBranch', visitor, options);
93✔
3526
            walk(this, 'catchStatement', visitor, options);
93✔
3527
        }
3528
    }
3529

3530
    public get leadingTrivia(): Token[] {
3531
        return this.tokens.try?.leadingTrivia ?? [];
88!
3532
    }
3533

3534
    public get endTrivia(): Token[] {
3535
        return this.tokens.endTry?.leadingTrivia ?? [];
1!
3536
    }
3537

3538
    public clone() {
3539
        return this.finalizeClone(
3✔
3540
            new TryCatchStatement({
3541
                try: util.cloneToken(this.tokens.try),
3542
                endTry: util.cloneToken(this.tokens.endTry),
3543
                tryBranch: this.tryBranch?.clone(),
9✔
3544
                catchStatement: this.catchStatement?.clone()
9✔
3545
            }),
3546
            ['tryBranch', 'catchStatement']
3547
        );
3548
    }
3549
}
3550

3551
export class CatchStatement extends Statement {
1✔
3552
    constructor(options?: {
3553
        catch?: Token;
3554
        exceptionVariableExpression?: Expression;
3555
        catchBranch?: Block;
3556
    }) {
3557
        super();
37✔
3558
        this.tokens = {
37✔
3559
            catch: options?.catch
111!
3560
        };
3561
        this.exceptionVariableExpression = options?.exceptionVariableExpression;
37!
3562
        this.catchBranch = options?.catchBranch;
37!
3563
        this.location = util.createBoundingLocation(
37✔
3564
            this.tokens.catch,
3565
            this.exceptionVariableExpression,
3566
            this.catchBranch
3567
        );
3568
    }
3569

3570
    public readonly tokens: {
3571
        readonly catch?: Token;
3572
    };
3573

3574
    public readonly exceptionVariableExpression?: Expression;
3575

3576
    public readonly catchBranch?: Block;
3577

3578
    public readonly kind = AstNodeKind.CatchStatement;
37✔
3579

3580
    public readonly location: Location | undefined;
3581

3582
    public transpile(state: BrsTranspileState): TranspileResult {
3583
        return [
7✔
3584
            state.transpileToken(this.tokens.catch, 'catch'),
3585
            ' ',
3586
            this.exceptionVariableExpression?.transpile(state) ?? [
42✔
3587
                //use the variable named `e` if it doesn't exist in this function body. otherwise use '__bsc_error' just to make sure we're out of the way
3588
                this.getSymbolTable()?.hasSymbol('e', SymbolTypeFlag.runtime)
6!
3589
                    ? '__bsc_error'
2✔
3590
                    : 'e'
3591
            ],
3592
            ...(this.catchBranch?.transpile(state) ?? [])
42!
3593
        ];
3594
    }
3595

3596
    public walk(visitor: WalkVisitor, options: WalkOptions) {
3597
        if (this.catchBranch && options.walkMode & InternalWalkMode.walkStatements) {
90!
3598
            walk(this, 'catchBranch', visitor, options);
90✔
3599
        }
3600
    }
3601

3602
    public get leadingTrivia(): Token[] {
3603
        return this.tokens.catch?.leadingTrivia ?? [];
50!
3604
    }
3605

3606
    public clone() {
3607
        return this.finalizeClone(
2✔
3608
            new CatchStatement({
3609
                catch: util.cloneToken(this.tokens.catch),
3610
                exceptionVariableExpression: this.exceptionVariableExpression?.clone(),
6!
3611
                catchBranch: this.catchBranch?.clone()
6✔
3612
            }),
3613
            ['catchBranch']
3614
        );
3615
    }
3616
}
3617

3618
export class ThrowStatement extends Statement {
1✔
3619
    constructor(options?: {
3620
        throw?: Token;
3621
        expression?: Expression;
3622
    }) {
3623
        super();
14✔
3624
        this.tokens = {
14✔
3625
            throw: options.throw
3626
        };
3627
        this.expression = options.expression;
14✔
3628
        this.location = util.createBoundingLocation(
14✔
3629
            this.tokens.throw,
3630
            this.expression
3631
        );
3632
    }
3633

3634
    public readonly tokens: {
3635
        readonly throw?: Token;
3636
    };
3637
    public readonly expression?: Expression;
3638

3639
    public readonly kind = AstNodeKind.ThrowStatement;
14✔
3640

3641
    public readonly location: Location | undefined;
3642

3643
    public transpile(state: BrsTranspileState) {
3644
        const result = [
5✔
3645
            state.transpileToken(this.tokens.throw, 'throw'),
3646
            ' '
3647
        ] as TranspileResult;
3648

3649
        //if we have an expression, transpile it
3650
        if (this.expression) {
5✔
3651
            result.push(
4✔
3652
                ...this.expression.transpile(state)
3653
            );
3654

3655
            //no expression found. Rather than emit syntax errors, provide a generic error message
3656
        } else {
3657
            result.push('"User-specified exception"');
1✔
3658
        }
3659
        return result;
5✔
3660
    }
3661

3662
    public walk(visitor: WalkVisitor, options: WalkOptions) {
3663
        if (this.expression && options.walkMode & InternalWalkMode.walkExpressions) {
38✔
3664
            walk(this, 'expression', visitor, options);
30✔
3665
        }
3666
    }
3667

3668
    public get leadingTrivia(): Token[] {
3669
        return this.tokens.throw?.leadingTrivia ?? [];
54!
3670
    }
3671

3672
    public clone() {
3673
        return this.finalizeClone(
2✔
3674
            new ThrowStatement({
3675
                throw: util.cloneToken(this.tokens.throw),
3676
                expression: this.expression?.clone()
6✔
3677
            }),
3678
            ['expression']
3679
        );
3680
    }
3681
}
3682

3683

3684
export class EnumStatement extends Statement implements TypedefProvider {
1✔
3685
    constructor(options: {
3686
        enum?: Token;
3687
        name: Identifier;
3688
        endEnum?: Token;
3689
        body: Array<EnumMemberStatement>;
3690
    }) {
3691
        super();
187✔
3692
        this.tokens = {
187✔
3693
            enum: options.enum,
3694
            name: options.name,
3695
            endEnum: options.endEnum
3696
        };
3697
        this.symbolTable = new SymbolTable('Enum');
187✔
3698
        this.body = options.body ?? [];
187✔
3699
    }
3700

3701
    public readonly tokens: {
3702
        readonly enum?: Token;
3703
        readonly name: Identifier;
3704
        readonly endEnum?: Token;
3705
    };
3706
    public readonly body: Array<EnumMemberStatement>;
3707

3708
    public readonly kind = AstNodeKind.EnumStatement;
187✔
3709

3710
    public get location(): Location | undefined {
3711
        return util.createBoundingLocation(
175✔
3712
            this.tokens.enum,
3713
            this.tokens.name,
3714
            ...this.body,
3715
            this.tokens.endEnum
3716
        );
3717
    }
3718

3719
    public getMembers() {
3720
        const result = [] as EnumMemberStatement[];
365✔
3721
        for (const statement of this.body) {
365✔
3722
            if (isEnumMemberStatement(statement)) {
763!
3723
                result.push(statement);
763✔
3724
            }
3725
        }
3726
        return result;
365✔
3727
    }
3728

3729
    public get leadingTrivia(): Token[] {
3730
        return this.tokens.enum?.leadingTrivia;
527!
3731
    }
3732

3733
    public get endTrivia(): Token[] {
UNCOV
3734
        return this.tokens.endEnum?.leadingTrivia ?? [];
×
3735
    }
3736

3737
    /**
3738
     * Get a map of member names and their values.
3739
     * All values are stored as their AST LiteralExpression representation (i.e. string enum values include the wrapping quotes)
3740
     */
3741
    public getMemberValueMap() {
3742
        const result = new Map<string, string>();
59✔
3743
        const members = this.getMembers();
59✔
3744
        let currentIntValue = 0;
59✔
3745
        for (const member of members) {
59✔
3746
            //if there is no value, assume an integer and increment the int counter
3747
            if (!member.value) {
148✔
3748
                result.set(member.name?.toLowerCase(), currentIntValue.toString());
33!
3749
                currentIntValue++;
33✔
3750

3751
                //if explicit integer value, use it and increment the int counter
3752
            } else if (isLiteralExpression(member.value) && member.value.tokens.value.kind === TokenKind.IntegerLiteral) {
115✔
3753
                //try parsing as integer literal, then as hex integer literal.
3754
                let tokenIntValue = util.parseInt(member.value.tokens.value.text) ?? util.parseInt(member.value.tokens.value.text.replace(/&h/i, '0x'));
29✔
3755
                if (tokenIntValue !== undefined) {
29!
3756
                    currentIntValue = tokenIntValue;
29✔
3757
                    currentIntValue++;
29✔
3758
                }
3759
                result.set(member.name?.toLowerCase(), member.value.tokens.value.text);
29!
3760

3761
                //simple unary expressions (like `-1`)
3762
            } else if (isUnaryExpression(member.value) && isLiteralExpression(member.value.right)) {
86✔
3763
                result.set(member.name?.toLowerCase(), member.value.tokens.operator.text + member.value.right.tokens.value.text);
1!
3764

3765
                //all other values
3766
            } else {
3767
                result.set(member.name?.toLowerCase(), (member.value as LiteralExpression)?.tokens?.value?.text ?? 'invalid');
85!
3768
            }
3769
        }
3770
        return result;
59✔
3771
    }
3772

3773
    public getMemberValue(name: string) {
3774
        return this.getMemberValueMap().get(name.toLowerCase());
56✔
3775
    }
3776

3777
    /**
3778
     * The name of the enum (without the namespace prefix)
3779
     */
3780
    public get name() {
3781
        return this.tokens.name?.text;
1!
3782
    }
3783

3784
    /**
3785
     * The name of the enum WITH its leading namespace (if applicable)
3786
     */
3787
    public get fullName() {
3788
        const name = this.tokens.name?.text;
739!
3789
        if (name) {
739!
3790
            const namespace = this.findAncestor<NamespaceStatement>(isNamespaceStatement);
739✔
3791

3792
            if (namespace) {
739✔
3793
                let namespaceName = namespace.getName(ParseMode.BrighterScript);
224✔
3794
                return `${namespaceName}.${name}`;
224✔
3795
            } else {
3796
                return name;
515✔
3797
            }
3798
        } else {
3799
            //return undefined which will allow outside callers to know that this doesn't have a name
UNCOV
3800
            return undefined;
×
3801
        }
3802
    }
3803

3804
    transpile(state: BrsTranspileState) {
3805
        //enum declarations don't exist at runtime, so just transpile comments and trivia
3806
        return [
28✔
3807
            state.transpileAnnotations(this),
3808
            state.transpileLeadingComments(this.tokens.enum)
3809
        ];
3810
    }
3811

3812
    getTypedef(state: BrsTranspileState) {
3813
        const result = [] as TranspileResult;
1✔
3814
        for (let comment of util.getLeadingComments(this) ?? []) {
1!
UNCOV
3815
            result.push(
×
3816
                comment.text,
3817
                state.newline,
3818
                state.indent()
3819
            );
3820
        }
3821
        for (let annotation of this.annotations ?? []) {
1!
UNCOV
3822
            result.push(
×
3823
                ...annotation.getTypedef(state),
3824
                state.newline,
3825
                state.indent()
3826
            );
3827
        }
3828
        result.push(
1✔
3829
            this.tokens.enum?.text ?? 'enum',
6!
3830
            ' ',
3831
            this.tokens.name.text
3832
        );
3833
        result.push(state.newline);
1✔
3834
        state.blockDepth++;
1✔
3835
        for (const member of this.body) {
1✔
3836
            if (isTypedefProvider(member)) {
1!
3837
                result.push(
1✔
3838
                    state.indent(),
3839
                    ...member.getTypedef(state),
3840
                    state.newline
3841
                );
3842
            }
3843
        }
3844
        state.blockDepth--;
1✔
3845
        result.push(
1✔
3846
            state.indent(),
3847
            this.tokens.endEnum?.text ?? 'end enum'
6!
3848
        );
3849
        return result;
1✔
3850
    }
3851

3852
    walk(visitor: WalkVisitor, options: WalkOptions) {
3853
        if (options.walkMode & InternalWalkMode.walkStatements) {
1,162!
3854
            walkArray(this.body, visitor, options, this);
1,162✔
3855

3856
        }
3857
    }
3858

3859
    getType(options: GetTypeOptions) {
3860
        const members = this.getMembers();
153✔
3861

3862
        const resultType = new EnumType(
153✔
3863
            this.fullName,
3864
            members[0]?.getType(options).underlyingType
459✔
3865
        );
3866
        resultType.pushMemberProvider(() => this.getSymbolTable());
647✔
3867
        for (const statement of members) {
153✔
3868
            const memberType = statement.getType({ ...options, typeChain: undefined });
306✔
3869
            memberType.parentEnumType = resultType;
306✔
3870
            resultType.addMember(statement?.tokens?.name?.text, { definingNode: statement }, memberType, SymbolTypeFlag.runtime);
306!
3871
        }
3872
        return resultType;
153✔
3873
    }
3874

3875
    public clone() {
3876
        return this.finalizeClone(
6✔
3877
            new EnumStatement({
3878
                enum: util.cloneToken(this.tokens.enum),
3879
                name: util.cloneToken(this.tokens.name),
3880
                endEnum: util.cloneToken(this.tokens.endEnum),
3881
                body: this.body?.map(x => x?.clone())
4✔
3882
            }),
3883
            ['body']
3884
        );
3885
    }
3886
}
3887

3888
export class EnumMemberStatement extends Statement implements TypedefProvider {
1✔
3889
    public constructor(options: {
3890
        name: Identifier;
3891
        equals?: Token;
3892
        value?: Expression;
3893
    }) {
3894
        super();
360✔
3895
        this.tokens = {
360✔
3896
            name: options.name,
3897
            equals: options.equals
3898
        };
3899
        this.value = options.value;
360✔
3900
    }
3901

3902
    public readonly tokens: {
3903
        readonly name: Identifier;
3904
        readonly equals?: Token;
3905
    };
3906
    public readonly value?: Expression;
3907

3908
    public readonly kind = AstNodeKind.EnumMemberStatement;
360✔
3909

3910
    public get location() {
3911
        return util.createBoundingLocation(
592✔
3912
            this.tokens.name,
3913
            this.tokens.equals,
3914
            this.value
3915
        );
3916
    }
3917

3918
    /**
3919
     * The name of the member
3920
     */
3921
    public get name() {
3922
        return this.tokens.name.text;
447✔
3923
    }
3924

3925
    public get leadingTrivia(): Token[] {
3926
        return this.tokens.name.leadingTrivia;
1,429✔
3927
    }
3928

3929
    public transpile(state: BrsTranspileState): TranspileResult {
UNCOV
3930
        return [];
×
3931
    }
3932

3933
    getTypedef(state: BrsTranspileState): TranspileResult {
3934
        const result: TranspileResult = [];
1✔
3935
        for (let comment of util.getLeadingComments(this) ?? []) {
1!
UNCOV
3936
            result.push(
×
3937
                comment.text,
3938
                state.newline,
3939
                state.indent()
3940
            );
3941
        }
3942
        result.push(this.tokens.name.text);
1✔
3943
        if (this.tokens.equals) {
1!
UNCOV
3944
            result.push(' ', this.tokens.equals.text, ' ');
×
3945
            if (this.value) {
×
3946
                result.push(
×
3947
                    ...this.value.transpile(state)
3948
                );
3949
            }
3950
        }
3951
        return result;
1✔
3952
    }
3953

3954
    walk(visitor: WalkVisitor, options: WalkOptions) {
3955
        if (this.value && options.walkMode & InternalWalkMode.walkExpressions) {
2,808✔
3956
            walk(this, 'value', visitor, options);
1,352✔
3957
        }
3958
    }
3959

3960
    getType(options: GetTypeOptions) {
3961
        return new EnumMemberType(
456✔
3962
            (this.parent as EnumStatement)?.fullName,
1,368!
3963
            this.tokens?.name?.text,
2,736!
3964
            this.value?.getType(options)
1,368✔
3965
        );
3966
    }
3967

3968
    public clone() {
3969
        return this.finalizeClone(
3✔
3970
            new EnumMemberStatement({
3971
                name: util.cloneToken(this.tokens.name),
3972
                equals: util.cloneToken(this.tokens.equals),
3973
                value: this.value?.clone()
9✔
3974
            }),
3975
            ['value']
3976
        );
3977
    }
3978
}
3979

3980
export class ConstStatement extends Statement implements TypedefProvider {
1✔
3981
    public constructor(options: {
3982
        const?: Token;
3983
        name: Identifier;
3984
        equals?: Token;
3985
        value: Expression;
3986
    }) {
3987
        super();
163✔
3988
        this.tokens = {
163✔
3989
            const: options.const,
3990
            name: options.name,
3991
            equals: options.equals
3992
        };
3993
        this.value = options.value;
163✔
3994
        this.location = util.createBoundingLocation(this.tokens.const, this.tokens.name, this.tokens.equals, this.value);
163✔
3995
    }
3996

3997
    public readonly tokens: {
3998
        readonly const: Token;
3999
        readonly name: Identifier;
4000
        readonly equals: Token;
4001
    };
4002
    public readonly value: Expression;
4003

4004
    public readonly kind = AstNodeKind.ConstStatement;
163✔
4005

4006
    public readonly location: Location | undefined;
4007

4008
    public get name() {
UNCOV
4009
        return this.tokens.name.text;
×
4010
    }
4011

4012
    public get leadingTrivia(): Token[] {
4013
        return this.tokens.const?.leadingTrivia;
487!
4014
    }
4015

4016
    /**
4017
     * The name of the statement WITH its leading namespace (if applicable)
4018
     */
4019
    public get fullName() {
4020
        const name = this.tokens.name?.text;
64!
4021
        if (name) {
64!
4022
            const namespace = this.findAncestor<NamespaceStatement>(isNamespaceStatement);
64✔
4023
            if (namespace) {
64✔
4024
                let namespaceName = namespace.getName(ParseMode.BrighterScript);
31✔
4025
                return `${namespaceName}.${name}`;
31✔
4026
            } else {
4027
                return name;
33✔
4028
            }
4029
        } else {
4030
            //return undefined which will allow outside callers to know that this doesn't have a name
UNCOV
4031
            return undefined;
×
4032
        }
4033
    }
4034

4035
    public transpile(state: BrsTranspileState): TranspileResult {
4036
        //const declarations don't exist at runtime, so just transpile comments and trivia
4037
        return [
27✔
4038
            state.transpileAnnotations(this),
4039
            state.transpileLeadingComments(this.tokens.const)
4040
        ];
4041
    }
4042

4043
    getTypedef(state: BrsTranspileState): TranspileResult {
4044
        const result: TranspileResult = [];
3✔
4045
        for (let comment of util.getLeadingComments(this) ?? []) {
3!
UNCOV
4046
            result.push(
×
4047
                comment.text,
4048
                state.newline,
4049
                state.indent()
4050
            );
4051
        }
4052
        result.push(
3✔
4053
            this.tokens.const ? state.tokenToSourceNode(this.tokens.const) : 'const',
3!
4054
            ' ',
4055
            state.tokenToSourceNode(this.tokens.name),
4056
            ' ',
4057
            this.tokens.equals ? state.tokenToSourceNode(this.tokens.equals) : '=',
3!
4058
            ' ',
4059
            ...this.value.transpile(state)
4060
        );
4061
        return result;
3✔
4062
    }
4063

4064
    walk(visitor: WalkVisitor, options: WalkOptions) {
4065
        if (this.value && options.walkMode & InternalWalkMode.walkExpressions) {
1,077✔
4066
            walk(this, 'value', visitor, options);
934✔
4067
        }
4068
    }
4069

4070
    getType(options: GetTypeOptions) {
4071
        return this.value.getType(options);
155✔
4072
    }
4073

4074
    public clone() {
4075
        return this.finalizeClone(
3✔
4076
            new ConstStatement({
4077
                const: util.cloneToken(this.tokens.const),
4078
                name: util.cloneToken(this.tokens.name),
4079
                equals: util.cloneToken(this.tokens.equals),
4080
                value: this.value?.clone()
9✔
4081
            }),
4082
            ['value']
4083
        );
4084
    }
4085
}
4086

4087
export class ContinueStatement extends Statement {
1✔
4088
    constructor(options: {
4089
        continue?: Token;
4090
        loopType: Token;
4091
    }
4092
    ) {
4093
        super();
13✔
4094
        this.tokens = {
13✔
4095
            continue: options.continue,
4096
            loopType: options.loopType
4097
        };
4098
        this.location = util.createBoundingLocation(
13✔
4099
            this.tokens.continue,
4100
            this.tokens.loopType
4101
        );
4102
    }
4103

4104
    public readonly tokens: {
4105
        readonly continue?: Token;
4106
        readonly loopType: Token;
4107
    };
4108

4109
    public readonly kind = AstNodeKind.ContinueStatement;
13✔
4110

4111
    public readonly location: Location | undefined;
4112

4113
    transpile(state: BrsTranspileState) {
4114
        return [
3✔
4115
            state.sourceNode(this.tokens.continue, this.tokens.continue?.text ?? 'continue'),
18!
4116
            this.tokens.loopType?.leadingWhitespace ?? ' ',
18✔
4117
            state.sourceNode(this.tokens.continue, this.tokens.loopType?.text)
9✔
4118
        ];
4119
    }
4120

4121
    walk(visitor: WalkVisitor, options: WalkOptions) {
4122
        //nothing to walk
4123
    }
4124

4125
    public get leadingTrivia(): Token[] {
4126
        return this.tokens.continue?.leadingTrivia ?? [];
86!
4127
    }
4128

4129
    public clone() {
4130
        return this.finalizeClone(
1✔
4131
            new ContinueStatement({
4132
                continue: util.cloneToken(this.tokens.continue),
4133
                loopType: util.cloneToken(this.tokens.loopType)
4134
            })
4135
        );
4136
    }
4137
}
4138

4139
export class TypecastStatement extends Statement {
1✔
4140
    constructor(options: {
4141
        typecast?: Token;
4142
        typecastExpression: TypecastExpression;
4143
    }
4144
    ) {
4145
        super();
27✔
4146
        this.tokens = {
27✔
4147
            typecast: options.typecast
4148
        };
4149
        this.typecastExpression = options.typecastExpression;
27✔
4150
        this.location = util.createBoundingLocation(
27✔
4151
            this.tokens.typecast,
4152
            this.typecastExpression
4153
        );
4154
    }
4155

4156
    public readonly tokens: {
4157
        readonly typecast?: Token;
4158
    };
4159

4160
    public readonly typecastExpression: TypecastExpression;
4161

4162
    public readonly kind = AstNodeKind.TypecastStatement;
27✔
4163

4164
    public readonly location: Location;
4165

4166
    transpile(state: BrsTranspileState) {
4167
        //the typecast statement is a comment just for debugging purposes
4168
        return [
2✔
4169
            state.transpileToken(this.tokens.typecast, 'typecast', true),
4170
            ' ',
4171
            this.typecastExpression.obj.transpile(state),
4172
            ' ',
4173
            state.transpileToken(this.typecastExpression.tokens.as, 'as'),
4174
            ' ',
4175
            this.typecastExpression.typeExpression.getName(ParseMode.BrighterScript)
4176
        ];
4177
    }
4178

4179
    walk(visitor: WalkVisitor, options: WalkOptions) {
4180
        if (options.walkMode & InternalWalkMode.walkExpressions) {
160✔
4181
            walk(this, 'typecastExpression', visitor, options);
147✔
4182
        }
4183
    }
4184

4185
    get leadingTrivia(): Token[] {
4186
        return this.tokens.typecast?.leadingTrivia ?? [];
119!
4187
    }
4188

4189
    getType(options: GetTypeOptions): BscType {
4190
        return this.typecastExpression.getType(options);
22✔
4191
    }
4192

4193
    public clone() {
4194
        return this.finalizeClone(
1✔
4195
            new TypecastStatement({
4196
                typecast: util.cloneToken(this.tokens.typecast),
4197
                typecastExpression: this.typecastExpression?.clone()
3!
4198
            }),
4199
            ['typecastExpression']
4200
        );
4201
    }
4202
}
4203

4204
export class ConditionalCompileErrorStatement extends Statement {
1✔
4205
    constructor(options: {
4206
        hashError?: Token;
4207
        message: Token;
4208
    }) {
4209
        super();
11✔
4210
        this.tokens = {
11✔
4211
            hashError: options.hashError,
4212
            message: options.message
4213
        };
4214
        this.location = util.createBoundingLocation(util.createBoundingLocationFromTokens(this.tokens));
11✔
4215
    }
4216

4217
    public readonly tokens: {
4218
        readonly hashError?: Token;
4219
        readonly message: Token;
4220
    };
4221

4222

4223
    public readonly kind = AstNodeKind.ConditionalCompileErrorStatement;
11✔
4224

4225
    public readonly location: Location | undefined;
4226

4227
    transpile(state: BrsTranspileState) {
4228
        return [
3✔
4229
            state.transpileToken(this.tokens.hashError, '#error'),
4230
            ' ',
4231
            state.transpileToken(this.tokens.message)
4232

4233
        ];
4234
    }
4235

4236
    walk(visitor: WalkVisitor, options: WalkOptions) {
4237
        // nothing to walk
4238
    }
4239

4240
    get leadingTrivia(): Token[] {
4241
        return this.tokens.hashError.leadingTrivia ?? [];
12!
4242
    }
4243

4244
    public clone() {
4245
        return this.finalizeClone(
1✔
4246
            new ConditionalCompileErrorStatement({
4247
                hashError: util.cloneToken(this.tokens.hashError),
4248
                message: util.cloneToken(this.tokens.message)
4249
            })
4250
        );
4251
    }
4252
}
4253

4254
export class AliasStatement extends Statement {
1✔
4255
    constructor(options: {
4256
        alias?: Token;
4257
        name: Token;
4258
        equals?: Token;
4259
        value: VariableExpression | DottedGetExpression;
4260
    }
4261
    ) {
4262
        super();
34✔
4263
        this.tokens = {
34✔
4264
            alias: options.alias,
4265
            name: options.name,
4266
            equals: options.equals
4267
        };
4268
        this.value = options.value;
34✔
4269
        this.location = util.createBoundingLocation(
34✔
4270
            this.tokens.alias,
4271
            this.tokens.name,
4272
            this.tokens.equals,
4273
            this.value
4274
        );
4275
    }
4276

4277
    public readonly tokens: {
4278
        readonly alias?: Token;
4279
        readonly name: Token;
4280
        readonly equals?: Token;
4281
    };
4282

4283
    public readonly value: Expression;
4284

4285
    public readonly kind = AstNodeKind.AliasStatement;
34✔
4286

4287
    public readonly location: Location;
4288

4289
    transpile(state: BrsTranspileState) {
4290
        //the alias statement is a comment just for debugging purposes
4291
        return [
12✔
4292
            state.transpileToken(this.tokens.alias, 'alias', true),
4293
            ' ',
4294
            state.transpileToken(this.tokens.name),
4295
            ' ',
4296
            state.transpileToken(this.tokens.equals, '='),
4297
            ' ',
4298
            this.value.transpile(state)
4299
        ];
4300
    }
4301

4302
    walk(visitor: WalkVisitor, options: WalkOptions) {
4303
        if (options.walkMode & InternalWalkMode.walkExpressions) {
235✔
4304
            walk(this, 'value', visitor, options);
206✔
4305
        }
4306
    }
4307

4308
    get leadingTrivia(): Token[] {
4309
        return this.tokens.alias?.leadingTrivia ?? [];
121!
4310
    }
4311

4312
    getType(options: GetTypeOptions): BscType {
4313
        return this.value.getType(options);
1✔
4314
    }
4315

4316
    public clone() {
4317
        return this.finalizeClone(
1✔
4318
            new AliasStatement({
4319
                alias: util.cloneToken(this.tokens.alias),
4320
                name: util.cloneToken(this.tokens.name),
4321
                equals: util.cloneToken(this.tokens.equals),
4322
                value: this.value?.clone()
3!
4323
            }),
4324
            ['value']
4325
        );
4326
    }
4327
}
4328

4329
export class ConditionalCompileStatement extends Statement {
1✔
4330
    constructor(options: {
4331
        hashIf?: Token;
4332
        not?: Token;
4333
        condition: Token;
4334
        hashElse?: Token;
4335
        hashEndIf?: Token;
4336
        thenBranch: Block;
4337
        elseBranch?: ConditionalCompileStatement | Block;
4338
    }) {
4339
        super();
58✔
4340
        this.thenBranch = options.thenBranch;
58✔
4341
        this.elseBranch = options.elseBranch;
58✔
4342

4343
        this.tokens = {
58✔
4344
            hashIf: options.hashIf,
4345
            not: options.not,
4346
            condition: options.condition,
4347
            hashElse: options.hashElse,
4348
            hashEndIf: options.hashEndIf
4349
        };
4350

4351
        this.location = util.createBoundingLocation(
58✔
4352
            util.createBoundingLocationFromTokens(this.tokens),
4353
            this.thenBranch,
4354
            this.elseBranch
4355
        );
4356
    }
4357

4358
    readonly tokens: {
4359
        readonly hashIf?: Token;
4360
        readonly not?: Token;
4361
        readonly condition: Token;
4362
        readonly hashElse?: Token;
4363
        readonly hashEndIf?: Token;
4364
    };
4365
    public readonly thenBranch: Block;
4366
    public readonly elseBranch?: ConditionalCompileStatement | Block;
4367

4368
    public readonly kind = AstNodeKind.ConditionalCompileStatement;
58✔
4369

4370
    public readonly location: Location | undefined;
4371

4372
    transpile(state: BrsTranspileState) {
4373
        let results = [] as TranspileResult;
6✔
4374
        //if   (already indented by block)
4375
        if (!state.conditionalCompileStatement) {
6✔
4376
            // only transpile the #if in the case when we're not in a conditionalCompileStatement already
4377
            results.push(state.transpileToken(this.tokens.hashIf ?? createToken(TokenKind.HashIf)));
3!
4378
        }
4379

4380
        results.push(' ');
6✔
4381
        //conditions
4382
        if (this.tokens.not) {
6✔
4383
            results.push('not');
2✔
4384
            results.push(' ');
2✔
4385
        }
4386
        results.push(state.transpileToken(this.tokens.condition));
6✔
4387
        state.lineage.unshift(this);
6✔
4388

4389
        //if statement body
4390
        let thenNodes = this.thenBranch.transpile(state);
6✔
4391
        state.lineage.shift();
6✔
4392
        if (thenNodes.length > 0) {
6!
4393
            results.push(thenNodes);
6✔
4394
        }
4395
        //else branch
4396
        if (this.elseBranch) {
6!
4397
            const elseIsCC = isConditionalCompileStatement(this.elseBranch);
6✔
4398
            const endBlockToken = elseIsCC ? (this.elseBranch as ConditionalCompileStatement).tokens.hashIf ?? createToken(TokenKind.HashElseIf) : this.tokens.hashElse;
6!
4399
            //else
4400

4401
            results.push(...state.transpileEndBlockToken(this.thenBranch, endBlockToken, createToken(TokenKind.HashElse).text));
6✔
4402

4403
            if (elseIsCC) {
6✔
4404
                //chained else if
4405
                state.lineage.unshift(this.elseBranch);
3✔
4406

4407
                // transpile following #if with knowledge of current
4408
                const existingCCStmt = state.conditionalCompileStatement;
3✔
4409
                state.conditionalCompileStatement = this;
3✔
4410
                let body = this.elseBranch.transpile(state);
3✔
4411
                state.conditionalCompileStatement = existingCCStmt;
3✔
4412

4413
                state.lineage.shift();
3✔
4414

4415
                if (body.length > 0) {
3!
4416
                    //zero or more spaces between the `else` and the `if`
4417
                    results.push(...body);
3✔
4418

4419
                    // stop here because chained if will transpile the rest
4420
                    return results;
3✔
4421
                } else {
UNCOV
4422
                    results.push('\n');
×
4423
                }
4424

4425
            } else {
4426
                //else body
4427
                state.lineage.unshift(this.tokens.hashElse!);
3✔
4428
                let body = this.elseBranch.transpile(state);
3✔
4429
                state.lineage.shift();
3✔
4430

4431
                if (body.length > 0) {
3!
4432
                    results.push(...body);
3✔
4433
                }
4434
            }
4435
        }
4436

4437
        //end if
4438
        results.push(...state.transpileEndBlockToken(this.elseBranch ?? this.thenBranch, this.tokens.hashEndIf, '#end if'));
3!
4439

4440
        return results;
3✔
4441
    }
4442

4443
    walk(visitor: WalkVisitor, options: WalkOptions) {
4444
        if (options.walkMode & InternalWalkMode.walkStatements) {
210!
4445
            const bsConsts = options.bsConsts ?? this.getBsConsts();
210✔
4446
            let conditionTrue = bsConsts?.get(this.tokens.condition.text.toLowerCase());
210✔
4447
            if (this.tokens.not) {
210✔
4448
                // flips the boolean value
4449
                conditionTrue = !conditionTrue;
25✔
4450
            }
4451
            const walkFalseBlocks = options.walkMode & InternalWalkMode.visitFalseConditionalCompilationBlocks;
210✔
4452
            if (conditionTrue || walkFalseBlocks) {
210✔
4453
                walk(this, 'thenBranch', visitor, options);
169✔
4454
            }
4455
            if (this.elseBranch && (!conditionTrue || walkFalseBlocks)) {
210✔
4456
                walk(this, 'elseBranch', visitor, options);
71✔
4457
            }
4458
        }
4459
    }
4460

4461
    get leadingTrivia(): Token[] {
4462
        return this.tokens.hashIf?.leadingTrivia ?? [];
175!
4463
    }
4464

4465
    public clone() {
4466
        return this.finalizeClone(
1✔
4467
            new ConditionalCompileStatement({
4468
                hashIf: util.cloneToken(this.tokens.hashIf),
4469
                not: util.cloneToken(this.tokens.not),
4470
                condition: util.cloneToken(this.tokens.condition),
4471
                hashElse: util.cloneToken(this.tokens.hashElse),
4472
                hashEndIf: util.cloneToken(this.tokens.hashEndIf),
4473
                thenBranch: this.thenBranch?.clone(),
3!
4474
                elseBranch: this.elseBranch?.clone()
3!
4475
            }),
4476
            ['thenBranch', 'elseBranch']
4477
        );
4478
    }
4479

4480
    public getBranchStatementIndex(stmt: Statement) {
NEW
4481
        if (this.thenBranch === stmt) {
×
NEW
4482
            return 0;
×
NEW
4483
        } else if (this.elseBranch === stmt) {
×
NEW
4484
            return 1;
×
4485
        }
NEW
4486
        return -1;
×
4487
    }
4488
}
4489

4490

4491
export class ConditionalCompileConstStatement extends Statement {
1✔
4492
    constructor(options: {
4493
        hashConst?: Token;
4494
        assignment: AssignmentStatement;
4495
    }) {
4496
        super();
19✔
4497
        this.tokens = {
19✔
4498
            hashConst: options.hashConst
4499
        };
4500
        this.assignment = options.assignment;
19✔
4501
        this.location = util.createBoundingLocation(util.createBoundingLocationFromTokens(this.tokens), this.assignment);
19✔
4502
    }
4503

4504
    public readonly tokens: {
4505
        readonly hashConst?: Token;
4506
    };
4507

4508
    public readonly assignment: AssignmentStatement;
4509

4510
    public readonly kind = AstNodeKind.ConditionalCompileConstStatement;
19✔
4511

4512
    public readonly location: Location | undefined;
4513

4514
    transpile(state: BrsTranspileState) {
4515
        return [
3✔
4516
            state.transpileToken(this.tokens.hashConst, '#const'),
4517
            ' ',
4518
            state.transpileToken(this.assignment.tokens.name),
4519
            ' ',
4520
            state.transpileToken(this.assignment.tokens.equals, '='),
4521
            ' ',
4522
            ...this.assignment.value.transpile(state)
4523
        ];
4524

4525
    }
4526

4527
    walk(visitor: WalkVisitor, options: WalkOptions) {
4528
        // nothing to walk
4529
    }
4530

4531

4532
    get leadingTrivia(): Token[] {
4533
        return this.tokens.hashConst.leadingTrivia ?? [];
78!
4534
    }
4535

4536
    public clone() {
4537
        return this.finalizeClone(
1✔
4538
            new ConditionalCompileConstStatement({
4539
                hashConst: util.cloneToken(this.tokens.hashConst),
4540
                assignment: this.assignment?.clone()
3!
4541
            }),
4542
            ['assignment']
4543
        );
4544
    }
4545
}
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