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

rokucommunity / brighterscript / #15520

30 Mar 2026 09:41PM UTC coverage: 88.885% (-0.2%) from 89.035%
#15520

push

web-flow
Merge 8787dd9e8 into f3673e7df

8258 of 9793 branches covered (84.33%)

Branch coverage included in aggregate %.

131 of 155 new or added lines in 5 files covered. (84.52%)

1 existing line in 1 file now uncovered.

10439 of 11242 relevant lines covered (92.86%)

2001.75 hits per line

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

90.54
/src/Program.ts
1
import * as assert from 'assert';
1✔
2
import * as fsExtra from 'fs-extra';
1✔
3
import * as path from 'path';
1✔
4
import type { CodeAction, CompletionItem, Position, Range, SignatureInformation, Location, DocumentSymbol, CancellationToken, WorkspaceEdit } from 'vscode-languageserver';
5
import { CancellationTokenSource, CompletionItemKind } from 'vscode-languageserver';
1✔
6
import type { BsConfig, FinalizedBsConfig } from './BsConfig';
7
import { Scope } from './Scope';
1✔
8
import { DiagnosticMessages } from './DiagnosticMessages';
1✔
9
import { BrsFile } from './files/BrsFile';
1✔
10
import { XmlFile } from './files/XmlFile';
1✔
11
import type { BsDiagnostic, File, FileReference, FileObj, BscFile, SemanticToken, AfterFileTranspileEvent, FileLink, ProvideHoverEvent, ProvideCompletionsEvent, Hover, ProvideDefinitionEvent, ProvideReferencesEvent, ProvideDocumentSymbolsEvent, ProvideWorkspaceSymbolsEvent } from './interfaces';
12
import { standardizePath as s, util } from './util';
1✔
13
import { XmlScope } from './XmlScope';
1✔
14
import { DiagnosticFilterer } from './DiagnosticFilterer';
1✔
15
import { DependencyGraph } from './DependencyGraph';
1✔
16
import type { Logger } from './logging';
17
import { LogLevel, createLogger } from './logging';
1✔
18
import chalk from 'chalk';
1✔
19
import { globalFile } from './globalCallables';
1✔
20
import { parseManifest, getBsConst } from './preprocessor/Manifest';
1✔
21
import { URI } from 'vscode-uri';
1✔
22
import PluginInterface from './PluginInterface';
1✔
23
import { isBrsFile, isXmlFile, isXmlScope, isNamespaceStatement } from './astUtils/reflection';
1✔
24
import type { FunctionStatement, NamespaceStatement } from './parser/Statement';
25
import { BscPlugin } from './bscPlugin/BscPlugin';
1✔
26
import { AstEditor } from './astUtils/AstEditor';
1✔
27
import type { SourceNode } from 'source-map';
28
import type { SourceMapGenerator } from 'source-map';
29
import { BrsTranspileState } from './parser/BrsTranspileState';
1✔
30
import type { Statement } from './parser/AstNode';
31
import { CallExpressionInfo } from './bscPlugin/CallExpressionInfo';
1✔
32
import { SignatureHelpUtil } from './bscPlugin/SignatureHelpUtil';
1✔
33
import { DiagnosticSeverityAdjuster } from './DiagnosticSeverityAdjuster';
1✔
34
import { Sequencer } from './common/Sequencer';
1✔
35
import { Deferred } from './deferred';
1✔
36

37
const startOfSourcePkgPath = `source${path.sep}`;
1✔
38
const bslibNonAliasedRokuModulesPkgPath = s`source/roku_modules/rokucommunity_bslib/bslib.brs`;
1✔
39
const bslibAliasedRokuModulesPkgPath = s`source/roku_modules/bslib/bslib.brs`;
1✔
40

41
export interface SourceObj {
42
    /**
43
     * @deprecated use `srcPath` instead
44
     */
45
    pathAbsolute: string;
46
    srcPath: string;
47
    source: string;
48
    definitions?: string;
49
}
50

51
export interface TranspileObj {
52
    file: BscFile;
53
    outputPath: string;
54
}
55

56
export interface SignatureInfoObj {
57
    index: number;
58
    key: string;
59
    signature: SignatureInformation;
60
}
61

62
/**
63
 * Context for a single CDATA block. Returned by `Program.resolveCdataContext` when a
64
 * position falls inside an inline script block. Because synthetic BrsFiles are created
65
 * with offset-padded content, their positions are already in parent XML coordinate space
66
 * — no coordinate transformation is required.
67
 */
68
export interface CdataContext {
69
    brsFile: BrsFile;
70
    xmlFile: XmlFile;
71
    cdataRange: Range;
72
}
73

74
export class Program {
1✔
75
    constructor(
76
        /**
77
         * The root directory for this program
78
         */
79
        options: BsConfig,
80
        logger?: Logger,
81
        plugins?: PluginInterface
82
    ) {
83
        this.options = util.normalizeConfig(options);
1,522✔
84
        this.logger = logger ?? createLogger(options);
1,522✔
85
        this.plugins = plugins || new PluginInterface([], { logger: this.logger });
1,522✔
86

87
        //inject the bsc plugin as the first plugin in the stack.
88
        this.plugins.addFirst(new BscPlugin());
1,522✔
89

90
        //normalize the root dir path
91
        this.options.rootDir = util.getRootDir(this.options);
1,522✔
92

93
        this.createGlobalScope();
1,522✔
94
    }
95

96
    public options: FinalizedBsConfig;
97
    public logger: Logger;
98

99
    private createGlobalScope() {
100
        //create the 'global' scope
101
        this.globalScope = new Scope('global', this, 'scope:global');
1,522✔
102
        this.globalScope.attachDependencyGraph(this.dependencyGraph);
1,522✔
103
        this.scopes.global = this.globalScope;
1,522✔
104
        //hardcode the files list for global scope to only contain the global file
105
        this.globalScope.getAllFiles = () => [globalFile];
23,288✔
106
        this.globalScope.validate();
1,522✔
107
        //for now, disable validation of global scope because the global files have some duplicate method declarations
108
        this.globalScope.getDiagnostics = () => [];
1,522✔
109
        //TODO we might need to fix this because the isValidated clears stuff now
110
        (this.globalScope as any).isValidated = true;
1,522✔
111
    }
112

113
    /**
114
     * A graph of all files and their dependencies.
115
     * For example:
116
     *      File.xml -> [lib1.brs, lib2.brs]
117
     *      lib2.brs -> [lib3.brs] //via an import statement
118
     */
119
    private dependencyGraph = new DependencyGraph();
1,522✔
120

121
    private diagnosticFilterer = new DiagnosticFilterer();
1,522✔
122

123
    private diagnosticAdjuster = new DiagnosticSeverityAdjuster();
1,522✔
124

125
    /**
126
     * A scope that contains all built-in global functions.
127
     * All scopes should directly or indirectly inherit from this scope
128
     */
129
    public globalScope: Scope = undefined as any;
1,522✔
130

131
    /**
132
     * Plugins which can provide extra diagnostics or transform AST
133
     */
134
    public plugins: PluginInterface;
135

136
    /**
137
     * A set of diagnostics. This does not include any of the scope diagnostics.
138
     * Should only be set from `this.validate()`
139
     */
140
    private diagnostics = [] as BsDiagnostic[];
1,522✔
141

142
    /**
143
     * The path to bslib.brs (the BrightScript runtime for certain BrighterScript features)
144
     */
145
    public get bslibPkgPath() {
146
        //if there's an aliased (preferred) version of bslib from roku_modules loaded into the program, use that
147
        if (this.getFile(bslibAliasedRokuModulesPkgPath)) {
472✔
148
            return bslibAliasedRokuModulesPkgPath;
2✔
149

150
            //if there's a non-aliased version of bslib from roku_modules, use that
151
        } else if (this.getFile(bslibNonAliasedRokuModulesPkgPath)) {
470✔
152
            return bslibNonAliasedRokuModulesPkgPath;
3✔
153

154
            //default to the embedded version
155
        } else {
156
            return `${this.options.bslibDestinationDir}${path.sep}bslib.brs`;
467✔
157
        }
158
    }
159

160
    public get bslibPrefix() {
161
        if (this.bslibPkgPath === bslibNonAliasedRokuModulesPkgPath) {
435✔
162
            return 'rokucommunity_bslib';
3✔
163
        } else {
164
            return 'bslib';
432✔
165
        }
166
    }
167

168

169
    /**
170
     * A map of every file loaded into this program, indexed by its original file location
171
     */
172
    public files = {} as Record<string, BscFile>;
1,522✔
173
    private pkgMap = {} as Record<string, BscFile>;
1,522✔
174

175
    /**
176
     * When set, `getDiagnostics()` will skip remapping diagnostics for this synthetic BrsFile,
177
     * leaving them in synthetic-file coordinate space. Used during code action events for CDATA
178
     * blocks so that plugins can match diagnostics by file identity (`x.file === event.file`).
179
     */
180
    private _cdataDiagnosticsContext: BrsFile | undefined;
181

182
    private scopes = {} as Record<string, Scope>;
1,522✔
183

184
    protected addScope(scope: Scope) {
185
        this.scopes[scope.name] = scope;
1,399✔
186
    }
187

188
    /**
189
     * A map of every component currently loaded into the program, indexed by the component name.
190
     * It is a compile-time error to have multiple components with the same name. However, we store an array of components
191
     * by name so we can provide a better developer expreience. You shouldn't be directly accessing this array,
192
     * but if you do, only ever use the component at index 0.
193
     */
194
    private components = {} as Record<string, { file: XmlFile; scope: XmlScope }[]>;
1,522✔
195

196
    /**
197
     * Get the component with the specified name
198
     */
199
    public getComponent(componentName: string) {
200
        if (componentName) {
704✔
201
            //return the first compoment in the list with this name
202
            //(components are ordered in this list by pkgPath to ensure consistency)
203
            return this.components[componentName.toLowerCase()]?.[0];
661✔
204
        } else {
205
            return undefined;
43✔
206
        }
207
    }
208

209
    /**
210
     * Register (or replace) the reference to a component in the component map
211
     */
212
    private registerComponent(xmlFile: XmlFile, scope: XmlScope) {
213
        const key = (xmlFile.componentName?.text ?? xmlFile.pkgPath).toLowerCase();
291✔
214
        if (!this.components[key]) {
291✔
215
            this.components[key] = [];
277✔
216
        }
217
        this.components[key].push({
291✔
218
            file: xmlFile,
219
            scope: scope
220
        });
221
        this.components[key].sort((a, b) => {
291✔
222
            const pathA = a.file.pkgPath.toLowerCase();
5✔
223
            const pathB = b.file.pkgPath.toLowerCase();
5✔
224
            if (pathA < pathB) {
5✔
225
                return -1;
1✔
226
            } else if (pathA > pathB) {
4!
227
                return 1;
4✔
228
            }
229
            return 0;
×
230
        });
231
        this.syncComponentDependencyGraph(this.components[key]);
291✔
232
    }
233

234
    /**
235
     * Remove the specified component from the components map
236
     */
237
    private unregisterComponent(xmlFile: XmlFile) {
238
        const key = (xmlFile.componentName?.text ?? xmlFile.pkgPath).toLowerCase();
14✔
239
        const arr = this.components[key] || [];
14!
240
        for (let i = 0; i < arr.length; i++) {
14✔
241
            if (arr[i].file === xmlFile) {
14!
242
                arr.splice(i, 1);
14✔
243
                break;
14✔
244
            }
245
        }
246
        this.syncComponentDependencyGraph(arr);
14✔
247
    }
248

249
    /**
250
     * re-attach the dependency graph with a new key for any component who changed
251
     * their position in their own named array (only matters when there are multiple
252
     * components with the same name)
253
     */
254
    private syncComponentDependencyGraph(components: Array<{ file: XmlFile; scope: XmlScope }>) {
255
        //reattach every dependency graph
256
        for (let i = 0; i < components.length; i++) {
305✔
257
            const { file, scope } = components[i];
297✔
258

259
            //attach (or re-attach) the dependencyGraph for every component whose position changed
260
            if (file.dependencyGraphIndex !== i) {
297✔
261
                file.dependencyGraphIndex = i;
293✔
262
                file.attachDependencyGraph(this.dependencyGraph);
293✔
263
                scope.attachDependencyGraph(this.dependencyGraph);
293✔
264
            }
265
        }
266
    }
267

268
    /**
269
     * Get a list of all files that are included in the project but are not referenced
270
     * by any scope in the program.
271
     */
272
    public getUnreferencedFiles() {
273
        let result = [] as File[];
1,017✔
274
        for (let filePath in this.files) {
1,017✔
275
            let file = this.files[filePath];
1,268✔
276
            //is this file part of a scope
277
            if (!this.getFirstScopeForFile(file)) {
1,268✔
278
                //no scopes reference this file. add it to the list
279
                result.push(file);
45✔
280
            }
281
        }
282
        return result;
1,017✔
283
    }
284

285
    /**
286
     * Get the list of errors for the entire program. It's calculated on the fly
287
     * by walking through every file, so call this sparingly.
288
     */
289
    public getDiagnostics() {
290
        return this.logger.time(LogLevel.info, ['Program.getDiagnostics()'], () => {
1,017✔
291

292
            let diagnostics = [...this.diagnostics];
1,017✔
293

294
            //get the diagnostics from all scopes
295
            for (let scopeName in this.scopes) {
1,017✔
296
                let scope = this.scopes[scopeName];
2,070✔
297
                diagnostics.push(
2,070✔
298
                    ...scope.getDiagnostics()
299
                );
300
            }
301

302
            //get the diagnostics from all unreferenced files
303
            let unreferencedFiles = this.getUnreferencedFiles();
1,017✔
304
            for (let file of unreferencedFiles) {
1,017✔
305
                diagnostics.push(
45✔
306
                    ...file.getDiagnostics()
307
                );
308
            }
309
            const filteredDiagnostics = this.logger.time(LogLevel.debug, ['filter diagnostics'], () => {
1,017✔
310
                //filter out diagnostics based on our diagnostic filters
311
                let finalDiagnostics = this.diagnosticFilterer.filter({
1,017✔
312
                    ...this.options,
313
                    rootDir: this.options.rootDir
314
                }, diagnostics);
315
                return finalDiagnostics;
1,017✔
316
            });
317

318
            this.logger.time(LogLevel.debug, ['adjust diagnostics severity'], () => {
1,017✔
319
                this.diagnosticAdjuster.adjust(this.options, diagnostics);
1,017✔
320
            });
321

322
            this.logger.info(`diagnostic counts: total=${chalk.yellow(diagnostics.length.toString())}, after filter=${chalk.yellow(filteredDiagnostics.length.toString())}`);
1,017✔
323
            return this._cdataDiagnosticsContext
1,017✔
324
                ? this.partialRemapSyntheticFileDiagnostics(filteredDiagnostics, this._cdataDiagnosticsContext)
1,017✔
325
                : this.remapSyntheticFileDiagnostics(filteredDiagnostics);
326
        });
327
    }
328

329
    /**
330
     * Redirects diagnostics from synthetic CDATA BrsFiles to their parent XmlFile.
331
     * Because synthetic files are created with offset-padded content, ranges are already
332
     * in XML coordinate space — only the file reference needs updating.
333
     */
334
    private remapSyntheticFileDiagnostics(diagnostics: BsDiagnostic[]): BsDiagnostic[] {
335
        return diagnostics.map(diagnostic => {
1,016✔
336
            if (!diagnostic.file?.isSynthetic) {
542!
337
                return diagnostic;
541✔
338
            }
339
            const parentXmlFile = (diagnostic.file as BrsFile).parentXmlFile;
1✔
340
            if (!parentXmlFile) {
1!
NEW
341
                return diagnostic;
×
342
            }
343
            return { ...diagnostic, file: parentXmlFile };
1✔
344
        });
345
    }
346

347
    /**
348
     * Like `remapSyntheticFileDiagnostics`, but keeps `contextFile`'s diagnostics pointing
349
     * at the synthetic BrsFile so plugins can match by file identity during code action events.
350
     */
351
    private partialRemapSyntheticFileDiagnostics(diagnostics: BsDiagnostic[], contextFile: BrsFile): BsDiagnostic[] {
352
        return diagnostics.map(diagnostic => {
1✔
NEW
353
            if (!diagnostic.file?.isSynthetic) {
×
NEW
354
                return diagnostic;
×
355
            }
NEW
356
            if (diagnostic.file === contextFile) {
×
NEW
357
                return diagnostic;
×
358
            }
NEW
359
            const parentXmlFile = (diagnostic.file as BrsFile).parentXmlFile;
×
NEW
360
            if (!parentXmlFile) {
×
NEW
361
                return diagnostic;
×
362
            }
NEW
363
            return { ...diagnostic, file: parentXmlFile };
×
364
        });
365
    }
366

367
    /**
368
     * Returns the CDATA metadata and corresponding synthetic BrsFile for the CDATA block whose
369
     * range intersects `range` within `xmlFile`, or `undefined` if no block matches.
370
     */
371
    private findCdataInfoForRange(xmlFile: XmlFile, range: Range): { meta: { xmlFile: XmlFile; cdataRange: Range }; brsFile: BrsFile } | undefined {
372
        for (const pkgPath of xmlFile.inlineScriptPkgPaths) {
27✔
373
            const brsFile = this.getFile<BrsFile>(pkgPath);
9✔
374
            if (!brsFile?.cdataScript?.cdata) {
9!
NEW
375
                continue;
×
376
            }
377
            if (util.rangesIntersectOrTouch(brsFile.cdataScript.cdata.range, range)) {
9✔
378
                return { meta: { xmlFile: xmlFile, cdataRange: brsFile.cdataScript.cdata.range }, brsFile: brsFile };
8✔
379
            }
380
        }
381
        return undefined;
19✔
382
    }
383

384
    /**
385
     * After code actions are generated using a synthetic BrsFile as the target, this substitutes
386
     * the synthetic file URI with the parent XML file URI in any workspace edit changes.
387
     * Ranges are already in XML coordinate space and need no adjustment.
388
     */
389
    private remapCodeActionChangesToXml(codeActions: CodeAction[], brsFile: BrsFile, xmlFile: XmlFile) {
390
        const syntheticUri = URI.file(brsFile.srcPath).toString();
1✔
391
        const xmlUri = URI.file(xmlFile.srcPath).toString();
1✔
392
        for (const action of codeActions) {
1✔
NEW
393
            const changes = (action.edit as WorkspaceEdit)?.changes;
×
NEW
394
            if (!changes?.[syntheticUri]) {
×
NEW
395
                continue;
×
396
            }
NEW
397
            const syntheticEdits = changes[syntheticUri];
×
NEW
398
            delete changes[syntheticUri];
×
NEW
399
            if (!changes[xmlUri]) {
×
NEW
400
                changes[xmlUri] = [];
×
401
            }
NEW
402
            changes[xmlUri].push(...syntheticEdits);
×
403
        }
404
    }
405

406
    /**
407
     * Given an XmlFile and a cursor position, returns a `CdataContext` if the position falls
408
     * inside a `<![CDATA[...]]>` block, or `undefined` if it does not.
409
     * Because synthetic files use offset-padded content, no position transformation is needed —
410
     * pass the original XML-space position directly to the synthetic BrsFile's handlers.
411
     */
412
    public resolveCdataContext(xmlFile: XmlFile, position: Position): CdataContext | undefined {
413
        const pointRange = util.createRange(position.line, position.character, position.line, position.character);
27✔
414
        const info = this.findCdataInfoForRange(xmlFile, pointRange);
27✔
415
        if (!info) {
27✔
416
            return undefined;
19✔
417
        }
418
        return {
8✔
419
            brsFile: info.brsFile,
420
            xmlFile: xmlFile,
421
            cdataRange: info.meta.cdataRange
422
        };
423
    }
424

425
    /**
426
     * Substitutes the synthetic BrsFile URI with the parent XML file URI in any Location
427
     * entries that reference it. Ranges are already in XML coordinate space.
428
     */
429
    private remapLocationsFromSynthetic(locations: Location[], cdataCtx: CdataContext): Location[] {
430
        const syntheticUri = URI.file(cdataCtx.brsFile.srcPath).toString();
2✔
431
        const xmlUri = URI.file(cdataCtx.xmlFile.srcPath).toString();
2✔
432
        return locations.map(loc => (loc.uri === syntheticUri ? { uri: xmlUri, range: loc.range } : loc));
2!
433
    }
434

435
    public addDiagnostics(diagnostics: BsDiagnostic[]) {
436
        this.diagnostics.push(...diagnostics);
45✔
437
    }
438

439
    /**
440
     * Determine if the specified file is loaded in this program right now.
441
     * @param filePath the absolute or relative path to the file
442
     * @param normalizePath should the provided path be normalized before use
443
     */
444
    public hasFile(filePath: string, normalizePath = true) {
1,641✔
445
        return !!this.getFile(filePath, normalizePath);
1,641✔
446
    }
447

448
    public getPkgPath(...args: any[]): any { //eslint-disable-line
449
        throw new Error('Not implemented');
×
450
    }
451

452
    /**
453
     * roku filesystem is case INsensitive, so find the scope by key case insensitive
454
     */
455
    public getScopeByName(scopeName: string): Scope | undefined {
456
        if (!scopeName) {
35!
457
            return undefined;
×
458
        }
459
        //most scopes are xml file pkg paths. however, the ones that are not are single names like "global" and "scope",
460
        //so it's safe to run the standardizePkgPath method
461
        scopeName = s`${scopeName}`;
35✔
462
        let key = Object.keys(this.scopes).find(x => x.toLowerCase() === scopeName.toLowerCase());
86✔
463
        return this.scopes[key!];
35✔
464
    }
465

466
    /**
467
     * Return all scopes
468
     */
469
    public getScopes() {
470
        return Object.values(this.scopes);
9✔
471
    }
472

473
    /**
474
     * Find the scope for the specified component
475
     */
476
    public getComponentScope(componentName: string) {
477
        return this.getComponent(componentName)?.scope;
209✔
478
    }
479

480
    /**
481
     * Update internal maps with this file reference
482
     */
483
    private assignFile<T extends BscFile = BscFile>(file: T) {
484
        this.files[file.srcPath.toLowerCase()] = file;
1,603✔
485
        this.pkgMap[file.pkgPath.toLowerCase()] = file;
1,603✔
486
        return file;
1,603✔
487
    }
488

489
    /**
490
     * Remove this file from internal maps
491
     */
492
    private unassignFile<T extends BscFile = BscFile>(file: T) {
493
        delete this.files[file.srcPath.toLowerCase()];
192✔
494
        delete this.pkgMap[file.pkgPath.toLowerCase()];
192✔
495
        return file;
192✔
496
    }
497

498
    /**
499
     * Load a file into the program. If that file already exists, it is replaced.
500
     * If file contents are provided, those are used, Otherwise, the file is loaded from the file system
501
     * @param srcPath the file path relative to the root dir
502
     * @param fileContents the file contents
503
     * @deprecated use `setFile` instead
504
     */
505
    public addOrReplaceFile<T extends BscFile>(srcPath: string, fileContents: string): T;
506
    /**
507
     * Load a file into the program. If that file already exists, it is replaced.
508
     * @param fileEntry an object that specifies src and dest for the file.
509
     * @param fileContents the file contents. If not provided, the file will be loaded from disk
510
     * @deprecated use `setFile` instead
511
     */
512
    public addOrReplaceFile<T extends BscFile>(fileEntry: FileObj, fileContents: string): T;
513
    public addOrReplaceFile<T extends BscFile>(fileParam: FileObj | string, fileContents: string): T {
514
        return this.setFile<T>(fileParam as any, fileContents);
1✔
515
    }
516

517
    /**
518
     * Load a file into the program. If that file already exists, it is replaced.
519
     * If file contents are provided, those are used, Otherwise, the file is loaded from the file system
520
     * @param srcDestOrPkgPath the absolute path, the pkg path (i.e. `pkg:/path/to/file.brs`), or the destPath (i.e. `path/to/file.brs` relative to `pkg:/`)
521
     * @param fileContents the file contents
522
     */
523
    public setFile<T extends BscFile>(srcDestOrPkgPath: string, fileContents: string): T;
524
    /**
525
     * Load a file into the program. If that file already exists, it is replaced.
526
     * @param fileEntry an object that specifies src and dest for the file.
527
     * @param fileContents the file contents. If not provided, the file will be loaded from disk
528
     */
529
    public setFile<T extends BscFile>(fileEntry: FileObj, fileContents: string): T;
530
    public setFile<T extends BscFile>(fileParam: FileObj | string, fileContents: string): T {
531
        //normalize the file paths
532
        const { srcPath, pkgPath } = this.getPaths(fileParam, this.options.rootDir);
1,607✔
533

534
        let file = this.logger.time(LogLevel.debug, ['Program.setFile()', chalk.green(srcPath)], () => {
1,607✔
535
            //if the file is already loaded, remove it
536
            if (this.hasFile(srcPath)) {
1,607✔
537
                this.removeFile(srcPath);
139✔
538
            }
539
            let fileExtension = path.extname(srcPath).toLowerCase();
1,607✔
540
            let file: BscFile | undefined;
541

542
            if (fileExtension === '.brs' || fileExtension === '.bs') {
1,607✔
543
                //add the file to the program
544
                const brsFile = this.assignFile(
1,312✔
545
                    new BrsFile(srcPath, pkgPath, this)
546
                );
547

548
                //add file to the `source` dependency list
549
                if (brsFile.pkgPath.startsWith(startOfSourcePkgPath)) {
1,312✔
550
                    this.createSourceScope();
1,086✔
551
                    this.dependencyGraph.addDependency('scope:source', brsFile.dependencyGraphKey);
1,086✔
552
                }
553

554
                let sourceObj: SourceObj = {
1,312✔
555
                    //TODO remove `pathAbsolute` in v1
556
                    pathAbsolute: srcPath,
557
                    srcPath: srcPath,
558
                    source: fileContents
559
                };
560
                this.plugins.emit('beforeFileParse', sourceObj);
1,312✔
561

562
                this.logger.time(LogLevel.debug, ['parse', chalk.green(srcPath)], () => {
1,312✔
563
                    brsFile.parse(sourceObj.source);
1,312✔
564
                });
565

566
                //notify plugins that this file has finished parsing
567
                this.plugins.emit('afterFileParse', brsFile);
1,312✔
568

569
                file = brsFile;
1,312✔
570

571
                brsFile.attachDependencyGraph(this.dependencyGraph);
1,312✔
572

573
            } else if (
295✔
574
                //is xml file
575
                fileExtension === '.xml' &&
589✔
576
                //resides in the components folder (Roku will only parse xml files in the components folder)
577
                pkgPath.toLowerCase().startsWith(util.pathSepNormalize(`components/`))
578
            ) {
579
                //add the file to the program
580
                const xmlFile = this.assignFile(
291✔
581
                    new XmlFile(srcPath, pkgPath, this)
582
                );
583

584
                let sourceObj: SourceObj = {
291✔
585
                    //TODO remove `pathAbsolute` in v1
586
                    pathAbsolute: srcPath,
587
                    srcPath: srcPath,
588
                    source: fileContents
589
                };
590
                this.plugins.emit('beforeFileParse', sourceObj);
291✔
591

592
                this.logger.time(LogLevel.debug, ['parse', chalk.green(srcPath)], () => {
291✔
593
                    xmlFile.parse(sourceObj.source);
291✔
594
                });
595

596
                //notify plugins that this file has finished parsing
597
                this.plugins.emit('afterFileParse', xmlFile);
291✔
598

599
                file = xmlFile;
291✔
600

601
                //register synthetic BrsFiles for any inline CDATA script blocks.
602
                //these are treated as first-class files so all plugins (linters, validators, etc.) see them normally.
603
                let cdataScriptIndex = 0;
291✔
604
                for (const script of xmlFile.ast.component?.scripts ?? []) {
291✔
605
                    if (script.cdata) {
220✔
606
                        const inlinePkgPath = xmlFile.inlineScriptPkgPaths[cdataScriptIndex++];
37✔
607
                        // Pad the content with leading newlines and spaces so that every
608
                        // position in the synthetic file naturally aligns with its position in
609
                        // the parent XML file. This eliminates all coordinate remapping for LSP
610
                        // events — only file URI substitution is needed in results.
611
                        const cdataRange = script.cdata.range;
37✔
612
                        const contentStartChar = cdataRange.start.character + '<![CDATA['.length;
37✔
613
                        const paddedContent = '\n'.repeat(cdataRange.start.line) +
37✔
614
                            ' '.repeat(contentStartChar) +
615
                            (script.cdataText ?? '');
111!
616
                        const inlineFile = this.setFile<BrsFile>(inlinePkgPath, paddedContent);
37✔
617
                        inlineFile.isSynthetic = true;
37✔
618
                        inlineFile.excludeFromOutput = true;
37✔
619
                        inlineFile.parentXmlFile = xmlFile;
37✔
620
                        inlineFile.cdataScript = script;
37✔
621
                        script.cdataTranspile = (state) => {
37✔
622
                            return inlineFile.needsTranspiled
11✔
623
                                ? this.transpileSyntheticBrsFileToSourceNode(inlineFile, state.srcPath)
11✔
624
                                : undefined;
625
                        };
626
                    }
627
                }
628

629
                //create a new scope for this xml file
630
                let scope = new XmlScope(xmlFile, this);
291✔
631
                this.addScope(scope);
291✔
632

633
                //register this compoent now that we have parsed it and know its component name
634
                this.registerComponent(xmlFile, scope);
291✔
635

636
                //notify plugins that the scope is created and the component is registered
637
                this.plugins.emit('afterScopeCreate', scope);
291✔
638
            } else {
639
                //TODO do we actually need to implement this? Figure out how to handle img paths
640
                // let genericFile = this.files[srcPath] = <any>{
641
                //     srcPath: srcPath,
642
                //     pkgPath: pkgPath,
643
                //     wasProcessed: true
644
                // } as File;
645
                // file = <any>genericFile;
646
            }
647
            return file;
1,607✔
648
        });
649
        return file as T;
1,607✔
650
    }
651

652
    /**
653
     * Given a srcPath, a pkgPath, or both, resolve whichever is missing, relative to rootDir.
654
     * @param fileParam an object representing file paths
655
     * @param rootDir must be a pre-normalized path
656
     */
657
    private getPaths(fileParam: string | FileObj | { srcPath?: string; pkgPath?: string }, rootDir: string) {
658
        let srcPath: string | undefined;
659
        let pkgPath: string | undefined;
660

661
        assert.ok(fileParam, 'fileParam is required');
1,614✔
662

663
        //lift the srcPath and pkgPath vars from the incoming param
664
        if (typeof fileParam === 'string') {
1,614✔
665
            fileParam = this.removePkgPrefix(fileParam);
1,152✔
666
            srcPath = s`${path.resolve(rootDir, fileParam)}`;
1,152✔
667
            pkgPath = s`${util.replaceCaseInsensitive(srcPath, rootDir, '')}`;
1,152✔
668
        } else {
669
            let param: any = fileParam;
462✔
670

671
            if (param.src) {
462✔
672
                srcPath = s`${param.src}`;
459✔
673
            }
674
            if (param.srcPath) {
462✔
675
                srcPath = s`${param.srcPath}`;
2✔
676
            }
677
            if (param.dest) {
462✔
678
                pkgPath = s`${this.removePkgPrefix(param.dest)}`;
459✔
679
            }
680
            if (param.pkgPath) {
462✔
681
                pkgPath = s`${this.removePkgPrefix(param.pkgPath)}`;
2✔
682
            }
683
        }
684

685
        //if there's no srcPath, use the pkgPath to build an absolute srcPath
686
        if (!srcPath) {
1,614✔
687
            srcPath = s`${rootDir}/${pkgPath}`;
1✔
688
        }
689
        //coerce srcPath to an absolute path
690
        if (!path.isAbsolute(srcPath)) {
1,614✔
691
            srcPath = util.standardizePath(srcPath);
1✔
692
        }
693

694
        //if there's no pkgPath, compute relative path from rootDir
695
        if (!pkgPath) {
1,614✔
696
            pkgPath = s`${util.replaceCaseInsensitive(srcPath, rootDir, '')}`;
1✔
697
        }
698

699
        assert.ok(srcPath, 'fileEntry.src is required');
1,614✔
700
        assert.ok(pkgPath, 'fileEntry.dest is required');
1,614✔
701

702
        return {
1,614✔
703
            srcPath: srcPath,
704
            //remove leading slash from pkgPath
705
            pkgPath: pkgPath.replace(/^[\/\\]+/, '')
706
        };
707
    }
708

709
    /**
710
     * Remove any leading `pkg:/` found in the path
711
     */
712
    private removePkgPrefix(path: string) {
713
        return path.replace(/^pkg:\//i, '');
1,613✔
714
    }
715

716
    /**
717
     * Ensure source scope is created.
718
     * Note: automatically called internally, and no-op if it exists already.
719
     */
720
    public createSourceScope() {
721
        if (!this.scopes.source) {
1,493✔
722
            const sourceScope = new Scope('source', this, 'scope:source');
1,108✔
723
            sourceScope.attachDependencyGraph(this.dependencyGraph);
1,108✔
724
            this.addScope(sourceScope);
1,108✔
725
            this.plugins.emit('afterScopeCreate', sourceScope);
1,108✔
726
        }
727
    }
728

729
    /**
730
     * Find the file by its absolute path. This is case INSENSITIVE, since
731
     * Roku is a case insensitive file system. It is an error to have multiple files
732
     * with the same path with only case being different.
733
     * @param srcPath the absolute path to the file
734
     * @deprecated use `getFile` instead, which auto-detects the path type
735
     */
736
    public getFileByPathAbsolute<T extends BrsFile | XmlFile>(srcPath: string) {
737
        srcPath = s`${srcPath}`;
×
738
        for (let filePath in this.files) {
×
739
            if (filePath.toLowerCase() === srcPath.toLowerCase()) {
×
740
                return this.files[filePath] as T;
×
741
            }
742
        }
743
    }
744

745
    /**
746
     * Get a list of files for the given (platform-normalized) pkgPath array.
747
     * Missing files are just ignored.
748
     * @deprecated use `getFiles` instead, which auto-detects the path types
749
     */
750
    public getFilesByPkgPaths<T extends BscFile[]>(pkgPaths: string[]) {
751
        return pkgPaths
×
752
            .map(pkgPath => this.getFileByPkgPath(pkgPath))
×
753
            .filter(file => file !== undefined) as T;
×
754
    }
755

756
    /**
757
     * Get a file with the specified (platform-normalized) pkg path.
758
     * If not found, return undefined
759
     * @deprecated use `getFile` instead, which auto-detects the path type
760
     */
761
    public getFileByPkgPath<T extends BscFile>(pkgPath: string) {
762
        return this.pkgMap[pkgPath.toLowerCase()] as T;
516✔
763
    }
764

765
    /**
766
     * Remove a set of files from the program
767
     * @param srcPaths can be an array of srcPath or destPath strings
768
     * @param normalizePath should this function repair and standardize the filePaths? Passing false should have a performance boost if you can guarantee your paths are already sanitized
769
     */
770
    public removeFiles(srcPaths: string[], normalizePath = true) {
1✔
771
        for (let srcPath of srcPaths) {
1✔
772
            this.removeFile(srcPath, normalizePath);
1✔
773
        }
774
    }
775

776
    /**
777
     * Remove a file from the program
778
     * @param filePath can be a srcPath, a pkgPath, or a destPath (same as pkgPath but without `pkg:/`)
779
     * @param normalizePath should this function repair and standardize the path? Passing false should have a performance boost if you can guarantee your path is already sanitized
780
     */
781
    public removeFile(filePath: string, normalizePath = true) {
188✔
782
        this.logger.debug('Program.removeFile()', filePath);
192✔
783

784
        let file = this.getFile(filePath, normalizePath);
192✔
785
        if (file) {
192!
786
            this.plugins.emit('beforeFileDispose', file);
192✔
787

788
            //if there is a scope named the same as this file's path, remove it (i.e. xml scopes)
789
            let scope = this.scopes[file.pkgPath];
192✔
790
            if (scope) {
192✔
791
                this.plugins.emit('beforeScopeDispose', scope);
14✔
792
                scope.dispose();
14✔
793
                //notify dependencies of this scope that it has been removed
794
                this.dependencyGraph.remove(scope.dependencyGraphKey!);
14✔
795
                delete this.scopes[file.pkgPath];
14✔
796
                this.plugins.emit('afterScopeDispose', scope);
14✔
797
            }
798
            //remove the file from the program
799
            this.unassignFile(file);
192✔
800

801
            this.dependencyGraph.remove(file.dependencyGraphKey);
192✔
802

803
            //if this is a pkg:/source file, notify the `source` scope that it has changed
804
            if (file.pkgPath.startsWith(startOfSourcePkgPath)) {
192✔
805
                this.dependencyGraph.removeDependency('scope:source', file.dependencyGraphKey);
101✔
806
            }
807

808
            //if this is a component, remove it from our components map
809
            if (isXmlFile(file)) {
192✔
810
                this.unregisterComponent(file);
14✔
811
            }
812
            //dispose file
813
            file?.dispose();
192!
814
            this.plugins.emit('afterFileDispose', file);
192✔
815
        }
816
    }
817

818
    /**
819
     * Counter used to track which validation run is being logged
820
     */
821
    private validationRunSequence = 1;
1,522✔
822

823
    /**
824
     * How many milliseconds can pass while doing synchronous operations in validate before we register a short timeout (i.e. yield to the event loop)
825
     */
826
    private validationMinSyncDuration = 75;
1,522✔
827

828
    private validatePromise: Promise<void> | undefined;
829

830
    /**
831
     * Traverse the entire project, and validate all scopes
832
     */
833
    public validate(): void;
834
    public validate(options: { async: false; cancellationToken?: CancellationToken }): void;
835
    public validate(options: { async: true; cancellationToken?: CancellationToken }): Promise<void>;
836
    public validate(options?: { async?: boolean; cancellationToken?: CancellationToken }) {
837
        const validationRunId = this.validationRunSequence++;
963✔
838
        const timeEnd = this.logger.timeStart(LogLevel.log, `Validating project${(this.logger.logLevel as LogLevel) > LogLevel.log ? ` (run ${validationRunId})` : ''}`);
963!
839

840
        let previousValidationPromise = this.validatePromise;
963✔
841
        const deferred = new Deferred();
963✔
842

843
        if (options?.async) {
963✔
844
            //we're async, so create a new promise chain to resolve after this validation is done
845
            this.validatePromise = Promise.resolve(previousValidationPromise).then(() => {
159✔
846
                return deferred.promise;
159✔
847
            });
848

849
            //we are not async but there's a pending promise, then we cannot run this validation
850
        } else if (previousValidationPromise !== undefined) {
804!
851
            throw new Error('Cannot run synchronous validation while an async validation is in progress');
×
852
        }
853

854
        if (options?.async) {
963✔
855
            //we're async, so create a new promise chain to resolve after this validation is done
856
            this.validatePromise = Promise.resolve(previousValidationPromise).then(() => {
159✔
857
                return deferred.promise;
159✔
858
            });
859

860
            //we are not async but there's a pending promise, then we cannot run this validation
861
        } else if (previousValidationPromise !== undefined) {
804!
862
            throw new Error('Cannot run synchronous validation while an async validation is in progress');
×
863
        }
864

865
        const sequencer = new Sequencer({
963✔
866
            name: 'program.validate',
867
            cancellationToken: options?.cancellationToken ?? new CancellationTokenSource().token,
5,778✔
868
            minSyncDuration: this.validationMinSyncDuration
869
        });
870

871
        let beforeProgramValidateWasEmitted = false;
963✔
872

873
        //this sequencer allows us to run in both sync and async mode, depending on whether options.async is enabled.
874
        //We use this to prevent starving the CPU during long validate cycles when running in a language server context
875
        sequencer
963✔
876
            .once(() => {
877
                //if running in async mode, return the previous validation promise to ensure we're only running one at a time
878
                if (options?.async) {
963✔
879
                    return previousValidationPromise;
159✔
880
                }
881
            })
882
            .once(() => {
883
                this.diagnostics = [];
961✔
884
                this.plugins.emit('beforeProgramValidate', this);
961✔
885
                beforeProgramValidateWasEmitted = true;
961✔
886
            })
887
            .forEach(() => Object.values(this.files), (file) => {
961✔
888
                if (!file.isValidated) {
1,255✔
889
                    this.plugins.emit('beforeFileValidate', {
1,188✔
890
                        program: this,
891
                        file: file
892
                    });
893

894
                    //emit an event to allow plugins to contribute to the file validation process
895
                    this.plugins.emit('onFileValidate', {
1,188✔
896
                        program: this,
897
                        file: file
898
                    });
899
                    //call file.validate() IF the file has that function defined
900
                    file.validate?.();
1,188!
901
                    file.isValidated = true;
1,187✔
902

903
                    this.plugins.emit('afterFileValidate', file);
1,187✔
904
                }
905
            })
906
            .forEach(Object.values(this.scopes), (scope) => {
907
                scope.linkSymbolTable();
1,992✔
908
                scope.validate();
1,992✔
909
                scope.unlinkSymbolTable();
1,990✔
910
            })
911
            .once(() => {
912
                this.detectDuplicateComponentNames();
953✔
913
            })
914
            .onCancel(() => {
915
                timeEnd('cancelled');
10✔
916
            })
917
            .onSuccess(() => {
918
                timeEnd();
953✔
919
            })
920
            .onComplete(() => {
921
                //if we emitted the beforeProgramValidate hook, emit the afterProgramValidate hook as well
922
                if (beforeProgramValidateWasEmitted) {
963✔
923
                    const wasCancelled = options?.cancellationToken?.isCancellationRequested ?? false;
961✔
924
                    this.plugins.emit('afterProgramValidate', this, wasCancelled);
961✔
925
                }
926

927
                //regardless of the success of the validation, mark this run as complete
928
                deferred.resolve();
963✔
929
                //clear the validatePromise which means we're no longer running a validation
930
                this.validatePromise = undefined;
963✔
931
            });
932

933
        //run the sequencer in async mode if enabled
934
        if (options?.async) {
963✔
935
            return sequencer.run();
159✔
936

937
            //run the sequencer in sync mode
938
        } else {
939
            return sequencer.runSync();
804✔
940
        }
941
    }
942

943
    /**
944
     * Flag all duplicate component names
945
     */
946
    private detectDuplicateComponentNames() {
947
        const componentsByName = Object.keys(this.files).reduce<Record<string, XmlFile[]>>((map, filePath) => {
953✔
948
            const file = this.files[filePath];
1,246✔
949
            //if this is an XmlFile, and it has a valid `componentName` property
950
            if (isXmlFile(file) && file.componentName?.text) {
1,246✔
951
                let lowerName = file.componentName.text.toLowerCase();
255✔
952
                if (!map[lowerName]) {
255✔
953
                    map[lowerName] = [];
252✔
954
                }
955
                map[lowerName].push(file);
255✔
956
            }
957
            return map;
1,246✔
958
        }, {});
959

960
        for (let name in componentsByName) {
953✔
961
            const xmlFiles = componentsByName[name];
252✔
962
            //add diagnostics for every duplicate component with this name
963
            if (xmlFiles.length > 1) {
252✔
964
                for (let xmlFile of xmlFiles) {
3✔
965
                    const { componentName } = xmlFile;
6✔
966
                    this.diagnostics.push({
6✔
967
                        ...DiagnosticMessages.duplicateComponentName(componentName.text),
968
                        range: xmlFile.componentName.range,
969
                        file: xmlFile,
970
                        relatedInformation: xmlFiles.filter(x => x !== xmlFile).map(x => {
12✔
971
                            return {
6✔
972
                                location: util.createLocation(
973
                                    URI.file(x.srcPath ?? xmlFile.srcPath).toString(),
18!
974
                                    x.componentName.range
975
                                ),
976
                                message: 'Also defined here'
977
                            };
978
                        })
979
                    });
980
                }
981
            }
982
        }
983
    }
984

985
    /**
986
     * Get the files for a list of filePaths
987
     * @param filePaths can be an array of srcPath or a destPath strings
988
     * @param normalizePath should this function repair and standardize the paths? Passing false should have a performance boost if you can guarantee your paths are already sanitized
989
     */
990
    public getFiles<T extends BscFile>(filePaths: string[], normalizePath = true) {
34✔
991
        return filePaths
34✔
992
            .map(filePath => this.getFile(filePath, normalizePath))
42✔
993
            .filter(file => file !== undefined) as T[];
42✔
994
    }
995

996
    /**
997
     * Get the file at the given path
998
     * @param filePath can be a srcPath or a destPath
999
     * @param normalizePath should this function repair and standardize the path? Passing false should have a performance boost if you can guarantee your path is already sanitized
1000
     */
1001
    public getFile<T extends BscFile>(filePath: string, normalizePath = true) {
6,534✔
1002
        if (typeof filePath !== 'string') {
8,409✔
1003
            return undefined;
1,739✔
1004
        } else if (path.isAbsolute(filePath)) {
6,670✔
1005
            return this.files[
3,467✔
1006
                (normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase()
3,467✔
1007
            ] as T;
1008
        } else {
1009
            return this.pkgMap[
3,203✔
1010
                (normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase()
3,203!
1011
            ] as T;
1012
        }
1013
    }
1014

1015
    /**
1016
     * Get a list of all scopes the file is loaded into
1017
     * @param file the file
1018
     */
1019
    public getScopesForFile(file: XmlFile | BrsFile | string) {
1020

1021
        const resolvedFile = typeof file === 'string' ? this.getFile(file) : file;
605✔
1022

1023
        let result = [] as Scope[];
605✔
1024
        if (resolvedFile) {
605✔
1025
            for (let key in this.scopes) {
604✔
1026
                let scope = this.scopes[key];
1,261✔
1027

1028
                if (scope.hasFile(resolvedFile)) {
1,261✔
1029
                    result.push(scope);
615✔
1030
                }
1031
            }
1032
        }
1033
        return result;
605✔
1034
    }
1035

1036
    /**
1037
     * Get the first found scope for a file.
1038
     */
1039
    public getFirstScopeForFile(file: XmlFile | BrsFile): Scope | undefined {
1040
        for (let key in this.scopes) {
2,802✔
1041
            let scope = this.scopes[key];
6,959✔
1042

1043
            if (scope.hasFile(file)) {
6,959✔
1044
                return scope;
2,661✔
1045
            }
1046
        }
1047
    }
1048

1049
    public getStatementsByName(name: string, originFile: BrsFile, namespaceName?: string): FileLink<Statement>[] {
1050
        let results = new Map<Statement, FileLink<Statement>>();
40✔
1051
        const filesSearched = new Set<BrsFile>();
40✔
1052
        let lowerNamespaceName = namespaceName?.toLowerCase();
40✔
1053
        let lowerName = name?.toLowerCase();
40!
1054
        //look through all files in scope for matches
1055
        for (const scope of this.getScopesForFile(originFile)) {
40✔
1056
            for (const file of scope.getAllFiles()) {
40✔
1057
                if (isXmlFile(file) || filesSearched.has(file)) {
47✔
1058
                    continue;
4✔
1059
                }
1060
                filesSearched.add(file);
43✔
1061

1062
                for (const statement of [...file.parser.references.functionStatements, ...file.parser.references.classStatements.flatMap((cs) => cs.methods)]) {
43✔
1063
                    let parentNamespaceName = statement.findAncestor<NamespaceStatement>(isNamespaceStatement)?.getName(originFile.parseMode)?.toLowerCase();
100✔
1064
                    if (statement.name.text.toLowerCase() === lowerName && (!lowerNamespaceName || parentNamespaceName === lowerNamespaceName)) {
100✔
1065
                        if (!results.has(statement)) {
37!
1066
                            results.set(statement, { item: statement, file: file });
37✔
1067
                        }
1068
                    }
1069
                }
1070
            }
1071
        }
1072
        return [...results.values()];
40✔
1073
    }
1074

1075
    public getStatementsForXmlFile(scope: XmlScope, filterName?: string): FileLink<FunctionStatement>[] {
1076
        let results = new Map<Statement, FileLink<FunctionStatement>>();
8✔
1077
        const filesSearched = new Set<BrsFile>();
8✔
1078

1079
        //get all function names for the xml file and parents
1080
        let funcNames = new Set<string>();
8✔
1081
        let currentScope = scope;
8✔
1082
        while (isXmlScope(currentScope)) {
8✔
1083
            for (let name of currentScope.xmlFile.ast.component.api?.functions.map((f) => f.name) ?? []) {
14✔
1084
                if (!filterName || name === filterName) {
14!
1085
                    funcNames.add(name);
14✔
1086
                }
1087
            }
1088
            currentScope = currentScope.getParentScope() as XmlScope;
10✔
1089
        }
1090

1091
        //look through all files in scope for matches
1092
        for (const file of scope.getOwnFiles()) {
8✔
1093
            if (isXmlFile(file) || filesSearched.has(file)) {
16✔
1094
                continue;
8✔
1095
            }
1096
            filesSearched.add(file);
8✔
1097

1098
            for (const statement of file.parser.references.functionStatements) {
8✔
1099
                if (funcNames.has(statement.name.text)) {
13!
1100
                    if (!results.has(statement)) {
13!
1101
                        results.set(statement, { item: statement, file: file });
13✔
1102
                    }
1103
                }
1104
            }
1105
        }
1106
        return [...results.values()];
8✔
1107
    }
1108

1109
    /**
1110
     * Find all available completion items at the given position
1111
     * @param filePath can be a srcPath or a destPath
1112
     * @param position the position (line & column) where completions should be found
1113
     */
1114
    public getCompletions(filePath: string, position: Position) {
1115
        let file = this.getFile(filePath);
79✔
1116
        if (!file) {
79!
1117
            return [];
×
1118
        }
1119

1120
        const effectiveFile = isXmlFile(file) ? (this.resolveCdataContext(file, position)?.brsFile ?? file) : file;
79✔
1121

1122
        //find the scopes for this file
1123
        let scopes = this.getScopesForFile(effectiveFile);
79✔
1124

1125
        //if there are no scopes, include the global scope so we at least get the built-in functions
1126
        scopes = scopes.length > 0 ? scopes : [this.globalScope];
79✔
1127

1128
        const event: ProvideCompletionsEvent = {
79✔
1129
            program: this,
1130
            file: effectiveFile,
1131
            scopes: scopes,
1132
            position: position,
1133
            completions: []
1134
        };
1135

1136
        this.plugins.emit('beforeProvideCompletions', event);
79✔
1137
        this.plugins.emit('provideCompletions', event);
79✔
1138
        this.plugins.emit('afterProvideCompletions', event);
79✔
1139

1140
        return event.completions;
79✔
1141
    }
1142

1143
    /**
1144
     * Goes through each file and builds a list of workspace symbols for the program. Used by LanguageServer's onWorkspaceSymbol functionality
1145
     */
1146
    public getWorkspaceSymbols() {
1147
        const event: ProvideWorkspaceSymbolsEvent = {
22✔
1148
            program: this,
1149
            workspaceSymbols: []
1150
        };
1151
        this.plugins.emit('beforeProvideWorkspaceSymbols', event);
22✔
1152
        this.plugins.emit('provideWorkspaceSymbols', event);
22✔
1153
        this.plugins.emit('afterProvideWorkspaceSymbols', event);
22✔
1154
        return event.workspaceSymbols;
22✔
1155
    }
1156

1157
    /**
1158
     * Given a position in a file, if the position is sitting on some type of identifier,
1159
     * go to the definition of that identifier (where this thing was first defined)
1160
     */
1161
    public getDefinition(srcPath: string, position: Position): Location[] {
1162
        let file = this.getFile(srcPath);
20✔
1163
        if (!file) {
20!
1164
            return [];
×
1165
        }
1166

1167
        const cdataCtx = isXmlFile(file) ? this.resolveCdataContext(file, position) : undefined;
20✔
1168
        const effectiveFile = cdataCtx?.brsFile ?? file;
20✔
1169

1170
        const event: ProvideDefinitionEvent = {
20✔
1171
            program: this,
1172
            file: effectiveFile,
1173
            position: position,
1174
            definitions: []
1175
        };
1176

1177
        this.plugins.emit('beforeProvideDefinition', event);
20✔
1178
        this.plugins.emit('provideDefinition', event);
20✔
1179
        this.plugins.emit('afterProvideDefinition', event);
20✔
1180
        return cdataCtx ? this.remapLocationsFromSynthetic(event.definitions, cdataCtx) : event.definitions;
20✔
1181
    }
1182

1183
    /**
1184
     * Get hover information for a file and position
1185
     */
1186
    public getHover(srcPath: string, position: Position): Hover[] {
1187
        let file = this.getFile(srcPath);
33✔
1188
        let result: Hover[];
1189
        if (file) {
33!
1190
            const effectiveFile = isXmlFile(file) ? (this.resolveCdataContext(file, position)?.brsFile ?? file) : file;
33!
1191

1192
            const event = {
33✔
1193
                program: this,
1194
                file: effectiveFile,
1195
                position: position,
1196
                scopes: this.getScopesForFile(effectiveFile),
1197
                hovers: []
1198
            } as ProvideHoverEvent;
1199
            this.plugins.emit('beforeProvideHover', event);
33✔
1200
            this.plugins.emit('provideHover', event);
33✔
1201
            this.plugins.emit('afterProvideHover', event);
33✔
1202

1203
            result = event.hovers;
33✔
1204
        }
1205

1206
        return result ?? [];
33!
1207
    }
1208

1209
    /**
1210
     * Get full list of document symbols for a file
1211
     * @param srcPath path to the file
1212
     */
1213
    public getDocumentSymbols(srcPath: string): DocumentSymbol[] | undefined {
1214
        let file = this.getFile(srcPath);
25✔
1215
        if (!file) {
25!
UNCOV
1216
            return undefined;
×
1217
        }
1218
        const event: ProvideDocumentSymbolsEvent = {
25✔
1219
            program: this,
1220
            file: file,
1221
            documentSymbols: []
1222
        };
1223
        this.plugins.emit('beforeProvideDocumentSymbols', event);
25✔
1224
        this.plugins.emit('provideDocumentSymbols', event);
25✔
1225
        this.plugins.emit('afterProvideDocumentSymbols', event);
25✔
1226

1227
        // For XML files, also collect symbols from each inline CDATA block.
1228
        // Ranges are already in XML coordinate space — no remapping needed.
1229
        if (isXmlFile(file)) {
25✔
1230
            for (const pkgPath of file.inlineScriptPkgPaths) {
2✔
1231
                const brsFile = this.getFile<BrsFile>(pkgPath);
1✔
1232
                if (!brsFile) {
1!
NEW
1233
                    continue;
×
1234
                }
1235
                const cdataEvent: ProvideDocumentSymbolsEvent = {
1✔
1236
                    program: this,
1237
                    file: brsFile,
1238
                    documentSymbols: []
1239
                };
1240
                this.plugins.emit('beforeProvideDocumentSymbols', cdataEvent);
1✔
1241
                this.plugins.emit('provideDocumentSymbols', cdataEvent);
1✔
1242
                this.plugins.emit('afterProvideDocumentSymbols', cdataEvent);
1✔
1243
                event.documentSymbols.push(...cdataEvent.documentSymbols);
1✔
1244
            }
1245
        }
1246

1247
        return event.documentSymbols;
25✔
1248
    }
1249

1250
    /**
1251
     * Compute code actions for the given file and range
1252
     */
1253
    public getCodeActions(srcPath: string, range: Range) {
1254
        const codeActions = [] as CodeAction[];
53✔
1255
        const file = this.getFile(srcPath);
53✔
1256
        if (file) {
53✔
1257
            // resolveCdataContext uses range.start as a probe point; findCdataInfoForRange
1258
            // is used internally to check intersection with the full range.
1259
            const cdataCtx = isXmlFile(file) ? this.resolveCdataContext(file, range.start) : undefined;
52✔
1260

1261
            // When the range falls inside a CDATA block, redirect the event to the synthetic
1262
            // BrsFile so that BrsFile-specific code actions work correctly. Setting
1263
            // _cdataDiagnosticsContext causes getDiagnostics() to keep that file's diagnostics
1264
            // in synthetic-file coordinate space (rather than remapping to the parent XML file),
1265
            // so that plugins can match diagnostics by file identity (x.file === event.file)
1266
            // and derive correct edit positions from diagnostic.data (AST node ranges).
1267
            const effectiveFile = cdataCtx?.brsFile ?? file;
52✔
1268

1269
            this._cdataDiagnosticsContext = cdataCtx?.brsFile;
52✔
1270

1271
            const diagnostics = this
52✔
1272
                //get all current diagnostics (filtered by diagnostic filters)
1273
                .getDiagnostics()
1274
                //only keep diagnostics related to this file
1275
                .filter(x => x.file === effectiveFile)
89✔
1276
                //only keep diagnostics that touch this range
1277
                .filter(x => util.rangesIntersectOrTouch(x.range, range));
66✔
1278

1279
            const scopes = this.getScopesForFile(effectiveFile);
52✔
1280

1281
            this.plugins.emit('onGetCodeActions', {
52✔
1282
                program: this,
1283
                file: effectiveFile,
1284
                range: range,
1285
                diagnostics: diagnostics,
1286
                scopes: scopes,
1287
                codeActions: codeActions
1288
            });
1289

1290
            this._cdataDiagnosticsContext = undefined;
52✔
1291

1292
            if (cdataCtx) {
52✔
1293
                this.remapCodeActionChangesToXml(codeActions, cdataCtx.brsFile, file as XmlFile);
1✔
1294
            }
1295
        }
1296
        return codeActions;
53✔
1297
    }
1298

1299
    /**
1300
     * Get semantic tokens for the specified file
1301
     */
1302
    public getSemanticTokens(srcPath: string): SemanticToken[] | undefined {
1303
        const file = this.getFile(srcPath);
17✔
1304
        if (!file) {
17!
NEW
1305
            return undefined;
×
1306
        }
1307
        const result = [] as SemanticToken[];
17✔
1308
        this.plugins.emit('onGetSemanticTokens', {
17✔
1309
            program: this,
1310
            file: file,
1311
            scopes: this.getScopesForFile(file),
1312
            semanticTokens: result
1313
        });
1314

1315
        // For XML files, also collect semantic tokens from each inline CDATA block.
1316
        // Ranges are already in XML coordinate space — no remapping needed.
1317
        if (isXmlFile(file)) {
17✔
1318
            for (const pkgPath of file.inlineScriptPkgPaths) {
1✔
1319
                const brsFile = this.getFile<BrsFile>(pkgPath);
1✔
1320
                if (!brsFile) {
1!
NEW
1321
                    continue;
×
1322
                }
1323
                const cdataTokens = [] as SemanticToken[];
1✔
1324
                this.plugins.emit('onGetSemanticTokens', {
1✔
1325
                    program: this,
1326
                    file: brsFile,
1327
                    scopes: this.getScopesForFile(brsFile),
1328
                    semanticTokens: cdataTokens
1329
                });
1330
                result.push(...cdataTokens);
1✔
1331
            }
1332
        }
1333

1334
        return result;
17✔
1335
    }
1336

1337
    public getSignatureHelp(filePath: string, position: Position): SignatureInfoObj[] {
1338
        let file = this.getFile(filePath);
189✔
1339
        if (!file) {
189✔
1340
            return [];
2✔
1341
        }
1342
        const effectiveFile = isXmlFile(file) ? (this.resolveCdataContext(file, position)?.brsFile ?? file) : file;
187✔
1343
        if (!isBrsFile(effectiveFile)) {
187✔
1344
            return [];
1✔
1345
        }
1346
        let callExpressionInfo = new CallExpressionInfo(effectiveFile, position);
186✔
1347
        let signatureHelpUtil = new SignatureHelpUtil();
186✔
1348
        return signatureHelpUtil.getSignatureHelpItems(callExpressionInfo);
186✔
1349
    }
1350

1351
    public getReferences(srcPath: string, position: Position): Location[] {
1352
        //find the file
1353
        let file = this.getFile(srcPath);
5✔
1354
        if (!file) {
5!
1355
            return null;
×
1356
        }
1357

1358
        const cdataCtx = isXmlFile(file) ? this.resolveCdataContext(file, position) : undefined;
5✔
1359
        const effectiveFile = cdataCtx?.brsFile ?? file;
5✔
1360

1361
        const event: ProvideReferencesEvent = {
5✔
1362
            program: this,
1363
            file: effectiveFile,
1364
            position: position,
1365
            references: []
1366
        };
1367

1368
        this.plugins.emit('beforeProvideReferences', event);
5✔
1369
        this.plugins.emit('provideReferences', event);
5✔
1370
        this.plugins.emit('afterProvideReferences', event);
5✔
1371

1372
        return cdataCtx ? this.remapLocationsFromSynthetic(event.references, cdataCtx) : event.references;
5✔
1373
    }
1374

1375
    /**
1376
     * Get a list of all script imports, relative to the specified pkgPath
1377
     * @param sourcePkgPath - the pkgPath of the source that wants to resolve script imports.
1378
     */
1379
    public getScriptImportCompletions(sourcePkgPath: string, scriptImport: FileReference) {
1380
        let lowerSourcePkgPath = sourcePkgPath.toLowerCase();
3✔
1381

1382
        let result = [] as CompletionItem[];
3✔
1383
        /**
1384
         * hashtable to prevent duplicate results
1385
         */
1386
        let resultPkgPaths = {} as Record<string, boolean>;
3✔
1387

1388
        //restrict to only .brs files
1389
        for (let key in this.files) {
3✔
1390
            let file = this.files[key];
4✔
1391
            if (
4✔
1392
                //is a BrightScript or BrighterScript file
1393
                (file.extension === '.bs' || file.extension === '.brs') &&
11✔
1394
                //this file is not the current file
1395
                lowerSourcePkgPath !== file.pkgPath.toLowerCase()
1396
            ) {
1397
                //add the relative path
1398
                let relativePath = util.getRelativePath(sourcePkgPath, file.pkgPath).replace(/\\/g, '/');
3✔
1399
                let pkgPathStandardized = file.pkgPath.replace(/\\/g, '/');
3✔
1400
                let filePkgPath = `pkg:/${pkgPathStandardized}`;
3✔
1401
                let lowerFilePkgPath = filePkgPath.toLowerCase();
3✔
1402
                if (!resultPkgPaths[lowerFilePkgPath]) {
3!
1403
                    resultPkgPaths[lowerFilePkgPath] = true;
3✔
1404

1405
                    result.push({
3✔
1406
                        label: relativePath,
1407
                        detail: file.srcPath,
1408
                        kind: CompletionItemKind.File,
1409
                        textEdit: {
1410
                            newText: relativePath,
1411
                            range: scriptImport.filePathRange
1412
                        }
1413
                    });
1414

1415
                    //add the absolute path
1416
                    result.push({
3✔
1417
                        label: filePkgPath,
1418
                        detail: file.srcPath,
1419
                        kind: CompletionItemKind.File,
1420
                        textEdit: {
1421
                            newText: filePkgPath,
1422
                            range: scriptImport.filePathRange
1423
                        }
1424
                    });
1425
                }
1426
            }
1427
        }
1428
        return result;
3✔
1429
    }
1430

1431
    /**
1432
     * Transpile a single file and get the result as a string.
1433
     * This does not write anything to the file system.
1434
     *
1435
     * This should only be called by `LanguageServer`.
1436
     * Internal usage should call `_getTranspiledFileContents` instead.
1437
     * @param filePath can be a srcPath or a destPath
1438
     */
1439
    public async getTranspiledFileContents(filePath: string) {
1440
        const file = this.getFile(filePath);
4✔
1441
        const fileMap: FileObj[] = [{
4✔
1442
            src: file.srcPath,
1443
            dest: file.pkgPath
1444
        }];
1445
        const { entries, astEditor } = this.beforeProgramTranspile(fileMap, this.options.stagingDir);
4✔
1446
        const result = this._getTranspiledFileContents(
4✔
1447
            file
1448
        );
1449
        this.afterProgramTranspile(entries, astEditor);
4✔
1450
        return Promise.resolve(result);
4✔
1451
    }
1452

1453
    /**
1454
     * Transpile a synthetic CDATA BrsFile and return a SourceNode suitable for embedding
1455
     * back into the parent XML file's transpile output. Plugin beforeFileTranspile events are
1456
     * fired so AST edits (e.g. built-in transpile transforms) are applied. afterFileTranspile
1457
     * is intentionally skipped — it is designed for standalone file output, not embedded content.
1458
     *
1459
     * Because synthetic BrsFiles are created with offset-padded content, their token positions
1460
     * already align with positions in the parent XML file. Overriding state.srcPath to the XML
1461
     * file's path makes the resulting SourceNode reference the XML file directly, producing a
1462
     * correct unified source map.
1463
     */
1464
    public transpileSyntheticBrsFileToSourceNode(brsFile: BrsFile, xmlSrcPath: string): SourceNode {
1465
        const editor = new AstEditor();
7✔
1466

1467
        this.plugins.emit('beforeFileTranspile', {
7✔
1468
            program: this,
1469
            file: brsFile,
1470
            outputPath: undefined,
1471
            editor: editor
1472
        });
1473
        if (editor.hasChanges) {
7✔
1474
            editor.setProperty(brsFile, 'needsTranspiled', true);
5✔
1475
        }
1476

1477
        // Override srcPath so every SourceNode references the XML file at the correct position
1478
        const state = new BrsTranspileState(brsFile);
7✔
1479
        state.srcPath = xmlSrcPath;
7✔
1480

1481
        const sourceNode = util.sourceNodeFromTranspileResult(
7✔
1482
            null, null, state.srcPath, brsFile.ast.transpile(state)
1483
        );
1484

1485
        state.editor.undoAll();
7✔
1486
        editor.undoAll();
7✔
1487

1488
        return sourceNode;
7✔
1489
    }
1490

1491
    /**
1492
     * Internal function used to transpile files.
1493
     * This does not write anything to the file system
1494
     */
1495
    private _getTranspiledFileContents(file: BscFile, outputPath?: string): FileTranspileResult {
1496
        const editor = new AstEditor();
333✔
1497
        this.plugins.emit('beforeFileTranspile', {
333✔
1498
            program: this,
1499
            file: file,
1500
            outputPath: outputPath,
1501
            editor: editor
1502
        });
1503

1504
        //if we have any edits, assume the file needs to be transpiled
1505
        if (editor.hasChanges) {
333✔
1506
            //use the `editor` because it'll track the previous value for us and revert later on
1507
            editor.setProperty(file, 'needsTranspiled', true);
77✔
1508
        }
1509

1510
        //transpile the file
1511
        const result = file.transpile();
333✔
1512

1513
        //generate the typedef if enabled
1514
        let typedef: string;
1515
        if (isBrsFile(file) && this.options.emitDefinitions) {
333✔
1516
            typedef = file.getTypedef();
2✔
1517
        }
1518

1519
        const event: AfterFileTranspileEvent = {
333✔
1520
            program: this,
1521
            file: file,
1522
            outputPath: outputPath,
1523
            editor: editor,
1524
            code: result.code,
1525
            map: result.map,
1526
            typedef: typedef
1527
        };
1528
        this.plugins.emit('afterFileTranspile', event);
333✔
1529

1530
        //undo all `editor` edits that may have been applied to this file.
1531
        editor.undoAll();
333✔
1532

1533
        return {
333✔
1534
            srcPath: file.srcPath,
1535
            pkgPath: file.pkgPath,
1536
            code: event.code,
1537
            map: event.map,
1538
            typedef: event.typedef
1539
        };
1540
    }
1541

1542
    private beforeProgramTranspile(fileEntries: FileObj[], stagingDir: string) {
1543
        // map fileEntries using their path as key, to avoid excessive "find()" operations
1544
        const mappedFileEntries = fileEntries.reduce<Record<string, FileObj>>((collection, entry) => {
37✔
1545
            collection[s`${entry.src}`] = entry;
20✔
1546
            return collection;
20✔
1547
        }, {});
1548

1549
        const getOutputPath = (file: BscFile) => {
37✔
1550
            let filePathObj = mappedFileEntries[s`${file.srcPath}`];
77✔
1551
            if (!filePathObj) {
77✔
1552
                //this file has been added in-memory, from a plugin, for example
1553
                filePathObj = {
47✔
1554
                    //add an interpolated src path (since it doesn't actually exist in memory)
1555
                    src: `bsc:/${file.pkgPath}`,
1556
                    dest: file.pkgPath
1557
                };
1558
            }
1559
            //replace the file extension
1560
            let outputPath = filePathObj.dest.replace(/\.bs$/gi, '.brs');
77✔
1561
            //prepend the staging folder path
1562
            outputPath = s`${stagingDir}/${outputPath}`;
77✔
1563
            return outputPath;
77✔
1564
        };
1565

1566
        const entries = Object.values(this.files)
37✔
1567
            //only include the files from fileEntries
1568
            .filter(file => !!mappedFileEntries[file.srcPath])
39✔
1569
            .map(file => {
1570
                return {
18✔
1571
                    file: file,
1572
                    outputPath: getOutputPath(file)
1573
                };
1574
            })
1575
            //sort the entries to make transpiling more deterministic
1576
            .sort((a, b) => {
1577
                return a.file.srcPath < b.file.srcPath ? -1 : 1;
6✔
1578
            });
1579

1580
        const astEditor = new AstEditor();
37✔
1581

1582
        this.plugins.emit('beforeProgramTranspile', this, entries, astEditor);
37✔
1583
        return {
37✔
1584
            entries: entries,
1585
            getOutputPath: getOutputPath,
1586
            astEditor: astEditor
1587
        };
1588
    }
1589

1590
    public async transpile(fileEntries: FileObj[], stagingDir: string) {
1591
        const { entries, getOutputPath, astEditor } = this.beforeProgramTranspile(fileEntries, stagingDir);
32✔
1592

1593
        const processedFiles = new Set<string>();
32✔
1594

1595
        const transpileFile = async (srcPath: string, outputPath?: string) => {
32✔
1596
            //find the file in the program
1597
            const file = this.getFile(srcPath);
35✔
1598
            //mark this file as processed so we don't process it more than once
1599
            processedFiles.add(outputPath?.toLowerCase());
35!
1600

1601
            if (file.excludeFromOutput) {
35!
NEW
1602
                return;
×
1603
            }
1604

1605
            if (!this.options.pruneEmptyCodeFiles || !file.canBePruned) {
35✔
1606
                //skip transpiling typedef files
1607
                if (isBrsFile(file) && file.isTypedef) {
34✔
1608
                    return;
1✔
1609
                }
1610

1611
                const fileTranspileResult = this._getTranspiledFileContents(file, outputPath);
33✔
1612

1613
                //make sure the full dir path exists
1614
                await fsExtra.ensureDir(path.dirname(outputPath));
33✔
1615

1616
                if (await fsExtra.pathExists(outputPath)) {
33!
1617
                    throw new Error(`Error while transpiling "${file.srcPath}". A file already exists at "${outputPath}" and will not be overwritten.`);
×
1618
                }
1619
                const writeMapPromise = fileTranspileResult.map ? fsExtra.writeFile(`${outputPath}.map`, fileTranspileResult.map.toString()) : null;
33✔
1620
                await Promise.all([
33✔
1621
                    fsExtra.writeFile(outputPath, fileTranspileResult.code),
1622
                    writeMapPromise
1623
                ]);
1624

1625
                if (fileTranspileResult.typedef) {
33✔
1626
                    const typedefPath = outputPath.replace(/\.brs$/i, '.d.bs');
2✔
1627
                    await fsExtra.writeFile(typedefPath, fileTranspileResult.typedef);
2✔
1628
                }
1629
            }
1630
        };
1631

1632
        let promises = entries.map(async (entry) => {
32✔
1633
            return transpileFile(entry?.file?.srcPath, entry.outputPath);
12!
1634
        });
1635

1636
        //if there's no bslib file already loaded into the program, copy it to the staging directory
1637
        if (!this.getFile(bslibAliasedRokuModulesPkgPath) && !this.getFile(s`source/bslib.brs`)) {
32✔
1638
            promises.push(util.copyBslibToStaging(stagingDir, this.options.bslibDestinationDir));
31✔
1639
        }
1640
        await Promise.all(promises);
32✔
1641

1642
        //transpile any new files that plugins added since the start of this transpile process
1643
        do {
32✔
1644
            promises = [];
52✔
1645
            for (const key in this.files) {
52✔
1646
                const file = this.files[key];
59✔
1647
                //this is a new file
1648
                const outputPath = getOutputPath(file);
59✔
1649
                if (!processedFiles.has(outputPath?.toLowerCase())) {
59!
1650
                    promises.push(
23✔
1651
                        transpileFile(file?.srcPath, outputPath)
69!
1652
                    );
1653
                }
1654
            }
1655
            if (promises.length > 0) {
52✔
1656
                this.logger.info(`Transpiling ${promises.length} new files`);
20✔
1657
                await Promise.all(promises);
20✔
1658
            }
1659
        }
1660
        while (promises.length > 0);
1661
        this.afterProgramTranspile(entries, astEditor);
32✔
1662
    }
1663

1664
    private afterProgramTranspile(entries: TranspileObj[], astEditor: AstEditor) {
1665
        this.plugins.emit('afterProgramTranspile', this, entries, astEditor);
36✔
1666
        astEditor.undoAll();
36✔
1667
    }
1668

1669
    /**
1670
     * Find a list of files in the program that have a function with the given name (case INsensitive)
1671
     */
1672
    public findFilesForFunction(functionName: string) {
1673
        const files = [] as BscFile[];
33✔
1674
        const lowerFunctionName = functionName.toLowerCase();
33✔
1675
        //find every file with this function defined
1676
        for (const file of Object.values(this.files)) {
33✔
1677
            if (isBrsFile(file)) {
123✔
1678
                //TODO handle namespace-relative function calls
1679
                //if the file has a function with this name
1680
                if (file.parser.references.functionStatementLookup.get(lowerFunctionName) !== undefined) {
88✔
1681
                    files.push(file);
24✔
1682
                }
1683
            }
1684
        }
1685
        return files;
33✔
1686
    }
1687

1688
    /**
1689
     * Find a list of files in the program that have a class with the given name (case INsensitive)
1690
     */
1691
    public findFilesForClass(className: string) {
1692
        const files = [] as BscFile[];
33✔
1693
        const lowerClassName = className.toLowerCase();
33✔
1694
        //find every file with this class defined
1695
        for (const file of Object.values(this.files)) {
33✔
1696
            if (isBrsFile(file)) {
123✔
1697
                //TODO handle namespace-relative classes
1698
                //if the file has a function with this name
1699
                if (file.parser.references.classStatementLookup.get(lowerClassName) !== undefined) {
88✔
1700
                    files.push(file);
3✔
1701
                }
1702
            }
1703
        }
1704
        return files;
33✔
1705
    }
1706

1707
    public findFilesForNamespace(name: string) {
1708
        const files = [] as BscFile[];
33✔
1709
        const lowerName = name.toLowerCase();
33✔
1710
        //find every file with this class defined
1711
        for (const file of Object.values(this.files)) {
33✔
1712
            if (isBrsFile(file)) {
123✔
1713
                if (file.parser.references.namespaceStatements.find((x) => {
88✔
1714
                    const namespaceName = x.name.toLowerCase();
14✔
1715
                    return (
14✔
1716
                        //the namespace name matches exactly
1717
                        namespaceName === lowerName ||
18✔
1718
                        //the full namespace starts with the name (honoring the part boundary)
1719
                        namespaceName.startsWith(lowerName + '.')
1720
                    );
1721
                })) {
1722
                    files.push(file);
12✔
1723
                }
1724
            }
1725
        }
1726
        return files;
33✔
1727
    }
1728

1729
    public findFilesForEnum(name: string) {
1730
        const files = [] as BscFile[];
34✔
1731
        const lowerName = name.toLowerCase();
34✔
1732
        //find every file with this class defined
1733
        for (const file of Object.values(this.files)) {
34✔
1734
            if (isBrsFile(file)) {
124✔
1735
                if (file.parser.references.enumStatementLookup.get(lowerName)) {
89✔
1736
                    files.push(file);
1✔
1737
                }
1738
            }
1739
        }
1740
        return files;
34✔
1741
    }
1742

1743
    private _manifest: Map<string, string>;
1744

1745
    /**
1746
     * Modify a parsed manifest map by reading `bs_const` and injecting values from `options.manifest.bs_const`
1747
     * @param parsedManifest The manifest map to read from and modify
1748
     */
1749
    private buildBsConstsIntoParsedManifest(parsedManifest: Map<string, string>) {
1750
        // Lift the bs_consts defined in the manifest
1751
        let bsConsts = getBsConst(parsedManifest, false);
19✔
1752

1753
        // Override or delete any bs_consts defined in the bs config
1754
        for (const key in this.options?.manifest?.bs_const) {
19!
1755
            const value = this.options.manifest.bs_const[key];
3✔
1756
            if (value === null) {
3✔
1757
                bsConsts.delete(key);
1✔
1758
            } else {
1759
                bsConsts.set(key, value);
2✔
1760
            }
1761
        }
1762

1763
        // convert the new list of bs consts back into a string for the rest of the down stream systems to use
1764
        let constString = '';
19✔
1765
        for (const [key, value] of bsConsts) {
19✔
1766
            constString += `${constString !== '' ? ';' : ''}${key}=${value.toString()}`;
6✔
1767
        }
1768

1769
        // Set the updated bs_const value
1770
        parsedManifest.set('bs_const', constString);
19✔
1771
    }
1772

1773
    /**
1774
     * Try to find and load the manifest into memory
1775
     * @param manifestFileObj A pointer to a potential manifest file object found during loading
1776
     * @param replaceIfAlreadyLoaded should we overwrite the internal `_manifest` if it already exists
1777
     */
1778
    public loadManifest(manifestFileObj?: FileObj, replaceIfAlreadyLoaded = true) {
1,052✔
1779
        //if we already have a manifest instance, and should not replace...then don't replace
1780
        if (!replaceIfAlreadyLoaded && this._manifest) {
1,064!
1781
            return;
×
1782
        }
1783
        let manifestPath = manifestFileObj
1,064✔
1784
            ? manifestFileObj.src
1,064✔
1785
            : path.join(this.options.rootDir, 'manifest');
1786

1787
        try {
1,064✔
1788
            // we only load this manifest once, so do it sync to improve speed downstream
1789
            const contents = fsExtra.readFileSync(manifestPath, 'utf-8');
1,064✔
1790
            const parsedManifest = parseManifest(contents);
19✔
1791
            this.buildBsConstsIntoParsedManifest(parsedManifest);
19✔
1792
            this._manifest = parsedManifest;
19✔
1793
        } catch (e) {
1794
            this._manifest = new Map();
1,045✔
1795
        }
1796
    }
1797

1798
    /**
1799
     * Get a map of the manifest information
1800
     */
1801
    public getManifest() {
1802
        if (!this._manifest) {
1,396✔
1803
            this.loadManifest();
1,051✔
1804
        }
1805
        return this._manifest;
1,396✔
1806
    }
1807

1808
    public dispose() {
1809
        this.plugins.emit('beforeProgramDispose', { program: this });
1,354✔
1810

1811
        for (let filePath in this.files) {
1,354✔
1812
            this.files[filePath].dispose();
1,361✔
1813
        }
1814
        for (let name in this.scopes) {
1,354✔
1815
            this.scopes[name].dispose();
2,687✔
1816
        }
1817
        this.globalScope.dispose();
1,354✔
1818
        this.dependencyGraph.dispose();
1,354✔
1819
    }
1820
}
1821

1822
export interface FileTranspileResult {
1823
    srcPath: string;
1824
    pkgPath: string;
1825
    code: string;
1826
    map: SourceMapGenerator;
1827
    typedef: string;
1828
}
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