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

rokucommunity / brighterscript / #13617

14 Jan 2025 07:43PM UTC coverage: 86.812%. Remained the same
#13617

push

web-flow
Merge f0626cae4 into 7fb92fff2

12436 of 15140 branches covered (82.14%)

Branch coverage included in aggregate %.

410 of 436 new or added lines in 36 files covered. (94.04%)

264 existing lines in 24 files now uncovered.

13335 of 14546 relevant lines covered (91.67%)

34016.4 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
                changedSymbols: 0,
916
                totalLinkTime: '',
917
                totalScopeValidationTime: '',
918
                componentValidationTime: '',
919
                changedSymbolsTime: ''
920
            };
921

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

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

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

952

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1086
            metrics.filesValidated = filesToBeValidatedInScopeContext.size;
1,412✔
1087

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

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

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

1130
            this.logValidationMetrics(metrics);
1,412✔
1131

1132
            this.isFirstValidation = false;
1,412✔
1133

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

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

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

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

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

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

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

1232
    private sortedScopeNames: string[] = undefined;
1,865✔
1233

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1403
        this.plugins.emit('afterProvideCompletions', event);
120✔
1404

1405
        return event.completions;
120✔
1406
    }
1407

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

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

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

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

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

1465
        return result ?? [];
69!
1466
    }
1467

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

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

1505
            const scopes = this.getScopesForFile(file);
12✔
1506

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

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

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

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

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

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

1561
        return event.references;
4✔
1562
    }
1563

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

1575
        return this.getTranspiledFileContentsPipeline.run(async () => {
318✔
1576

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

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

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

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

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

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

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

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

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

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

1675
        const stagingDir = this.getStagingDir();
359✔
1676

1677
        const entries: TranspileObj[] = [];
359✔
1678

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

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

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

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

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

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

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

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

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

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

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

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

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

1756
        this.plugins.emit('afterSerializeProgram', serializeProgramEvent);
358✔
1757

1758
        return allFiles;
358✔
1759
    }
1760

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

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

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

1787
                await this.plugins.emitAsync('writeFile', event);
1,103✔
1788

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

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

1796
    private buildPipeline = new ActionPipeline();
1,865✔
1797

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

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

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

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

1819
            await this.write(stagingDir, serializedFilesByFile);
358✔
1820

1821
            await this.plugins.emitAsync('afterBuildProgram', event);
358✔
1822

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

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

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

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

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

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

1895
        return files;
7✔
1896
    }
1897

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

1913
    private _manifest: Map<string, string>;
1914

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

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

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

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

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

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

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

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

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

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

2001

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

2013
    public srcExtension: string;
2014

2015
    public files: TFile[] = [];
2,481✔
2016
}
2017

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