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

rokucommunity / brighterscript / #13683

03 Feb 2025 04:19PM UTC coverage: 86.753% (-1.4%) from 88.185%
#13683

push

web-flow
Merge 34e72243e into 4afb6f658

12476 of 15203 branches covered (82.06%)

Branch coverage included in aggregate %.

7751 of 8408 new or added lines in 101 files covered. (92.19%)

85 existing lines in 17 files now uncovered.

13398 of 14622 relevant lines covered (91.63%)

34302.41 hits per line

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

88.46
/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

32
export class EmptyStatement extends Statement {
1✔
33
    constructor(options?: { range?: Location }
34
    ) {
35
        super();
6✔
36
        this.location = undefined;
6✔
37
    }
38
    /**
39
     * Create a negative range to indicate this is an interpolated location
40
     */
41
    public readonly location?: Location;
42

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

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

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

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

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

75
    public readonly symbolTable = new SymbolTable('Body', () => this.parent?.getSymbolTable());
30,939✔
76

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

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

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

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

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

118
            result.push(...statement.transpile(state));
1,618✔
119
        }
120
        return result;
742✔
121
    }
122

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

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

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

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

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

179
    public readonly value: Expression;
180

181
    public readonly typeExpression?: TypeExpression;
182

183
    public readonly kind = AstNodeKind.AssignmentStatement;
1,607✔
184

185
    public readonly location: Location | undefined;
186

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

197
    walk(visitor: WalkVisitor, options: WalkOptions) {
198
        if (options.walkMode & InternalWalkMode.walkExpressions) {
6,897✔
199
            walk(this, 'typeExpression', visitor, options);
6,765✔
200
            walk(this, 'value', visitor, options);
6,765✔
201
        }
202
    }
203

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

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

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

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

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

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

254
    public readonly item: Expression;
255

256
    public readonly value: Expression;
257

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

260
    public readonly location: Location | undefined;
261

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

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

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

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

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

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

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

306
export class Block extends Statement {
1✔
307
    constructor(options: {
308
        statements: Statement[];
309
    }) {
310
        super();
7,114✔
311
        this.statements = options.statements;
7,114✔
312
    }
313

314
    public readonly statements: Statement[];
315

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

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

325
        if (isFunctionExpression(this.parent)) {
246✔
326
            lastBitBefore = util.createBoundingLocation(
127✔
327
                this.parent.tokens.functionType,
328
                this.parent.tokens.leftParen,
329
                ...(this.parent.parameters ?? []),
381!
330
                this.parent.tokens.rightParen,
331
                this.parent.tokens.as,
332
                this.parent.returnTypeExpression
333
            );
334
            firstBitAfter = this.parent.tokens.endFunctionType?.location;
127!
335
        } else if (isIfStatement(this.parent)) {
119✔
336
            if (this.parent.thenBranch === this) {
2!
337
                lastBitBefore = util.createBoundingLocation(
2✔
338
                    this.parent.tokens.then,
339
                    this.parent.condition
340
                );
341
                firstBitAfter = util.createBoundingLocation(
2✔
342
                    this.parent.tokens.else,
343
                    this.parent.elseBranch,
344
                    this.parent.tokens.endIf
345
                );
NEW
346
            } else if (this.parent.elseBranch === this) {
×
NEW
347
                lastBitBefore = this.parent.tokens.else?.location;
×
NEW
348
                firstBitAfter = this.parent.tokens.endIf?.location;
×
349
            }
350
        } else if (isConditionalCompileStatement(this.parent)) {
117!
NEW
351
            if (this.parent.thenBranch === this) {
×
NEW
352
                lastBitBefore = util.createBoundingLocation(
×
353
                    this.parent.tokens.condition,
354
                    this.parent.tokens.not,
355
                    this.parent.tokens.hashIf
356
                );
NEW
357
                firstBitAfter = util.createBoundingLocation(
×
358
                    this.parent.tokens.hashElse,
359
                    this.parent.elseBranch,
360
                    this.parent.tokens.hashEndIf
361
                );
NEW
362
            } else if (this.parent.elseBranch === this) {
×
NEW
363
                lastBitBefore = this.parent.tokens.hashElse?.location;
×
NEW
364
                firstBitAfter = this.parent.tokens.hashEndIf?.location;
×
365
            }
366
        } else if (isForStatement(this.parent)) {
117✔
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)) {
115✔
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)) {
113✔
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)) {
111✔
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)) {
110!
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) {
246!
406
            return util.createLocation(
113✔
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
339✔
412
            );
413
        }
414
    }
415

416
    public get location() {
417
        if (!this._location) {
4,468✔
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,639✔
420
        }
421
        return this._location;
4,468✔
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,473✔
430
        let results = [] as TranspileResult;
4,473✔
431
        for (let i = 0; i < this.statements.length; i++) {
4,473✔
432
            let previousStatement = this.statements[i - 1];
5,407✔
433
            let statement = this.statements[i];
5,407✔
434
            //is not a comment
435
            //if comment is on same line as parent
436
            if (util.isLeadingCommentOnSameLine(state.lineage[0]?.location, statement) ||
5,407!
437
                util.isLeadingCommentOnSameLine(previousStatement?.location, statement)
16,173✔
438
            ) {
439
                results.push(' ');
50✔
440

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

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

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

465
    walk(visitor: WalkVisitor, options: WalkOptions) {
466
        if (options.walkMode & InternalWalkMode.walkStatements) {
31,727✔
467
            walkArray(this.statements, visitor, options, this);
31,721✔
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();
897✔
486
        this.expression = options.expression;
897✔
487
        this.location = this.expression?.location;
897✔
488
    }
489
    public readonly expression: Expression;
490
    public readonly kind = AstNodeKind.ExpressionStatement;
897✔
491

492
    public readonly location: Location | undefined;
493

494
    transpile(state: BrsTranspileState) {
495
        return [
63✔
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,471✔
503
            walk(this, 'expression', visitor, options);
3,442✔
504
        }
505
    }
506

507
    get leadingTrivia(): Token[] {
508
        return this.expression.leadingTrivia;
3,571✔
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,236✔
578
        this.tokens = {
4,236✔
579
            name: options.name
580
        };
581
        this.func = options.func;
4,236✔
582
        if (this.func) {
4,236✔
583
            this.func.symbolTable.name += `: '${this.tokens.name?.text}'`;
4,234!
584
        }
585

586
        this.location = this.func?.location;
4,236✔
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,236✔
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);
13,092✔
603
        if (namespace) {
13,092✔
604
            let delimiter = parseMode === ParseMode.BrighterScript ? '.' : '_';
3,056✔
605
            let namespaceName = namespace.getName(parseMode);
3,056✔
606
            return namespaceName + delimiter + this.tokens.name?.text;
3,056!
607
        } else {
608
            return this.tokens.name.text;
10,036✔
609
        }
610
    }
611

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

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

623
        return [
1,407✔
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) {
18,476✔
654
            walk(this, 'func', visitor, options);
16,563✔
655
        }
656
    }
657

658
    getType(options: GetTypeOptions) {
659
        const funcExprType = this.func.getType(options);
3,596✔
660
        funcExprType.setName(this.getName(ParseMode.BrighterScript));
3,596✔
661
        return funcExprType;
3,596✔
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,155✔
687
        this.condition = options.condition;
2,155✔
688
        this.thenBranch = options.thenBranch;
2,155✔
689
        this.elseBranch = options.elseBranch;
2,155✔
690

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

698
        this.location = util.createBoundingLocation(
2,155✔
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,155✔
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,199✔
734
        //if   (already indented by block)
735
        results.push(state.transpileToken(this.tokens.if ?? createToken(TokenKind.If)));
2,199!
736
        results.push(' ');
2,199✔
737
        //conditions
738
        results.push(...this.condition.transpile(state));
2,199✔
739
        //then
740
        if (this.tokens.then) {
2,199✔
741
            results.push(' ');
1,834✔
742
            results.push(
1,834✔
743
                state.transpileToken(this.tokens.then, 'then')
744
            );
745
        }
746
        state.lineage.unshift(this);
2,199✔
747

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

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

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

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

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

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

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

791
        return results;
1,118✔
792
    }
793

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

806
    get leadingTrivia(): Token[] {
807
        return this.tokens.if?.leadingTrivia ?? [];
2,932!
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,280✔
898
        this.tokens = {
1,280✔
899
            print: options.print
900
        };
901
        this.expressions = options.expressions;
1,280✔
902
        this.location = util.createBoundingLocation(
1,280✔
903
            this.tokens.print,
904
            ...(this.expressions ?? [])
3,840✔
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,280✔
915

916
    public readonly location: Location | undefined;
917

918
    transpile(state: BrsTranspileState) {
919
        let result = [
232✔
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)) {
232✔
925
            result.push(' ');
6✔
926
        }
927

928
        // eslint-disable-next-line @typescript-eslint/prefer-for-of
929
        for (let i = 0; i < this.expressions.length; i++) {
232✔
930
            const expression = this.expressions[i];
296✔
931
            let leadingWhitespace = expression.leadingTrivia.find(t => t.kind === TokenKind.Whitespace)?.text;
296✔
932
            if (leadingWhitespace) {
296✔
933
                result.push(leadingWhitespace);
250✔
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) {
46✔
936
                result.push(' ');
6✔
937
            }
938

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

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

952
    get leadingTrivia(): Token[] {
953
        return this.tokens.print?.leadingTrivia ?? [];
7,457✔
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,342✔
1163
        this.tokens = {
3,342✔
1164
            return: options?.return
10,026!
1165
        };
1166
        this.value = options?.value;
3,342!
1167
        this.location = util.createBoundingLocation(
3,342✔
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,342✔
1178

1179
    public readonly location: Location | undefined;
1180

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

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

1199
    get leadingTrivia(): Token[] {
1200
        return this.tokens.return?.leadingTrivia ?? [];
10,008!
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[] {
NEW
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);
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();
37✔
1537
        this.tokens = {
37✔
1538
            while: options.while,
1539
            endWhile: options.endWhile
1540
        };
1541
        this.body = options.body;
37✔
1542
        this.condition = options.condition;
37✔
1543
        this.location = util.createBoundingLocation(
37✔
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;
37✔
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) {
121✔
1586
            walk(this, 'condition', visitor, options);
118✔
1587
        }
1588
        if (options.walkMode & InternalWalkMode.walkStatements) {
121✔
1589
            walk(this, 'body', visitor, options);
120✔
1590
        }
1591
    }
1592

1593
    get leadingTrivia(): Token[] {
1594
        return this.tokens.while?.leadingTrivia ?? [];
107!
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) {
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();
639✔
1870
        this.tokens = {
639✔
1871
            namespace: options.namespace,
1872
            endNamespace: options.endNamespace
1873
        };
1874
        this.nameExpression = options.nameExpression;
639✔
1875
        this.body = options.body;
639✔
1876
        this.symbolTable = new SymbolTable(`NamespaceStatement: '${this.name}'`, () => this.getRoot()?.getSymbolTable());
6,096!
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;
639✔
1888

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

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

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

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

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

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

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

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

1939
    transpile(state: BrsTranspileState) {
1940
        //namespaces don't actually have any real content, so just transpile their bodies
1941
        return [
60✔
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!
NEW
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,248✔
1978
            walk(this, 'nameExpression', visitor, options);
2,661✔
1979
        }
1980

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

1986
    getType(options: GetTypeOptions) {
1987
        const resultType = new NamespaceType(this.name);
1,119✔
1988
        return resultType;
1,119✔
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();
212✔
2012
        this.tokens = {
212✔
2013
            import: options.import,
2014
            path: options.path
2015
        };
2016
        this.location = util.createBoundingLocation(
212✔
2017
            this.tokens.import,
2018
            this.tokens.path
2019
        );
2020
        if (this.tokens.path) {
212✔
2021
            //remove quotes
2022
            this.filePath = this.tokens.path.text.replace(/"/g, '');
210✔
2023
            if (this.tokens.path?.location?.range) {
210!
2024
                //adjust the range to exclude the quotes
2025
                this.tokens.path.location = util.createLocation(
206✔
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;
212✔
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 ?? [];
591!
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();
181✔
2097
        this.tokens = {
181✔
2098
            interface: options.interface,
2099
            name: options.name,
2100
            extends: options.extends,
2101
            endInterface: options.endInterface
2102
        };
2103
        this.parentInterfaceName = options.parentInterfaceName;
181✔
2104
        this.body = options.body;
181✔
2105
        this.location = util.createBoundingLocation(
181✔
2106
            this.tokens.interface,
2107
            this.tokens.name,
2108
            this.tokens.extends,
2109
            this.parentInterfaceName,
2110
            ...this.body ?? [],
543✔
2111
            this.tokens.endInterface
2112
        );
2113
    }
2114
    public readonly parentInterfaceName?: TypeExpression;
2115
    public readonly body: Statement[];
2116

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

2119
    public readonly tokens = {} as {
181✔
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[];
231✔
2130
    }
2131

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

2136

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

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

2145
    public get endTrivia(): Token[] {
NEW
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() {
2154
        const name = this.tokens.name?.text;
2!
2155
        if (name) {
2!
2156
            const namespace = this.findAncestor<NamespaceStatement>(isNamespaceStatement);
2✔
2157
            if (namespace) {
2✔
2158
                let namespaceName = namespace.getName(ParseMode.BrighterScript);
1✔
2159
                return `${namespaceName}.${name}`;
1✔
2160
            } else {
2161
                return name;
1✔
2162
            }
2163
        } else {
2164
            //return undefined which will allow outside callers to know that this interface doesn't have a name
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;
158!
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);
158✔
2181
        if (namespace) {
158✔
2182
            let delimiter = parseMode === ParseMode.BrighterScript ? '.' : '_';
23!
2183
            let namespaceName = namespace.getName(parseMode);
23✔
2184
            return namespaceName + delimiter + this.name;
23✔
2185
        } else {
2186
            return this.name;
135✔
2187
        }
2188
    }
2189

2190
    public transpile(state: BrsTranspileState): TranspileResult {
2191
        //interfaces should completely disappear at runtime
2192
        return [
13✔
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!
NEW
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!
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);
796✔
2259

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

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

2268
        const resultType = new InterfaceType(this.getName(ParseMode.BrighterScript), superIface);
151✔
2269
        for (const statement of this.methods) {
151✔
2270
            const memberType = statement?.getType({ ...options, typeChain: undefined }); // no typechain info needed
28!
2271
            const flag = statement.isOptional ? SymbolTypeFlag.runtime | SymbolTypeFlag.optional : SymbolTypeFlag.runtime;
28✔
2272
            resultType.addMember(statement?.tokens.name?.text, { definingNode: statement }, memberType, flag);
28!
2273
        }
2274
        for (const statement of this.fields) {
151✔
2275
            const memberType = statement?.getType({ ...options, typeChain: undefined }); // no typechain info needed
193!
2276
            const flag = statement.isOptional ? SymbolTypeFlag.runtime | SymbolTypeFlag.optional : SymbolTypeFlag.runtime;
193✔
2277
            resultType.addMember(statement?.tokens.name?.text, { definingNode: statement, isInstance: true }, memberType, flag);
193!
2278
        }
2279
        options.typeChain?.push(new TypeChainEntry({
151✔
2280
            name: this.getName(ParseMode.BrighterScript),
2281
            type: resultType,
2282
            data: options.data,
2283
            astNode: this
2284
        }));
2285
        return resultType;
151✔
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 {
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();
212✔
2314
        this.tokens = {
212✔
2315
            optional: options.optional,
2316
            name: options.name,
2317
            as: options.as
2318
        };
2319
        this.typeExpression = options.typeExpression;
212✔
2320
        this.location = util.createBoundingLocation(
212✔
2321
            this.tokens.optional,
2322
            this.tokens.name,
2323
            this.tokens.as,
2324
            this.typeExpression
2325
        );
2326
    }
2327

2328
    public readonly kind = AstNodeKind.InterfaceFieldStatement;
212✔
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;
571✔
2342
    }
2343

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

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

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

2358
    getTypedef(state: BrsTranspileState): TranspileResult {
2359
        const result = [] as TranspileResult;
12✔
2360
        for (let comment of util.getLeadingComments(this) ?? []) {
12!
NEW
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;
204✔
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 {
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();
46✔
2427
        this.tokens = {
46✔
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 ?? [];
46✔
2436
        this.returnTypeExpression = options.returnTypeExpression;
46✔
2437
    }
2438

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

2441
    public get location() {
2442
        return util.createBoundingLocation(
72✔
2443
            this.tokens.optional,
2444
            this.tokens.functionType,
2445
            this.tokens.name,
2446
            this.tokens.leftParen,
2447
            ...(this.params ?? []),
216!
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;
28✔
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;
41✔
2474
    }
2475

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

2480
    walk(visitor: WalkVisitor, options: WalkOptions) {
2481
        if (options.walkMode & InternalWalkMode.walkExpressions) {
215✔
2482
            walk(this, 'returnTypeExpression', visitor, options);
190✔
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);
28✔
2543
        const isSub = this.tokens.functionType?.kind === TokenKind.Sub || !returnType;
28!
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) {
28✔
2546
            returnType = isSub ? VoidType.instance : DynamicType.instance;
10!
2547
        }
2548

2549
        const resultType = new TypedFunctionType(returnType);
28✔
2550
        resultType.isSub = isSub;
28✔
2551
        for (let param of this.params) {
28✔
2552
            resultType.addParameter(param.tokens.name.text, param.getType(options), !!param.defaultValue);
7✔
2553
        }
2554
        if (options.typeChain) {
28!
2555
            // need Interface type for type chain
NEW
2556
            this.parent?.getType(options);
×
2557
        }
2558
        let funcName = this.getName(ParseMode.BrighterScript);
28✔
2559
        resultType.setName(funcName);
28✔
2560
        options.typeChain?.push(new TypeChainEntry({ name: resultType.name, type: resultType, data: options.data, astNode: this }));
28!
2561
        return resultType;
28✔
2562
    }
2563

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

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

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

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

2621
    public readonly kind = AstNodeKind.ClassStatement;
703✔
2622

2623

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

2636

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

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

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

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

2666
    public readonly location: Location | undefined;
2667

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3146
    public readonly kind = AstNodeKind.MethodStatement as AstNodeKind;
407✔
3147

3148
    public readonly modifiers: Token[] = [];
407✔
3149

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

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

3159
    public readonly location: Location | undefined;
3160

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3400
    public readonly location: Location | undefined;
3401

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

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

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

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

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

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

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

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

3475
export type MemberStatement = FieldStatement | MethodStatement;
3476

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

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

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

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

3509
    public readonly location: Location | undefined;
3510

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

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

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

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

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

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

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

3575
    public readonly exceptionVariableExpression?: Expression;
3576

3577
    public readonly catchBranch?: Block;
3578

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

3581
    public readonly location: Location | undefined;
3582

3583
    public transpile(state: BrsTranspileState): TranspileResult {
3584
        return [
7✔
3585
            state.transpileToken(this.tokens.catch, 'catch'),
3586
            ' ',
3587
            this.exceptionVariableExpression?.transpile(state) ?? [
42✔
3588
                //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
3589
                this.getSymbolTable()?.hasSymbol('e', SymbolTypeFlag.runtime)
6!
3590
                    ? '__bsc_error'
2✔
3591
                    : 'e'
3592
            ],
3593
            ...(this.catchBranch?.transpile(state) ?? [])
42!
3594
        ];
3595
    }
3596

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

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

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

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

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

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

3642
    public readonly location: Location | undefined;
3643

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

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

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

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

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

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

3684

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

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

3709
    public readonly kind = AstNodeKind.EnumStatement;
181✔
3710

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3857
        }
3858
    }
3859

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

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

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

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

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

3909
    public readonly kind = AstNodeKind.EnumMemberStatement;
357✔
3910

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

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

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

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

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

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

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

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

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

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

4005
    public readonly kind = AstNodeKind.ConstStatement;
162✔
4006

4007
    public readonly location: Location | undefined;
4008

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

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

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

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

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

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

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

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

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

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

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

4112
    public readonly location: Location | undefined;
4113

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

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

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

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

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

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

4161
    public readonly typecastExpression: TypecastExpression;
4162

4163
    public readonly kind = AstNodeKind.TypecastStatement;
26✔
4164

4165
    public readonly location: Location;
4166

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

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

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

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

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

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

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

4223

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

4226
    public readonly location: Location | undefined;
4227

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

4234
        ];
4235
    }
4236

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

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

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

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

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

4284
    public readonly value: Expression;
4285

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

4288
    public readonly location: Location;
4289

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

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

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

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

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

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

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

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

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

4369
    public readonly kind = AstNodeKind.ConditionalCompileStatement;
56✔
4370

4371
    public readonly location: Location | undefined;
4372

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

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

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

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

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

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

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

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

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

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

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

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

4441
        return results;
3✔
4442
    }
4443

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

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

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

4482

4483
export class ConditionalCompileConstStatement extends Statement {
1✔
4484
    constructor(options: {
4485
        hashConst?: Token;
4486
        assignment: AssignmentStatement;
4487
    }) {
4488
        super();
19✔
4489
        this.tokens = {
19✔
4490
            hashConst: options.hashConst
4491
        };
4492
        this.assignment = options.assignment;
19✔
4493
        this.location = util.createBoundingLocation(util.createBoundingLocationFromTokens(this.tokens), this.assignment);
19✔
4494
    }
4495

4496
    public readonly tokens: {
4497
        readonly hashConst?: Token;
4498
    };
4499

4500
    public readonly assignment: AssignmentStatement;
4501

4502
    public readonly kind = AstNodeKind.ConditionalCompileConstStatement;
19✔
4503

4504
    public readonly location: Location | undefined;
4505

4506
    transpile(state: BrsTranspileState) {
4507
        return [
3✔
4508
            state.transpileToken(this.tokens.hashConst, '#const'),
4509
            ' ',
4510
            state.transpileToken(this.assignment.tokens.name),
4511
            ' ',
4512
            state.transpileToken(this.assignment.tokens.equals, '='),
4513
            ' ',
4514
            ...this.assignment.value.transpile(state)
4515
        ];
4516

4517
    }
4518

4519
    walk(visitor: WalkVisitor, options: WalkOptions) {
4520
        // nothing to walk
4521
    }
4522

4523

4524
    get leadingTrivia(): Token[] {
4525
        return this.tokens.hashConst.leadingTrivia ?? [];
78!
4526
    }
4527

4528
    public clone() {
4529
        return this.finalizeClone(
1✔
4530
            new ConditionalCompileConstStatement({
4531
                hashConst: util.cloneToken(this.tokens.hashConst),
4532
                assignment: this.assignment?.clone()
3!
4533
            }),
4534
            ['assignment']
4535
        );
4536
    }
4537
}
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