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

rokucommunity / brighterscript / #13182

14 Oct 2024 03:33PM UTC coverage: 86.831%. Remained the same
#13182

push

web-flow
Merge 7db2dd331 into d585c29e9

11596 of 14122 branches covered (82.11%)

Branch coverage included in aggregate %.

26 of 27 new or added lines in 6 files covered. (96.3%)

112 existing lines in 4 files now uncovered.

12721 of 13883 relevant lines covered (91.63%)

29829.73 hits per line

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

88.2
/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, FunctionExpression, FunctionParameterExpression, LiteralExpression, TypeExpression, TypecastExpression } from './Expression';
5
import { CallExpression, VariableExpression } from './Expression';
1✔
6
import { util } from '../util';
1✔
7
import type { Location } from 'vscode-languageserver';
8
import type { BrsTranspileState } from './BrsTranspileState';
9
import { ParseMode } from './Parser';
1✔
10
import type { WalkVisitor, WalkOptions } from '../astUtils/visitors';
11
import { InternalWalkMode, walk, createVisitor, WalkMode, walkArray } from '../astUtils/visitors';
1✔
12
import { isCallExpression, isCatchStatement, isConditionalCompileStatement, isEnumMemberStatement, isExpressionStatement, isFieldStatement, isForEachStatement, isForStatement, isFunctionExpression, isFunctionStatement, isIfStatement, isInterfaceFieldStatement, isInterfaceMethodStatement, isInvalidType, isLiteralExpression, isMethodStatement, isNamespaceStatement, isPrintSeparatorExpression, isTryCatchStatement, isTypedefProvider, isUnaryExpression, isVoidType, isWhileStatement } from '../astUtils/reflection';
1✔
13
import { TypeChainEntry, type GetTypeOptions, type TranspileResult, type TypedefProvider } from '../interfaces';
1✔
14
import { createInvalidLiteral, createMethodStatement, createToken } from '../astUtils/creators';
1✔
15
import { DynamicType } from '../types/DynamicType';
1✔
16
import type { BscType } from '../types/BscType';
17
import { SymbolTable } from '../SymbolTable';
1✔
18
import type { Expression } from './AstNode';
19
import { AstNodeKind } from './AstNode';
1✔
20
import { Statement } from './AstNode';
1✔
21
import { ClassType } from '../types/ClassType';
1✔
22
import { EnumMemberType, EnumType } from '../types/EnumType';
1✔
23
import { NamespaceType } from '../types/NamespaceType';
1✔
24
import { InterfaceType } from '../types/InterfaceType';
1✔
25
import { VoidType } from '../types/VoidType';
1✔
26
import { TypedFunctionType } from '../types/TypedFunctionType';
1✔
27
import { ArrayType } from '../types/ArrayType';
1✔
28
import { SymbolTypeFlag } from '../SymbolTypeFlag';
1✔
29
import brsDocParser from './BrightScriptDocParser';
1✔
30

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

178
    public readonly value: Expression;
179

180
    public readonly typeExpression?: TypeExpression;
181

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

184
    public readonly location: Location | undefined;
185

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

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

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

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

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

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

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

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

253
    public readonly item: Expression;
254

255
    public readonly value: Expression;
256

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

259
    public readonly location: Location | undefined;
260

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

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

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

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

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

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

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

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

313
    public readonly statements: Statement[];
314

315
    public readonly kind = AstNodeKind.Block;
6,656✔
316

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

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

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

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

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

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

460
    public get leadingTrivia(): Token[] {
461
        return this.statements[0]?.leadingTrivia ?? [];
9,979✔
462
    }
463

464
    walk(visitor: WalkVisitor, options: WalkOptions) {
465
        if (options.walkMode & InternalWalkMode.walkStatements) {
25,438✔
466
            walkArray(this.statements, visitor, options, this);
25,432✔
467
        }
468
    }
469

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

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

491
    public readonly location: Location | undefined;
492

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

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

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

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

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

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

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

543
    public readonly location?: Location;
544

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

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

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

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

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

585
        this.location = this.func?.location;
3,989✔
586
    }
587

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

593
    public readonly kind = AstNodeKind.FunctionStatement as AstNodeKind;
3,989✔
594

595
    public readonly location: Location | undefined;
596

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

611
    public get leadingTrivia(): Token[] {
612
        return this.func.leadingTrivia;
16,143✔
613
    }
614

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

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

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

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

651
    walk(visitor: WalkVisitor, options: WalkOptions) {
652
        if (options.walkMode & InternalWalkMode.walkExpressions) {
15,734✔
653
            walk(this, 'func', visitor, options);
13,983✔
654
        }
655
    }
656

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

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

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

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

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

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

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

715
    public readonly kind = AstNodeKind.IfStatement;
2,009✔
716

717
    public readonly location: Location | undefined;
718

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

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

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

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

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

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

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

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

781
                if (body.length > 0) {
684✔
782
                    results.push(...body);
682✔
783
                }
784
            }
785
        }
786

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

790
        return results;
1,040✔
791
    }
792

793
    walk(visitor: WalkVisitor, options: WalkOptions) {
794
        if (options.walkMode & InternalWalkMode.walkExpressions) {
6,364✔
795
            walk(this, 'condition', visitor, options);
6,348✔
796
        }
797
        if (options.walkMode & InternalWalkMode.walkStatements) {
6,364✔
798
            walk(this, 'thenBranch', visitor, options);
6,362✔
799
        }
800
        if (this.elseBranch && options.walkMode & InternalWalkMode.walkStatements) {
6,364✔
801
            walk(this, 'elseBranch', visitor, options);
5,032✔
802
        }
803
    }
804

805
    get leadingTrivia(): Token[] {
806
        return this.tokens.if?.leadingTrivia ?? [];
2,668!
807
    }
808

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

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

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

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

850
    public readonly kind = AstNodeKind.IncrementStatement;
27✔
851

852
    public readonly location: Location | undefined;
853

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

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

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

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

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

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

911
    public readonly expressions: Array<Expression>;
912

913
    public readonly kind = AstNodeKind.PrintStatement;
1,202✔
914

915
    public readonly location: Location | undefined;
916

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

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

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

938
            result.push(
295✔
939
                ...expression.transpile(state)
940
            );
941
        }
942
        return result;
231✔
943
    }
944

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

951
    get leadingTrivia(): Token[] {
952
        return this.tokens.print?.leadingTrivia ?? [];
6,980!
953
    }
954

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

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

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

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

1001
    public readonly location: Location | undefined;
1002

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

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

1026
        }
1027
    }
1028

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

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

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

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

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

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

1079
    public readonly location: Location | undefined;
1080

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

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

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

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

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

1128
    public readonly location: Location | undefined;
1129

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

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

1139
        ];
1140
    }
1141

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

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

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

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

1178
    public readonly location: Location | undefined;
1179

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

1192
    walk(visitor: WalkVisitor, options: WalkOptions) {
1193
        if (options.walkMode & InternalWalkMode.walkExpressions) {
10,708✔
1194
            walk(this, 'value', visitor, options);
10,690✔
1195
        }
1196
    }
1197

1198
    get leadingTrivia(): Token[] {
1199
        return this.tokens.return?.leadingTrivia ?? [];
9,355!
1200
    }
1201

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

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

1228
    public readonly location: Location;
1229

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

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

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

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

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

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

1267
    public readonly location: Location;
1268

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

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

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

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

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

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

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

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

1339
    public readonly kind = AstNodeKind.ForStatement;
45✔
1340

1341
    public readonly location: Location | undefined;
1342

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

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

1379
        return result;
11✔
1380
    }
1381

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

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

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

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

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

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

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

1458
    public readonly kind = AstNodeKind.ForEachStatement;
40✔
1459

1460
    public readonly location: Location | undefined;
1461

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

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

1489
        return result;
5✔
1490
    }
1491

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

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

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

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

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

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

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

1557
    public readonly kind = AstNodeKind.WhileStatement;
37✔
1558

1559
    public readonly location: Location | undefined;
1560

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

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

1580
        return result;
8✔
1581
    }
1582

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

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

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

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

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

1642
    public readonly obj: Expression;
1643
    public readonly value: Expression;
1644

1645
    public readonly kind = AstNodeKind.DottedSetStatement;
299✔
1646

1647
    public readonly location: Location | undefined;
1648

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

1664
    }
1665

1666
    walk(visitor: WalkVisitor, options: WalkOptions) {
1667
        if (options.walkMode & InternalWalkMode.walkExpressions) {
754✔
1668
            walk(this, 'obj', visitor, options);
752✔
1669
            walk(this, 'value', visitor, options);
752✔
1670
        }
1671
    }
1672

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

1685
    get leadingTrivia(): Token[] {
1686
        return this.obj.leadingTrivia;
759✔
1687
    }
1688

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

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

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

1739
    public readonly kind = AstNodeKind.IndexedSetStatement;
37✔
1740

1741
    public readonly location: Location | undefined;
1742

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

1770
    }
1771

1772
    walk(visitor: WalkVisitor, options: WalkOptions) {
1773
        if (options.walkMode & InternalWalkMode.walkExpressions) {
117✔
1774
            walk(this, 'obj', visitor, options);
116✔
1775
            walkArray(this.indexes, visitor, options, this);
116✔
1776
            walk(this, 'value', visitor, options);
116✔
1777
        }
1778
    }
1779

1780
    get leadingTrivia(): Token[] {
1781
        return this.obj.leadingTrivia;
126✔
1782
    }
1783

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

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

1819
    public readonly kind = AstNodeKind.LibraryStatement;
16✔
1820

1821
    public readonly location: Location | undefined;
1822

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

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

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

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

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

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

1877
    public readonly tokens: {
1878
        readonly namespace?: Token;
1879
        readonly endNamespace?: Token;
1880
    };
1881

1882
    public readonly nameExpression: VariableExpression | DottedGetExpression;
1883
    public readonly body: Body;
1884

1885
    public readonly kind = AstNodeKind.NamespaceStatement;
626✔
1886

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

1894
    public get location() {
1895
        return this.cacheLocation();
384✔
1896
    }
1897
    private _location: Location | undefined;
1898

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

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

1920
    public get leadingTrivia(): Token[] {
1921
        return this.tokens.namespace?.leadingTrivia;
1,822!
1922
    }
1923

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

1928
    public getNameParts() {
1929
        let parts = util.getAllDottedGetParts(this.nameExpression);
1,406✔
1930

1931
        if ((this.parent as Body)?.parent?.kind === AstNodeKind.NamespaceStatement) {
1,406!
1932
            parts = (this.parent.parent as NamespaceStatement).getNameParts().concat(parts);
63✔
1933
        }
1934
        return parts;
1,406✔
1935
    }
1936

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

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

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

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

1974
    walk(visitor: WalkVisitor, options: WalkOptions) {
1975
        if (options.walkMode & InternalWalkMode.walkExpressions) {
3,119✔
1976
            walk(this, 'nameExpression', visitor, options);
2,544✔
1977
        }
1978

1979
        if (this.body.statements.length > 0 && options.walkMode & InternalWalkMode.walkStatements) {
3,119✔
1980
            walk(this, 'body', visitor, options);
2,919✔
1981
        }
1982
    }
1983

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

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

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

2034
    public readonly tokens: {
2035
        readonly import?: Token;
2036
        readonly path: Token;
2037
    };
2038

2039
    public readonly kind = AstNodeKind.ImportStatement;
207✔
2040

2041
    public readonly location: Location;
2042

2043
    public readonly filePath: string;
2044

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

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

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

2071
    get leadingTrivia(): Token[] {
2072
        return this.tokens.import?.leadingTrivia ?? [];
576!
2073
    }
2074

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

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

2115
    public readonly kind = AstNodeKind.InterfaceStatement;
163✔
2116

2117
    public readonly tokens = {} as {
163✔
2118
        readonly interface?: Token;
2119
        readonly name: Identifier;
2120
        readonly extends?: Token;
2121
        readonly endInterface?: Token;
2122
    };
2123

2124
    public readonly location: Location | undefined;
2125

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

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

2134

2135
    public hasParentInterface() {
2136
        return !!this.parentInterfaceName;
×
2137
    }
2138

2139
    public get leadingTrivia(): Token[] {
2140
        return this.tokens.interface?.leadingTrivia;
407!
2141
    }
2142

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

2147

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

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

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

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

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

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

2258
        if (options.walkMode & InternalWalkMode.walkStatements) {
693!
2259
            walkArray(this.body, visitor, options, this);
693✔
2260
        }
2261
    }
2262

2263
    getType(options: GetTypeOptions) {
2264
        const superIface = this.parentInterfaceName?.getType(options) as InterfaceType;
133✔
2265

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

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

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

2326
    public readonly kind = AstNodeKind.InterfaceFieldStatement;
189✔
2327

2328
    public readonly typeExpression?: TypeExpression;
2329

2330
    public readonly location: Location | undefined;
2331

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

2338
    public get leadingTrivia(): Token[] {
2339
        return this.tokens.optional?.leadingTrivia ?? this.tokens.name.leadingTrivia;
502✔
2340
    }
2341

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

2346
    public get isOptional() {
2347
        return !!this.tokens.optional;
190✔
2348
    }
2349

2350
    walk(visitor: WalkVisitor, options: WalkOptions) {
2351
        if (options.walkMode & InternalWalkMode.walkExpressions) {
1,175✔
2352
            walk(this, 'typeExpression', visitor, options);
1,018✔
2353
        }
2354
    }
2355

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

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

2391
    public getType(options: GetTypeOptions): BscType {
2392
        return this.typeExpression?.getType(options) ?? DynamicType.instance;
174✔
2393
    }
2394

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

2406
}
2407

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

2437
    public readonly kind = AstNodeKind.InterfaceMethodStatement;
46✔
2438

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

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

2467
    public readonly params: FunctionParameterExpression[];
2468
    public readonly returnTypeExpression?: TypeExpression;
2469

2470
    public get isOptional() {
2471
        return !!this.tokens.optional;
41✔
2472
    }
2473

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

2478
    walk(visitor: WalkVisitor, options: WalkOptions) {
2479
        if (options.walkMode & InternalWalkMode.walkExpressions) {
204✔
2480
            walk(this, 'returnTypeExpression', visitor, options);
179✔
2481
        }
2482
    }
2483

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

2538
    public getType(options: GetTypeOptions): TypedFunctionType {
2539
        //if there's a defined return type, use that
2540
        let returnType = this.returnTypeExpression?.getType(options);
28✔
2541
        const isSub = this.tokens.functionType?.kind === TokenKind.Sub || !returnType;
28!
2542
        //if we don't have a return type and this is a sub, set the return type to `void`. else use `dynamic`
2543
        if (!returnType) {
28✔
2544
            returnType = isSub ? VoidType.instance : DynamicType.instance;
10!
2545
        }
2546

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

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

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

2602
        for (let statement of this.body) {
688✔
2603
            if (isMethodStatement(statement)) {
689✔
2604
                this.methods.push(statement);
361✔
2605
                this.memberMap[statement?.tokens.name?.text.toLowerCase()] = statement;
361!
2606
            } else if (isFieldStatement(statement)) {
328✔
2607
                this.fields.push(statement);
327✔
2608
                this.memberMap[statement?.tokens.name?.text.toLowerCase()] = statement;
327!
2609
            }
2610
        }
2611

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

2619
    public readonly kind = AstNodeKind.ClassStatement;
688✔
2620

2621

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

2634

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

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

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

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

2664
    public readonly location: Location | undefined;
2665

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

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

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

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

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

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

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

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

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

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

2819
    /**
2820
     * Determine if the specified field was declared in one of the ancestor classes
2821
     */
2822
    public isFieldDeclaredByAncestor(fieldName: string, ancestors: ClassStatement[]) {
UNCOV
2823
        let lowerFieldName = fieldName.toLowerCase();
×
UNCOV
2824
        for (let ancestor of ancestors) {
×
UNCOV
2825
            if (ancestor.memberMap[lowerFieldName]) {
×
UNCOV
2826
                return true;
×
2827
            }
2828
        }
UNCOV
2829
        return false;
×
2830
    }
2831

2832
    /**
2833
     * The builder is a function that assigns all of the methods and property names to a class instance.
2834
     * This needs to be a separate function so that child classes can call the builder from their parent
2835
     * without instantiating the parent constructor at that point in time.
2836
     */
2837
    private getTranspiledBuilder(state: BrsTranspileState) {
2838
        let result = [] as TranspileResult;
50✔
2839
        result.push(`function ${this.getBuilderName(this.getName(ParseMode.BrightScript)!)}()\n`);
50✔
2840
        state.blockDepth++;
50✔
2841
        //indent
2842
        result.push(state.indent());
50✔
2843

2844
        /**
2845
         * The lineage of this class. index 0 is a direct parent, index 1 is index 0's parent, etc...
2846
         */
2847
        let ancestors = this.getAncestors(state);
50✔
2848

2849
        //construct parent class or empty object
2850
        if (ancestors[0]) {
50✔
2851
            const ancestorNamespace = ancestors[0].findAncestor<NamespaceStatement>(isNamespaceStatement);
18✔
2852
            let fullyQualifiedClassName = util.getFullyQualifiedClassName(
18✔
2853
                ancestors[0].getName(ParseMode.BrighterScript)!,
2854
                ancestorNamespace?.getName(ParseMode.BrighterScript)
54✔
2855
            );
2856
            result.push(
18✔
2857
                'instance = ',
2858
                this.getBuilderName(fullyQualifiedClassName), '()');
2859
        } else {
2860
            //use an empty object.
2861
            result.push('instance = {}');
32✔
2862
        }
2863
        result.push(
50✔
2864
            state.newline,
2865
            state.indent()
2866
        );
2867
        let parentClassIndex = this.getParentClassIndex(state);
50✔
2868

2869
        let body = this.body;
50✔
2870
        //inject an empty "new" method if missing
2871
        if (!this.getConstructorFunction()) {
50✔
2872
            body = [
29✔
2873
                createMethodStatement('new', TokenKind.Sub),
2874
                ...this.body
2875
            ];
2876
        }
2877

2878
        for (let statement of body) {
50✔
2879
            //is field statement
2880
            if (isFieldStatement(statement)) {
79✔
2881
                //do nothing with class fields in this situation, they are handled elsewhere
2882
                continue;
14✔
2883

2884
                //methods
2885
            } else if (isMethodStatement(statement)) {
65!
2886

2887
                //store overridden parent methods as super{parentIndex}_{methodName}
2888
                if (
65✔
2889
                    //is override method
2890
                    statement.tokens.override ||
176✔
2891
                    //is constructor function in child class
2892
                    (statement.tokens.name.text.toLowerCase() === 'new' && ancestors[0])
2893
                ) {
2894
                    result.push(
22✔
2895
                        `instance.super${parentClassIndex}_${statement.tokens.name.text} = instance.${statement.tokens.name.text}`,
2896
                        state.newline,
2897
                        state.indent()
2898
                    );
2899
                }
2900

2901
                state.classStatement = this;
65✔
2902
                state.skipLeadingComments = true;
65✔
2903
                //add leading comments
2904
                if (statement.leadingTrivia.filter(token => token.kind === TokenKind.Comment).length > 0) {
78✔
2905
                    result.push(
2✔
2906
                        ...state.transpileComments(statement.leadingTrivia),
2907
                        state.indent()
2908
                    );
2909
                }
2910
                result.push(
65✔
2911
                    'instance.',
2912
                    state.transpileToken(statement.tokens.name),
2913
                    ' = ',
2914
                    ...statement.transpile(state),
2915
                    state.newline,
2916
                    state.indent()
2917
                );
2918
                state.skipLeadingComments = false;
65✔
2919
                delete state.classStatement;
65✔
2920
            } else {
2921
                //other random statements (probably just comments)
UNCOV
2922
                result.push(
×
2923
                    ...statement.transpile(state),
2924
                    state.newline,
2925
                    state.indent()
2926
                );
2927
            }
2928
        }
2929
        //return the instance
2930
        result.push('return instance\n');
50✔
2931
        state.blockDepth--;
50✔
2932
        result.push(state.indent());
50✔
2933
        result.push(`end function`);
50✔
2934
        return result;
50✔
2935
    }
2936

2937
    /**
2938
     * The class function is the function with the same name as the class. This is the function that
2939
     * consumers should call to create a new instance of that class.
2940
     * This invokes the builder, gets an instance of the class, then invokes the "new" function on that class.
2941
     */
2942
    private getTranspiledClassFunction(state: BrsTranspileState) {
2943
        let result: TranspileResult = state.transpileAnnotations(this);
50✔
2944
        const constructorFunction = this.getConstructorFunction();
50✔
2945
        const constructorParams = constructorFunction ? constructorFunction.func.parameters : [];
50✔
2946

2947
        result.push(
50✔
2948
            state.transpileLeadingComments(this.tokens.class),
2949
            state.sourceNode(this.tokens.class, 'function'),
2950
            state.sourceNode(this.tokens.class, ' '),
2951
            state.sourceNode(this.tokens.name, this.getName(ParseMode.BrightScript)),
2952
            `(`
2953
        );
2954
        let i = 0;
50✔
2955
        for (let param of constructorParams) {
50✔
2956
            if (i > 0) {
8✔
2957
                result.push(', ');
2✔
2958
            }
2959
            result.push(
8✔
2960
                param.transpile(state)
2961
            );
2962
            i++;
8✔
2963
        }
2964
        result.push(
50✔
2965
            ')',
2966
            '\n'
2967
        );
2968

2969
        state.blockDepth++;
50✔
2970
        result.push(state.indent());
50✔
2971
        result.push(`instance = ${this.getBuilderName(this.getName(ParseMode.BrightScript)!)}()\n`);
50✔
2972

2973
        result.push(state.indent());
50✔
2974
        result.push(`instance.new(`);
50✔
2975

2976
        //append constructor arguments
2977
        i = 0;
50✔
2978
        for (let param of constructorParams) {
50✔
2979
            if (i > 0) {
8✔
2980
                result.push(', ');
2✔
2981
            }
2982
            result.push(
8✔
2983
                state.transpileToken(param.tokens.name)
2984
            );
2985
            i++;
8✔
2986
        }
2987
        result.push(
50✔
2988
            ')',
2989
            '\n'
2990
        );
2991

2992
        result.push(state.indent());
50✔
2993
        result.push(`return instance\n`);
50✔
2994

2995
        state.blockDepth--;
50✔
2996
        result.push(state.indent());
50✔
2997
        result.push(`end function`);
50✔
2998
        return result;
50✔
2999
    }
3000

3001
    walk(visitor: WalkVisitor, options: WalkOptions) {
3002
        //visitor-less walk function to do parent linking
3003
        walk(this, 'parentClassName', null, options);
2,635✔
3004

3005
        if (options.walkMode & InternalWalkMode.walkStatements) {
2,635!
3006
            walkArray(this.body, visitor, options, this);
2,635✔
3007
        }
3008
    }
3009

3010
    getType(options: GetTypeOptions) {
3011
        const superClass = this.parentClassName?.getType(options) as ClassType;
542✔
3012

3013
        const resultType = new ClassType(this.getName(ParseMode.BrighterScript), superClass);
542✔
3014

3015
        for (const statement of this.methods) {
542✔
3016
            const funcType = statement?.func.getType({ ...options, typeChain: undefined }); //no typechain needed
285!
3017
            let flag = SymbolTypeFlag.runtime;
285✔
3018
            if (statement.accessModifier?.kind === TokenKind.Private) {
285✔
3019
                flag |= SymbolTypeFlag.private;
9✔
3020
            }
3021
            if (statement.accessModifier?.kind === TokenKind.Protected) {
285✔
3022
                flag |= SymbolTypeFlag.protected;
8✔
3023
            }
3024
            resultType.addMember(statement?.tokens.name?.text, { definingNode: statement }, funcType, flag);
285!
3025
        }
3026
        for (const statement of this.fields) {
542✔
3027
            const fieldType = statement.getType({ ...options, typeChain: undefined }); //no typechain needed
270✔
3028
            let flag = SymbolTypeFlag.runtime;
270✔
3029
            if (statement.isOptional) {
270✔
3030
                flag |= SymbolTypeFlag.optional;
7✔
3031
            }
3032
            if (statement.tokens.accessModifier?.kind === TokenKind.Private) {
270✔
3033
                flag |= SymbolTypeFlag.private;
19✔
3034
            }
3035
            if (statement.tokens.accessModifier?.kind === TokenKind.Protected) {
270✔
3036
                flag |= SymbolTypeFlag.protected;
9✔
3037
            }
3038
            resultType.addMember(statement?.tokens.name?.text, { definingNode: statement, isInstance: true }, fieldType, flag);
270!
3039
        }
3040
        options.typeChain?.push(new TypeChainEntry({ name: resultType.name, type: resultType, data: options.data, astNode: this }));
542✔
3041
        return resultType;
542✔
3042
    }
3043

3044
    public clone() {
3045
        return this.finalizeClone(
11✔
3046
            new ClassStatement({
3047
                class: util.cloneToken(this.tokens.class),
3048
                name: util.cloneToken(this.tokens.name),
3049
                body: this.body?.map(x => x?.clone()),
10✔
3050
                endClass: util.cloneToken(this.tokens.endClass),
3051
                extends: util.cloneToken(this.tokens.extends),
3052
                parentClassName: this.parentClassName?.clone()
33✔
3053
            }),
3054
            ['body', 'parentClassName']
3055
        );
3056
    }
3057
}
3058

3059
const accessModifiers = [
1✔
3060
    TokenKind.Public,
3061
    TokenKind.Protected,
3062
    TokenKind.Private
3063
];
3064
export class MethodStatement extends FunctionStatement {
1✔
3065
    constructor(
3066
        options: {
3067
            modifiers?: Token | Token[];
3068
            name: Identifier;
3069
            func: FunctionExpression;
3070
            override?: Token;
3071
        }
3072
    ) {
3073
        super(options);
401✔
3074
        if (options.modifiers) {
401✔
3075
            if (Array.isArray(options.modifiers)) {
40✔
3076
                this.modifiers.push(...options.modifiers);
4✔
3077
            } else {
3078
                this.modifiers.push(options.modifiers);
36✔
3079
            }
3080
        }
3081
        this.tokens = {
401✔
3082
            ...this.tokens,
3083
            override: options.override
3084
        };
3085
        this.location = util.createBoundingLocation(
401✔
3086
            ...(this.modifiers),
3087
            util.createBoundingLocationFromTokens(this.tokens),
3088
            this.func
3089
        );
3090
    }
3091

3092
    public readonly kind = AstNodeKind.MethodStatement as AstNodeKind;
401✔
3093

3094
    public readonly modifiers: Token[] = [];
401✔
3095

3096
    public readonly tokens: {
3097
        readonly name: Identifier;
3098
        readonly override?: Token;
3099
    };
3100

3101
    public get accessModifier() {
3102
        return this.modifiers.find(x => accessModifiers.includes(x.kind));
678✔
3103
    }
3104

3105
    public readonly location: Location | undefined;
3106

3107
    /**
3108
     * Get the name of this method.
3109
     */
3110
    public getName(parseMode: ParseMode) {
3111
        return this.tokens.name.text;
359✔
3112
    }
3113

3114
    public get leadingTrivia(): Token[] {
3115
        return this.func.leadingTrivia;
800✔
3116
    }
3117

3118
    transpile(state: BrsTranspileState) {
3119
        if (this.tokens.name.text.toLowerCase() === 'new') {
65✔
3120
            this.ensureSuperConstructorCall(state);
50✔
3121
            //TODO we need to undo this at the bottom of this method
3122
            this.injectFieldInitializersForConstructor(state);
50✔
3123
        }
3124
        //TODO - remove type information from these methods because that doesn't work
3125
        //convert the `super` calls into the proper methods
3126
        const parentClassIndex = state.classStatement.getParentClassIndex(state);
65✔
3127
        const visitor = createVisitor({
65✔
3128
            VariableExpression: e => {
3129
                if (e.tokens.name.text.toLocaleLowerCase() === 'super') {
61✔
3130
                    state.editor.setProperty(e.tokens.name, 'text', `m.super${parentClassIndex}_new`);
18✔
3131
                }
3132
            },
3133
            DottedGetExpression: e => {
3134
                const beginningVariable = util.findBeginningVariableExpression(e);
30✔
3135
                const lowerName = beginningVariable?.getName(ParseMode.BrighterScript).toLowerCase();
30!
3136
                if (lowerName === 'super') {
30✔
3137
                    state.editor.setProperty(beginningVariable.tokens.name, 'text', 'm');
7✔
3138
                    state.editor.setProperty(e.tokens.name, 'text', `super${parentClassIndex}_${e.tokens.name.text}`);
7✔
3139
                }
3140
            }
3141
        });
3142
        const walkOptions: WalkOptions = { walkMode: WalkMode.visitExpressions };
65✔
3143
        for (const statement of this.func.body.statements) {
65✔
3144
            visitor(statement, undefined);
62✔
3145
            statement.walk(visitor, walkOptions);
62✔
3146
        }
3147
        return this.func.transpile(state);
65✔
3148
    }
3149

3150
    getTypedef(state: BrsTranspileState) {
3151
        const result: TranspileResult = [];
23✔
3152
        for (let comment of util.getLeadingComments(this) ?? []) {
23!
UNCOV
3153
            result.push(
×
3154
                comment.text,
3155
                state.newline,
3156
                state.indent()
3157
            );
3158
        }
3159
        for (let annotation of this.annotations ?? []) {
23✔
3160
            result.push(
2✔
3161
                ...annotation.getTypedef(state),
3162
                state.newline,
3163
                state.indent()
3164
            );
3165
        }
3166
        if (this.accessModifier) {
23✔
3167
            result.push(
8✔
3168
                this.accessModifier.text,
3169
                ' '
3170
            );
3171
        }
3172
        if (this.tokens.override) {
23✔
3173
            result.push('override ');
1✔
3174
        }
3175
        result.push(
23✔
3176
            ...this.func.getTypedef(state)
3177
        );
3178
        return result;
23✔
3179
    }
3180

3181
    /**
3182
     * All child classes must call the parent constructor. The type checker will warn users when they don't call it in their own class,
3183
     * but we still need to call it even if they have omitted it. This injects the super call if it's missing
3184
     */
3185
    private ensureSuperConstructorCall(state: BrsTranspileState) {
3186
        //if this class doesn't extend another class, quit here
3187
        if (state.classStatement!.getAncestors(state).length === 0) {
50✔
3188
            return;
32✔
3189
        }
3190

3191
        //check whether any calls to super exist
3192
        let containsSuperCall =
3193
            this.func.body.statements.findIndex((x) => {
18✔
3194
                //is a call statement
3195
                return isExpressionStatement(x) && isCallExpression(x.expression) &&
8✔
3196
                    //is a call to super
3197
                    util.findBeginningVariableExpression(x.expression.callee as any).tokens.name?.text.toLowerCase() === 'super';
21!
3198
            }) !== -1;
3199

3200
        //if a call to super exists, quit here
3201
        if (containsSuperCall) {
18✔
3202
            return;
7✔
3203
        }
3204

3205
        //this is a child class, and the constructor doesn't contain a call to super. Inject one
3206
        const superCall = new ExpressionStatement({
11✔
3207
            expression: new CallExpression({
3208
                callee: new VariableExpression({
3209
                    name: {
3210
                        kind: TokenKind.Identifier,
3211
                        text: 'super',
3212
                        isReserved: false,
3213
                        location: state.classStatement.tokens.name.location,
3214
                        leadingWhitespace: '',
3215
                        leadingTrivia: []
3216
                    }
3217
                }),
3218
                openingParen: {
3219
                    kind: TokenKind.LeftParen,
3220
                    text: '(',
3221
                    isReserved: false,
3222
                    location: state.classStatement.tokens.name.location,
3223
                    leadingWhitespace: '',
3224
                    leadingTrivia: []
3225
                },
3226
                closingParen: {
3227
                    kind: TokenKind.RightParen,
3228
                    text: ')',
3229
                    isReserved: false,
3230
                    location: state.classStatement.tokens.name.location,
3231
                    leadingWhitespace: '',
3232
                    leadingTrivia: []
3233
                },
3234
                args: []
3235
            })
3236
        });
3237
        state.editor.arrayUnshift(this.func.body.statements, superCall);
11✔
3238
    }
3239

3240
    /**
3241
     * Inject field initializers at the top of the `new` function (after any present `super()` call)
3242
     */
3243
    private injectFieldInitializersForConstructor(state: BrsTranspileState) {
3244
        let startingIndex = state.classStatement!.hasParentClass() ? 1 : 0;
50✔
3245

3246
        let newStatements = [] as Statement[];
50✔
3247
        //insert the field initializers in order
3248
        for (let field of state.classStatement!.fields) {
50✔
3249
            let thisQualifiedName = { ...field.tokens.name };
14✔
3250
            thisQualifiedName.text = 'm.' + field.tokens.name?.text;
14!
3251
            const fieldAssignment = field.initialValue
14✔
3252
                ? new AssignmentStatement({
14✔
3253
                    equals: field.tokens.equals,
3254
                    name: thisQualifiedName,
3255
                    value: field.initialValue
3256
                })
3257
                : new AssignmentStatement({
3258
                    equals: createToken(TokenKind.Equal, '=', field.tokens.name.location),
3259
                    name: thisQualifiedName,
3260
                    //if there is no initial value, set the initial value to `invalid`
3261
                    value: createInvalidLiteral('invalid', field.tokens.name.location)
3262
                });
3263
            // Add parent so namespace lookups work
3264
            fieldAssignment.parent = state.classStatement;
14✔
3265
            newStatements.push(fieldAssignment);
14✔
3266
        }
3267
        state.editor.arraySplice(this.func.body.statements, startingIndex, 0, ...newStatements);
50✔
3268
    }
3269

3270
    walk(visitor: WalkVisitor, options: WalkOptions) {
3271
        if (options.walkMode & InternalWalkMode.walkExpressions) {
2,170✔
3272
            walk(this, 'func', visitor, options);
1,729✔
3273
        }
3274
    }
3275

3276
    public clone() {
3277
        return this.finalizeClone(
5✔
3278
            new MethodStatement({
3279
                modifiers: this.modifiers?.map(m => util.cloneToken(m)),
1✔
3280
                name: util.cloneToken(this.tokens.name),
3281
                func: this.func?.clone(),
15✔
3282
                override: util.cloneToken(this.tokens.override)
3283
            }),
3284
            ['func']
3285
        );
3286
    }
3287
}
3288

3289
export class FieldStatement extends Statement implements TypedefProvider {
1✔
3290
    constructor(options: {
3291
        accessModifier?: Token;
3292
        name: Identifier;
3293
        as?: Token;
3294
        typeExpression?: TypeExpression;
3295
        equals?: Token;
3296
        initialValue?: Expression;
3297
        optional?: Token;
3298
    }) {
3299
        super();
327✔
3300
        this.tokens = {
327✔
3301
            accessModifier: options.accessModifier,
3302
            name: options.name,
3303
            as: options.as,
3304
            equals: options.equals,
3305
            optional: options.optional
3306
        };
3307
        this.typeExpression = options.typeExpression;
327✔
3308
        this.initialValue = options.initialValue;
327✔
3309

3310
        this.location = util.createBoundingLocation(
327✔
3311
            util.createBoundingLocationFromTokens(this.tokens),
3312
            this.typeExpression,
3313
            this.initialValue
3314
        );
3315
    }
3316

3317
    public readonly tokens: {
3318
        readonly accessModifier?: Token;
3319
        readonly name: Identifier;
3320
        readonly as?: Token;
3321
        readonly equals?: Token;
3322
        readonly optional?: Token;
3323
    };
3324

3325
    public readonly typeExpression?: TypeExpression;
3326
    public readonly initialValue?: Expression;
3327

3328
    public readonly kind = AstNodeKind.FieldStatement;
327✔
3329

3330
    /**
3331
     * Derive a ValueKind from the type token, or the initial value.
3332
     * Defaults to `DynamicType`
3333
     */
3334
    getType(options: GetTypeOptions) {
3335
        return this.typeExpression?.getType({ ...options, flags: SymbolTypeFlag.typetime }) ??
311✔
3336
            this.initialValue?.getType({ ...options, flags: SymbolTypeFlag.runtime }) ?? DynamicType.instance;
725✔
3337
    }
3338

3339
    public readonly location: Location | undefined;
3340

3341
    public get leadingTrivia(): Token[] {
3342
        return this.tokens.accessModifier?.leadingTrivia ?? this.tokens.optional?.leadingTrivia ?? this.tokens.name.leadingTrivia;
639✔
3343
    }
3344

3345
    public get isOptional() {
3346
        return !!this.tokens.optional;
287✔
3347
    }
3348

3349
    transpile(state: BrsTranspileState): TranspileResult {
UNCOV
3350
        throw new Error('transpile not implemented for ' + Object.getPrototypeOf(this).constructor.name);
×
3351
    }
3352

3353
    getTypedef(state: BrsTranspileState) {
3354
        const result = [];
10✔
3355
        if (this.tokens.name) {
10!
3356
            for (let comment of util.getLeadingComments(this) ?? []) {
10!
UNCOV
3357
                result.push(
×
3358
                    comment.text,
3359
                    state.newline,
3360
                    state.indent()
3361
                );
3362
            }
3363
            for (let annotation of this.annotations ?? []) {
10✔
3364
                result.push(
2✔
3365
                    ...annotation.getTypedef(state),
3366
                    state.newline,
3367
                    state.indent()
3368
                );
3369
            }
3370

3371
            let type = this.getType({ flags: SymbolTypeFlag.typetime });
10✔
3372
            if (isInvalidType(type) || isVoidType(type)) {
10!
3373
                type = new DynamicType();
×
3374
            }
3375

3376
            result.push(
10✔
3377
                this.tokens.accessModifier?.text ?? 'public',
60!
3378
                ' '
3379
            );
3380
            if (this.isOptional) {
10!
UNCOV
3381
                result.push(this.tokens.optional.text, ' ');
×
3382
            }
3383
            result.push(this.tokens.name?.text,
10!
3384
                ' as ',
3385
                type.toTypeString()
3386
            );
3387
        }
3388
        return result;
10✔
3389
    }
3390

3391
    walk(visitor: WalkVisitor, options: WalkOptions) {
3392
        if (options.walkMode & InternalWalkMode.walkExpressions) {
1,596✔
3393
            walk(this, 'typeExpression', visitor, options);
1,392✔
3394
            walk(this, 'initialValue', visitor, options);
1,392✔
3395
        }
3396
    }
3397

3398
    public clone() {
3399
        return this.finalizeClone(
4✔
3400
            new FieldStatement({
3401
                accessModifier: util.cloneToken(this.tokens.accessModifier),
3402
                name: util.cloneToken(this.tokens.name),
3403
                as: util.cloneToken(this.tokens.as),
3404
                typeExpression: this.typeExpression?.clone(),
12✔
3405
                equals: util.cloneToken(this.tokens.equals),
3406
                initialValue: this.initialValue?.clone(),
12✔
3407
                optional: util.cloneToken(this.tokens.optional)
3408
            }),
3409
            ['initialValue']
3410
        );
3411
    }
3412
}
3413

3414
export type MemberStatement = FieldStatement | MethodStatement;
3415

3416
export class TryCatchStatement extends Statement {
1✔
3417
    constructor(options?: {
3418
        try?: Token;
3419
        endTry?: Token;
3420
        tryBranch?: Block;
3421
        catchStatement?: CatchStatement;
3422
    }) {
3423
        super();
40✔
3424
        this.tokens = {
40✔
3425
            try: options.try,
3426
            endTry: options.endTry
3427
        };
3428
        this.tryBranch = options.tryBranch;
40✔
3429
        this.catchStatement = options.catchStatement;
40✔
3430
        this.location = util.createBoundingLocation(
40✔
3431
            this.tokens.try,
3432
            this.tryBranch,
3433
            this.catchStatement,
3434
            this.tokens.endTry
3435
        );
3436
    }
3437

3438
    public readonly tokens: {
3439
        readonly try?: Token;
3440
        readonly endTry?: Token;
3441
    };
3442

3443
    public readonly tryBranch: Block;
3444
    public readonly catchStatement: CatchStatement;
3445

3446
    public readonly kind = AstNodeKind.TryCatchStatement;
40✔
3447

3448
    public readonly location: Location | undefined;
3449

3450
    public transpile(state: BrsTranspileState): TranspileResult {
3451
        return [
7✔
3452
            state.transpileToken(this.tokens.try, 'try'),
3453
            ...this.tryBranch.transpile(state),
3454
            state.newline,
3455
            state.indent(),
3456
            ...(this.catchStatement?.transpile(state) ?? ['catch']),
42!
3457
            state.newline,
3458
            state.indent(),
3459
            state.transpileToken(this.tokens.endTry!, 'end try')
3460
        ];
3461
    }
3462

3463
    public walk(visitor: WalkVisitor, options: WalkOptions) {
3464
        if (this.tryBranch && options.walkMode & InternalWalkMode.walkStatements) {
87!
3465
            walk(this, 'tryBranch', visitor, options);
87✔
3466
            walk(this, 'catchStatement', visitor, options);
87✔
3467
        }
3468
    }
3469

3470
    public get leadingTrivia(): Token[] {
3471
        return this.tokens.try?.leadingTrivia ?? [];
88!
3472
    }
3473

3474
    public get endTrivia(): Token[] {
3475
        return this.tokens.endTry?.leadingTrivia ?? [];
1!
3476
    }
3477

3478
    public clone() {
3479
        return this.finalizeClone(
3✔
3480
            new TryCatchStatement({
3481
                try: util.cloneToken(this.tokens.try),
3482
                endTry: util.cloneToken(this.tokens.endTry),
3483
                tryBranch: this.tryBranch?.clone(),
9✔
3484
                catchStatement: this.catchStatement?.clone()
9✔
3485
            }),
3486
            ['tryBranch', 'catchStatement']
3487
        );
3488
    }
3489
}
3490

3491
export class CatchStatement extends Statement {
1✔
3492
    constructor(options?: {
3493
        catch?: Token;
3494
        exceptionVariableExpression?: Expression;
3495
        catchBranch?: Block;
3496
    }) {
3497
        super();
37✔
3498
        this.tokens = {
37✔
3499
            catch: options?.catch
111!
3500
        };
3501
        this.exceptionVariableExpression = options?.exceptionVariableExpression;
37!
3502
        this.catchBranch = options?.catchBranch;
37!
3503
        this.location = util.createBoundingLocation(
37✔
3504
            this.tokens.catch,
3505
            this.exceptionVariableExpression,
3506
            this.catchBranch
3507
        );
3508
    }
3509

3510
    public readonly tokens: {
3511
        readonly catch?: Token;
3512
    };
3513

3514
    public readonly exceptionVariableExpression?: Expression;
3515

3516
    public readonly catchBranch?: Block;
3517

3518
    public readonly kind = AstNodeKind.CatchStatement;
37✔
3519

3520
    public readonly location: Location | undefined;
3521

3522
    public transpile(state: BrsTranspileState): TranspileResult {
3523
        return [
7✔
3524
            state.transpileToken(this.tokens.catch, 'catch'),
3525
            ' ',
3526
            this.exceptionVariableExpression?.transpile(state) ?? [
42✔
3527
                //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
3528
                this.getSymbolTable()?.hasSymbol('e', SymbolTypeFlag.runtime)
6!
3529
                    ? '__bsc_error'
2✔
3530
                    : 'e'
3531
            ],
3532
            ...(this.catchBranch?.transpile(state) ?? [])
42!
3533
        ];
3534
    }
3535

3536
    public walk(visitor: WalkVisitor, options: WalkOptions) {
3537
        if (this.catchBranch && options.walkMode & InternalWalkMode.walkStatements) {
84!
3538
            walk(this, 'catchBranch', visitor, options);
84✔
3539
        }
3540
    }
3541

3542
    public get leadingTrivia(): Token[] {
3543
        return this.tokens.catch?.leadingTrivia ?? [];
50!
3544
    }
3545

3546
    public clone() {
3547
        return this.finalizeClone(
2✔
3548
            new CatchStatement({
3549
                catch: util.cloneToken(this.tokens.catch),
3550
                exceptionVariableExpression: this.exceptionVariableExpression?.clone(),
6!
3551
                catchBranch: this.catchBranch?.clone()
6✔
3552
            }),
3553
            ['catchBranch']
3554
        );
3555
    }
3556
}
3557

3558
export class ThrowStatement extends Statement {
1✔
3559
    constructor(options?: {
3560
        throw?: Token;
3561
        expression?: Expression;
3562
    }) {
3563
        super();
14✔
3564
        this.tokens = {
14✔
3565
            throw: options.throw
3566
        };
3567
        this.expression = options.expression;
14✔
3568
        this.location = util.createBoundingLocation(
14✔
3569
            this.tokens.throw,
3570
            this.expression
3571
        );
3572
    }
3573

3574
    public readonly tokens: {
3575
        readonly throw?: Token;
3576
    };
3577
    public readonly expression?: Expression;
3578

3579
    public readonly kind = AstNodeKind.ThrowStatement;
14✔
3580

3581
    public readonly location: Location | undefined;
3582

3583
    public transpile(state: BrsTranspileState) {
3584
        const result = [
5✔
3585
            state.transpileToken(this.tokens.throw, 'throw'),
3586
            ' '
3587
        ] as TranspileResult;
3588

3589
        //if we have an expression, transpile it
3590
        if (this.expression) {
5✔
3591
            result.push(
4✔
3592
                ...this.expression.transpile(state)
3593
            );
3594

3595
            //no expression found. Rather than emit syntax errors, provide a generic error message
3596
        } else {
3597
            result.push('"User-specified exception"');
1✔
3598
        }
3599
        return result;
5✔
3600
    }
3601

3602
    public walk(visitor: WalkVisitor, options: WalkOptions) {
3603
        if (this.expression && options.walkMode & InternalWalkMode.walkExpressions) {
35✔
3604
            walk(this, 'expression', visitor, options);
28✔
3605
        }
3606
    }
3607

3608
    public get leadingTrivia(): Token[] {
3609
        return this.tokens.throw?.leadingTrivia ?? [];
54!
3610
    }
3611

3612
    public clone() {
3613
        return this.finalizeClone(
2✔
3614
            new ThrowStatement({
3615
                throw: util.cloneToken(this.tokens.throw),
3616
                expression: this.expression?.clone()
6✔
3617
            }),
3618
            ['expression']
3619
        );
3620
    }
3621
}
3622

3623

3624
export class EnumStatement extends Statement implements TypedefProvider {
1✔
3625
    constructor(options: {
3626
        enum?: Token;
3627
        name: Identifier;
3628
        endEnum?: Token;
3629
        body: Array<EnumMemberStatement>;
3630
    }) {
3631
        super();
170✔
3632
        this.tokens = {
170✔
3633
            enum: options.enum,
3634
            name: options.name,
3635
            endEnum: options.endEnum
3636
        };
3637
        this.symbolTable = new SymbolTable('Enum');
170✔
3638
        this.body = options.body ?? [];
170✔
3639
    }
3640

3641
    public readonly tokens: {
3642
        readonly enum?: Token;
3643
        readonly name: Identifier;
3644
        readonly endEnum?: Token;
3645
    };
3646
    public readonly body: Array<EnumMemberStatement>;
3647

3648
    public readonly kind = AstNodeKind.EnumStatement;
170✔
3649

3650
    public get location(): Location | undefined {
3651
        return util.createBoundingLocation(
129✔
3652
            this.tokens.enum,
3653
            this.tokens.name,
3654
            ...this.body,
3655
            this.tokens.endEnum
3656
        );
3657
    }
3658

3659
    public getMembers() {
3660
        const result = [] as EnumMemberStatement[];
331✔
3661
        for (const statement of this.body) {
331✔
3662
            if (isEnumMemberStatement(statement)) {
685!
3663
                result.push(statement);
685✔
3664
            }
3665
        }
3666
        return result;
331✔
3667
    }
3668

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

3673
    public get endTrivia(): Token[] {
UNCOV
3674
        return this.tokens.endEnum?.leadingTrivia ?? [];
×
3675
    }
3676

3677
    /**
3678
     * Get a map of member names and their values.
3679
     * All values are stored as their AST LiteralExpression representation (i.e. string enum values include the wrapping quotes)
3680
     */
3681
    public getMemberValueMap() {
3682
        const result = new Map<string, string>();
59✔
3683
        const members = this.getMembers();
59✔
3684
        let currentIntValue = 0;
59✔
3685
        for (const member of members) {
59✔
3686
            //if there is no value, assume an integer and increment the int counter
3687
            if (!member.value) {
148✔
3688
                result.set(member.name?.toLowerCase(), currentIntValue.toString());
33!
3689
                currentIntValue++;
33✔
3690

3691
                //if explicit integer value, use it and increment the int counter
3692
            } else if (isLiteralExpression(member.value) && member.value.tokens.value.kind === TokenKind.IntegerLiteral) {
115✔
3693
                //try parsing as integer literal, then as hex integer literal.
3694
                let tokenIntValue = util.parseInt(member.value.tokens.value.text) ?? util.parseInt(member.value.tokens.value.text.replace(/&h/i, '0x'));
29✔
3695
                if (tokenIntValue !== undefined) {
29!
3696
                    currentIntValue = tokenIntValue;
29✔
3697
                    currentIntValue++;
29✔
3698
                }
3699
                result.set(member.name?.toLowerCase(), member.value.tokens.value.text);
29!
3700

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

3705
                //all other values
3706
            } else {
3707
                result.set(member.name?.toLowerCase(), (member.value as LiteralExpression)?.tokens?.value?.text ?? 'invalid');
85!
3708
            }
3709
        }
3710
        return result;
59✔
3711
    }
3712

3713
    public getMemberValue(name: string) {
3714
        return this.getMemberValueMap().get(name.toLowerCase());
56✔
3715
    }
3716

3717
    /**
3718
     * The name of the enum (without the namespace prefix)
3719
     */
3720
    public get name() {
3721
        return this.tokens.name?.text;
1!
3722
    }
3723

3724
    /**
3725
     * The name of the enum WITH its leading namespace (if applicable)
3726
     */
3727
    public get fullName() {
3728
        const name = this.tokens.name?.text;
685!
3729
        if (name) {
685!
3730
            const namespace = this.findAncestor<NamespaceStatement>(isNamespaceStatement);
685✔
3731

3732
            if (namespace) {
685✔
3733
                let namespaceName = namespace.getName(ParseMode.BrighterScript);
258✔
3734
                return `${namespaceName}.${name}`;
258✔
3735
            } else {
3736
                return name;
427✔
3737
            }
3738
        } else {
3739
            //return undefined which will allow outside callers to know that this doesn't have a name
UNCOV
3740
            return undefined;
×
3741
        }
3742
    }
3743

3744
    transpile(state: BrsTranspileState) {
3745
        //enum declarations don't exist at runtime, so just transpile comments and trivia
3746
        return [
25✔
3747
            state.transpileAnnotations(this),
3748
            state.transpileLeadingComments(this.tokens.enum)
3749
        ];
3750
    }
3751

3752
    getTypedef(state: BrsTranspileState) {
3753
        const result = [] as TranspileResult;
1✔
3754
        for (let comment of util.getLeadingComments(this) ?? []) {
1!
UNCOV
3755
            result.push(
×
3756
                comment.text,
3757
                state.newline,
3758
                state.indent()
3759
            );
3760
        }
3761
        for (let annotation of this.annotations ?? []) {
1!
UNCOV
3762
            result.push(
×
3763
                ...annotation.getTypedef(state),
3764
                state.newline,
3765
                state.indent()
3766
            );
3767
        }
3768
        result.push(
1✔
3769
            this.tokens.enum?.text ?? 'enum',
6!
3770
            ' ',
3771
            this.tokens.name.text
3772
        );
3773
        result.push(state.newline);
1✔
3774
        state.blockDepth++;
1✔
3775
        for (const member of this.body) {
1✔
3776
            if (isTypedefProvider(member)) {
1!
3777
                result.push(
1✔
3778
                    state.indent(),
3779
                    ...member.getTypedef(state),
3780
                    state.newline
3781
                );
3782
            }
3783
        }
3784
        state.blockDepth--;
1✔
3785
        result.push(
1✔
3786
            state.indent(),
3787
            this.tokens.endEnum?.text ?? 'end enum'
6!
3788
        );
3789
        return result;
1✔
3790
    }
3791

3792
    walk(visitor: WalkVisitor, options: WalkOptions) {
3793
        if (options.walkMode & InternalWalkMode.walkStatements) {
1,017!
3794
            walkArray(this.body, visitor, options, this);
1,017✔
3795

3796
        }
3797
    }
3798

3799
    getType(options: GetTypeOptions) {
3800
        const members = this.getMembers();
136✔
3801

3802
        const resultType = new EnumType(
136✔
3803
            this.fullName,
3804
            members[0]?.getType(options).underlyingType
408✔
3805
        );
3806
        resultType.pushMemberProvider(() => this.getSymbolTable());
136✔
3807
        for (const statement of members) {
136✔
3808
            resultType.addMember(statement?.tokens?.name?.text, { definingNode: statement }, statement.getType(options), SymbolTypeFlag.runtime);
267!
3809
        }
3810
        return resultType;
136✔
3811
    }
3812

3813
    public clone() {
3814
        return this.finalizeClone(
6✔
3815
            new EnumStatement({
3816
                enum: util.cloneToken(this.tokens.enum),
3817
                name: util.cloneToken(this.tokens.name),
3818
                endEnum: util.cloneToken(this.tokens.endEnum),
3819
                body: this.body?.map(x => x?.clone())
4✔
3820
            }),
3821
            ['body']
3822
        );
3823
    }
3824
}
3825

3826
export class EnumMemberStatement extends Statement implements TypedefProvider {
1✔
3827
    public constructor(options: {
3828
        name: Identifier;
3829
        equals?: Token;
3830
        value?: Expression;
3831
    }) {
3832
        super();
321✔
3833
        this.tokens = {
321✔
3834
            name: options.name,
3835
            equals: options.equals
3836
        };
3837
        this.value = options.value;
321✔
3838
    }
3839

3840
    public readonly tokens: {
3841
        readonly name: Identifier;
3842
        readonly equals?: Token;
3843
    };
3844
    public readonly value?: Expression;
3845

3846
    public readonly kind = AstNodeKind.EnumMemberStatement;
321✔
3847

3848
    public get location() {
3849
        return util.createBoundingLocation(
420✔
3850
            this.tokens.name,
3851
            this.tokens.equals,
3852
            this.value
3853
        );
3854
    }
3855

3856
    /**
3857
     * The name of the member
3858
     */
3859
    public get name() {
3860
        return this.tokens.name.text;
408✔
3861
    }
3862

3863
    public get leadingTrivia(): Token[] {
3864
        return this.tokens.name.leadingTrivia;
1,236✔
3865
    }
3866

3867
    public transpile(state: BrsTranspileState): TranspileResult {
UNCOV
3868
        return [];
×
3869
    }
3870

3871
    getTypedef(state: BrsTranspileState): TranspileResult {
3872
        const result: TranspileResult = [];
1✔
3873
        for (let comment of util.getLeadingComments(this) ?? []) {
1!
3874
            result.push(
×
3875
                comment.text,
3876
                state.newline,
3877
                state.indent()
3878
            );
3879
        }
3880
        result.push(this.tokens.name.text);
1✔
3881
        if (this.tokens.equals) {
1!
UNCOV
3882
            result.push(' ', this.tokens.equals.text, ' ');
×
UNCOV
3883
            if (this.value) {
×
UNCOV
3884
                result.push(
×
3885
                    ...this.value.transpile(state)
3886
                );
3887
            }
3888
        }
3889
        return result;
1✔
3890
    }
3891

3892
    walk(visitor: WalkVisitor, options: WalkOptions) {
3893
        if (this.value && options.walkMode & InternalWalkMode.walkExpressions) {
2,415✔
3894
            walk(this, 'value', visitor, options);
1,143✔
3895
        }
3896
    }
3897

3898
    getType(options: GetTypeOptions) {
3899
        return new EnumMemberType(
403✔
3900
            (this.parent as EnumStatement)?.fullName,
1,209!
3901
            this.tokens?.name?.text,
2,418!
3902
            this.value?.getType(options)
1,209✔
3903
        );
3904
    }
3905

3906
    public clone() {
3907
        return this.finalizeClone(
3✔
3908
            new EnumMemberStatement({
3909
                name: util.cloneToken(this.tokens.name),
3910
                equals: util.cloneToken(this.tokens.equals),
3911
                value: this.value?.clone()
9✔
3912
            }),
3913
            ['value']
3914
        );
3915
    }
3916
}
3917

3918
export class ConstStatement extends Statement implements TypedefProvider {
1✔
3919
    public constructor(options: {
3920
        const?: Token;
3921
        name: Identifier;
3922
        equals?: Token;
3923
        value: Expression;
3924
    }) {
3925
        super();
158✔
3926
        this.tokens = {
158✔
3927
            const: options.const,
3928
            name: options.name,
3929
            equals: options.equals
3930
        };
3931
        this.value = options.value;
158✔
3932
        this.location = util.createBoundingLocation(this.tokens.const, this.tokens.name, this.tokens.equals, this.value);
158✔
3933
    }
3934

3935
    public readonly tokens: {
3936
        readonly const: Token;
3937
        readonly name: Identifier;
3938
        readonly equals: Token;
3939
    };
3940
    public readonly value: Expression;
3941

3942
    public readonly kind = AstNodeKind.ConstStatement;
158✔
3943

3944
    public readonly location: Location | undefined;
3945

3946
    public get name() {
UNCOV
3947
        return this.tokens.name.text;
×
3948
    }
3949

3950
    public get leadingTrivia(): Token[] {
3951
        return this.tokens.const?.leadingTrivia;
471!
3952
    }
3953

3954
    /**
3955
     * The name of the statement WITH its leading namespace (if applicable)
3956
     */
3957
    public get fullName() {
3958
        const name = this.tokens.name?.text;
227!
3959
        if (name) {
227!
3960
            const namespace = this.findAncestor<NamespaceStatement>(isNamespaceStatement);
227✔
3961
            if (namespace) {
227✔
3962
                let namespaceName = namespace.getName(ParseMode.BrighterScript);
204✔
3963
                return `${namespaceName}.${name}`;
204✔
3964
            } else {
3965
                return name;
23✔
3966
            }
3967
        } else {
3968
            //return undefined which will allow outside callers to know that this doesn't have a name
UNCOV
3969
            return undefined;
×
3970
        }
3971
    }
3972

3973
    public transpile(state: BrsTranspileState): TranspileResult {
3974
        //const declarations don't exist at runtime, so just transpile comments and trivia
3975
        return [
27✔
3976
            state.transpileAnnotations(this),
3977
            state.transpileLeadingComments(this.tokens.const)
3978
        ];
3979
    }
3980

3981
    getTypedef(state: BrsTranspileState): TranspileResult {
3982
        const result: TranspileResult = [];
3✔
3983
        for (let comment of util.getLeadingComments(this) ?? []) {
3!
UNCOV
3984
            result.push(
×
3985
                comment.text,
3986
                state.newline,
3987
                state.indent()
3988
            );
3989
        }
3990
        result.push(
3✔
3991
            this.tokens.const ? state.tokenToSourceNode(this.tokens.const) : 'const',
3!
3992
            ' ',
3993
            state.tokenToSourceNode(this.tokens.name),
3994
            ' ',
3995
            this.tokens.equals ? state.tokenToSourceNode(this.tokens.equals) : '=',
3!
3996
            ' ',
3997
            ...this.value.transpile(state)
3998
        );
3999
        return result;
3✔
4000
    }
4001

4002
    walk(visitor: WalkVisitor, options: WalkOptions) {
4003
        if (this.value && options.walkMode & InternalWalkMode.walkExpressions) {
1,015✔
4004
            walk(this, 'value', visitor, options);
877✔
4005
        }
4006
    }
4007

4008
    getType(options: GetTypeOptions) {
4009
        return this.value.getType(options);
150✔
4010
    }
4011

4012
    public clone() {
4013
        return this.finalizeClone(
3✔
4014
            new ConstStatement({
4015
                const: util.cloneToken(this.tokens.const),
4016
                name: util.cloneToken(this.tokens.name),
4017
                equals: util.cloneToken(this.tokens.equals),
4018
                value: this.value?.clone()
9✔
4019
            }),
4020
            ['value']
4021
        );
4022
    }
4023
}
4024

4025
export class ContinueStatement extends Statement {
1✔
4026
    constructor(options: {
4027
        continue?: Token;
4028
        loopType: Token;
4029
    }
4030
    ) {
4031
        super();
13✔
4032
        this.tokens = {
13✔
4033
            continue: options.continue,
4034
            loopType: options.loopType
4035
        };
4036
        this.location = util.createBoundingLocation(
13✔
4037
            this.tokens.continue,
4038
            this.tokens.loopType
4039
        );
4040
    }
4041

4042
    public readonly tokens: {
4043
        readonly continue?: Token;
4044
        readonly loopType: Token;
4045
    };
4046

4047
    public readonly kind = AstNodeKind.ContinueStatement;
13✔
4048

4049
    public readonly location: Location | undefined;
4050

4051
    transpile(state: BrsTranspileState) {
4052
        return [
3✔
4053
            state.sourceNode(this.tokens.continue, this.tokens.continue?.text ?? 'continue'),
18!
4054
            this.tokens.loopType?.leadingWhitespace ?? ' ',
18✔
4055
            state.sourceNode(this.tokens.continue, this.tokens.loopType?.text)
9✔
4056
        ];
4057
    }
4058

4059
    walk(visitor: WalkVisitor, options: WalkOptions) {
4060
        //nothing to walk
4061
    }
4062

4063
    public get leadingTrivia(): Token[] {
4064
        return this.tokens.continue?.leadingTrivia ?? [];
86!
4065
    }
4066

4067
    public clone() {
4068
        return this.finalizeClone(
1✔
4069
            new ContinueStatement({
4070
                continue: util.cloneToken(this.tokens.continue),
4071
                loopType: util.cloneToken(this.tokens.loopType)
4072
            })
4073
        );
4074
    }
4075
}
4076

4077
export class TypecastStatement extends Statement {
1✔
4078
    constructor(options: {
4079
        typecast?: Token;
4080
        typecastExpression: TypecastExpression;
4081
    }
4082
    ) {
4083
        super();
25✔
4084
        this.tokens = {
25✔
4085
            typecast: options.typecast
4086
        };
4087
        this.typecastExpression = options.typecastExpression;
25✔
4088
        this.location = util.createBoundingLocation(
25✔
4089
            this.tokens.typecast,
4090
            this.typecastExpression
4091
        );
4092
    }
4093

4094
    public readonly tokens: {
4095
        readonly typecast?: Token;
4096
    };
4097

4098
    public readonly typecastExpression: TypecastExpression;
4099

4100
    public readonly kind = AstNodeKind.TypecastStatement;
25✔
4101

4102
    public readonly location: Location;
4103

4104
    transpile(state: BrsTranspileState) {
4105
        //the typecast statement is a comment just for debugging purposes
4106
        return [
1✔
4107
            state.transpileToken(this.tokens.typecast, 'typecast', true),
4108
            ' ',
4109
            this.typecastExpression.obj.transpile(state),
4110
            ' ',
4111
            state.transpileToken(this.typecastExpression.tokens.as, 'as'),
4112
            ' ',
4113
            this.typecastExpression.typeExpression.transpile(state)
4114
        ];
4115
    }
4116

4117
    walk(visitor: WalkVisitor, options: WalkOptions) {
4118
        if (options.walkMode & InternalWalkMode.walkExpressions) {
136✔
4119
            walk(this, 'typecastExpression', visitor, options);
126✔
4120
        }
4121
    }
4122

4123
    get leadingTrivia(): Token[] {
4124
        return this.tokens.typecast?.leadingTrivia ?? [];
110!
4125
    }
4126

4127
    getType(options: GetTypeOptions): BscType {
4128
        return this.typecastExpression.getType(options);
19✔
4129
    }
4130

4131
    public clone() {
4132
        return this.finalizeClone(
1✔
4133
            new TypecastStatement({
4134
                typecast: util.cloneToken(this.tokens.typecast),
4135
                typecastExpression: this.typecastExpression?.clone()
3!
4136
            }),
4137
            ['typecastExpression']
4138
        );
4139
    }
4140
}
4141

4142
export class ConditionalCompileErrorStatement extends Statement {
1✔
4143
    constructor(options: {
4144
        hashError?: Token;
4145
        message: Token;
4146
    }) {
4147
        super();
11✔
4148
        this.tokens = {
11✔
4149
            hashError: options.hashError,
4150
            message: options.message
4151
        };
4152
        this.location = util.createBoundingLocation(util.createBoundingLocationFromTokens(this.tokens));
11✔
4153
    }
4154

4155
    public readonly tokens: {
4156
        readonly hashError?: Token;
4157
        readonly message: Token;
4158
    };
4159

4160

4161
    public readonly kind = AstNodeKind.ConditionalCompileErrorStatement;
11✔
4162

4163
    public readonly location: Location | undefined;
4164

4165
    transpile(state: BrsTranspileState) {
4166
        return [
3✔
4167
            state.transpileToken(this.tokens.hashError, '#error'),
4168
            ' ',
4169
            state.transpileToken(this.tokens.message)
4170

4171
        ];
4172
    }
4173

4174
    walk(visitor: WalkVisitor, options: WalkOptions) {
4175
        // nothing to walk
4176
    }
4177

4178
    get leadingTrivia(): Token[] {
4179
        return this.tokens.hashError.leadingTrivia ?? [];
12!
4180
    }
4181

4182
    public clone() {
4183
        return this.finalizeClone(
1✔
4184
            new ConditionalCompileErrorStatement({
4185
                hashError: util.cloneToken(this.tokens.hashError),
4186
                message: util.cloneToken(this.tokens.message)
4187
            })
4188
        );
4189
    }
4190
}
4191

4192
export class AliasStatement extends Statement {
1✔
4193
    constructor(options: {
4194
        alias?: Token;
4195
        name: Token;
4196
        equals?: Token;
4197
        value: VariableExpression | DottedGetExpression;
4198
    }
4199
    ) {
4200
        super();
34✔
4201
        this.tokens = {
34✔
4202
            alias: options.alias,
4203
            name: options.name,
4204
            equals: options.equals
4205
        };
4206
        this.value = options.value;
34✔
4207
        this.location = util.createBoundingLocation(
34✔
4208
            this.tokens.alias,
4209
            this.tokens.name,
4210
            this.tokens.equals,
4211
            this.value
4212
        );
4213
    }
4214

4215
    public readonly tokens: {
4216
        readonly alias?: Token;
4217
        readonly name: Token;
4218
        readonly equals?: Token;
4219
    };
4220

4221
    public readonly value: Expression;
4222

4223
    public readonly kind = AstNodeKind.AliasStatement;
34✔
4224

4225
    public readonly location: Location;
4226

4227
    transpile(state: BrsTranspileState) {
4228
        //the alias statement is a comment just for debugging purposes
4229
        return [
12✔
4230
            state.transpileToken(this.tokens.alias, 'alias', true),
4231
            ' ',
4232
            state.transpileToken(this.tokens.name),
4233
            ' ',
4234
            state.transpileToken(this.tokens.equals, '='),
4235
            ' ',
4236
            this.value.transpile(state)
4237
        ];
4238
    }
4239

4240
    walk(visitor: WalkVisitor, options: WalkOptions) {
4241
        if (options.walkMode & InternalWalkMode.walkExpressions) {
222✔
4242
            walk(this, 'value', visitor, options);
193✔
4243
        }
4244
    }
4245

4246
    get leadingTrivia(): Token[] {
4247
        return this.tokens.alias?.leadingTrivia ?? [];
121!
4248
    }
4249

4250
    getType(options: GetTypeOptions): BscType {
4251
        return this.value.getType(options);
1✔
4252
    }
4253

4254
    public clone() {
4255
        return this.finalizeClone(
1✔
4256
            new AliasStatement({
4257
                alias: util.cloneToken(this.tokens.alias),
4258
                name: util.cloneToken(this.tokens.name),
4259
                equals: util.cloneToken(this.tokens.equals),
4260
                value: this.value?.clone()
3!
4261
            }),
4262
            ['value']
4263
        );
4264
    }
4265
}
4266

4267
export class ConditionalCompileStatement extends Statement {
1✔
4268
    constructor(options: {
4269
        hashIf?: Token;
4270
        not?: Token;
4271
        condition: Token;
4272
        hashElse?: Token;
4273
        hashEndIf?: Token;
4274
        thenBranch: Block;
4275
        elseBranch?: ConditionalCompileStatement | Block;
4276
    }) {
4277
        super();
56✔
4278
        this.thenBranch = options.thenBranch;
56✔
4279
        this.elseBranch = options.elseBranch;
56✔
4280

4281
        this.tokens = {
56✔
4282
            hashIf: options.hashIf,
4283
            not: options.not,
4284
            condition: options.condition,
4285
            hashElse: options.hashElse,
4286
            hashEndIf: options.hashEndIf
4287
        };
4288

4289
        this.location = util.createBoundingLocation(
56✔
4290
            util.createBoundingLocationFromTokens(this.tokens),
4291
            this.thenBranch,
4292
            this.elseBranch
4293
        );
4294
    }
4295

4296
    readonly tokens: {
4297
        readonly hashIf?: Token;
4298
        readonly not?: Token;
4299
        readonly condition: Token;
4300
        readonly hashElse?: Token;
4301
        readonly hashEndIf?: Token;
4302
    };
4303
    public readonly thenBranch: Block;
4304
    public readonly elseBranch?: ConditionalCompileStatement | Block;
4305

4306
    public readonly kind = AstNodeKind.ConditionalCompileStatement;
56✔
4307

4308
    public readonly location: Location | undefined;
4309

4310
    transpile(state: BrsTranspileState) {
4311
        let results = [] as TranspileResult;
6✔
4312
        //if   (already indented by block)
4313
        if (!state.conditionalCompileStatement) {
6✔
4314
            // only transpile the #if in the case when we're not in a conditionalCompileStatement already
4315
            results.push(state.transpileToken(this.tokens.hashIf ?? createToken(TokenKind.HashIf)));
3!
4316
        }
4317

4318
        results.push(' ');
6✔
4319
        //conditions
4320
        if (this.tokens.not) {
6✔
4321
            results.push('not');
2✔
4322
            results.push(' ');
2✔
4323
        }
4324
        results.push(state.transpileToken(this.tokens.condition));
6✔
4325
        state.lineage.unshift(this);
6✔
4326

4327
        //if statement body
4328
        let thenNodes = this.thenBranch.transpile(state);
6✔
4329
        state.lineage.shift();
6✔
4330
        if (thenNodes.length > 0) {
6!
4331
            results.push(thenNodes);
6✔
4332
        }
4333
        //else branch
4334
        if (this.elseBranch) {
6!
4335
            const elseIsCC = isConditionalCompileStatement(this.elseBranch);
6✔
4336
            const endBlockToken = elseIsCC ? (this.elseBranch as ConditionalCompileStatement).tokens.hashIf ?? createToken(TokenKind.HashElseIf) : this.tokens.hashElse;
6!
4337
            //else
4338

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

4341
            if (elseIsCC) {
6✔
4342
                //chained else if
4343
                state.lineage.unshift(this.elseBranch);
3✔
4344

4345
                // transpile following #if with knowledge of current
4346
                const existingCCStmt = state.conditionalCompileStatement;
3✔
4347
                state.conditionalCompileStatement = this;
3✔
4348
                let body = this.elseBranch.transpile(state);
3✔
4349
                state.conditionalCompileStatement = existingCCStmt;
3✔
4350

4351
                state.lineage.shift();
3✔
4352

4353
                if (body.length > 0) {
3!
4354
                    //zero or more spaces between the `else` and the `if`
4355
                    results.push(...body);
3✔
4356

4357
                    // stop here because chained if will transpile the rest
4358
                    return results;
3✔
4359
                } else {
UNCOV
4360
                    results.push('\n');
×
4361
                }
4362

4363
            } else {
4364
                //else body
4365
                state.lineage.unshift(this.tokens.hashElse!);
3✔
4366
                let body = this.elseBranch.transpile(state);
3✔
4367
                state.lineage.shift();
3✔
4368

4369
                if (body.length > 0) {
3!
4370
                    results.push(...body);
3✔
4371
                }
4372
            }
4373
        }
4374

4375
        //end if
4376
        results.push(...state.transpileEndBlockToken(this.elseBranch ?? this.thenBranch, this.tokens.hashEndIf, '#end if'));
3!
4377

4378
        return results;
3✔
4379
    }
4380

4381
    walk(visitor: WalkVisitor, options: WalkOptions) {
4382
        if (options.walkMode & InternalWalkMode.walkStatements) {
186!
4383
            const bsConsts = options.bsConsts ?? this.getBsConsts();
186✔
4384
            let conditionTrue = bsConsts?.get(this.tokens.condition.text.toLowerCase());
186✔
4385
            if (this.tokens.not) {
186✔
4386
                // flips the boolean value
4387
                conditionTrue = !conditionTrue;
23✔
4388
            }
4389
            const walkFalseBlocks = options.walkMode & InternalWalkMode.visitFalseConditionalCompilationBlocks;
186✔
4390
            if (conditionTrue || walkFalseBlocks) {
186✔
4391
                walk(this, 'thenBranch', visitor, options);
124✔
4392
            }
4393
            if (this.elseBranch && (!conditionTrue || walkFalseBlocks)) {
186✔
4394
                walk(this, 'elseBranch', visitor, options);
53✔
4395
            }
4396
        }
4397
    }
4398

4399
    get leadingTrivia(): Token[] {
4400
        return this.tokens.hashIf?.leadingTrivia ?? [];
164!
4401
    }
4402

4403
    public clone() {
4404
        return this.finalizeClone(
1✔
4405
            new ConditionalCompileStatement({
4406
                hashIf: util.cloneToken(this.tokens.hashIf),
4407
                not: util.cloneToken(this.tokens.not),
4408
                condition: util.cloneToken(this.tokens.condition),
4409
                hashElse: util.cloneToken(this.tokens.hashElse),
4410
                hashEndIf: util.cloneToken(this.tokens.hashEndIf),
4411
                thenBranch: this.thenBranch?.clone(),
3!
4412
                elseBranch: this.elseBranch?.clone()
3!
4413
            }),
4414
            ['thenBranch', 'elseBranch']
4415
        );
4416
    }
4417
}
4418

4419

4420
export class ConditionalCompileConstStatement extends Statement {
1✔
4421
    constructor(options: {
4422
        hashConst?: Token;
4423
        assignment: AssignmentStatement;
4424
    }) {
4425
        super();
19✔
4426
        this.tokens = {
19✔
4427
            hashConst: options.hashConst
4428
        };
4429
        this.assignment = options.assignment;
19✔
4430
        this.location = util.createBoundingLocation(util.createBoundingLocationFromTokens(this.tokens), this.assignment);
19✔
4431
    }
4432

4433
    public readonly tokens: {
4434
        readonly hashConst?: Token;
4435
    };
4436

4437
    public readonly assignment: AssignmentStatement;
4438

4439
    public readonly kind = AstNodeKind.ConditionalCompileConstStatement;
19✔
4440

4441
    public readonly location: Location | undefined;
4442

4443
    transpile(state: BrsTranspileState) {
4444
        return [
3✔
4445
            state.transpileToken(this.tokens.hashConst, '#const'),
4446
            ' ',
4447
            state.transpileToken(this.assignment.tokens.name),
4448
            ' ',
4449
            state.transpileToken(this.assignment.tokens.equals, '='),
4450
            ' ',
4451
            ...this.assignment.value.transpile(state)
4452
        ];
4453

4454
    }
4455

4456
    walk(visitor: WalkVisitor, options: WalkOptions) {
4457
        // nothing to walk
4458
    }
4459

4460

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

4465
    public clone() {
4466
        return this.finalizeClone(
1✔
4467
            new ConditionalCompileConstStatement({
4468
                hashConst: util.cloneToken(this.tokens.hashConst),
4469
                assignment: this.assignment?.clone()
3!
4470
            }),
4471
            ['assignment']
4472
        );
4473
    }
4474
}
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