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

rokucommunity / brighterscript / #13615

14 Jan 2025 06:19PM UTC coverage: 86.812%. Remained the same
#13615

push

web-flow
Merge 05a55830c into 7fb92fff2

12436 of 15140 branches covered (82.14%)

Branch coverage included in aggregate %.

409 of 435 new or added lines in 36 files covered. (94.02%)

264 existing lines in 24 files now uncovered.

13334 of 14545 relevant lines covered (91.67%)

34016.38 hits per line

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

93.29
/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, ScopeValidationOptions, 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, isReferenceType } 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 { ReferenceType } from './types';
1✔
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,865✔
80
        this.logger = logger ?? createLogger(options);
1,865✔
81
        this.plugins = plugins || new PluginInterface([], { logger: this.logger });
1,865✔
82
        this.diagnostics = diagnosticsManager || new DiagnosticManager();
1,865✔
83

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

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

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

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

97
        this.fileFactory = new FileFactory(this);
1,865✔
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,865✔
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,865✔
116
        this.globalScope.attachDependencyGraph(this.dependencyGraph);
1,865✔
117
        this.scopes.global = this.globalScope;
1,865✔
118

119
        this.populateGlobalSymbolTable();
1,865✔
120
        this.globalScope.symbolTable.addSibling(this.componentsTable);
1,865✔
121

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

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

131

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

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

168
        const builtInSymbolData: ExtraSymbolData = { isBuiltIn: true };
1,865✔
169

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

181
        BuiltInInterfaceAdder.getLookupTable = () => this.globalScope.symbolTable;
832,245✔
182

183
        for (const callable of globalCallables) {
1,865✔
184
            this.globalScope.symbolTable.addSymbol(callable.name, { ...builtInSymbolData, description: callable.shortDescription }, callable.type, SymbolTypeFlag.runtime);
145,470✔
185
        }
186

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

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

204
        for (const nodeData of Object.values(nodes) as SGNodeData[]) {
1,865✔
205
            this.recursivelyAddNodeToSymbolTable(nodeData);
179,040✔
206
        }
207

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

215
    }
216

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

225
    public diagnostics: DiagnosticManager;
226

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

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

238
    private fileSymbolInformation = new Map<string, { provides: ProvidedSymbolInfo; requires: UnresolvedSymbol[] }>();
1,865✔
239

240
    private currentScopeValidationOptions: ScopeValidationOptions;
241

242
    /**
243
     *  Map of typetime symbols which depend upon the key symbol
244
     */
245
    private symbolDependencies = new Map<string, Set<string>>();
1,865✔
246

247

248
    /**
249
     * Symbol Table for storing custom component types
250
     * This is a sibling to the global table (as Components can be used/referenced anywhere)
251
     * Keeping custom components out of the global table and in a specific symbol table
252
     * compartmentalizes their use
253
     */
254
    private componentsTable = new SymbolTable('Custom Components');
1,865✔
255

256
    public addFileSymbolInfo(file: BrsFile) {
257
        this.fileSymbolInformation.set(file.pkgPath, {
1,750✔
258
            provides: file.providedSymbols,
259
            requires: file.requiredSymbols
260
        });
261
    }
262

263
    public getFileSymbolInfo(file: BrsFile) {
264
        return this.fileSymbolInformation.get(file.pkgPath);
1,754✔
265
    }
266

267
    /**
268
     * The path to bslib.brs (the BrightScript runtime for certain BrighterScript features)
269
     */
270
    public get bslibPkgPath() {
271
        //if there's an aliased (preferred) version of bslib from roku_modules loaded into the program, use that
272
        if (this.getFile(bslibAliasedRokuModulesPkgPath)) {
2,466✔
273
            return bslibAliasedRokuModulesPkgPath;
11✔
274

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

279
            //default to the embedded version
280
        } else {
281
            return `${this.options.bslibDestinationDir}${path.sep}bslib.brs`;
2,431✔
282
        }
283
    }
284

285
    public get bslibPrefix() {
286
        if (this.bslibPkgPath === bslibNonAliasedRokuModulesPkgPath) {
1,797✔
287
            return 'rokucommunity_bslib';
18✔
288
        } else {
289
            return 'bslib';
1,779✔
290
        }
291
    }
292

293

294
    /**
295
     * A map of every file loaded into this program, indexed by its original file location
296
     */
297
    public files = {} as Record<string, BscFile>;
1,865✔
298
    /**
299
     * A map of every file loaded into this program, indexed by its destPath
300
     */
301
    private destMap = new Map<string, BscFile>();
1,865✔
302
    /**
303
     * Plugins can contribute multiple virtual files for a single physical file.
304
     * This collection links the virtual files back to the physical file that produced them.
305
     * The key is the standardized and lower-cased srcPath
306
     */
307
    private fileClusters = new Map<string, BscFile[]>();
1,865✔
308

309
    private scopes = {} as Record<string, Scope>;
1,865✔
310

311
    protected addScope(scope: Scope) {
312
        this.scopes[scope.name] = scope;
2,046✔
313
        delete this.sortedScopeNames;
2,046✔
314
    }
315

316
    protected removeScope(scope: Scope) {
317
        if (this.scopes[scope.name]) {
16!
318
            delete this.scopes[scope.name];
16✔
319
            delete this.sortedScopeNames;
16✔
320
        }
321
    }
322

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

331
    /**
332
     * Get the component with the specified name
333
     */
334
    public getComponent(componentName: string) {
335
        if (componentName) {
2,874✔
336
            //return the first compoment in the list with this name
337
            //(components are ordered in this list by destPath to ensure consistency)
338
            return this.components[componentName.toLowerCase()]?.[0];
2,860✔
339
        } else {
340
            return undefined;
14✔
341
        }
342
    }
343

344
    /**
345
     * Get the sorted names of custom components
346
     */
347
    public getSortedComponentNames() {
348
        const componentNames = Object.keys(this.components);
1,412✔
349
        componentNames.sort((a, b) => {
1,412✔
350
            if (a < b) {
715✔
351
                return -1;
287✔
352
            } else if (b < a) {
428!
353
                return 1;
428✔
354
            }
UNCOV
355
            return 0;
×
356
        });
357
        return componentNames;
1,412✔
358
    }
359

360
    /**
361
     * Keeps a set of all the components that need to have their types updated during the current validation cycle
362
     * Map <componentKey, componentName>
363
     */
364
    private componentSymbolsToUpdate = new Map<string, string>();
1,865✔
365

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

392
    /**
393
     * Remove the specified component from the components map
394
     */
395
    private unregisterComponent(xmlFile: XmlFile) {
396
        const key = this.getComponentKey(xmlFile);
16✔
397
        const arr = this.components[key] || [];
16!
398
        for (let i = 0; i < arr.length; i++) {
16✔
399
            if (arr[i].file === xmlFile) {
16!
400
                arr.splice(i, 1);
16✔
401
                break;
16✔
402
            }
403
        }
404

405
        this.syncComponentDependencyGraph(arr);
16✔
406
        this.addDeferredComponentTypeSymbolCreation(xmlFile);
16✔
407
    }
408

409
    /**
410
     * Adds a component described in an XML to the set of components that needs to be updated this validation cycle.
411
     * @param xmlFile XML file with <component> tag
412
     */
413
    private addDeferredComponentTypeSymbolCreation(xmlFile: XmlFile) {
414
        const componentKey = this.getComponentKey(xmlFile);
1,400✔
415
        const componentName = xmlFile.componentName?.text;
1,400✔
416
        if (this.componentSymbolsToUpdate.has(componentKey)) {
1,400✔
417
            return;
852✔
418
        }
419
        this.componentSymbolsToUpdate.set(componentKey, componentName);
548✔
420
    }
421

422
    private getComponentKey(xmlFile: XmlFile) {
423
        return (xmlFile.componentName?.text ?? xmlFile.pkgPath).toLowerCase();
1,839✔
424
    }
425

426
    /**
427
     * Resolves symbol table with the first component in this.components to have the same name as the component in the file
428
     * @param componentKey key getting a component from `this.components`
429
     * @param componentName the unprefixed name of the component that will be added (e.g. 'MyLabel' NOT 'roSgNodeMyLabel')
430
     */
431
    private updateComponentSymbolInGlobalScope(componentKey: string, componentName: string) {
432
        const symbolName = componentName ? util.getSgNodeTypeName(componentName) : undefined;
481✔
433
        if (!symbolName) {
481✔
434
            return;
7✔
435
        }
436
        const components = this.components[componentKey] || [];
474!
437
        const previousComponentType = this.componentsTable.getSymbolType(symbolName, { flags: SymbolTypeFlag.typetime });
474✔
438
        // Remove any existing symbols that match
439
        this.componentsTable.removeSymbol(symbolName);
474✔
440
        if (components.length > 0) {
474✔
441
            // There is a component that can be added - use it.
442
            const componentScope = components[0].scope;
473✔
443

444
            this.componentsTable.removeSymbol(symbolName);
473✔
445
            componentScope.linkSymbolTable();
473✔
446
            const componentType = componentScope.getComponentType();
473✔
447
            if (componentType) {
473!
448
                this.componentsTable.addSymbol(symbolName, {}, componentType, SymbolTypeFlag.typetime);
473✔
449
            }
450
            const typeData = {};
473✔
451
            const isSameAsPrevious = previousComponentType && componentType.isEqual(previousComponentType, typeData);
473✔
452
            const isComponentTypeDifferent = !previousComponentType || isReferenceType(previousComponentType) || !isSameAsPrevious;
473✔
453
            componentScope.unlinkSymbolTable();
473✔
454
            return isComponentTypeDifferent;
473✔
455

456
        }
457
        // There was a previous component type, but no new one, so it's different
458
        return !!previousComponentType;
1✔
459
    }
460

461
    /**
462
     * Adds a reference type to the global symbol table with the first component in this.components to have the same name as the component in the file
463
     * This is so on a first validation, these types can be resolved in teh future (eg. when the actual component is created)
464
     * If we don't add reference types at this top level, they will be created at the file level, and will never get resolved
465
     * @param componentKey key getting a component from `this.components`
466
     * @param componentName the unprefixed name of the component that will be added (e.g. 'MyLabel' NOT 'roSgNodeMyLabel')
467
     */
468
    private addComponentReferenceType(componentKey: string, componentName: string) {
469
        const symbolName = componentName ? util.getSgNodeTypeName(componentName) : undefined;
481✔
470
        if (!symbolName) {
481✔
471
            return;
7✔
472
        }
473
        const components = this.components[componentKey] || [];
474!
474

475
        if (components.length > 0) {
474✔
476
            // There is a component that can be added,
477
            if (!this.componentsTable.hasSymbol(symbolName, SymbolTypeFlag.typetime)) {
473✔
478
                // it doesn't already exist in the table
479
                const componentRefType = new ReferenceType(symbolName, symbolName, SymbolTypeFlag.typetime, () => this.componentsTable);
3,217✔
480
                if (componentRefType) {
333!
481
                    this.componentsTable.addSymbol(symbolName, {}, componentRefType, SymbolTypeFlag.typetime);
333✔
482
                }
483
            }
484
        } else {
485
            // there is no component. remove from table
486
            this.componentsTable.removeSymbol(symbolName);
1✔
487
        }
488
    }
489

490
    /**
491
     * re-attach the dependency graph with a new key for any component who changed
492
     * their position in their own named array (only matters when there are multiple
493
     * components with the same name)
494
     */
495
    private syncComponentDependencyGraph(components: Array<{ file: XmlFile; scope: XmlScope }>) {
496
        //reattach every dependency graph
497
        for (let i = 0; i < components.length; i++) {
439✔
498
            const { file, scope } = components[i];
429✔
499

500
            //attach (or re-attach) the dependencyGraph for every component whose position changed
501
            if (file.dependencyGraphIndex !== i) {
429✔
502
                file.dependencyGraphIndex = i;
425✔
503
                this.dependencyGraph.addOrReplace(file.dependencyGraphKey, file.dependencies);
425✔
504
                file.attachDependencyGraph(this.dependencyGraph);
425✔
505
                scope.attachDependencyGraph(this.dependencyGraph);
425✔
506
            }
507
        }
508
    }
509

510
    /**
511
     * Get a list of all files that are included in the project but are not referenced
512
     * by any scope in the program.
513
     */
514
    public getUnreferencedFiles() {
UNCOV
515
        let result = [] as BscFile[];
×
UNCOV
516
        for (let filePath in this.files) {
×
UNCOV
517
            let file = this.files[filePath];
×
518
            //is this file part of a scope
UNCOV
519
            if (!this.getFirstScopeForFile(file)) {
×
520
                //no scopes reference this file. add it to the list
UNCOV
521
                result.push(file);
×
522
            }
523
        }
UNCOV
524
        return result;
×
525
    }
526

527
    /**
528
     * Get the list of errors for the entire program.
529
     */
530
    public getDiagnostics() {
531
        return this.diagnostics.getDiagnostics();
1,208✔
532
    }
533

534
    /**
535
     * Determine if the specified file is loaded in this program right now.
536
     * @param filePath the absolute or relative path to the file
537
     * @param normalizePath should the provided path be normalized before use
538
     */
539
    public hasFile(filePath: string, normalizePath = true) {
2,673✔
540
        return !!this.getFile(filePath, normalizePath);
2,673✔
541
    }
542

543
    /**
544
     * roku filesystem is case INsensitive, so find the scope by key case insensitive
545
     * @param scopeName xml scope names are their `destPath`. Source scope is stored with the key `"source"`
546
     */
547
    public getScopeByName(scopeName: string): Scope | undefined {
548
        if (!scopeName) {
61!
UNCOV
549
            return undefined;
×
550
        }
551
        //most scopes are xml file pkg paths. however, the ones that are not are single names like "global" and "scope",
552
        //so it's safe to run the standardizePkgPath method
553
        scopeName = s`${scopeName}`;
61✔
554
        let key = Object.keys(this.scopes).find(x => x.toLowerCase() === scopeName.toLowerCase());
139✔
555
        return this.scopes[key!];
61✔
556
    }
557

558
    /**
559
     * Return all scopes
560
     */
561
    public getScopes() {
562
        return Object.values(this.scopes);
13✔
563
    }
564

565
    /**
566
     * Find the scope for the specified component
567
     */
568
    public getComponentScope(componentName: string) {
569
        return this.getComponent(componentName)?.scope;
896✔
570
    }
571

572
    /**
573
     * Update internal maps with this file reference
574
     */
575
    private assignFile<T extends BscFile = BscFile>(file: T) {
576
        const fileAddEvent: BeforeFileAddEvent = {
2,485✔
577
            file: file,
578
            program: this
579
        };
580

581
        this.plugins.emit('beforeFileAdd', fileAddEvent);
2,485✔
582

583
        this.files[file.srcPath.toLowerCase()] = file;
2,485✔
584
        this.destMap.set(file.destPath.toLowerCase(), file);
2,485✔
585

586
        this.plugins.emit('afterFileAdd', fileAddEvent);
2,485✔
587

588
        return file;
2,485✔
589
    }
590

591
    /**
592
     * Remove this file from internal maps
593
     */
594
    private unassignFile<T extends BscFile = BscFile>(file: T) {
595
        delete this.files[file.srcPath.toLowerCase()];
161✔
596
        this.destMap.delete(file.destPath.toLowerCase());
161✔
597
        return file;
161✔
598
    }
599

600
    /**
601
     * Load a file into the program. If that file already exists, it is replaced.
602
     * If file contents are provided, those are used, Otherwise, the file is loaded from the file system
603
     * @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:/`)
604
     * @param fileData the file contents. omit or pass `undefined` to prevent loading the data at this time
605
     */
606
    public setFile<T extends BscFile>(srcDestOrPkgPath: string, fileData?: FileData): T;
607
    /**
608
     * Load a file into the program. If that file already exists, it is replaced.
609
     * @param fileEntry an object that specifies src and dest for the file.
610
     * @param fileData the file contents. omit or pass `undefined` to prevent loading the data at this time
611
     */
612
    public setFile<T extends BscFile>(fileEntry: FileObj, fileData: FileData): T;
613
    public setFile<T extends BscFile>(fileParam: FileObj | string, fileData: FileData): T {
614
        //normalize the file paths
615
        const { srcPath, destPath } = this.getPaths(fileParam, this.options.rootDir);
2,481✔
616

617
        let file = this.logger.time(LogLevel.debug, ['Program.setFile()', chalk.green(srcPath)], () => {
2,481✔
618
            //if the file is already loaded, remove it
619
            if (this.hasFile(srcPath)) {
2,481✔
620
                this.removeFile(srcPath, true, true);
145✔
621
            }
622

623
            const data = new LazyFileData(fileData);
2,481✔
624

625
            const event = new ProvideFileEventInternal(this, srcPath, destPath, data, this.fileFactory);
2,481✔
626

627
            this.plugins.emit('beforeProvideFile', event);
2,481✔
628
            this.plugins.emit('provideFile', event);
2,481✔
629
            this.plugins.emit('afterProvideFile', event);
2,481✔
630

631
            //if no files were provided, create a AssetFile to represent it.
632
            if (event.files.length === 0) {
2,481✔
633
                event.files.push(
18✔
634
                    this.fileFactory.AssetFile({
635
                        srcPath: event.srcPath,
636
                        destPath: event.destPath,
637
                        pkgPath: event.destPath,
638
                        data: data
639
                    })
640
                );
641
            }
642

643
            //find the file instance for the srcPath that triggered this action.
644
            const primaryFile = event.files.find(x => x.srcPath === srcPath);
2,481✔
645

646
            if (!primaryFile) {
2,481!
UNCOV
647
                throw new Error(`No file provided for srcPath '${srcPath}'. Instead, received ${JSON.stringify(event.files.map(x => ({
×
648
                    type: x.type,
649
                    srcPath: x.srcPath,
650
                    destPath: x.destPath
651
                })))}`);
652
            }
653

654
            //link the virtual files to the primary file
655
            this.fileClusters.set(primaryFile.srcPath?.toLowerCase(), event.files);
2,481!
656

657
            for (const file of event.files) {
2,481✔
658
                file.srcPath = s(file.srcPath);
2,485✔
659
                if (file.destPath) {
2,485!
660
                    file.destPath = s`${util.replaceCaseInsensitive(file.destPath, this.options.rootDir, '')}`;
2,485✔
661
                }
662
                if (file.pkgPath) {
2,485✔
663
                    file.pkgPath = s`${util.replaceCaseInsensitive(file.pkgPath, this.options.rootDir, '')}`;
2,481✔
664
                } else {
665
                    file.pkgPath = file.destPath;
4✔
666
                }
667
                file.excludeFromOutput = file.excludeFromOutput === true;
2,485✔
668

669
                //set the dependencyGraph key for every file to its destPath
670
                file.dependencyGraphKey = file.destPath.toLowerCase();
2,485✔
671

672
                this.assignFile(file);
2,485✔
673

674
                //register a callback anytime this file's dependencies change
675
                if (typeof file.onDependenciesChanged === 'function') {
2,485✔
676
                    file.disposables ??= [];
2,459!
677
                    file.disposables.push(
2,459✔
678
                        this.dependencyGraph.onchange(file.dependencyGraphKey, file.onDependenciesChanged.bind(file))
679
                    );
680
                }
681

682
                //register this file (and its dependencies) with the dependency graph
683
                this.dependencyGraph.addOrReplace(file.dependencyGraphKey, file.dependencies ?? []);
2,485✔
684

685
                //if this is a `source` file, add it to the source scope's dependency list
686
                if (this.isSourceBrsFile(file)) {
2,485✔
687
                    this.createSourceScope();
1,668✔
688
                    this.dependencyGraph.addDependency('scope:source', file.dependencyGraphKey);
1,668✔
689
                }
690

691
                //if this is an xml file in the components folder, register it as a component
692
                if (this.isComponentsXmlFile(file)) {
2,485✔
693
                    //create a new scope for this xml file
694
                    let scope = new XmlScope(file, this);
423✔
695
                    this.addScope(scope);
423✔
696

697
                    //register this componet now that we have parsed it and know its component name
698
                    this.registerComponent(file, scope);
423✔
699

700
                    //notify plugins that the scope is created and the component is registered
701
                    this.plugins.emit('afterScopeCreate', {
423✔
702
                        program: this,
703
                        scope: scope
704
                    });
705
                }
706
            }
707

708
            return primaryFile;
2,481✔
709
        });
710
        return file as T;
2,481✔
711
    }
712

713
    /**
714
     * Given a srcPath, a destPath, or both, resolve whichever is missing, relative to rootDir.
715
     * @param fileParam an object representing file paths
716
     * @param rootDir must be a pre-normalized path
717
     */
718
    private getPaths(fileParam: string | FileObj | { srcPath?: string; pkgPath?: string }, rootDir: string) {
719
        let srcPath: string | undefined;
720
        let destPath: string | undefined;
721

722
        assert.ok(fileParam, 'fileParam is required');
2,645✔
723

724
        //lift the path vars from the incoming param
725
        if (typeof fileParam === 'string') {
2,645✔
726
            fileParam = this.removePkgPrefix(fileParam);
2,283✔
727
            srcPath = s`${path.resolve(rootDir, fileParam)}`;
2,283✔
728
            destPath = s`${util.replaceCaseInsensitive(srcPath, rootDir, '')}`;
2,283✔
729
        } else {
730
            let param: any = fileParam;
362✔
731

732
            if (param.src) {
362✔
733
                srcPath = s`${param.src}`;
361✔
734
            }
735
            if (param.srcPath) {
362!
UNCOV
736
                srcPath = s`${param.srcPath}`;
×
737
            }
738
            if (param.dest) {
362✔
739
                destPath = s`${this.removePkgPrefix(param.dest)}`;
361✔
740
            }
741
            if (param.pkgPath) {
362!
UNCOV
742
                destPath = s`${this.removePkgPrefix(param.pkgPath)}`;
×
743
            }
744
        }
745

746
        //if there's no srcPath, use the destPath to build an absolute srcPath
747
        if (!srcPath) {
2,645✔
748
            srcPath = s`${rootDir}/${destPath}`;
1✔
749
        }
750
        //coerce srcPath to an absolute path
751
        if (!path.isAbsolute(srcPath)) {
2,645✔
752
            srcPath = util.standardizePath(srcPath);
1✔
753
        }
754

755
        //if destPath isn't set, compute it from the other paths
756
        if (!destPath) {
2,645✔
757
            destPath = s`${util.replaceCaseInsensitive(srcPath, rootDir, '')}`;
1✔
758
        }
759

760
        assert.ok(srcPath, 'fileEntry.src is required');
2,645✔
761
        assert.ok(destPath, 'fileEntry.dest is required');
2,645✔
762

763
        return {
2,645✔
764
            srcPath: srcPath,
765
            //remove leading slash
766
            destPath: destPath.replace(/^[\/\\]+/, '')
767
        };
768
    }
769

770
    /**
771
     * Remove any leading `pkg:/` found in the path
772
     */
773
    private removePkgPrefix(path: string) {
774
        return path.replace(/^pkg:\//i, '');
2,644✔
775
    }
776

777
    /**
778
     * Is this file a .brs file found somewhere within the `pkg:/source/` folder?
779
     */
780
    private isSourceBrsFile(file: BscFile) {
781
        return !!/^(pkg:\/)?source[\/\\]/.exec(file.destPath);
2,646✔
782
    }
783

784
    /**
785
     * Is this file a .brs file found somewhere within the `pkg:/source/` folder?
786
     */
787
    private isComponentsXmlFile(file: BscFile): file is XmlFile {
788
        return isXmlFile(file) && !!/^(pkg:\/)?components[\/\\]/.exec(file.destPath);
2,485✔
789
    }
790

791
    /**
792
     * Ensure source scope is created.
793
     * Note: automatically called internally, and no-op if it exists already.
794
     */
795
    public createSourceScope() {
796
        if (!this.scopes.source) {
2,472✔
797
            const sourceScope = new Scope('source', this, 'scope:source');
1,623✔
798
            sourceScope.attachDependencyGraph(this.dependencyGraph);
1,623✔
799
            this.addScope(sourceScope);
1,623✔
800
            this.plugins.emit('afterScopeCreate', {
1,623✔
801
                program: this,
802
                scope: sourceScope
803
            });
804
        }
805
    }
806

807
    /**
808
     * Remove a set of files from the program
809
     * @param srcPaths can be an array of srcPath or destPath strings
810
     * @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
811
     */
812
    public removeFiles(srcPaths: string[], normalizePath = true) {
1✔
813
        for (let srcPath of srcPaths) {
1✔
814
            this.removeFile(srcPath, normalizePath);
1✔
815
        }
816
    }
817

818
    /**
819
     * Remove a file from the program
820
     * @param filePath can be a srcPath, a destPath, or a destPath with leading `pkg:/`
821
     * @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
822
     */
823
    public removeFile(filePath: string, normalizePath = true, keepSymbolInformation = false) {
27✔
824
        this.logger.debug('Program.removeFile()', filePath);
159✔
825
        const paths = this.getPaths(filePath, this.options.rootDir);
159✔
826

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

830
        for (const file of files) {
159✔
831
            //if a file has already been removed, nothing more needs to be done here
832
            if (!file || !this.hasFile(file.srcPath)) {
162✔
833
                continue;
1✔
834
            }
835
            this.diagnostics.clearForFile(file.srcPath);
161✔
836

837
            const event: BeforeFileRemoveEvent = { file: file, program: this };
161✔
838
            this.plugins.emit('beforeFileRemove', event);
161✔
839

840
            //if there is a scope named the same as this file's path, remove it (i.e. xml scopes)
841
            let scope = this.scopes[file.destPath];
161✔
842
            if (scope) {
161✔
843
                this.logger.debug('Removing associated scope', scope.name);
16✔
844
                const scopeDisposeEvent = {
16✔
845
                    program: this,
846
                    scope: scope
847
                };
848
                this.plugins.emit('beforeScopeDispose', scopeDisposeEvent);
16✔
849
                this.plugins.emit('onScopeDispose', scopeDisposeEvent);
16✔
850
                scope.dispose();
16✔
851
                //notify dependencies of this scope that it has been removed
852
                this.dependencyGraph.remove(scope.dependencyGraphKey!);
16✔
853
                this.removeScope(this.scopes[file.destPath]);
16✔
854
                this.plugins.emit('afterScopeDispose', scopeDisposeEvent);
16✔
855
            }
856
            //remove the file from the program
857
            this.unassignFile(file);
161✔
858

859
            this.dependencyGraph.remove(file.dependencyGraphKey);
161✔
860

861
            //if this is a pkg:/source file, notify the `source` scope that it has changed
862
            if (this.isSourceBrsFile(file)) {
161✔
863
                this.dependencyGraph.removeDependency('scope:source', file.dependencyGraphKey);
127✔
864
            }
865
            if (isBrsFile(file)) {
161✔
866
                this.logger.debug('Removing file symbol info', file.srcPath);
139✔
867

868
                if (!keepSymbolInformation) {
139✔
869
                    this.fileSymbolInformation.delete(file.pkgPath);
8✔
870
                }
871
                this.crossScopeValidation.clearResolutionsForFile(file);
139✔
872
            }
873

874
            //if this is a component, remove it from our components map
875
            if (isXmlFile(file)) {
161✔
876
                this.logger.debug('Unregistering component', file.srcPath);
16✔
877

878
                this.unregisterComponent(file);
16✔
879
            }
880
            this.logger.debug('Disposing file', file.srcPath);
161✔
881

882
            //dispose any disposable things on the file
883
            for (const disposable of file?.disposables ?? []) {
161!
884
                disposable();
155✔
885
            }
886
            //dispose file
887
            file?.dispose?.();
161!
888

889
            this.plugins.emit('afterFileRemove', event);
161✔
890
        }
891
    }
892

893
    public crossScopeValidation = new CrossScopeValidator(this);
1,865✔
894

895
    private isFirstValidation = true;
1,865✔
896

897
    /**
898
     * Traverse the entire project, and validate all scopes
899
     */
900
    public validate() {
901
        this.logger.time(LogLevel.log, ['Validating project'], () => {
1,412✔
902
            this.diagnostics.clearForTag(ProgramValidatorDiagnosticsTag);
1,412✔
903
            const programValidateEvent = {
1,412✔
904
                program: this
905
            };
906
            this.plugins.emit('beforeProgramValidate', programValidateEvent);
1,412✔
907
            this.plugins.emit('onProgramValidate', programValidateEvent);
1,412✔
908

909
            const metrics = {
1,412✔
910
                filesChanged: 0,
911
                filesValidated: 0,
912
                fileValidationTime: '',
913
                crossScopeValidationTime: '',
914
                scopesValidated: 0,
915
                totalLinkTime: '',
916
                totalScopeValidationTime: '',
917
                componentValidationTime: '',
918
                changedSymbolsTime: ''
919
            };
920

921
            const validationStopwatch = new Stopwatch();
1,412✔
922
            //validate every file
923
            const brsFilesValidated: BrsFile[] = [];
1,412✔
924
            const xmlFilesValidated: XmlFile[] = [];
1,412✔
925

926
            const afterValidateFiles: BscFile[] = [];
1,412✔
927
            const sortedFiles = Object.values(this.files).sort(firstBy(x => x.srcPath));
3,804✔
928
            this.logger.time(LogLevel.info, ['Prebuild component types'], () => {
1,412✔
929
                // cast a wide net for potential changes in components
930
                for (const file of sortedFiles) {
1,412✔
931
                    if (file.isValidated) {
2,396✔
932
                        continue;
353✔
933
                    }
934
                    if (isXmlFile(file)) {
2,043✔
935
                        this.addDeferredComponentTypeSymbolCreation(file);
350✔
936
                    } else if (isBrsFile(file)) {
1,693!
937
                        for (const scope of this.getScopesForFile(file)) {
1,693✔
938
                            if (isXmlScope(scope)) {
1,987✔
939
                                this.addDeferredComponentTypeSymbolCreation(scope.xmlFile);
611✔
940
                            }
941
                        }
942
                    }
943
                }
944

945
                // Create reference component types for any component that changes
946
                for (let [componentKey, componentName] of this.componentSymbolsToUpdate.entries()) {
1,412✔
947
                    this.addComponentReferenceType(componentKey, componentName);
481✔
948
                }
949
            });
950

951

952
            metrics.fileValidationTime = validationStopwatch.getDurationTextFor(() => {
1,412✔
953
                //sort files by path so we get consistent results
954
                for (const file of sortedFiles) {
1,412✔
955
                    //for every unvalidated file, validate it
956
                    if (!file.isValidated) {
2,396✔
957
                        const validateFileEvent = {
2,043✔
958
                            program: this,
959
                            file: file
960
                        };
961
                        this.plugins.emit('beforeFileValidate', validateFileEvent);
2,043✔
962
                        //emit an event to allow plugins to contribute to the file validation process
963
                        this.plugins.emit('onFileValidate', validateFileEvent);
2,043✔
964
                        file.isValidated = true;
2,043✔
965
                        if (isBrsFile(file)) {
2,043✔
966
                            brsFilesValidated.push(file);
1,693✔
967
                        } else if (isXmlFile(file)) {
350!
968
                            xmlFilesValidated.push(file);
350✔
969
                        }
970
                        afterValidateFiles.push(file);
2,043✔
971
                    }
972
                }
973
                // AfterFileValidate is after all files have been validated
974
                for (const file of afterValidateFiles) {
1,412✔
975
                    const validateFileEvent = {
2,043✔
976
                        program: this,
977
                        file: file
978
                    };
979
                    this.plugins.emit('afterFileValidate', validateFileEvent);
2,043✔
980
                }
981
            }).durationText;
982

983
            metrics.filesChanged = afterValidateFiles.length;
1,412✔
984

985
            const changedComponentTypes: string[] = [];
1,412✔
986

987
            // Build component types for any component that changes
988
            this.logger.time(LogLevel.info, ['Build component types'], () => {
1,412✔
989
                for (let [componentKey, componentName] of this.componentSymbolsToUpdate.entries()) {
1,412✔
990
                    if (this.updateComponentSymbolInGlobalScope(componentKey, componentName)) {
481✔
991
                        changedComponentTypes.push(util.getSgNodeTypeName(componentName).toLowerCase());
341✔
992
                    }
993
                }
994
                this.componentSymbolsToUpdate.clear();
1,412✔
995
            });
996

997
            // get set of changed symbols
998
            const changedSymbols = new Map<SymbolTypeFlag, Set<string>>();
1,412✔
999
            metrics.changedSymbolsTime = validationStopwatch.getDurationTextFor(() => {
1,412✔
1000

1001
                const changedSymbolsMapArr = [...brsFilesValidated, ...xmlFilesValidated]?.map(f => {
1,412!
1002
                    if (isBrsFile(f)) {
2,043✔
1003
                        return f.providedSymbols.changes;
1,693✔
1004
                    }
1005
                    return null;
350✔
1006
                }).filter(x => x);
2,043✔
1007

1008
                // update the map of typetime dependencies
1009
                for (const file of brsFilesValidated) {
1,412✔
1010
                    for (const [symbolName, provided] of file.providedSymbols.symbolMap.get(SymbolTypeFlag.typetime).entries()) {
1,693✔
1011
                        // clear existing dependencies
1012
                        for (const values of this.symbolDependencies.values()) {
652✔
1013
                            values.delete(symbolName);
61✔
1014
                        }
1015

1016
                        // map types to the set of types that depend upon them
1017
                        for (const dependentSymbol of provided.requiredSymbolNames?.values() ?? []) {
652!
1018
                            const dependentSymbolLower = dependentSymbol.toLowerCase();
179✔
1019
                            if (!this.symbolDependencies.has(dependentSymbolLower)) {
179✔
1020
                                this.symbolDependencies.set(dependentSymbolLower, new Set<string>());
157✔
1021
                            }
1022
                            const symbolsDependentUpon = this.symbolDependencies.get(dependentSymbolLower);
179✔
1023
                            symbolsDependentUpon.add(symbolName);
179✔
1024
                        }
1025
                    }
1026
                }
1027

1028
                for (const flag of [SymbolTypeFlag.runtime, SymbolTypeFlag.typetime]) {
1,412✔
1029
                    const changedSymbolsSetArr = changedSymbolsMapArr.map(symMap => symMap.get(flag));
3,386✔
1030
                    const changedSymbolSet = new Set<string>();
2,824✔
1031
                    for (const changeSet of changedSymbolsSetArr) {
2,824✔
1032
                        for (const change of changeSet) {
3,386✔
1033
                            changedSymbolSet.add(change);
3,448✔
1034
                        }
1035
                    }
1036
                    changedSymbols.set(flag, changedSymbolSet);
2,824✔
1037
                }
1038

1039
                // update changed symbol set with any changed component
1040
                for (const changedComponentType of changedComponentTypes) {
1,412✔
1041
                    changedSymbols.get(SymbolTypeFlag.typetime).add(changedComponentType);
341✔
1042
                }
1043

1044
                // Add any additional types that depend on a changed type
1045
                // as each iteration of the loop might add new types, need to keep checking until nothing new is added
1046
                const dependentTypesChanged = new Set<string>();
1,412✔
1047
                let foundDependentTypes = false;
1,412✔
1048
                const changedTypeSymbols = changedSymbols.get(SymbolTypeFlag.typetime);
1,412✔
1049
                do {
1,412✔
1050
                    foundDependentTypes = false;
1,418✔
1051
                    const allChangedTypesSofar = [...Array.from(changedTypeSymbols), ...Array.from(dependentTypesChanged)];
1,418✔
1052
                    for (const changedSymbol of allChangedTypesSofar) {
1,418✔
1053
                        const symbolsDependentUponChangedSymbol = this.symbolDependencies.get(changedSymbol) ?? [];
997✔
1054
                        for (const symbolName of symbolsDependentUponChangedSymbol) {
997✔
1055
                            if (!changedTypeSymbols.has(symbolName) && !dependentTypesChanged.has(symbolName)) {
183✔
1056
                                foundDependentTypes = true;
6✔
1057
                                dependentTypesChanged.add(symbolName);
6✔
1058
                            }
1059
                        }
1060
                    }
1061
                } while (foundDependentTypes);
1062

1063
                changedSymbols.set(SymbolTypeFlag.typetime, new Set([...changedTypeSymbols, ...dependentTypesChanged]));
1,412✔
1064
            }).durationText;
1065

1066
            if (this.options.logLevel === LogLevel.debug) {
1,412!
NEW
1067
                const changedRuntime = Array.from(changedSymbols.get(SymbolTypeFlag.runtime)).sort();
×
NEW
1068
                this.logger.debug('Changed Symbols (runTime):', changedRuntime.join(', '));
×
NEW
1069
                const changedTypetime = Array.from(changedSymbols.get(SymbolTypeFlag.typetime)).sort();
×
NEW
1070
                this.logger.debug('Changed Symbols (typeTime):', changedTypetime.join(', '));
×
1071
            }
1072
            const filesToBeValidatedInScopeContext = new Set<BscFile>(afterValidateFiles);
1,412✔
1073

1074
            metrics.crossScopeValidationTime = validationStopwatch.getDurationTextFor(() => {
1,412✔
1075
                const scopesToCheck = this.getScopesForCrossScopeValidation(changedComponentTypes.length > 0);
1,412✔
1076
                this.crossScopeValidation.buildComponentsMap();
1,412✔
1077
                this.crossScopeValidation.addDiagnosticsForScopes(scopesToCheck);
1,412✔
1078
                const filesToRevalidate = this.crossScopeValidation.getFilesRequiringChangedSymbol(scopesToCheck, changedSymbols);
1,412✔
1079
                for (const file of filesToRevalidate) {
1,412✔
1080
                    filesToBeValidatedInScopeContext.add(file);
416✔
1081
                }
1082
            }).durationText;
1083

1084
            metrics.filesValidated = filesToBeValidatedInScopeContext.size;
1,412✔
1085

1086
            let linkTime = 0;
1,412✔
1087
            let validationTime = 0;
1,412✔
1088
            let scopesValidated = 0;
1,412✔
1089
            let changedFiles = new Set<BscFile>(afterValidateFiles);
1,412✔
1090
            this.currentScopeValidationOptions = {
1,412✔
1091
                filesToBeValidatedInScopeContext: filesToBeValidatedInScopeContext,
1092
                changedSymbols: changedSymbols,
1093
                changedFiles: changedFiles,
1094
                initialValidation: this.isFirstValidation
1095
            };
1096
            this.logger.time(LogLevel.info, ['Validate all scopes'], () => {
1,412✔
1097
                //sort the scope names so we get consistent results
1098
                const scopeNames = this.getSortedScopeNames();
1,412✔
1099
                for (const file of filesToBeValidatedInScopeContext) {
1,412✔
1100
                    if (isBrsFile(file)) {
2,172✔
1101
                        file.validationSegmenter.unValidateAllSegments();
1,822✔
1102
                        for (const scope of this.getScopesForFile(file)) {
1,822✔
1103
                            scope.invalidate();
2,118✔
1104
                        }
1105
                    }
1106
                }
1107
                for (let scopeName of scopeNames) {
1,412✔
1108
                    let scope = this.scopes[scopeName];
3,227✔
1109
                    const scopeValidated = scope.validate(this.currentScopeValidationOptions);
3,227✔
1110
                    if (scopeValidated) {
3,227✔
1111
                        scopesValidated++;
1,756✔
1112
                    }
1113
                    linkTime += scope.validationMetrics.linkTime;
3,227✔
1114
                    validationTime += scope.validationMetrics.validationTime;
3,227✔
1115
                }
1116
            });
1117
            metrics.scopesValidated = scopesValidated;
1,412✔
1118
            validationStopwatch.totalMilliseconds = linkTime;
1,412✔
1119
            metrics.totalLinkTime = validationStopwatch.getDurationText();
1,412✔
1120

1121
            validationStopwatch.totalMilliseconds = validationTime;
1,412✔
1122
            metrics.totalScopeValidationTime = validationStopwatch.getDurationText();
1,412✔
1123

1124
            metrics.componentValidationTime = validationStopwatch.getDurationTextFor(() => {
1,412✔
1125
                this.detectDuplicateComponentNames();
1,412✔
1126
            }).durationText;
1127

1128
            this.logValidationMetrics(metrics);
1,412✔
1129

1130
            this.isFirstValidation = false;
1,412✔
1131

1132
            this.plugins.emit('afterProgramValidate', programValidateEvent);
1,412✔
1133
        });
1134
    }
1135

1136
    // eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style
1137
    private logValidationMetrics(metrics: { [key: string]: number | string }) {
1138
        let logs = [] as string[];
1,412✔
1139
        for (const key in metrics) {
1,412✔
1140
            logs.push(`${key}=${chalk.yellow(metrics[key].toString())}`);
12,708✔
1141
        }
1142
        this.logger.info(`Validation Metrics: ${logs.join(', ')}`);
1,412✔
1143
    }
1144

1145
    private getScopesForCrossScopeValidation(someComponentTypeChanged = false) {
×
1146
        const scopesForCrossScopeValidation = [];
1,412✔
1147
        for (let scopeName of this.getSortedScopeNames()) {
1,412✔
1148
            let scope = this.scopes[scopeName];
3,227✔
1149
            if (this.globalScope !== scope && (someComponentTypeChanged || !scope.isValidated)) {
3,227✔
1150
                scopesForCrossScopeValidation.push(scope);
1,789✔
1151
            }
1152
        }
1153
        return scopesForCrossScopeValidation;
1,412✔
1154
    }
1155

1156
    /**
1157
     * Flag all duplicate component names
1158
     */
1159
    private detectDuplicateComponentNames() {
1160
        const componentsByName = Object.keys(this.files).reduce<Record<string, XmlFile[]>>((map, filePath) => {
1,412✔
1161
            const file = this.files[filePath];
2,396✔
1162
            //if this is an XmlFile, and it has a valid `componentName` property
1163
            if (isXmlFile(file) && file.componentName?.text) {
2,396✔
1164
                let lowerName = file.componentName.text.toLowerCase();
491✔
1165
                if (!map[lowerName]) {
491✔
1166
                    map[lowerName] = [];
488✔
1167
                }
1168
                map[lowerName].push(file);
491✔
1169
            }
1170
            return map;
2,396✔
1171
        }, {});
1172

1173
        for (let name in componentsByName) {
1,412✔
1174
            const xmlFiles = componentsByName[name];
488✔
1175
            //add diagnostics for every duplicate component with this name
1176
            if (xmlFiles.length > 1) {
488✔
1177
                for (let xmlFile of xmlFiles) {
3✔
1178
                    const { componentName } = xmlFile;
6✔
1179
                    this.diagnostics.register({
6✔
1180
                        ...DiagnosticMessages.duplicateComponentName(componentName.text),
1181
                        location: xmlFile.componentName.location,
1182
                        relatedInformation: xmlFiles.filter(x => x !== xmlFile).map(x => {
12✔
1183
                            return {
6✔
1184
                                location: x.componentName.location,
1185
                                message: 'Also defined here'
1186
                            };
1187
                        })
1188
                    }, { tags: [ProgramValidatorDiagnosticsTag] });
1189
                }
1190
            }
1191
        }
1192
    }
1193

1194
    /**
1195
     * Get the files for a list of filePaths
1196
     * @param filePaths can be an array of srcPath or a destPath strings
1197
     * @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
1198
     */
1199
    public getFiles<T extends BscFile>(filePaths: string[], normalizePath = true) {
29✔
1200
        return filePaths
29✔
1201
            .map(filePath => this.getFile(filePath, normalizePath))
39✔
1202
            .filter(file => file !== undefined) as T[];
39✔
1203
    }
1204

1205
    /**
1206
     * Get the file at the given path
1207
     * @param filePath can be a srcPath or a destPath
1208
     * @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
1209
     */
1210
    public getFile<T extends BscFile>(filePath: string, normalizePath = true) {
18,681✔
1211
        if (typeof filePath !== 'string') {
25,307✔
1212
            return undefined;
3,527✔
1213
            //is the path absolute (or the `virtual:` prefix)
1214
        } else if (/^(?:(?:virtual:[\/\\])|(?:\w:)|(?:[\/\\]))/gmi.exec(filePath)) {
21,780✔
1215
            return this.files[
4,741✔
1216
                (normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase()
4,741!
1217
            ] as T;
1218
        } else if (util.isUriLike(filePath)) {
17,039✔
1219
            const path = URI.parse(filePath).fsPath;
1,366✔
1220
            return this.files[
1,366✔
1221
                (normalizePath ? util.standardizePath(path) : path).toLowerCase()
1,366!
1222
            ] as T;
1223
        } else {
1224
            return this.destMap.get(
15,673✔
1225
                (normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase()
15,673✔
1226
            ) as T;
1227
        }
1228
    }
1229

1230
    private sortedScopeNames: string[] = undefined;
1,865✔
1231

1232
    /**
1233
     * Gets a sorted list of all scopeNames, always beginning with "global", "source", then any others in alphabetical order
1234
     */
1235
    private getSortedScopeNames() {
1236
        if (!this.sortedScopeNames) {
11,181✔
1237
            this.sortedScopeNames = Object.keys(this.scopes).sort((a, b) => {
1,363✔
1238
                if (a === 'global') {
1,972!
1239
                    return -1;
×
1240
                } else if (b === 'global') {
1,972✔
1241
                    return 1;
1,348✔
1242
                }
1243
                if (a === 'source') {
624✔
1244
                    return -1;
30✔
1245
                } else if (b === 'source') {
594✔
1246
                    return 1;
148✔
1247
                }
1248
                if (a < b) {
446✔
1249
                    return -1;
193✔
1250
                } else if (b < a) {
253!
1251
                    return 1;
253✔
1252
                }
UNCOV
1253
                return 0;
×
1254
            });
1255
        }
1256
        return this.sortedScopeNames;
11,181✔
1257
    }
1258

1259
    /**
1260
     * Get a list of all scopes the file is loaded into
1261
     * @param file the file
1262
     */
1263
    public getScopesForFile(file: BscFile | string) {
1264
        const resolvedFile = typeof file === 'string' ? this.getFile(file) : file;
4,245✔
1265

1266
        let result = [] as Scope[];
4,245✔
1267
        if (resolvedFile) {
4,245✔
1268
            const scopeKeys = this.getSortedScopeNames();
4,244✔
1269
            for (let key of scopeKeys) {
4,244✔
1270
                let scope = this.scopes[key];
39,856✔
1271

1272
                if (scope.hasFile(resolvedFile)) {
39,856✔
1273
                    result.push(scope);
4,848✔
1274
                }
1275
            }
1276
        }
1277
        return result;
4,245✔
1278
    }
1279

1280
    /**
1281
     * Get the first found scope for a file.
1282
     */
1283
    public getFirstScopeForFile(file: BscFile): Scope | undefined {
1284
        const scopeKeys = this.getSortedScopeNames();
4,113✔
1285
        for (let key of scopeKeys) {
4,113✔
1286
            let scope = this.scopes[key];
18,637✔
1287

1288
            if (scope.hasFile(file)) {
18,637✔
1289
                return scope;
3,002✔
1290
            }
1291
        }
1292
    }
1293

1294
    public getStatementsByName(name: string, originFile: BrsFile, namespaceName?: string): FileLink<Statement>[] {
1295
        let results = new Map<Statement, FileLink<Statement>>();
39✔
1296
        const filesSearched = new Set<BrsFile>();
39✔
1297
        let lowerNamespaceName = namespaceName?.toLowerCase();
39✔
1298
        let lowerName = name?.toLowerCase();
39!
1299

1300
        function addToResults(statement: FunctionStatement | MethodStatement, file: BrsFile) {
1301
            let parentNamespaceName = statement.findAncestor<NamespaceStatement>(isNamespaceStatement)?.getName(originFile.parseMode)?.toLowerCase();
98✔
1302
            if (statement.tokens.name.text.toLowerCase() === lowerName && (!lowerNamespaceName || parentNamespaceName === lowerNamespaceName)) {
98✔
1303
                if (!results.has(statement)) {
36!
1304
                    results.set(statement, { item: statement, file: file as BrsFile });
36✔
1305
                }
1306
            }
1307
        }
1308

1309
        //look through all files in scope for matches
1310
        for (const scope of this.getScopesForFile(originFile)) {
39✔
1311
            for (const file of scope.getAllFiles()) {
39✔
1312
                //skip non-brs files, or files we've already processed
1313
                if (!isBrsFile(file) || filesSearched.has(file)) {
45✔
1314
                    continue;
3✔
1315
                }
1316
                filesSearched.add(file);
42✔
1317

1318
                file.ast.walk(createVisitor({
42✔
1319
                    FunctionStatement: (statement: FunctionStatement) => {
1320
                        addToResults(statement, file);
95✔
1321
                    },
1322
                    MethodStatement: (statement: MethodStatement) => {
1323
                        addToResults(statement, file);
3✔
1324
                    }
1325
                }), {
1326
                    walkMode: WalkMode.visitStatements
1327
                });
1328
            }
1329
        }
1330
        return [...results.values()];
39✔
1331
    }
1332

1333
    public getStatementsForXmlFile(scope: XmlScope, filterName?: string): FileLink<FunctionStatement>[] {
1334
        let results = new Map<Statement, FileLink<FunctionStatement>>();
14✔
1335
        const filesSearched = new Set<BrsFile>();
14✔
1336

1337
        //get all function names for the xml file and parents
1338
        let funcNames = new Set<string>();
14✔
1339
        let currentScope = scope;
14✔
1340
        while (isXmlScope(currentScope)) {
14✔
1341
            for (let name of currentScope.xmlFile.ast.componentElement.interfaceElement?.functions.map((f) => f.name) ?? []) {
20✔
1342
                if (!filterName || name === filterName) {
20!
1343
                    funcNames.add(name);
20✔
1344
                }
1345
            }
1346
            currentScope = currentScope.getParentScope() as XmlScope;
16✔
1347
        }
1348

1349
        //look through all files in scope for matches
1350
        for (const file of scope.getOwnFiles()) {
14✔
1351
            //skip non-brs files, or files we've already processed
1352
            if (!isBrsFile(file) || filesSearched.has(file)) {
28✔
1353
                continue;
14✔
1354
            }
1355
            filesSearched.add(file);
14✔
1356

1357
            file.ast.walk(createVisitor({
14✔
1358
                FunctionStatement: (statement: FunctionStatement) => {
1359
                    if (funcNames.has(statement.tokens.name.text)) {
19!
1360
                        if (!results.has(statement)) {
19!
1361
                            results.set(statement, { item: statement, file: file });
19✔
1362
                        }
1363
                    }
1364
                }
1365
            }), {
1366
                walkMode: WalkMode.visitStatements
1367
            });
1368
        }
1369
        return [...results.values()];
14✔
1370
    }
1371

1372
    /**
1373
     * Find all available completion items at the given position
1374
     * @param filePath can be a srcPath or a destPath
1375
     * @param position the position (line & column) where completions should be found
1376
     */
1377
    public getCompletions(filePath: string, position: Position) {
1378
        let file = this.getFile(filePath);
120✔
1379
        if (!file) {
120!
UNCOV
1380
            return [];
×
1381
        }
1382

1383
        //find the scopes for this file
1384
        let scopes = this.getScopesForFile(file);
120✔
1385

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

1389
        const event: ProvideCompletionsEvent = {
120✔
1390
            program: this,
1391
            file: file,
1392
            scopes: scopes,
1393
            position: position,
1394
            completions: []
1395
        };
1396

1397
        this.plugins.emit('beforeProvideCompletions', event);
120✔
1398

1399
        this.plugins.emit('provideCompletions', event);
120✔
1400

1401
        this.plugins.emit('afterProvideCompletions', event);
120✔
1402

1403
        return event.completions;
120✔
1404
    }
1405

1406
    /**
1407
     * Goes through each file and builds a list of workspace symbols for the program. Used by LanguageServer's onWorkspaceSymbol functionality
1408
     */
1409
    public getWorkspaceSymbols() {
1410
        const event: ProvideWorkspaceSymbolsEvent = {
22✔
1411
            program: this,
1412
            workspaceSymbols: []
1413
        };
1414
        this.plugins.emit('beforeProvideWorkspaceSymbols', event);
22✔
1415
        this.plugins.emit('provideWorkspaceSymbols', event);
22✔
1416
        this.plugins.emit('afterProvideWorkspaceSymbols', event);
22✔
1417
        return event.workspaceSymbols;
22✔
1418
    }
1419

1420
    /**
1421
     * Given a position in a file, if the position is sitting on some type of identifier,
1422
     * go to the definition of that identifier (where this thing was first defined)
1423
     */
1424
    public getDefinition(srcPath: string, position: Position): Location[] {
1425
        let file = this.getFile(srcPath);
18✔
1426
        if (!file) {
18!
UNCOV
1427
            return [];
×
1428
        }
1429

1430
        const event: ProvideDefinitionEvent = {
18✔
1431
            program: this,
1432
            file: file,
1433
            position: position,
1434
            definitions: []
1435
        };
1436

1437
        this.plugins.emit('beforeProvideDefinition', event);
18✔
1438
        this.plugins.emit('provideDefinition', event);
18✔
1439
        this.plugins.emit('afterProvideDefinition', event);
18✔
1440
        return event.definitions;
18✔
1441
    }
1442

1443
    /**
1444
     * Get hover information for a file and position
1445
     */
1446
    public getHover(srcPath: string, position: Position): Hover[] {
1447
        let file = this.getFile(srcPath);
69✔
1448
        let result: Hover[];
1449
        if (file) {
69!
1450
            const event = {
69✔
1451
                program: this,
1452
                file: file,
1453
                position: position,
1454
                scopes: this.getScopesForFile(file),
1455
                hovers: []
1456
            } as ProvideHoverEvent;
1457
            this.plugins.emit('beforeProvideHover', event);
69✔
1458
            this.plugins.emit('provideHover', event);
69✔
1459
            this.plugins.emit('afterProvideHover', event);
69✔
1460
            result = event.hovers;
69✔
1461
        }
1462

1463
        return result ?? [];
69!
1464
    }
1465

1466
    /**
1467
     * Get full list of document symbols for a file
1468
     * @param srcPath path to the file
1469
     */
1470
    public getDocumentSymbols(srcPath: string): DocumentSymbol[] | undefined {
1471
        let file = this.getFile(srcPath);
18✔
1472
        if (file) {
18!
1473
            const event: ProvideDocumentSymbolsEvent = {
18✔
1474
                program: this,
1475
                file: file,
1476
                documentSymbols: []
1477
            };
1478
            this.plugins.emit('beforeProvideDocumentSymbols', event);
18✔
1479
            this.plugins.emit('provideDocumentSymbols', event);
18✔
1480
            this.plugins.emit('afterProvideDocumentSymbols', event);
18✔
1481
            return event.documentSymbols;
18✔
1482
        } else {
UNCOV
1483
            return undefined;
×
1484
        }
1485
    }
1486

1487
    /**
1488
     * Compute code actions for the given file and range
1489
     */
1490
    public getCodeActions(srcPath: string, range: Range) {
1491
        const codeActions = [] as CodeAction[];
13✔
1492
        const file = this.getFile(srcPath);
13✔
1493
        if (file) {
13✔
1494
            const fileUri = util.pathToUri(file?.srcPath);
12!
1495
            const diagnostics = this
12✔
1496
                //get all current diagnostics (filtered by diagnostic filters)
1497
                .getDiagnostics()
1498
                //only keep diagnostics related to this file
1499
                .filter(x => x.location?.uri === fileUri)
22✔
1500
                //only keep diagnostics that touch this range
1501
                .filter(x => util.rangesIntersectOrTouch(x.location.range, range));
12✔
1502

1503
            const scopes = this.getScopesForFile(file);
12✔
1504

1505
            this.plugins.emit('onGetCodeActions', {
12✔
1506
                program: this,
1507
                file: file,
1508
                range: range,
1509
                diagnostics: diagnostics,
1510
                scopes: scopes,
1511
                codeActions: codeActions
1512
            });
1513
        }
1514
        return codeActions;
13✔
1515
    }
1516

1517
    /**
1518
     * Get semantic tokens for the specified file
1519
     */
1520
    public getSemanticTokens(srcPath: string): SemanticToken[] | undefined {
1521
        const file = this.getFile(srcPath);
24✔
1522
        if (file) {
24!
1523
            const result = [] as SemanticToken[];
24✔
1524
            this.plugins.emit('onGetSemanticTokens', {
24✔
1525
                program: this,
1526
                file: file,
1527
                scopes: this.getScopesForFile(file),
1528
                semanticTokens: result
1529
            });
1530
            return result;
24✔
1531
        }
1532
    }
1533

1534
    public getSignatureHelp(filepath: string, position: Position): SignatureInfoObj[] {
1535
        let file: BrsFile = this.getFile(filepath);
185✔
1536
        if (!file || !isBrsFile(file)) {
185✔
1537
            return [];
3✔
1538
        }
1539
        let callExpressionInfo = new CallExpressionInfo(file, position);
182✔
1540
        let signatureHelpUtil = new SignatureHelpUtil();
182✔
1541
        return signatureHelpUtil.getSignatureHelpItems(callExpressionInfo);
182✔
1542
    }
1543

1544
    public getReferences(srcPath: string, position: Position): Location[] {
1545
        //find the file
1546
        let file = this.getFile(srcPath);
4✔
1547

1548
        const event: ProvideReferencesEvent = {
4✔
1549
            program: this,
1550
            file: file,
1551
            position: position,
1552
            references: []
1553
        };
1554

1555
        this.plugins.emit('beforeProvideReferences', event);
4✔
1556
        this.plugins.emit('provideReferences', event);
4✔
1557
        this.plugins.emit('afterProvideReferences', event);
4✔
1558

1559
        return event.references;
4✔
1560
    }
1561

1562
    /**
1563
     * Transpile a single file and get the result as a string.
1564
     * This does not write anything to the file system.
1565
     *
1566
     * This should only be called by `LanguageServer`.
1567
     * Internal usage should call `_getTranspiledFileContents` instead.
1568
     * @param filePath can be a srcPath or a destPath
1569
     */
1570
    public async getTranspiledFileContents(filePath: string): Promise<FileTranspileResult> {
1571
        const file = this.getFile(filePath);
318✔
1572

1573
        return this.getTranspiledFileContentsPipeline.run(async () => {
318✔
1574

1575
            const result = {
318✔
1576
                destPath: file.destPath,
1577
                pkgPath: file.pkgPath,
1578
                srcPath: file.srcPath
1579
            } as FileTranspileResult;
1580

1581
            const expectedPkgPath = file.pkgPath.toLowerCase();
318✔
1582
            const expectedMapPath = `${expectedPkgPath}.map`;
318✔
1583
            const expectedTypedefPkgPath = expectedPkgPath.replace(/\.brs$/i, '.d.bs');
318✔
1584

1585
            //add a temporary plugin to tap into the file writing process
1586
            const plugin = this.plugins.addFirst({
318✔
1587
                name: 'getTranspiledFileContents',
1588
                beforeWriteFile: (event) => {
1589
                    const pkgPath = event.file.pkgPath.toLowerCase();
992✔
1590
                    switch (pkgPath) {
992✔
1591
                        //this is the actual transpiled file
1592
                        case expectedPkgPath:
992✔
1593
                            result.code = event.file.data.toString();
318✔
1594
                            break;
318✔
1595
                        //this is the sourcemap
1596
                        case expectedMapPath:
1597
                            result.map = event.file.data.toString();
170✔
1598
                            break;
170✔
1599
                        //this is the typedef
1600
                        case expectedTypedefPkgPath:
1601
                            result.typedef = event.file.data.toString();
8✔
1602
                            break;
8✔
1603
                        default:
1604
                        //no idea what this file is. just ignore it
1605
                    }
1606
                    //mark every file as processed so it they don't get written to the output directory
1607
                    event.processedFiles.add(event.file);
992✔
1608
                }
1609
            });
1610

1611
            try {
318✔
1612
                //now that the plugin has been registered, run the build with just this file
1613
                await this.build({
318✔
1614
                    files: [file]
1615
                });
1616
            } finally {
1617
                this.plugins.remove(plugin);
318✔
1618
            }
1619
            return result;
318✔
1620
        });
1621
    }
1622
    private getTranspiledFileContentsPipeline = new ActionPipeline();
1,865✔
1623

1624
    /**
1625
     * Get the absolute output path for a file
1626
     */
1627
    private getOutputPath(file: { pkgPath?: string }, stagingDir = this.getStagingDir()) {
×
1628
        return s`${stagingDir}/${file.pkgPath}`;
1,831✔
1629
    }
1630

1631
    private getStagingDir(stagingDir?: string) {
1632
        let result = stagingDir ?? this.options.stagingDir ?? this.options.stagingDir;
717✔
1633
        if (!result) {
717✔
1634
            result = rokuDeploy.getOptions(this.options as any).stagingDir;
531✔
1635
        }
1636
        result = s`${path.resolve(this.options.cwd ?? process.cwd(), result ?? '/')}`;
717!
1637
        return result;
717✔
1638
    }
1639

1640
    /**
1641
     * Prepare the program for building
1642
     * @param files the list of files that should be prepared
1643
     */
1644
    private async prepare(files: BscFile[]) {
1645
        const programEvent: PrepareProgramEvent = {
359✔
1646
            program: this,
1647
            editor: this.editor,
1648
            files: files
1649
        };
1650

1651
        //assign an editor to every file
1652
        for (const file of programEvent.files) {
359✔
1653
            //if the file doesn't have an editor yet, assign one now
1654
            if (!file.editor) {
728✔
1655
                file.editor = new Editor();
681✔
1656
            }
1657
        }
1658

1659
        //sort the entries to make transpiling more deterministic
1660
        programEvent.files.sort((a, b) => {
359✔
1661
            if (a.pkgPath < b.pkgPath) {
385✔
1662
                return -1;
324✔
1663
            } else if (a.pkgPath > b.pkgPath) {
61!
1664
                return 1;
61✔
1665
            } else {
UNCOV
1666
                return 1;
×
1667
            }
1668
        });
1669

1670
        await this.plugins.emitAsync('beforePrepareProgram', programEvent);
359✔
1671
        await this.plugins.emitAsync('prepareProgram', programEvent);
359✔
1672

1673
        const stagingDir = this.getStagingDir();
359✔
1674

1675
        const entries: TranspileObj[] = [];
359✔
1676

1677
        for (const file of files) {
359✔
1678
            const scope = this.getFirstScopeForFile(file);
728✔
1679
            //link the symbol table for all the files in this scope
1680
            scope?.linkSymbolTable();
728✔
1681

1682
            //if the file doesn't have an editor yet, assign one now
1683
            if (!file.editor) {
728!
UNCOV
1684
                file.editor = new Editor();
×
1685
            }
1686
            const event = {
728✔
1687
                program: this,
1688
                file: file,
1689
                editor: file.editor,
1690
                scope: scope,
1691
                outputPath: this.getOutputPath(file, stagingDir)
1692
            } as PrepareFileEvent & { outputPath: string };
1693

1694
            await this.plugins.emitAsync('beforePrepareFile', event);
728✔
1695
            await this.plugins.emitAsync('prepareFile', event);
728✔
1696
            await this.plugins.emitAsync('afterPrepareFile', event);
728✔
1697

1698
            //TODO remove this in v1
1699
            entries.push(event);
728✔
1700

1701
            //unlink the symbolTable so the next loop iteration can link theirs
1702
            scope?.unlinkSymbolTable();
728✔
1703
        }
1704

1705
        await this.plugins.emitAsync('afterPrepareProgram', programEvent);
359✔
1706
        return files;
359✔
1707
    }
1708

1709
    /**
1710
     * Generate the contents of every file
1711
     */
1712
    private async serialize(files: BscFile[]) {
1713

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

1716
        //exclude prunable files if that option is enabled
1717
        if (this.options.pruneEmptyCodeFiles === true) {
358✔
1718
            files = files.filter(x => x.canBePruned !== true);
9✔
1719
        }
1720

1721
        const serializeProgramEvent = await this.plugins.emitAsync('beforeSerializeProgram', {
358✔
1722
            program: this,
1723
            files: files,
1724
            result: allFiles
1725
        });
1726
        await this.plugins.emitAsync('onSerializeProgram', serializeProgramEvent);
358✔
1727

1728
        // serialize each file
1729
        for (const file of files) {
358✔
1730
            let scope = this.getFirstScopeForFile(file);
725✔
1731

1732
            //if the file doesn't have a scope, create a temporary scope for the file so it can depend on scope-level items
1733
            if (!scope) {
725✔
1734
                scope = new Scope(`temporary-for-${file.pkgPath}`, this);
369✔
1735
                scope.getAllFiles = () => [file];
3,308✔
1736
                scope.getOwnFiles = scope.getAllFiles;
369✔
1737
            }
1738

1739
            //link the symbol table for all the files in this scope
1740
            scope?.linkSymbolTable();
725!
1741
            const event: SerializeFileEvent = {
725✔
1742
                program: this,
1743
                file: file,
1744
                scope: scope,
1745
                result: allFiles
1746
            };
1747
            await this.plugins.emitAsync('beforeSerializeFile', event);
725✔
1748
            await this.plugins.emitAsync('serializeFile', event);
725✔
1749
            await this.plugins.emitAsync('afterSerializeFile', event);
725✔
1750
            //unlink the symbolTable so the next loop iteration can link theirs
1751
            scope?.unlinkSymbolTable();
725!
1752
        }
1753

1754
        this.plugins.emit('afterSerializeProgram', serializeProgramEvent);
358✔
1755

1756
        return allFiles;
358✔
1757
    }
1758

1759
    /**
1760
     * Write the entire project to disk
1761
     */
1762
    private async write(stagingDir: string, files: Map<BscFile, SerializedFile[]>) {
1763
        const programEvent = await this.plugins.emitAsync('beforeWriteProgram', {
358✔
1764
            program: this,
1765
            files: files,
1766
            stagingDir: stagingDir
1767
        });
1768
        //empty the staging directory
1769
        await fsExtra.emptyDir(stagingDir);
358✔
1770

1771
        const serializedFiles = [...files]
358✔
1772
            .map(([, serializedFiles]) => serializedFiles)
725✔
1773
            .flat();
1774

1775
        //write all the files to disk (asynchronously)
1776
        await Promise.all(
358✔
1777
            serializedFiles.map(async (file) => {
1778
                const event = await this.plugins.emitAsync('beforeWriteFile', {
1,103✔
1779
                    program: this,
1780
                    file: file,
1781
                    outputPath: this.getOutputPath(file, stagingDir),
1782
                    processedFiles: new Set<SerializedFile>()
1783
                });
1784

1785
                await this.plugins.emitAsync('writeFile', event);
1,103✔
1786

1787
                await this.plugins.emitAsync('afterWriteFile', event);
1,103✔
1788
            })
1789
        );
1790

1791
        await this.plugins.emitAsync('afterWriteProgram', programEvent);
358✔
1792
    }
1793

1794
    private buildPipeline = new ActionPipeline();
1,865✔
1795

1796
    /**
1797
     * Build the project. This transpiles/transforms/copies all files and moves them to the staging directory
1798
     * @param options the list of options used to build the program
1799
     */
1800
    public async build(options?: ProgramBuildOptions) {
1801
        //run a single build at a time
1802
        await this.buildPipeline.run(async () => {
358✔
1803
            const stagingDir = this.getStagingDir(options?.stagingDir);
358✔
1804

1805
            const event = await this.plugins.emitAsync('beforeBuildProgram', {
358✔
1806
                program: this,
1807
                editor: this.editor,
1808
                files: options?.files ?? Object.values(this.files)
2,148✔
1809
            });
1810

1811
            //prepare the program (and files) for building
1812
            event.files = await this.prepare(event.files);
358✔
1813

1814
            //stage the entire program
1815
            const serializedFilesByFile = await this.serialize(event.files);
358✔
1816

1817
            await this.write(stagingDir, serializedFilesByFile);
358✔
1818

1819
            await this.plugins.emitAsync('afterBuildProgram', event);
358✔
1820

1821
            //undo all edits for the program
1822
            this.editor.undoAll();
358✔
1823
            //undo all edits for each file
1824
            for (const file of event.files) {
358✔
1825
                file.editor.undoAll();
726✔
1826
            }
1827
        });
1828
    }
1829

1830
    /**
1831
     * Find a list of files in the program that have a function with the given name (case INsensitive)
1832
     */
1833
    public findFilesForFunction(functionName: string) {
1834
        const files = [] as BscFile[];
7✔
1835
        const lowerFunctionName = functionName.toLowerCase();
7✔
1836
        //find every file with this function defined
1837
        for (const file of Object.values(this.files)) {
7✔
1838
            if (isBrsFile(file)) {
25✔
1839
                //TODO handle namespace-relative function calls
1840
                //if the file has a function with this name
1841
                // eslint-disable-next-line @typescript-eslint/dot-notation
1842
                if (file['_cachedLookups'].functionStatementMap.get(lowerFunctionName)) {
17✔
1843
                    files.push(file);
2✔
1844
                }
1845
            }
1846
        }
1847
        return files;
7✔
1848
    }
1849

1850
    /**
1851
     * Find a list of files in the program that have a class with the given name (case INsensitive)
1852
     */
1853
    public findFilesForClass(className: string) {
1854
        const files = [] as BscFile[];
7✔
1855
        const lowerClassName = className.toLowerCase();
7✔
1856
        //find every file with this class defined
1857
        for (const file of Object.values(this.files)) {
7✔
1858
            if (isBrsFile(file)) {
25✔
1859
                //TODO handle namespace-relative classes
1860
                //if the file has a function with this name
1861

1862
                // eslint-disable-next-line @typescript-eslint/dot-notation
1863
                if (file['_cachedLookups'].classStatementMap.get(lowerClassName) !== undefined) {
17✔
1864
                    files.push(file);
1✔
1865
                }
1866
            }
1867
        }
1868
        return files;
7✔
1869
    }
1870

1871
    public findFilesForNamespace(name: string) {
1872
        const files = [] as BscFile[];
7✔
1873
        const lowerName = name.toLowerCase();
7✔
1874
        //find every file with this class defined
1875
        for (const file of Object.values(this.files)) {
7✔
1876
            if (isBrsFile(file)) {
25✔
1877

1878
                // eslint-disable-next-line @typescript-eslint/dot-notation
1879
                if (file['_cachedLookups'].namespaceStatements.find((x) => {
17✔
1880
                    const namespaceName = x.name.toLowerCase();
7✔
1881
                    return (
7✔
1882
                        //the namespace name matches exactly
1883
                        namespaceName === lowerName ||
9✔
1884
                        //the full namespace starts with the name (honoring the part boundary)
1885
                        namespaceName.startsWith(lowerName + '.')
1886
                    );
1887
                })) {
1888
                    files.push(file);
6✔
1889
                }
1890
            }
1891
        }
1892

1893
        return files;
7✔
1894
    }
1895

1896
    public findFilesForEnum(name: string) {
1897
        const files = [] as BscFile[];
8✔
1898
        const lowerName = name.toLowerCase();
8✔
1899
        //find every file with this enum defined
1900
        for (const file of Object.values(this.files)) {
8✔
1901
            if (isBrsFile(file)) {
26✔
1902
                // eslint-disable-next-line @typescript-eslint/dot-notation
1903
                if (file['_cachedLookups'].enumStatementMap.get(lowerName)) {
18✔
1904
                    files.push(file);
1✔
1905
                }
1906
            }
1907
        }
1908
        return files;
8✔
1909
    }
1910

1911
    private _manifest: Map<string, string>;
1912

1913
    /**
1914
     * Modify a parsed manifest map by reading `bs_const` and injecting values from `options.manifest.bs_const`
1915
     * @param parsedManifest The manifest map to read from and modify
1916
     */
1917
    private buildBsConstsIntoParsedManifest(parsedManifest: Map<string, string>) {
1918
        // Lift the bs_consts defined in the manifest
1919
        let bsConsts = getBsConst(parsedManifest, false);
15✔
1920

1921
        // Override or delete any bs_consts defined in the bs config
1922
        for (const key in this.options?.manifest?.bs_const) {
15!
1923
            const value = this.options.manifest.bs_const[key];
3✔
1924
            if (value === null) {
3✔
1925
                bsConsts.delete(key);
1✔
1926
            } else {
1927
                bsConsts.set(key, value);
2✔
1928
            }
1929
        }
1930

1931
        // convert the new list of bs consts back into a string for the rest of the down stream systems to use
1932
        let constString = '';
15✔
1933
        for (const [key, value] of bsConsts) {
15✔
1934
            constString += `${constString !== '' ? ';' : ''}${key}=${value.toString()}`;
8✔
1935
        }
1936

1937
        // Set the updated bs_const value
1938
        parsedManifest.set('bs_const', constString);
15✔
1939
    }
1940

1941
    /**
1942
     * Try to find and load the manifest into memory
1943
     * @param manifestFileObj A pointer to a potential manifest file object found during loading
1944
     * @param replaceIfAlreadyLoaded should we overwrite the internal `_manifest` if it already exists
1945
     */
1946
    public loadManifest(manifestFileObj?: FileObj, replaceIfAlreadyLoaded = true) {
1,537✔
1947
        //if we already have a manifest instance, and should not replace...then don't replace
1948
        if (!replaceIfAlreadyLoaded && this._manifest) {
1,543!
UNCOV
1949
            return;
×
1950
        }
1951
        let manifestPath = manifestFileObj
1,543✔
1952
            ? manifestFileObj.src
1,543✔
1953
            : path.join(this.options.rootDir, 'manifest');
1954

1955
        try {
1,543✔
1956
            // we only load this manifest once, so do it sync to improve speed downstream
1957
            const contents = fsExtra.readFileSync(manifestPath, 'utf-8');
1,543✔
1958
            const parsedManifest = parseManifest(contents);
15✔
1959
            this.buildBsConstsIntoParsedManifest(parsedManifest);
15✔
1960
            this._manifest = parsedManifest;
15✔
1961
        } catch (e) {
1962
            this._manifest = new Map();
1,528✔
1963
        }
1964
    }
1965

1966
    /**
1967
     * Get a map of the manifest information
1968
     */
1969
    public getManifest() {
1970
        if (!this._manifest) {
2,397✔
1971
            this.loadManifest();
1,536✔
1972
        }
1973
        return this._manifest;
2,397✔
1974
    }
1975

1976
    public dispose() {
1977
        this.plugins.emit('beforeProgramDispose', { program: this });
1,715✔
1978

1979
        for (let filePath in this.files) {
1,715✔
1980
            this.files[filePath]?.dispose?.();
2,152!
1981
        }
1982
        for (let name in this.scopes) {
1,715✔
1983
            this.scopes[name]?.dispose?.();
3,629!
1984
        }
1985
        this.globalScope?.dispose?.();
1,715!
1986
        this.dependencyGraph?.dispose?.();
1,715!
1987
    }
1988
}
1989

1990
export interface FileTranspileResult {
1991
    srcPath: string;
1992
    destPath: string;
1993
    pkgPath: string;
1994
    code: string;
1995
    map: string;
1996
    typedef: string;
1997
}
1998

1999

2000
class ProvideFileEventInternal<TFile extends BscFile = BscFile> implements ProvideFileEvent<TFile> {
2001
    constructor(
2002
        public program: Program,
2,481✔
2003
        public srcPath: string,
2,481✔
2004
        public destPath: string,
2,481✔
2005
        public data: LazyFileData,
2,481✔
2006
        public fileFactory: FileFactory
2,481✔
2007
    ) {
2008
        this.srcExtension = path.extname(srcPath)?.toLowerCase();
2,481!
2009
    }
2010

2011
    public srcExtension: string;
2012

2013
    public files: TFile[] = [];
2,481✔
2014
}
2015

2016
export interface ProgramBuildOptions {
2017
    /**
2018
     * The directory where the final built files should be placed. This directory will be cleared before running
2019
     */
2020
    stagingDir?: string;
2021
    /**
2022
     * An array of files to build. If omitted, the entire list of files from the program will be used instead.
2023
     * Typically you will want to leave this blank
2024
     */
2025
    files?: BscFile[];
2026
}
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