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

rokucommunity / brighterscript / #13604

13 Jan 2025 03:29PM UTC coverage: 86.902%. Remained the same
#13604

push

web-flow
Merge 6255e8be5 into 9d6ef67ba

12080 of 14675 branches covered (82.32%)

Branch coverage included in aggregate %.

94 of 100 new or added lines in 13 files covered. (94.0%)

103 existing lines in 10 files now uncovered.

13052 of 14245 relevant lines covered (91.63%)

31874.8 hits per line

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

92.65
/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, Position, Range, SignatureInformation, Location, DocumentSymbol } from 'vscode-languageserver';
5
import type { BsConfig, FinalizedBsConfig } from './BsConfig';
6
import { Scope } from './Scope';
1✔
7
import { DiagnosticMessages } from './DiagnosticMessages';
1✔
8
import type { FileObj, SemanticToken, FileLink, ProvideHoverEvent, ProvideCompletionsEvent, Hover, ProvideDefinitionEvent, ProvideReferencesEvent, ProvideDocumentSymbolsEvent, ProvideWorkspaceSymbolsEvent, BeforeFileAddEvent, BeforeFileRemoveEvent, PrepareFileEvent, PrepareProgramEvent, ProvideFileEvent, SerializedFile, TranspileObj, SerializeFileEvent, ExtraSymbolData } from './interfaces';
9
import { standardizePath as s, util } from './util';
1✔
10
import { XmlScope } from './XmlScope';
1✔
11
import { DependencyGraph } from './DependencyGraph';
1✔
12
import type { Logger } from './logging';
13
import { LogLevel, createLogger } from './logging';
1✔
14
import chalk from 'chalk';
1✔
15
import { globalCallables, globalFile } from './globalCallables';
1✔
16
import { parseManifest, getBsConst } from './preprocessor/Manifest';
1✔
17
import { URI } from 'vscode-uri';
1✔
18
import PluginInterface from './PluginInterface';
1✔
19
import { isBrsFile, isXmlFile, isXmlScope, isNamespaceStatement, isTypedFunctionType, isAnnotationDeclaration } from './astUtils/reflection';
1✔
20
import type { FunctionStatement, MethodStatement, NamespaceStatement } from './parser/Statement';
21
import { BscPlugin } from './bscPlugin/BscPlugin';
1✔
22
import { Editor } from './astUtils/Editor';
1✔
23
import type { Statement } from './parser/AstNode';
24
import { CallExpressionInfo } from './bscPlugin/CallExpressionInfo';
1✔
25
import { SignatureHelpUtil } from './bscPlugin/SignatureHelpUtil';
1✔
26
import { IntegerType } from './types/IntegerType';
1✔
27
import { StringType } from './types/StringType';
1✔
28
import { SymbolTypeFlag } from './SymbolTypeFlag';
1✔
29
import { BooleanType } from './types/BooleanType';
1✔
30
import { DoubleType } from './types/DoubleType';
1✔
31
import { DynamicType } from './types/DynamicType';
1✔
32
import { FloatType } from './types/FloatType';
1✔
33
import { LongIntegerType } from './types/LongIntegerType';
1✔
34
import { ObjectType } from './types/ObjectType';
1✔
35
import { VoidType } from './types/VoidType';
1✔
36
import { FunctionType } from './types/FunctionType';
1✔
37
import { FileFactory } from './files/Factory';
1✔
38
import { ActionPipeline } from './ActionPipeline';
1✔
39
import type { FileData } from './files/LazyFileData';
40
import { LazyFileData } from './files/LazyFileData';
1✔
41
import { rokuDeploy } from 'roku-deploy';
1✔
42
import type { SGNodeData, BRSComponentData, BRSEventData, BRSInterfaceData } from './roku-types';
43
import { nodes, components, interfaces, events } from './roku-types';
1✔
44
import { ComponentType } from './types/ComponentType';
1✔
45
import { InterfaceType } from './types/InterfaceType';
1✔
46
import { BuiltInInterfaceAdder } from './types/BuiltInInterfaceAdder';
1✔
47
import type { UnresolvedSymbol } from './AstValidationSegmenter';
48
import { WalkMode, createVisitor } from './astUtils/visitors';
1✔
49
import type { BscFile } from './files/BscFile';
50
import { Stopwatch } from './Stopwatch';
1✔
51
import { firstBy } from 'thenby';
1✔
52
import { CrossScopeValidator } from './CrossScopeValidator';
1✔
53
import { DiagnosticManager } from './DiagnosticManager';
1✔
54
import { ProgramValidatorDiagnosticsTag } from './bscPlugin/validation/ProgramValidator';
1✔
55
import type { ProvidedSymbolInfo, BrsFile } from './files/BrsFile';
56
import type { XmlFile } from './files/XmlFile';
57
import { SymbolTable } from './SymbolTable';
1✔
58
import type { TypedFunctionType } from './types/TypedFunctionType';
59

60
const bslibNonAliasedRokuModulesPkgPath = s`source/roku_modules/rokucommunity_bslib/bslib.brs`;
1✔
61
const bslibAliasedRokuModulesPkgPath = s`source/roku_modules/bslib/bslib.brs`;
1✔
62

63
export interface SignatureInfoObj {
64
    index: number;
65
    key: string;
66
    signature: SignatureInformation;
67
}
68

69
export class Program {
1✔
70
    constructor(
71
        /**
72
         * The root directory for this program
73
         */
74
        options: BsConfig,
75
        logger?: Logger,
76
        plugins?: PluginInterface,
77
        diagnosticsManager?: DiagnosticManager
78
    ) {
79
        this.options = util.normalizeConfig(options);
1,841✔
80
        this.logger = logger ?? createLogger(options);
1,841✔
81
        this.plugins = plugins || new PluginInterface([], { logger: this.logger });
1,841✔
82
        this.diagnostics = diagnosticsManager || new DiagnosticManager();
1,841✔
83

84
        // initialize the diagnostics Manager
85
        this.diagnostics.logger = this.logger;
1,841✔
86
        this.diagnostics.options = this.options;
1,841✔
87
        this.diagnostics.program = this;
1,841✔
88

89
        //inject the bsc plugin as the first plugin in the stack.
90
        this.plugins.addFirst(new BscPlugin());
1,841✔
91

92
        //normalize the root dir path
93
        this.options.rootDir = util.getRootDir(this.options);
1,841✔
94

95
        this.createGlobalScope();
1,841✔
96

97
        this.fileFactory = new FileFactory(this);
1,841✔
98
    }
99

100
    public options: FinalizedBsConfig;
101
    public logger: Logger;
102

103
    /**
104
     * An editor that plugins can use to modify program-level things during the build flow. Don't use this to edit files (they have their own `.editor`)
105
     */
106
    public editor = new Editor();
1,841✔
107

108
    /**
109
     * A factory that creates `File` instances
110
     */
111
    private fileFactory: FileFactory;
112

113
    private createGlobalScope() {
114
        //create the 'global' scope
115
        this.globalScope = new Scope('global', this, 'scope:global');
1,841✔
116
        this.globalScope.attachDependencyGraph(this.dependencyGraph);
1,841✔
117
        this.scopes.global = this.globalScope;
1,841✔
118

119
        this.populateGlobalSymbolTable();
1,841✔
120

121
        //hardcode the files list for global scope to only contain the global file
122
        this.globalScope.getAllFiles = () => [globalFile];
15,671✔
123
        globalFile.isValidated = true;
1,841✔
124
        this.globalScope.validate();
1,841✔
125

126
        //TODO we might need to fix this because the isValidated clears stuff now
127
        (this.globalScope as any).isValidated = true;
1,841✔
128

129
        // Get declarations for all annotations from all plugins
130
        this.populateAnnotationSymbolTable();
1,841✔
131
    }
132

133

134
    private recursivelyAddNodeToSymbolTable(nodeData: SGNodeData) {
135
        if (!nodeData) {
340,585!
UNCOV
136
            return;
×
137
        }
138
        let nodeType: ComponentType;
139
        const nodeName = util.getSgNodeTypeName(nodeData.name);
340,585✔
140
        if (!this.globalScope.symbolTable.hasSymbol(nodeName, SymbolTypeFlag.typetime)) {
340,585✔
141
            let parentNode: ComponentType;
142
            if (nodeData.extends) {
176,736✔
143
                const parentNodeData = nodes[nodeData.extends.name.toLowerCase()];
163,849✔
144
                try {
163,849✔
145
                    parentNode = this.recursivelyAddNodeToSymbolTable(parentNodeData);
163,849✔
146
                } catch (error) {
UNCOV
147
                    this.logger.error(error, nodeData);
×
148
                }
149
            }
150
            nodeType = new ComponentType(nodeData.name, parentNode);
176,736✔
151
            nodeType.addBuiltInInterfaces();
176,736✔
152
            if (nodeData.name === 'Node') {
176,736✔
153
                // Add `roSGNode` as shorthand for `roSGNodeNode`
154
                this.globalScope.symbolTable.addSymbol('roSGNode', { description: nodeData.description, isBuiltIn: true }, nodeType, SymbolTypeFlag.typetime);
1,841✔
155
            }
156
            this.globalScope.symbolTable.addSymbol(nodeName, { description: nodeData.description, isBuiltIn: true }, nodeType, SymbolTypeFlag.typetime);
176,736✔
157
        } else {
158
            nodeType = this.globalScope.symbolTable.getSymbolType(nodeName, { flags: SymbolTypeFlag.typetime }) as ComponentType;
163,849✔
159
        }
160

161
        return nodeType;
340,585✔
162
    }
163
    /**
164
     * Do all setup required for the global symbol table.
165
     */
166
    private populateGlobalSymbolTable() {
167
        //Setup primitive types in global symbolTable
168

169
        const builtInSymbolData: ExtraSymbolData = { isBuiltIn: true };
1,841✔
170

171
        this.globalScope.symbolTable.addSymbol('boolean', builtInSymbolData, BooleanType.instance, SymbolTypeFlag.typetime);
1,841✔
172
        this.globalScope.symbolTable.addSymbol('double', builtInSymbolData, DoubleType.instance, SymbolTypeFlag.typetime);
1,841✔
173
        this.globalScope.symbolTable.addSymbol('dynamic', builtInSymbolData, DynamicType.instance, SymbolTypeFlag.typetime);
1,841✔
174
        this.globalScope.symbolTable.addSymbol('float', builtInSymbolData, FloatType.instance, SymbolTypeFlag.typetime);
1,841✔
175
        this.globalScope.symbolTable.addSymbol('function', builtInSymbolData, new FunctionType(), SymbolTypeFlag.typetime);
1,841✔
176
        this.globalScope.symbolTable.addSymbol('integer', builtInSymbolData, IntegerType.instance, SymbolTypeFlag.typetime);
1,841✔
177
        this.globalScope.symbolTable.addSymbol('longinteger', builtInSymbolData, LongIntegerType.instance, SymbolTypeFlag.typetime);
1,841✔
178
        this.globalScope.symbolTable.addSymbol('object', builtInSymbolData, new ObjectType(), SymbolTypeFlag.typetime);
1,841✔
179
        this.globalScope.symbolTable.addSymbol('string', builtInSymbolData, StringType.instance, SymbolTypeFlag.typetime);
1,841✔
180
        this.globalScope.symbolTable.addSymbol('void', builtInSymbolData, VoidType.instance, SymbolTypeFlag.typetime);
1,841✔
181

182
        BuiltInInterfaceAdder.getLookupTable = () => this.globalScope.symbolTable;
809,387✔
183

184
        for (const callable of globalCallables) {
1,841✔
185
            this.globalScope.symbolTable.addSymbol(callable.name, { ...builtInSymbolData, description: callable.shortDescription }, callable.type, SymbolTypeFlag.runtime);
143,598✔
186
        }
187

188
        for (const ifaceData of Object.values(interfaces) as BRSInterfaceData[]) {
1,841✔
189
            const nodeType = new InterfaceType(ifaceData.name);
162,008✔
190
            nodeType.addBuiltInInterfaces();
162,008✔
191
            this.globalScope.symbolTable.addSymbol(ifaceData.name, { ...builtInSymbolData, description: ifaceData.description }, nodeType, SymbolTypeFlag.typetime);
162,008✔
192
        }
193

194
        for (const componentData of Object.values(components) as BRSComponentData[]) {
1,841✔
195
            const nodeType = new InterfaceType(componentData.name);
119,665✔
196
            nodeType.addBuiltInInterfaces();
119,665✔
197
            if (componentData.name !== 'roSGNode') {
119,665✔
198
                // we will add `roSGNode` as shorthand for `roSGNodeNode`, since all roSgNode components are SceneGraph nodes
199
                this.globalScope.symbolTable.addSymbol(componentData.name, { ...builtInSymbolData, description: componentData.description }, nodeType, SymbolTypeFlag.typetime);
117,824✔
200
            }
201
        }
202

203
        for (const nodeData of Object.values(nodes) as SGNodeData[]) {
1,841✔
204
            this.recursivelyAddNodeToSymbolTable(nodeData);
176,736✔
205
        }
206

207
        for (const eventData of Object.values(events) as BRSEventData[]) {
1,841✔
208
            const nodeType = new InterfaceType(eventData.name);
33,138✔
209
            nodeType.addBuiltInInterfaces();
33,138✔
210
            this.globalScope.symbolTable.addSymbol(eventData.name, { ...builtInSymbolData, description: eventData.description }, nodeType, SymbolTypeFlag.typetime);
33,138✔
211
        }
212

213
    }
214

215
    /**
216
     * A graph of all files and their dependencies.
217
     * For example:
218
     *      File.xml -> [lib1.brs, lib2.brs]
219
     *      lib2.brs -> [lib3.brs] //via an import statement
220
     */
221
    private dependencyGraph = new DependencyGraph();
1,841✔
222

223
    public diagnostics: DiagnosticManager;
224

225
    /**
226
     * A scope that contains all built-in global functions.
227
     * All scopes should directly or indirectly inherit from this scope
228
     */
229
    public globalScope: Scope = undefined as any;
1,841✔
230

231
    /**
232
     * Plugins which can provide extra diagnostics or transform AST
233
     */
234
    public plugins: PluginInterface;
235

236
    public pluginAnnotationTable = new SymbolTable('Plugin Annotations', () => this.globalScope?.symbolTable);
1,841!
237

238
    private populateAnnotationSymbolTable() {
239
        for (const [pluginName, annotations] of this.plugins.getAnnotationMap().entries()) {
1,841✔
240
            for (const annotation of annotations) {
1✔
241
                if (isTypedFunctionType(annotation) && annotation.name) {
1!
NEW
242
                    this.addAnnotationSymbol(annotation.name, annotation, { pluginName: pluginName });
×
243
                } else if (isAnnotationDeclaration(annotation)) {
1!
244
                    const annoType = annotation.type;
1✔
245
                    let description = (typeof annotation.description === 'string') ? annotation.description : undefined;
1!
246
                    this.addAnnotationSymbol(annoType.name, annoType, { pluginName: pluginName, description: description });
1✔
NEW
247
                } else if (typeof annotation === 'string') {
×
248
                    // TODO: Do we need to parse this?
249
                }
250
            }
251
        }
252
    }
253

254
    public addAnnotationSymbol(name: string, annoType: TypedFunctionType, extraData: ExtraSymbolData = {}) {
22✔
255
        if (name && annoType) {
24!
256
            annoType.setName(name);
24✔
257
            const pluginName = extraData?.pluginName ?? '';
24!
258
            this.logger.info(`Adding annotation '${name}' (${pluginName})`);
24✔
259
            this.pluginAnnotationTable.addSymbol(name, extraData, annoType, SymbolTypeFlag.annotation);
24✔
260
        }
261
    }
262

263
    private fileSymbolInformation = new Map<string, { provides: ProvidedSymbolInfo; requires: UnresolvedSymbol[] }>();
1,841✔
264

265
    public addFileSymbolInfo(file: BrsFile) {
266
        this.fileSymbolInformation.set(file.pkgPath, {
1,690✔
267
            provides: file.providedSymbols,
268
            requires: file.requiredSymbols
269
        });
270
    }
271

272
    public getFileSymbolInfo(file: BrsFile) {
273
        return this.fileSymbolInformation.get(file.pkgPath);
1,693✔
274
    }
275

276
    /**
277
     * The path to bslib.brs (the BrightScript runtime for certain BrighterScript features)
278
     */
279
    public get bslibPkgPath() {
280
        //if there's an aliased (preferred) version of bslib from roku_modules loaded into the program, use that
281
        if (this.getFile(bslibAliasedRokuModulesPkgPath)) {
2,466✔
282
            return bslibAliasedRokuModulesPkgPath;
11✔
283

284
            //if there's a non-aliased version of bslib from roku_modules, use that
285
        } else if (this.getFile(bslibNonAliasedRokuModulesPkgPath)) {
2,455✔
286
            return bslibNonAliasedRokuModulesPkgPath;
24✔
287

288
            //default to the embedded version
289
        } else {
290
            return `${this.options.bslibDestinationDir}${path.sep}bslib.brs`;
2,431✔
291
        }
292
    }
293

294
    public get bslibPrefix() {
295
        if (this.bslibPkgPath === bslibNonAliasedRokuModulesPkgPath) {
1,797✔
296
            return 'rokucommunity_bslib';
18✔
297
        } else {
298
            return 'bslib';
1,779✔
299
        }
300
    }
301

302

303
    /**
304
     * A map of every file loaded into this program, indexed by its original file location
305
     */
306
    public files = {} as Record<string, BscFile>;
1,841✔
307
    /**
308
     * A map of every file loaded into this program, indexed by its destPath
309
     */
310
    private destMap = new Map<string, BscFile>();
1,841✔
311
    /**
312
     * Plugins can contribute multiple virtual files for a single physical file.
313
     * This collection links the virtual files back to the physical file that produced them.
314
     * The key is the standardized and lower-cased srcPath
315
     */
316
    private fileClusters = new Map<string, BscFile[]>();
1,841✔
317

318
    private scopes = {} as Record<string, Scope>;
1,841✔
319

320
    protected addScope(scope: Scope) {
321
        this.scopes[scope.name] = scope;
1,976✔
322
        delete this.sortedScopeNames;
1,976✔
323
    }
324

325
    protected removeScope(scope: Scope) {
326
        if (this.scopes[scope.name]) {
11!
327
            delete this.scopes[scope.name];
11✔
328
            delete this.sortedScopeNames;
11✔
329
        }
330
    }
331

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

340
    /**
341
     * Get the component with the specified name
342
     */
343
    public getComponent(componentName: string) {
344
        if (componentName) {
1,807✔
345
            //return the first compoment in the list with this name
346
            //(components are ordered in this list by destPath to ensure consistency)
347
            return this.components[componentName.toLowerCase()]?.[0];
1,793✔
348
        } else {
349
            return undefined;
14✔
350
        }
351
    }
352

353
    /**
354
     * Get the sorted names of custom components
355
     */
356
    public getSortedComponentNames() {
357
        const componentNames = Object.keys(this.components);
1,377✔
358
        componentNames.sort((a, b) => {
1,377✔
359
            if (a < b) {
696✔
360
                return -1;
272✔
361
            } else if (b < a) {
424!
362
                return 1;
424✔
363
            }
UNCOV
364
            return 0;
×
365
        });
366
        return componentNames;
1,377✔
367
    }
368

369
    /**
370
     * Keeps a set of all the components that need to have their types updated during the current validation cycle
371
     */
372
    private componentSymbolsToUpdate = new Set<{ componentKey: string; componentName: string }>();
1,841✔
373

374
    /**
375
     * Register (or replace) the reference to a component in the component map
376
     */
377
    private registerComponent(xmlFile: XmlFile, scope: XmlScope) {
378
        const key = this.getComponentKey(xmlFile);
378✔
379
        if (!this.components[key]) {
378✔
380
            this.components[key] = [];
366✔
381
        }
382
        this.components[key].push({
378✔
383
            file: xmlFile,
384
            scope: scope
385
        });
386
        this.components[key].sort((a, b) => {
378✔
387
            const pathA = a.file.destPath.toLowerCase();
5✔
388
            const pathB = b.file.destPath.toLowerCase();
5✔
389
            if (pathA < pathB) {
5✔
390
                return -1;
1✔
391
            } else if (pathA > pathB) {
4!
392
                return 1;
4✔
393
            }
UNCOV
394
            return 0;
×
395
        });
396
        this.syncComponentDependencyGraph(this.components[key]);
378✔
397
        this.addDeferredComponentTypeSymbolCreation(xmlFile);
378✔
398
    }
399

400
    /**
401
     * Remove the specified component from the components map
402
     */
403
    private unregisterComponent(xmlFile: XmlFile) {
404
        const key = this.getComponentKey(xmlFile);
11✔
405
        const arr = this.components[key] || [];
11!
406
        for (let i = 0; i < arr.length; i++) {
11✔
407
            if (arr[i].file === xmlFile) {
11!
408
                arr.splice(i, 1);
11✔
409
                break;
11✔
410
            }
411
        }
412

413
        this.syncComponentDependencyGraph(arr);
11✔
414
        this.addDeferredComponentTypeSymbolCreation(xmlFile);
11✔
415
    }
416

417
    /**
418
     * Adds a component described in an XML to the set of components that needs to be updated this validation cycle.
419
     * @param xmlFile XML file with <component> tag
420
     */
421
    private addDeferredComponentTypeSymbolCreation(xmlFile: XmlFile) {
422
        this.componentSymbolsToUpdate.add({ componentKey: this.getComponentKey(xmlFile), componentName: xmlFile.componentName?.text });
389✔
423

424
    }
425

426
    private getComponentKey(xmlFile: XmlFile) {
427
        return (xmlFile.componentName?.text ?? xmlFile.pkgPath).toLowerCase();
778✔
428
    }
429

430
    /**
431
     * Updates the global symbol table with the first component in this.components to have the same name as the component in the file
432
     * @param componentKey key getting a component from `this.components`
433
     * @param componentName the unprefixed name of the component that will be added (e.g. 'MyLabel' NOT 'roSgNodeMyLabel')
434
     */
435
    private updateComponentSymbolInGlobalScope(componentKey: string, componentName: string) {
436
        const symbolName = componentName ? util.getSgNodeTypeName(componentName) : undefined;
308✔
437
        if (!symbolName) {
308✔
438
            return;
7✔
439
        }
440
        const components = this.components[componentKey] || [];
301!
441
        // Remove any existing symbols that match
442
        this.globalScope.symbolTable.removeSymbol(symbolName);
301✔
443
        // There is a component that can be added - use it.
444
        if (components.length > 0) {
301✔
445
            const componentScope = components[0].scope;
300✔
446
            // TODO: May need to link symbol tables to get correct types for callfuncs
447
            // componentScope.linkSymbolTable();
448
            const componentType = componentScope.getComponentType();
300✔
449
            if (componentType) {
300!
450
                this.globalScope.symbolTable.addSymbol(symbolName, {}, componentType, SymbolTypeFlag.typetime);
300✔
451
            }
452
            // TODO: Remember to unlink! componentScope.unlinkSymbolTable();
453
        }
454
    }
455

456
    /**
457
     * re-attach the dependency graph with a new key for any component who changed
458
     * their position in their own named array (only matters when there are multiple
459
     * components with the same name)
460
     */
461
    private syncComponentDependencyGraph(components: Array<{ file: XmlFile; scope: XmlScope }>) {
462
        //reattach every dependency graph
463
        for (let i = 0; i < components.length; i++) {
389✔
464
            const { file, scope } = components[i];
384✔
465

466
            //attach (or re-attach) the dependencyGraph for every component whose position changed
467
            if (file.dependencyGraphIndex !== i) {
384✔
468
                file.dependencyGraphIndex = i;
380✔
469
                this.dependencyGraph.addOrReplace(file.dependencyGraphKey, file.dependencies);
380✔
470
                file.attachDependencyGraph(this.dependencyGraph);
380✔
471
                scope.attachDependencyGraph(this.dependencyGraph);
380✔
472
            }
473
        }
474
    }
475

476
    /**
477
     * Get a list of all files that are included in the project but are not referenced
478
     * by any scope in the program.
479
     */
480
    public getUnreferencedFiles() {
UNCOV
481
        let result = [] as BscFile[];
×
UNCOV
482
        for (let filePath in this.files) {
×
UNCOV
483
            let file = this.files[filePath];
×
484
            //is this file part of a scope
UNCOV
485
            if (!this.getFirstScopeForFile(file)) {
×
486
                //no scopes reference this file. add it to the list
UNCOV
487
                result.push(file);
×
488
            }
489
        }
UNCOV
490
        return result;
×
491
    }
492

493
    /**
494
     * Get the list of errors for the entire program.
495
     */
496
    public getDiagnostics() {
497
        return this.diagnostics.getDiagnostics();
1,175✔
498
    }
499

500
    /**
501
     * Determine if the specified file is loaded in this program right now.
502
     * @param filePath the absolute or relative path to the file
503
     * @param normalizePath should the provided path be normalized before use
504
     */
505
    public hasFile(filePath: string, normalizePath = true) {
2,558✔
506
        return !!this.getFile(filePath, normalizePath);
2,558✔
507
    }
508

509
    /**
510
     * roku filesystem is case INsensitive, so find the scope by key case insensitive
511
     * @param scopeName xml scope names are their `destPath`. Source scope is stored with the key `"source"`
512
     */
513
    public getScopeByName(scopeName: string): Scope | undefined {
514
        if (!scopeName) {
57!
515
            return undefined;
×
516
        }
517
        //most scopes are xml file pkg paths. however, the ones that are not are single names like "global" and "scope",
518
        //so it's safe to run the standardizePkgPath method
519
        scopeName = s`${scopeName}`;
57✔
520
        let key = Object.keys(this.scopes).find(x => x.toLowerCase() === scopeName.toLowerCase());
131✔
521
        return this.scopes[key!];
57✔
522
    }
523

524
    /**
525
     * Return all scopes
526
     */
527
    public getScopes() {
528
        return Object.values(this.scopes);
12✔
529
    }
530

531
    /**
532
     * Find the scope for the specified component
533
     */
534
    public getComponentScope(componentName: string) {
535
        return this.getComponent(componentName)?.scope;
427✔
536
    }
537

538
    /**
539
     * Update internal maps with this file reference
540
     */
541
    private assignFile<T extends BscFile = BscFile>(file: T) {
542
        const fileAddEvent: BeforeFileAddEvent = {
2,379✔
543
            file: file,
544
            program: this
545
        };
546

547
        this.plugins.emit('beforeFileAdd', fileAddEvent);
2,379✔
548

549
        this.files[file.srcPath.toLowerCase()] = file;
2,379✔
550
        this.destMap.set(file.destPath.toLowerCase(), file);
2,379✔
551

552
        this.plugins.emit('afterFileAdd', fileAddEvent);
2,379✔
553

554
        return file;
2,379✔
555
    }
556

557
    /**
558
     * Remove this file from internal maps
559
     */
560
    private unassignFile<T extends BscFile = BscFile>(file: T) {
561
        delete this.files[file.srcPath.toLowerCase()];
152✔
562
        this.destMap.delete(file.destPath.toLowerCase());
152✔
563
        return file;
152✔
564
    }
565

566
    /**
567
     * Load a file into the program. If that file already exists, it is replaced.
568
     * If file contents are provided, those are used, Otherwise, the file is loaded from the file system
569
     * @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:/`)
570
     * @param fileData the file contents. omit or pass `undefined` to prevent loading the data at this time
571
     */
572
    public setFile<T extends BscFile>(srcDestOrPkgPath: string, fileData?: FileData): T;
573
    /**
574
     * Load a file into the program. If that file already exists, it is replaced.
575
     * @param fileEntry an object that specifies src and dest for the file.
576
     * @param fileData the file contents. omit or pass `undefined` to prevent loading the data at this time
577
     */
578
    public setFile<T extends BscFile>(fileEntry: FileObj, fileData: FileData): T;
579
    public setFile<T extends BscFile>(fileParam: FileObj | string, fileData: FileData): T {
580
        //normalize the file paths
581
        const { srcPath, destPath } = this.getPaths(fileParam, this.options.rootDir);
2,375✔
582

583
        let file = this.logger.time(LogLevel.debug, ['Program.setFile()', chalk.green(srcPath)], () => {
2,375✔
584
            //if the file is already loaded, remove it
585
            if (this.hasFile(srcPath)) {
2,375✔
586
                this.removeFile(srcPath, true, true);
136✔
587
            }
588

589
            const data = new LazyFileData(fileData);
2,375✔
590

591
            const event = new ProvideFileEventInternal(this, srcPath, destPath, data, this.fileFactory);
2,375✔
592

593
            this.plugins.emit('beforeProvideFile', event);
2,375✔
594
            this.plugins.emit('provideFile', event);
2,375✔
595
            this.plugins.emit('afterProvideFile', event);
2,375✔
596

597
            //if no files were provided, create a AssetFile to represent it.
598
            if (event.files.length === 0) {
2,375✔
599
                event.files.push(
18✔
600
                    this.fileFactory.AssetFile({
601
                        srcPath: event.srcPath,
602
                        destPath: event.destPath,
603
                        pkgPath: event.destPath,
604
                        data: data
605
                    })
606
                );
607
            }
608

609
            //find the file instance for the srcPath that triggered this action.
610
            const primaryFile = event.files.find(x => x.srcPath === srcPath);
2,375✔
611

612
            if (!primaryFile) {
2,375!
UNCOV
613
                throw new Error(`No file provided for srcPath '${srcPath}'. Instead, received ${JSON.stringify(event.files.map(x => ({
×
614
                    type: x.type,
615
                    srcPath: x.srcPath,
616
                    destPath: x.destPath
617
                })))}`);
618
            }
619

620
            //link the virtual files to the primary file
621
            this.fileClusters.set(primaryFile.srcPath?.toLowerCase(), event.files);
2,375!
622

623
            for (const file of event.files) {
2,375✔
624
                file.srcPath = s(file.srcPath);
2,379✔
625
                if (file.destPath) {
2,379!
626
                    file.destPath = s`${util.replaceCaseInsensitive(file.destPath, this.options.rootDir, '')}`;
2,379✔
627
                }
628
                if (file.pkgPath) {
2,379✔
629
                    file.pkgPath = s`${util.replaceCaseInsensitive(file.pkgPath, this.options.rootDir, '')}`;
2,375✔
630
                } else {
631
                    file.pkgPath = file.destPath;
4✔
632
                }
633
                file.excludeFromOutput = file.excludeFromOutput === true;
2,379✔
634

635
                //set the dependencyGraph key for every file to its destPath
636
                file.dependencyGraphKey = file.destPath.toLowerCase();
2,379✔
637

638
                this.assignFile(file);
2,379✔
639

640
                //register a callback anytime this file's dependencies change
641
                if (typeof file.onDependenciesChanged === 'function') {
2,379✔
642
                    file.disposables ??= [];
2,353!
643
                    file.disposables.push(
2,353✔
644
                        this.dependencyGraph.onchange(file.dependencyGraphKey, file.onDependenciesChanged.bind(file))
645
                    );
646
                }
647

648
                //register this file (and its dependencies) with the dependency graph
649
                this.dependencyGraph.addOrReplace(file.dependencyGraphKey, file.dependencies ?? []);
2,379✔
650

651
                //if this is a `source` file, add it to the source scope's dependency list
652
                if (this.isSourceBrsFile(file)) {
2,379✔
653
                    this.createSourceScope();
1,648✔
654
                    this.dependencyGraph.addDependency('scope:source', file.dependencyGraphKey);
1,648✔
655
                }
656

657
                //if this is an xml file in the components folder, register it as a component
658
                if (this.isComponentsXmlFile(file)) {
2,379✔
659
                    //create a new scope for this xml file
660
                    let scope = new XmlScope(file, this);
378✔
661
                    this.addScope(scope);
378✔
662

663
                    //register this compoent now that we have parsed it and know its component name
664
                    this.registerComponent(file, scope);
378✔
665

666
                    //notify plugins that the scope is created and the component is registered
667
                    this.plugins.emit('afterScopeCreate', {
378✔
668
                        program: this,
669
                        scope: scope
670
                    });
671
                }
672
            }
673

674
            return primaryFile;
2,375✔
675
        });
676
        return file as T;
2,375✔
677
    }
678

679
    /**
680
     * Given a srcPath, a destPath, or both, resolve whichever is missing, relative to rootDir.
681
     * @param fileParam an object representing file paths
682
     * @param rootDir must be a pre-normalized path
683
     */
684
    private getPaths(fileParam: string | FileObj | { srcPath?: string; pkgPath?: string }, rootDir: string) {
685
        let srcPath: string | undefined;
686
        let destPath: string | undefined;
687

688
        assert.ok(fileParam, 'fileParam is required');
2,530✔
689

690
        //lift the path vars from the incoming param
691
        if (typeof fileParam === 'string') {
2,530✔
692
            fileParam = this.removePkgPrefix(fileParam);
2,168✔
693
            srcPath = s`${path.resolve(rootDir, fileParam)}`;
2,168✔
694
            destPath = s`${util.replaceCaseInsensitive(srcPath, rootDir, '')}`;
2,168✔
695
        } else {
696
            let param: any = fileParam;
362✔
697

698
            if (param.src) {
362✔
699
                srcPath = s`${param.src}`;
361✔
700
            }
701
            if (param.srcPath) {
362!
UNCOV
702
                srcPath = s`${param.srcPath}`;
×
703
            }
704
            if (param.dest) {
362✔
705
                destPath = s`${this.removePkgPrefix(param.dest)}`;
361✔
706
            }
707
            if (param.pkgPath) {
362!
UNCOV
708
                destPath = s`${this.removePkgPrefix(param.pkgPath)}`;
×
709
            }
710
        }
711

712
        //if there's no srcPath, use the destPath to build an absolute srcPath
713
        if (!srcPath) {
2,530✔
714
            srcPath = s`${rootDir}/${destPath}`;
1✔
715
        }
716
        //coerce srcPath to an absolute path
717
        if (!path.isAbsolute(srcPath)) {
2,530✔
718
            srcPath = util.standardizePath(srcPath);
1✔
719
        }
720

721
        //if destPath isn't set, compute it from the other paths
722
        if (!destPath) {
2,530✔
723
            destPath = s`${util.replaceCaseInsensitive(srcPath, rootDir, '')}`;
1✔
724
        }
725

726
        assert.ok(srcPath, 'fileEntry.src is required');
2,530✔
727
        assert.ok(destPath, 'fileEntry.dest is required');
2,530✔
728

729
        return {
2,530✔
730
            srcPath: srcPath,
731
            //remove leading slash
732
            destPath: destPath.replace(/^[\/\\]+/, '')
733
        };
734
    }
735

736
    /**
737
     * Remove any leading `pkg:/` found in the path
738
     */
739
    private removePkgPrefix(path: string) {
740
        return path.replace(/^pkg:\//i, '');
2,529✔
741
    }
742

743
    /**
744
     * Is this file a .brs file found somewhere within the `pkg:/source/` folder?
745
     */
746
    private isSourceBrsFile(file: BscFile) {
747
        return !!/^(pkg:\/)?source[\/\\]/.exec(file.destPath);
2,531✔
748
    }
749

750
    /**
751
     * Is this file a .brs file found somewhere within the `pkg:/source/` folder?
752
     */
753
    private isComponentsXmlFile(file: BscFile): file is XmlFile {
754
        return isXmlFile(file) && !!/^(pkg:\/)?components[\/\\]/.exec(file.destPath);
2,379✔
755
    }
756

757
    /**
758
     * Ensure source scope is created.
759
     * Note: automatically called internally, and no-op if it exists already.
760
     */
761
    public createSourceScope() {
762
        if (!this.scopes.source) {
2,419✔
763
            const sourceScope = new Scope('source', this, 'scope:source');
1,598✔
764
            sourceScope.attachDependencyGraph(this.dependencyGraph);
1,598✔
765
            this.addScope(sourceScope);
1,598✔
766
            this.plugins.emit('afterScopeCreate', {
1,598✔
767
                program: this,
768
                scope: sourceScope
769
            });
770
        }
771
    }
772

773
    /**
774
     * Remove a set of files from the program
775
     * @param srcPaths can be an array of srcPath or destPath strings
776
     * @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
777
     */
778
    public removeFiles(srcPaths: string[], normalizePath = true) {
1✔
779
        for (let srcPath of srcPaths) {
1✔
780
            this.removeFile(srcPath, normalizePath);
1✔
781
        }
782
    }
783

784
    /**
785
     * Remove a file from the program
786
     * @param filePath can be a srcPath, a destPath, or a destPath with leading `pkg:/`
787
     * @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
788
     */
789
    public removeFile(filePath: string, normalizePath = true, keepSymbolInformation = false) {
27✔
790
        this.logger.debug('Program.removeFile()', filePath);
150✔
791
        const paths = this.getPaths(filePath, this.options.rootDir);
150✔
792

793
        //there can be one or more File entries for a single srcPath, so get all of them and remove them all
794
        const files = this.fileClusters.get(paths.srcPath?.toLowerCase()) ?? [this.getFile(filePath, normalizePath)];
150!
795

796
        for (const file of files) {
150✔
797
            //if a file has already been removed, nothing more needs to be done here
798
            if (!file || !this.hasFile(file.srcPath)) {
153✔
799
                continue;
1✔
800
            }
801
            this.diagnostics.clearForFile(file.srcPath);
152✔
802

803
            const event: BeforeFileRemoveEvent = { file: file, program: this };
152✔
804
            this.plugins.emit('beforeFileRemove', event);
152✔
805

806
            //if there is a scope named the same as this file's path, remove it (i.e. xml scopes)
807
            let scope = this.scopes[file.destPath];
152✔
808
            if (scope) {
152✔
809
                const scopeDisposeEvent = {
11✔
810
                    program: this,
811
                    scope: scope
812
                };
813
                this.plugins.emit('beforeScopeDispose', scopeDisposeEvent);
11✔
814
                this.plugins.emit('onScopeDispose', scopeDisposeEvent);
11✔
815
                scope.dispose();
11✔
816
                //notify dependencies of this scope that it has been removed
817
                this.dependencyGraph.remove(scope.dependencyGraphKey!);
11✔
818
                this.removeScope(this.scopes[file.destPath]);
11✔
819
                this.plugins.emit('afterScopeDispose', scopeDisposeEvent);
11✔
820
            }
821
            //remove the file from the program
822
            this.unassignFile(file);
152✔
823

824
            this.dependencyGraph.remove(file.dependencyGraphKey);
152✔
825

826
            //if this is a pkg:/source file, notify the `source` scope that it has changed
827
            if (this.isSourceBrsFile(file)) {
152✔
828
                this.dependencyGraph.removeDependency('scope:source', file.dependencyGraphKey);
126✔
829
            }
830
            if (isBrsFile(file)) {
152✔
831
                if (!keepSymbolInformation) {
135✔
832
                    this.fileSymbolInformation.delete(file.pkgPath);
8✔
833
                }
834
                this.crossScopeValidation.clearResolutionsForFile(file);
135✔
835
            }
836

837
            //if this is a component, remove it from our components map
838
            if (isXmlFile(file)) {
152✔
839
                this.unregisterComponent(file);
11✔
840
            }
841
            //dispose any disposable things on the file
842
            for (const disposable of file?.disposables ?? []) {
152!
843
                disposable();
146✔
844
            }
845
            //dispose file
846
            file?.dispose?.();
152!
847

848
            this.plugins.emit('afterFileRemove', event);
152✔
849
        }
850
    }
851

852
    public crossScopeValidation = new CrossScopeValidator(this);
1,841✔
853

854
    private isFirstValidation = true;
1,841✔
855

856
    /**
857
     * Traverse the entire project, and validate all scopes
858
     */
859
    public validate() {
860
        this.logger.time(LogLevel.log, ['Validating project'], () => {
1,377✔
861
            this.diagnostics.clearForTag(ProgramValidatorDiagnosticsTag);
1,377✔
862
            const programValidateEvent = {
1,377✔
863
                program: this
864
            };
865
            this.plugins.emit('beforeProgramValidate', programValidateEvent);
1,377✔
866
            this.plugins.emit('onProgramValidate', programValidateEvent);
1,377✔
867

868
            const metrics = {
1,377✔
869
                filesChanged: 0,
870
                filesValidated: 0,
871
                fileValidationTime: '',
872
                crossScopeValidationTime: '',
873
                scopesValidated: 0,
874
                totalLinkTime: '',
875
                totalScopeValidationTime: '',
876
                componentValidationTime: ''
877
            };
878

879
            const validationStopwatch = new Stopwatch();
1,377✔
880
            //validate every file
881
            const brsFilesValidated: BrsFile[] = [];
1,377✔
882
            const afterValidateFiles: BscFile[] = [];
1,377✔
883

884
            metrics.fileValidationTime = validationStopwatch.getDurationTextFor(() => {
1,377✔
885
                //sort files by path so we get consistent results
886
                const files = Object.values(this.files).sort(firstBy(x => x.srcPath));
3,488✔
887
                for (const file of files) {
1,377✔
888
                    //for every unvalidated file, validate it
889
                    if (!file.isValidated) {
2,269✔
890
                        const validateFileEvent = {
1,937✔
891
                            program: this,
892
                            file: file
893
                        };
894
                        this.plugins.emit('beforeFileValidate', validateFileEvent);
1,937✔
895
                        //emit an event to allow plugins to contribute to the file validation process
896
                        this.plugins.emit('onFileValidate', validateFileEvent);
1,937✔
897
                        file.isValidated = true;
1,937✔
898
                        if (isBrsFile(file)) {
1,937✔
899
                            brsFilesValidated.push(file);
1,632✔
900
                        }
901
                        afterValidateFiles.push(file);
1,937✔
902
                    }
903
                }
904
                // AfterFileValidate is after all files have been validated
905
                for (const file of afterValidateFiles) {
1,377✔
906
                    const validateFileEvent = {
1,937✔
907
                        program: this,
908
                        file: file
909
                    };
910
                    this.plugins.emit('afterFileValidate', validateFileEvent);
1,937✔
911
                }
912
            }).durationText;
913

914
            metrics.filesChanged = afterValidateFiles.length;
1,377✔
915

916
            // Build component types for any component that changes
917
            this.logger.time(LogLevel.info, ['Build component types'], () => {
1,377✔
918
                for (let { componentKey, componentName } of this.componentSymbolsToUpdate) {
1,377✔
919
                    this.updateComponentSymbolInGlobalScope(componentKey, componentName);
308✔
920
                }
921
                this.componentSymbolsToUpdate.clear();
1,377✔
922
            });
923

924

925
            const changedSymbolsMapArr = brsFilesValidated?.map(f => {
1,377!
926
                if (isBrsFile(f)) {
1,632!
927
                    return f.providedSymbols.changes;
1,632✔
928
                }
UNCOV
929
                return null;
×
930
            }).filter(x => x);
1,632✔
931

932
            const changedSymbols = new Map<SymbolTypeFlag, Set<string>>();
1,377✔
933
            for (const flag of [SymbolTypeFlag.runtime, SymbolTypeFlag.typetime]) {
1,377✔
934
                const changedSymbolsSetArr = changedSymbolsMapArr.map(symMap => symMap.get(flag));
3,264✔
935
                changedSymbols.set(flag, new Set(...changedSymbolsSetArr));
2,754✔
936
            }
937

938
            const filesToBeValidatedInScopeContext = new Set<BscFile>(afterValidateFiles);
1,377✔
939

940
            metrics.crossScopeValidationTime = validationStopwatch.getDurationTextFor(() => {
1,377✔
941
                const scopesToCheck = this.getScopesForCrossScopeValidation();
1,377✔
942
                this.crossScopeValidation.buildComponentsMap();
1,377✔
943
                this.crossScopeValidation.addDiagnosticsForScopes(scopesToCheck);
1,377✔
944
                const filesToRevalidate = this.crossScopeValidation.getFilesRequiringChangedSymbol(scopesToCheck, changedSymbols);
1,377✔
945
                for (const file of filesToRevalidate) {
1,377✔
946
                    filesToBeValidatedInScopeContext.add(file);
178✔
947
                }
948
            }).durationText;
949

950
            metrics.filesValidated = filesToBeValidatedInScopeContext.size;
1,377✔
951

952
            let linkTime = 0;
1,377✔
953
            let validationTime = 0;
1,377✔
954
            let scopesValidated = 0;
1,377✔
955
            let changedFiles = new Set<BscFile>(afterValidateFiles);
1,377✔
956
            this.logger.time(LogLevel.info, ['Validate all scopes'], () => {
1,377✔
957
                //sort the scope names so we get consistent results
958
                const scopeNames = this.getSortedScopeNames();
1,377✔
959
                for (const file of filesToBeValidatedInScopeContext) {
1,377✔
960
                    if (isBrsFile(file)) {
2,058✔
961
                        file.validationSegmenter.unValidateAllSegments();
1,753✔
962
                    }
963
                }
964
                for (let scopeName of scopeNames) {
1,377✔
965
                    let scope = this.scopes[scopeName];
3,104✔
966
                    const scopeValidated = scope.validate({
3,104✔
967
                        filesToBeValidatedInScopeContext: filesToBeValidatedInScopeContext,
968
                        changedSymbols: changedSymbols,
969
                        changedFiles: changedFiles,
970
                        initialValidation: this.isFirstValidation
971
                    });
972
                    if (scopeValidated) {
3,104✔
973
                        scopesValidated++;
1,677✔
974
                    }
975
                    linkTime += scope.validationMetrics.linkTime;
3,104✔
976
                    validationTime += scope.validationMetrics.validationTime;
3,104✔
977
                }
978
            });
979
            metrics.scopesValidated = scopesValidated;
1,377✔
980
            validationStopwatch.totalMilliseconds = linkTime;
1,377✔
981
            metrics.totalLinkTime = validationStopwatch.getDurationText();
1,377✔
982

983
            validationStopwatch.totalMilliseconds = validationTime;
1,377✔
984
            metrics.totalScopeValidationTime = validationStopwatch.getDurationText();
1,377✔
985

986
            metrics.componentValidationTime = validationStopwatch.getDurationTextFor(() => {
1,377✔
987
                this.detectDuplicateComponentNames();
1,377✔
988
            }).durationText;
989

990
            this.logValidationMetrics(metrics);
1,377✔
991

992
            this.isFirstValidation = false;
1,377✔
993

994
            this.plugins.emit('afterProgramValidate', programValidateEvent);
1,377✔
995
        });
996
    }
997

998
    // eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style
999
    private logValidationMetrics(metrics: { [key: string]: number | string }) {
1000
        let logs = [] as string[];
1,377✔
1001
        for (const key in metrics) {
1,377✔
1002
            logs.push(`${key}=${chalk.yellow(metrics[key].toString())}`);
11,016✔
1003
        }
1004
        this.logger.info(`Validation Metrics: ${logs.join(', ')}`);
1,377✔
1005
    }
1006

1007
    private getScopesForCrossScopeValidation() {
1008
        const scopesForCrossScopeValidation = [];
1,377✔
1009
        for (let scopeName of this.getSortedScopeNames()) {
1,377✔
1010
            let scope = this.scopes[scopeName];
3,104✔
1011
            if (this.globalScope !== scope && !scope.isValidated) {
3,104✔
1012
                scopesForCrossScopeValidation.push(scope);
1,698✔
1013
            }
1014
        }
1015
        return scopesForCrossScopeValidation;
1,377✔
1016
    }
1017

1018
    /**
1019
     * Flag all duplicate component names
1020
     */
1021
    private detectDuplicateComponentNames() {
1022
        const componentsByName = Object.keys(this.files).reduce<Record<string, XmlFile[]>>((map, filePath) => {
1,377✔
1023
            const file = this.files[filePath];
2,269✔
1024
            //if this is an XmlFile, and it has a valid `componentName` property
1025
            if (isXmlFile(file) && file.componentName?.text) {
2,269✔
1026
                let lowerName = file.componentName.text.toLowerCase();
437✔
1027
                if (!map[lowerName]) {
437✔
1028
                    map[lowerName] = [];
434✔
1029
                }
1030
                map[lowerName].push(file);
437✔
1031
            }
1032
            return map;
2,269✔
1033
        }, {});
1034

1035
        for (let name in componentsByName) {
1,377✔
1036
            const xmlFiles = componentsByName[name];
434✔
1037
            //add diagnostics for every duplicate component with this name
1038
            if (xmlFiles.length > 1) {
434✔
1039
                for (let xmlFile of xmlFiles) {
3✔
1040
                    const { componentName } = xmlFile;
6✔
1041
                    this.diagnostics.register({
6✔
1042
                        ...DiagnosticMessages.duplicateComponentName(componentName.text),
1043
                        location: xmlFile.componentName.location,
1044
                        relatedInformation: xmlFiles.filter(x => x !== xmlFile).map(x => {
12✔
1045
                            return {
6✔
1046
                                location: x.componentName.location,
1047
                                message: 'Also defined here'
1048
                            };
1049
                        })
1050
                    }, { tags: [ProgramValidatorDiagnosticsTag] });
1051
                }
1052
            }
1053
        }
1054
    }
1055

1056
    /**
1057
     * Get the files for a list of filePaths
1058
     * @param filePaths can be an array of srcPath or a destPath strings
1059
     * @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
1060
     */
1061
    public getFiles<T extends BscFile>(filePaths: string[], normalizePath = true) {
29✔
1062
        return filePaths
29✔
1063
            .map(filePath => this.getFile(filePath, normalizePath))
39✔
1064
            .filter(file => file !== undefined) as T[];
39✔
1065
    }
1066

1067
    /**
1068
     * Get the file at the given path
1069
     * @param filePath can be a srcPath or a destPath
1070
     * @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
1071
     */
1072
    public getFile<T extends BscFile>(filePath: string, normalizePath = true) {
15,162✔
1073
        if (typeof filePath !== 'string') {
19,158✔
1074
            return undefined;
3,407✔
1075
            //is the path absolute (or the `virtual:` prefix)
1076
        } else if (/^(?:(?:virtual:[\/\\])|(?:\w:)|(?:[\/\\]))/gmi.exec(filePath)) {
15,751✔
1077
            return this.files[
4,618✔
1078
                (normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase()
4,618!
1079
            ] as T;
1080
        } else if (util.isUriLike(filePath)) {
11,133✔
1081
            const path = URI.parse(filePath).fsPath;
1,344✔
1082
            return this.files[
1,344✔
1083
                (normalizePath ? util.standardizePath(path) : path).toLowerCase()
1,344!
1084
            ] as T;
1085
        } else {
1086
            return this.destMap.get(
9,789✔
1087
                (normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase()
9,789✔
1088
            ) as T;
1089
        }
1090
    }
1091

1092
    private sortedScopeNames: string[] = undefined;
1,841✔
1093

1094
    /**
1095
     * Gets a sorted list of all scopeNames, always beginning with "global", "source", then any others in alphabetical order
1096
     */
1097
    private getSortedScopeNames() {
1098
        if (!this.sortedScopeNames) {
7,510✔
1099
            this.sortedScopeNames = Object.keys(this.scopes).sort((a, b) => {
1,332✔
1100
                if (a === 'global') {
1,862!
UNCOV
1101
                    return -1;
×
1102
                } else if (b === 'global') {
1,862✔
1103
                    return 1;
1,312✔
1104
                }
1105
                if (a === 'source') {
550✔
1106
                    return -1;
26✔
1107
                } else if (b === 'source') {
524✔
1108
                    return 1;
108✔
1109
                }
1110
                if (a < b) {
416✔
1111
                    return -1;
166✔
1112
                } else if (b < a) {
250!
1113
                    return 1;
250✔
1114
                }
UNCOV
1115
                return 0;
×
1116
            });
1117
        }
1118
        return this.sortedScopeNames;
7,510✔
1119
    }
1120

1121
    /**
1122
     * Get a list of all scopes the file is loaded into
1123
     * @param file the file
1124
     */
1125
    public getScopesForFile(file: BscFile | string) {
1126
        const resolvedFile = typeof file === 'string' ? this.getFile(file) : file;
717✔
1127

1128
        let result = [] as Scope[];
717✔
1129
        if (resolvedFile) {
717✔
1130
            const scopeKeys = this.getSortedScopeNames();
716✔
1131
            for (let key of scopeKeys) {
716✔
1132
                let scope = this.scopes[key];
1,495✔
1133

1134
                if (scope.hasFile(resolvedFile)) {
1,495✔
1135
                    result.push(scope);
730✔
1136
                }
1137
            }
1138
        }
1139
        return result;
717✔
1140
    }
1141

1142
    /**
1143
     * Get the first found scope for a file.
1144
     */
1145
    public getFirstScopeForFile(file: BscFile): Scope | undefined {
1146
        const scopeKeys = this.getSortedScopeNames();
4,040✔
1147
        for (let key of scopeKeys) {
4,040✔
1148
            let scope = this.scopes[key];
18,423✔
1149

1150
            if (scope.hasFile(file)) {
18,423✔
1151
                return scope;
2,929✔
1152
            }
1153
        }
1154
    }
1155

1156
    public getStatementsByName(name: string, originFile: BrsFile, namespaceName?: string): FileLink<Statement>[] {
1157
        let results = new Map<Statement, FileLink<Statement>>();
39✔
1158
        const filesSearched = new Set<BrsFile>();
39✔
1159
        let lowerNamespaceName = namespaceName?.toLowerCase();
39✔
1160
        let lowerName = name?.toLowerCase();
39!
1161

1162
        function addToResults(statement: FunctionStatement | MethodStatement, file: BrsFile) {
1163
            let parentNamespaceName = statement.findAncestor<NamespaceStatement>(isNamespaceStatement)?.getName(originFile.parseMode)?.toLowerCase();
98✔
1164
            if (statement.tokens.name.text.toLowerCase() === lowerName && (!lowerNamespaceName || parentNamespaceName === lowerNamespaceName)) {
98✔
1165
                if (!results.has(statement)) {
36!
1166
                    results.set(statement, { item: statement, file: file as BrsFile });
36✔
1167
                }
1168
            }
1169
        }
1170

1171
        //look through all files in scope for matches
1172
        for (const scope of this.getScopesForFile(originFile)) {
39✔
1173
            for (const file of scope.getAllFiles()) {
39✔
1174
                //skip non-brs files, or files we've already processed
1175
                if (!isBrsFile(file) || filesSearched.has(file)) {
45✔
1176
                    continue;
3✔
1177
                }
1178
                filesSearched.add(file);
42✔
1179

1180
                file.ast.walk(createVisitor({
42✔
1181
                    FunctionStatement: (statement: FunctionStatement) => {
1182
                        addToResults(statement, file);
95✔
1183
                    },
1184
                    MethodStatement: (statement: MethodStatement) => {
1185
                        addToResults(statement, file);
3✔
1186
                    }
1187
                }), {
1188
                    walkMode: WalkMode.visitStatements
1189
                });
1190
            }
1191
        }
1192
        return [...results.values()];
39✔
1193
    }
1194

1195
    public getStatementsForXmlFile(scope: XmlScope, filterName?: string): FileLink<FunctionStatement>[] {
1196
        let results = new Map<Statement, FileLink<FunctionStatement>>();
10✔
1197
        const filesSearched = new Set<BrsFile>();
10✔
1198

1199
        //get all function names for the xml file and parents
1200
        let funcNames = new Set<string>();
10✔
1201
        let currentScope = scope;
10✔
1202
        while (isXmlScope(currentScope)) {
10✔
1203
            for (let name of currentScope.xmlFile.ast.componentElement.interfaceElement?.functions.map((f) => f.name) ?? []) {
16✔
1204
                if (!filterName || name === filterName) {
16!
1205
                    funcNames.add(name);
16✔
1206
                }
1207
            }
1208
            currentScope = currentScope.getParentScope() as XmlScope;
12✔
1209
        }
1210

1211
        //look through all files in scope for matches
1212
        for (const file of scope.getOwnFiles()) {
10✔
1213
            //skip non-brs files, or files we've already processed
1214
            if (!isBrsFile(file) || filesSearched.has(file)) {
20✔
1215
                continue;
10✔
1216
            }
1217
            filesSearched.add(file);
10✔
1218

1219
            file.ast.walk(createVisitor({
10✔
1220
                FunctionStatement: (statement: FunctionStatement) => {
1221
                    if (funcNames.has(statement.tokens.name.text)) {
15!
1222
                        if (!results.has(statement)) {
15!
1223
                            results.set(statement, { item: statement, file: file });
15✔
1224
                        }
1225
                    }
1226
                }
1227
            }), {
1228
                walkMode: WalkMode.visitStatements
1229
            });
1230
        }
1231
        return [...results.values()];
10✔
1232
    }
1233

1234
    /**
1235
     * Find all available completion items at the given position
1236
     * @param filePath can be a srcPath or a destPath
1237
     * @param position the position (line & column) where completions should be found
1238
     */
1239
    public getCompletions(filePath: string, position: Position) {
1240
        let file = this.getFile(filePath);
116✔
1241
        if (!file) {
116!
UNCOV
1242
            return [];
×
1243
        }
1244

1245
        //find the scopes for this file
1246
        let scopes = this.getScopesForFile(file);
116✔
1247

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

1251
        const event: ProvideCompletionsEvent = {
116✔
1252
            program: this,
1253
            file: file,
1254
            scopes: scopes,
1255
            position: position,
1256
            completions: []
1257
        };
1258

1259
        this.plugins.emit('beforeProvideCompletions', event);
116✔
1260

1261
        this.plugins.emit('provideCompletions', event);
116✔
1262

1263
        this.plugins.emit('afterProvideCompletions', event);
116✔
1264

1265
        return event.completions;
116✔
1266
    }
1267

1268
    /**
1269
     * Goes through each file and builds a list of workspace symbols for the program. Used by LanguageServer's onWorkspaceSymbol functionality
1270
     */
1271
    public getWorkspaceSymbols() {
1272
        const event: ProvideWorkspaceSymbolsEvent = {
22✔
1273
            program: this,
1274
            workspaceSymbols: []
1275
        };
1276
        this.plugins.emit('beforeProvideWorkspaceSymbols', event);
22✔
1277
        this.plugins.emit('provideWorkspaceSymbols', event);
22✔
1278
        this.plugins.emit('afterProvideWorkspaceSymbols', event);
22✔
1279
        return event.workspaceSymbols;
22✔
1280
    }
1281

1282
    /**
1283
     * Given a position in a file, if the position is sitting on some type of identifier,
1284
     * go to the definition of that identifier (where this thing was first defined)
1285
     */
1286
    public getDefinition(srcPath: string, position: Position): Location[] {
1287
        let file = this.getFile(srcPath);
18✔
1288
        if (!file) {
18!
UNCOV
1289
            return [];
×
1290
        }
1291

1292
        const event: ProvideDefinitionEvent = {
18✔
1293
            program: this,
1294
            file: file,
1295
            position: position,
1296
            definitions: []
1297
        };
1298

1299
        this.plugins.emit('beforeProvideDefinition', event);
18✔
1300
        this.plugins.emit('provideDefinition', event);
18✔
1301
        this.plugins.emit('afterProvideDefinition', event);
18✔
1302
        return event.definitions;
18✔
1303
    }
1304

1305
    /**
1306
     * Get hover information for a file and position
1307
     */
1308
    public getHover(srcPath: string, position: Position): Hover[] {
1309
        let file = this.getFile(srcPath);
68✔
1310
        let result: Hover[];
1311
        if (file) {
68!
1312
            const event = {
68✔
1313
                program: this,
1314
                file: file,
1315
                position: position,
1316
                scopes: this.getScopesForFile(file),
1317
                hovers: []
1318
            } as ProvideHoverEvent;
1319
            this.plugins.emit('beforeProvideHover', event);
68✔
1320
            this.plugins.emit('provideHover', event);
68✔
1321
            this.plugins.emit('afterProvideHover', event);
68✔
1322
            result = event.hovers;
68✔
1323
        }
1324

1325
        return result ?? [];
68!
1326
    }
1327

1328
    /**
1329
     * Get full list of document symbols for a file
1330
     * @param srcPath path to the file
1331
     */
1332
    public getDocumentSymbols(srcPath: string): DocumentSymbol[] | undefined {
1333
        let file = this.getFile(srcPath);
18✔
1334
        if (file) {
18!
1335
            const event: ProvideDocumentSymbolsEvent = {
18✔
1336
                program: this,
1337
                file: file,
1338
                documentSymbols: []
1339
            };
1340
            this.plugins.emit('beforeProvideDocumentSymbols', event);
18✔
1341
            this.plugins.emit('provideDocumentSymbols', event);
18✔
1342
            this.plugins.emit('afterProvideDocumentSymbols', event);
18✔
1343
            return event.documentSymbols;
18✔
1344
        } else {
UNCOV
1345
            return undefined;
×
1346
        }
1347
    }
1348

1349
    /**
1350
     * Compute code actions for the given file and range
1351
     */
1352
    public getCodeActions(srcPath: string, range: Range) {
1353
        const codeActions = [] as CodeAction[];
13✔
1354
        const file = this.getFile(srcPath);
13✔
1355
        if (file) {
13✔
1356
            const fileUri = util.pathToUri(file?.srcPath);
12!
1357
            const diagnostics = this
12✔
1358
                //get all current diagnostics (filtered by diagnostic filters)
1359
                .getDiagnostics()
1360
                //only keep diagnostics related to this file
1361
                .filter(x => x.location?.uri === fileUri)
22✔
1362
                //only keep diagnostics that touch this range
1363
                .filter(x => util.rangesIntersectOrTouch(x.location.range, range));
12✔
1364

1365
            const scopes = this.getScopesForFile(file);
12✔
1366

1367
            this.plugins.emit('onGetCodeActions', {
12✔
1368
                program: this,
1369
                file: file,
1370
                range: range,
1371
                diagnostics: diagnostics,
1372
                scopes: scopes,
1373
                codeActions: codeActions
1374
            });
1375
        }
1376
        return codeActions;
13✔
1377
    }
1378

1379
    /**
1380
     * Get semantic tokens for the specified file
1381
     */
1382
    public getSemanticTokens(srcPath: string): SemanticToken[] | undefined {
1383
        const file = this.getFile(srcPath);
24✔
1384
        if (file) {
24!
1385
            const result = [] as SemanticToken[];
24✔
1386
            this.plugins.emit('onGetSemanticTokens', {
24✔
1387
                program: this,
1388
                file: file,
1389
                scopes: this.getScopesForFile(file),
1390
                semanticTokens: result
1391
            });
1392
            return result;
24✔
1393
        }
1394
    }
1395

1396
    public getSignatureHelp(filepath: string, position: Position): SignatureInfoObj[] {
1397
        let file: BrsFile = this.getFile(filepath);
185✔
1398
        if (!file || !isBrsFile(file)) {
185✔
1399
            return [];
3✔
1400
        }
1401
        let callExpressionInfo = new CallExpressionInfo(file, position);
182✔
1402
        let signatureHelpUtil = new SignatureHelpUtil();
182✔
1403
        return signatureHelpUtil.getSignatureHelpItems(callExpressionInfo);
182✔
1404
    }
1405

1406
    public getReferences(srcPath: string, position: Position): Location[] {
1407
        //find the file
1408
        let file = this.getFile(srcPath);
4✔
1409

1410
        const event: ProvideReferencesEvent = {
4✔
1411
            program: this,
1412
            file: file,
1413
            position: position,
1414
            references: []
1415
        };
1416

1417
        this.plugins.emit('beforeProvideReferences', event);
4✔
1418
        this.plugins.emit('provideReferences', event);
4✔
1419
        this.plugins.emit('afterProvideReferences', event);
4✔
1420

1421
        return event.references;
4✔
1422
    }
1423

1424
    /**
1425
     * Transpile a single file and get the result as a string.
1426
     * This does not write anything to the file system.
1427
     *
1428
     * This should only be called by `LanguageServer`.
1429
     * Internal usage should call `_getTranspiledFileContents` instead.
1430
     * @param filePath can be a srcPath or a destPath
1431
     */
1432
    public async getTranspiledFileContents(filePath: string): Promise<FileTranspileResult> {
1433
        const file = this.getFile(filePath);
318✔
1434

1435
        return this.getTranspiledFileContentsPipeline.run(async () => {
318✔
1436

1437
            const result = {
318✔
1438
                destPath: file.destPath,
1439
                pkgPath: file.pkgPath,
1440
                srcPath: file.srcPath
1441
            } as FileTranspileResult;
1442

1443
            const expectedPkgPath = file.pkgPath.toLowerCase();
318✔
1444
            const expectedMapPath = `${expectedPkgPath}.map`;
318✔
1445
            const expectedTypedefPkgPath = expectedPkgPath.replace(/\.brs$/i, '.d.bs');
318✔
1446

1447
            //add a temporary plugin to tap into the file writing process
1448
            const plugin = this.plugins.addFirst({
318✔
1449
                name: 'getTranspiledFileContents',
1450
                beforeWriteFile: (event) => {
1451
                    const pkgPath = event.file.pkgPath.toLowerCase();
992✔
1452
                    switch (pkgPath) {
992✔
1453
                        //this is the actual transpiled file
1454
                        case expectedPkgPath:
992✔
1455
                            result.code = event.file.data.toString();
318✔
1456
                            break;
318✔
1457
                        //this is the sourcemap
1458
                        case expectedMapPath:
1459
                            result.map = event.file.data.toString();
170✔
1460
                            break;
170✔
1461
                        //this is the typedef
1462
                        case expectedTypedefPkgPath:
1463
                            result.typedef = event.file.data.toString();
8✔
1464
                            break;
8✔
1465
                        default:
1466
                        //no idea what this file is. just ignore it
1467
                    }
1468
                    //mark every file as processed so it they don't get written to the output directory
1469
                    event.processedFiles.add(event.file);
992✔
1470
                }
1471
            });
1472

1473
            try {
318✔
1474
                //now that the plugin has been registered, run the build with just this file
1475
                await this.build({
318✔
1476
                    files: [file]
1477
                });
1478
            } finally {
1479
                this.plugins.remove(plugin);
318✔
1480
            }
1481
            return result;
318✔
1482
        });
1483
    }
1484
    private getTranspiledFileContentsPipeline = new ActionPipeline();
1,841✔
1485

1486
    /**
1487
     * Get the absolute output path for a file
1488
     */
1489
    private getOutputPath(file: { pkgPath?: string }, stagingDir = this.getStagingDir()) {
×
1490
        return s`${stagingDir}/${file.pkgPath}`;
1,831✔
1491
    }
1492

1493
    private getStagingDir(stagingDir?: string) {
1494
        let result = stagingDir ?? this.options.stagingDir ?? this.options.stagingDir;
717✔
1495
        if (!result) {
717✔
1496
            result = rokuDeploy.getOptions(this.options as any).stagingDir;
531✔
1497
        }
1498
        result = s`${path.resolve(this.options.cwd ?? process.cwd(), result ?? '/')}`;
717!
1499
        return result;
717✔
1500
    }
1501

1502
    /**
1503
     * Prepare the program for building
1504
     * @param files the list of files that should be prepared
1505
     */
1506
    private async prepare(files: BscFile[]) {
1507
        const programEvent: PrepareProgramEvent = {
359✔
1508
            program: this,
1509
            editor: this.editor,
1510
            files: files
1511
        };
1512

1513
        //assign an editor to every file
1514
        for (const file of programEvent.files) {
359✔
1515
            //if the file doesn't have an editor yet, assign one now
1516
            if (!file.editor) {
728✔
1517
                file.editor = new Editor();
681✔
1518
            }
1519
        }
1520

1521
        //sort the entries to make transpiling more deterministic
1522
        programEvent.files.sort((a, b) => {
359✔
1523
            if (a.pkgPath < b.pkgPath) {
384✔
1524
                return -1;
324✔
1525
            } else if (a.pkgPath > b.pkgPath) {
60!
1526
                return 1;
60✔
1527
            } else {
UNCOV
1528
                return 1;
×
1529
            }
1530
        });
1531

1532
        await this.plugins.emitAsync('beforePrepareProgram', programEvent);
359✔
1533
        await this.plugins.emitAsync('prepareProgram', programEvent);
359✔
1534

1535
        const stagingDir = this.getStagingDir();
359✔
1536

1537
        const entries: TranspileObj[] = [];
359✔
1538

1539
        for (const file of files) {
359✔
1540
            const scope = this.getFirstScopeForFile(file);
728✔
1541
            //link the symbol table for all the files in this scope
1542
            scope?.linkSymbolTable();
728✔
1543

1544
            //if the file doesn't have an editor yet, assign one now
1545
            if (!file.editor) {
728!
UNCOV
1546
                file.editor = new Editor();
×
1547
            }
1548
            const event = {
728✔
1549
                program: this,
1550
                file: file,
1551
                editor: file.editor,
1552
                scope: scope,
1553
                outputPath: this.getOutputPath(file, stagingDir)
1554
            } as PrepareFileEvent & { outputPath: string };
1555

1556
            await this.plugins.emitAsync('beforePrepareFile', event);
728✔
1557
            await this.plugins.emitAsync('prepareFile', event);
728✔
1558
            await this.plugins.emitAsync('afterPrepareFile', event);
728✔
1559

1560
            //TODO remove this in v1
1561
            entries.push(event);
728✔
1562

1563
            //unlink the symbolTable so the next loop iteration can link theirs
1564
            scope?.unlinkSymbolTable();
728✔
1565
        }
1566

1567
        await this.plugins.emitAsync('afterPrepareProgram', programEvent);
359✔
1568
        return files;
359✔
1569
    }
1570

1571
    /**
1572
     * Generate the contents of every file
1573
     */
1574
    private async serialize(files: BscFile[]) {
1575

1576
        const allFiles = new Map<BscFile, SerializedFile[]>();
358✔
1577

1578
        //exclude prunable files if that option is enabled
1579
        if (this.options.pruneEmptyCodeFiles === true) {
358✔
1580
            files = files.filter(x => x.canBePruned !== true);
9✔
1581
        }
1582

1583
        const serializeProgramEvent = await this.plugins.emitAsync('beforeSerializeProgram', {
358✔
1584
            program: this,
1585
            files: files,
1586
            result: allFiles
1587
        });
1588
        await this.plugins.emitAsync('onSerializeProgram', serializeProgramEvent);
358✔
1589

1590
        // serialize each file
1591
        for (const file of files) {
358✔
1592
            let scope = this.getFirstScopeForFile(file);
725✔
1593

1594
            //if the file doesn't have a scope, create a temporary scope for the file so it can depend on scope-level items
1595
            if (!scope) {
725✔
1596
                scope = new Scope(`temporary-for-${file.pkgPath}`, this);
369✔
1597
                scope.getAllFiles = () => [file];
3,308✔
1598
                scope.getOwnFiles = scope.getAllFiles;
369✔
1599
            }
1600

1601
            //link the symbol table for all the files in this scope
1602
            scope?.linkSymbolTable();
725!
1603
            const event: SerializeFileEvent = {
725✔
1604
                program: this,
1605
                file: file,
1606
                scope: scope,
1607
                result: allFiles
1608
            };
1609
            await this.plugins.emitAsync('beforeSerializeFile', event);
725✔
1610
            await this.plugins.emitAsync('serializeFile', event);
725✔
1611
            await this.plugins.emitAsync('afterSerializeFile', event);
725✔
1612
            //unlink the symbolTable so the next loop iteration can link theirs
1613
            scope?.unlinkSymbolTable();
725!
1614
        }
1615

1616
        this.plugins.emit('afterSerializeProgram', serializeProgramEvent);
358✔
1617

1618
        return allFiles;
358✔
1619
    }
1620

1621
    /**
1622
     * Write the entire project to disk
1623
     */
1624
    private async write(stagingDir: string, files: Map<BscFile, SerializedFile[]>) {
1625
        const programEvent = await this.plugins.emitAsync('beforeWriteProgram', {
358✔
1626
            program: this,
1627
            files: files,
1628
            stagingDir: stagingDir
1629
        });
1630
        //empty the staging directory
1631
        await fsExtra.emptyDir(stagingDir);
358✔
1632

1633
        const serializedFiles = [...files]
358✔
1634
            .map(([, serializedFiles]) => serializedFiles)
725✔
1635
            .flat();
1636

1637
        //write all the files to disk (asynchronously)
1638
        await Promise.all(
358✔
1639
            serializedFiles.map(async (file) => {
1640
                const event = await this.plugins.emitAsync('beforeWriteFile', {
1,103✔
1641
                    program: this,
1642
                    file: file,
1643
                    outputPath: this.getOutputPath(file, stagingDir),
1644
                    processedFiles: new Set<SerializedFile>()
1645
                });
1646

1647
                await this.plugins.emitAsync('writeFile', event);
1,103✔
1648

1649
                await this.plugins.emitAsync('afterWriteFile', event);
1,103✔
1650
            })
1651
        );
1652

1653
        await this.plugins.emitAsync('afterWriteProgram', programEvent);
358✔
1654
    }
1655

1656
    private buildPipeline = new ActionPipeline();
1,841✔
1657

1658
    /**
1659
     * Build the project. This transpiles/transforms/copies all files and moves them to the staging directory
1660
     * @param options the list of options used to build the program
1661
     */
1662
    public async build(options?: ProgramBuildOptions) {
1663
        //run a single build at a time
1664
        await this.buildPipeline.run(async () => {
358✔
1665
            const stagingDir = this.getStagingDir(options?.stagingDir);
358✔
1666

1667
            const event = await this.plugins.emitAsync('beforeBuildProgram', {
358✔
1668
                program: this,
1669
                editor: this.editor,
1670
                files: options?.files ?? Object.values(this.files)
2,148✔
1671
            });
1672

1673
            //prepare the program (and files) for building
1674
            event.files = await this.prepare(event.files);
358✔
1675

1676
            //stage the entire program
1677
            const serializedFilesByFile = await this.serialize(event.files);
358✔
1678

1679
            await this.write(stagingDir, serializedFilesByFile);
358✔
1680

1681
            await this.plugins.emitAsync('afterBuildProgram', event);
358✔
1682

1683
            //undo all edits for the program
1684
            this.editor.undoAll();
358✔
1685
            //undo all edits for each file
1686
            for (const file of event.files) {
358✔
1687
                file.editor.undoAll();
726✔
1688
            }
1689
        });
1690
    }
1691

1692
    /**
1693
     * Find a list of files in the program that have a function with the given name (case INsensitive)
1694
     */
1695
    public findFilesForFunction(functionName: string) {
1696
        const files = [] as BscFile[];
7✔
1697
        const lowerFunctionName = functionName.toLowerCase();
7✔
1698
        //find every file with this function defined
1699
        for (const file of Object.values(this.files)) {
7✔
1700
            if (isBrsFile(file)) {
25✔
1701
                //TODO handle namespace-relative function calls
1702
                //if the file has a function with this name
1703
                // eslint-disable-next-line @typescript-eslint/dot-notation
1704
                if (file['_cachedLookups'].functionStatementMap.get(lowerFunctionName)) {
17✔
1705
                    files.push(file);
2✔
1706
                }
1707
            }
1708
        }
1709
        return files;
7✔
1710
    }
1711

1712
    /**
1713
     * Find a list of files in the program that have a class with the given name (case INsensitive)
1714
     */
1715
    public findFilesForClass(className: string) {
1716
        const files = [] as BscFile[];
7✔
1717
        const lowerClassName = className.toLowerCase();
7✔
1718
        //find every file with this class defined
1719
        for (const file of Object.values(this.files)) {
7✔
1720
            if (isBrsFile(file)) {
25✔
1721
                //TODO handle namespace-relative classes
1722
                //if the file has a function with this name
1723

1724
                // eslint-disable-next-line @typescript-eslint/dot-notation
1725
                if (file['_cachedLookups'].classStatementMap.get(lowerClassName) !== undefined) {
17✔
1726
                    files.push(file);
1✔
1727
                }
1728
            }
1729
        }
1730
        return files;
7✔
1731
    }
1732

1733
    public findFilesForNamespace(name: string) {
1734
        const files = [] as BscFile[];
7✔
1735
        const lowerName = name.toLowerCase();
7✔
1736
        //find every file with this class defined
1737
        for (const file of Object.values(this.files)) {
7✔
1738
            if (isBrsFile(file)) {
25✔
1739

1740
                // eslint-disable-next-line @typescript-eslint/dot-notation
1741
                if (file['_cachedLookups'].namespaceStatements.find((x) => {
17✔
1742
                    const namespaceName = x.name.toLowerCase();
7✔
1743
                    return (
7✔
1744
                        //the namespace name matches exactly
1745
                        namespaceName === lowerName ||
9✔
1746
                        //the full namespace starts with the name (honoring the part boundary)
1747
                        namespaceName.startsWith(lowerName + '.')
1748
                    );
1749
                })) {
1750
                    files.push(file);
6✔
1751
                }
1752
            }
1753
        }
1754

1755
        return files;
7✔
1756
    }
1757

1758
    public findFilesForEnum(name: string) {
1759
        const files = [] as BscFile[];
8✔
1760
        const lowerName = name.toLowerCase();
8✔
1761
        //find every file with this enum defined
1762
        for (const file of Object.values(this.files)) {
8✔
1763
            if (isBrsFile(file)) {
26✔
1764
                // eslint-disable-next-line @typescript-eslint/dot-notation
1765
                if (file['_cachedLookups'].enumStatementMap.get(lowerName)) {
18✔
1766
                    files.push(file);
1✔
1767
                }
1768
            }
1769
        }
1770
        return files;
8✔
1771
    }
1772

1773
    private _manifest: Map<string, string>;
1774

1775
    /**
1776
     * Modify a parsed manifest map by reading `bs_const` and injecting values from `options.manifest.bs_const`
1777
     * @param parsedManifest The manifest map to read from and modify
1778
     */
1779
    private buildBsConstsIntoParsedManifest(parsedManifest: Map<string, string>) {
1780
        // Lift the bs_consts defined in the manifest
1781
        let bsConsts = getBsConst(parsedManifest, false);
15✔
1782

1783
        // Override or delete any bs_consts defined in the bs config
1784
        for (const key in this.options?.manifest?.bs_const) {
15!
1785
            const value = this.options.manifest.bs_const[key];
3✔
1786
            if (value === null) {
3✔
1787
                bsConsts.delete(key);
1✔
1788
            } else {
1789
                bsConsts.set(key, value);
2✔
1790
            }
1791
        }
1792

1793
        // convert the new list of bs consts back into a string for the rest of the down stream systems to use
1794
        let constString = '';
15✔
1795
        for (const [key, value] of bsConsts) {
15✔
1796
            constString += `${constString !== '' ? ';' : ''}${key}=${value.toString()}`;
8✔
1797
        }
1798

1799
        // Set the updated bs_const value
1800
        parsedManifest.set('bs_const', constString);
15✔
1801
    }
1802

1803
    /**
1804
     * Try to find and load the manifest into memory
1805
     * @param manifestFileObj A pointer to a potential manifest file object found during loading
1806
     * @param replaceIfAlreadyLoaded should we overwrite the internal `_manifest` if it already exists
1807
     */
1808
    public loadManifest(manifestFileObj?: FileObj, replaceIfAlreadyLoaded = true) {
1,511✔
1809
        //if we already have a manifest instance, and should not replace...then don't replace
1810
        if (!replaceIfAlreadyLoaded && this._manifest) {
1,517!
UNCOV
1811
            return;
×
1812
        }
1813
        let manifestPath = manifestFileObj
1,517✔
1814
            ? manifestFileObj.src
1,517✔
1815
            : path.join(this.options.rootDir, 'manifest');
1816

1817
        try {
1,517✔
1818
            // we only load this manifest once, so do it sync to improve speed downstream
1819
            const contents = fsExtra.readFileSync(manifestPath, 'utf-8');
1,517✔
1820
            const parsedManifest = parseManifest(contents);
15✔
1821
            this.buildBsConstsIntoParsedManifest(parsedManifest);
15✔
1822
            this._manifest = parsedManifest;
15✔
1823
        } catch (e) {
1824
            this._manifest = new Map();
1,502✔
1825
        }
1826
    }
1827

1828
    /**
1829
     * Get a map of the manifest information
1830
     */
1831
    public getManifest() {
1832
        if (!this._manifest) {
2,336✔
1833
            this.loadManifest();
1,510✔
1834
        }
1835
        return this._manifest;
2,336✔
1836
    }
1837

1838
    public dispose() {
1839
        this.plugins.emit('beforeProgramDispose', { program: this });
1,679✔
1840

1841
        for (let filePath in this.files) {
1,679✔
1842
            this.files[filePath]?.dispose?.();
2,044!
1843
        }
1844
        for (let name in this.scopes) {
1,679✔
1845
            this.scopes[name]?.dispose?.();
3,517!
1846
        }
1847
        this.globalScope?.dispose?.();
1,679!
1848
        this.dependencyGraph?.dispose?.();
1,679!
1849
    }
1850
}
1851

1852
export interface FileTranspileResult {
1853
    srcPath: string;
1854
    destPath: string;
1855
    pkgPath: string;
1856
    code: string;
1857
    map: string;
1858
    typedef: string;
1859
}
1860

1861

1862
class ProvideFileEventInternal<TFile extends BscFile = BscFile> implements ProvideFileEvent<TFile> {
1863
    constructor(
1864
        public program: Program,
2,375✔
1865
        public srcPath: string,
2,375✔
1866
        public destPath: string,
2,375✔
1867
        public data: LazyFileData,
2,375✔
1868
        public fileFactory: FileFactory
2,375✔
1869
    ) {
1870
        this.srcExtension = path.extname(srcPath)?.toLowerCase();
2,375!
1871
    }
1872

1873
    public srcExtension: string;
1874

1875
    public files: TFile[] = [];
2,375✔
1876
}
1877

1878
export interface ProgramBuildOptions {
1879
    /**
1880
     * The directory where the final built files should be placed. This directory will be cleared before running
1881
     */
1882
    stagingDir?: string;
1883
    /**
1884
     * An array of files to build. If omitted, the entire list of files from the program will be used instead.
1885
     * Typically you will want to leave this blank
1886
     */
1887
    files?: BscFile[];
1888
}
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