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

rokucommunity / brighterscript / #14058

27 Mar 2025 06:03PM UTC coverage: 87.115% (+0.004%) from 87.111%
#14058

push

web-flow
Merge 557cb4aec into 0eceb0830

13279 of 16114 branches covered (82.41%)

Branch coverage included in aggregate %.

1241 of 1357 new or added lines in 24 files covered. (91.45%)

235 existing lines in 8 files now uncovered.

14379 of 15635 relevant lines covered (91.97%)

19544.19 hits per line

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

92.97
/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, type Position, type Range, type SignatureInformation, type Location, type DocumentSymbol, type CancellationToken, CancellationTokenSource } from 'vscode-languageserver';
1✔
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 { firstBy } from 'thenby';
1✔
51
import { CrossScopeValidator } from './CrossScopeValidator';
1✔
52
import { DiagnosticManager } from './DiagnosticManager';
1✔
53
import { ProgramValidatorDiagnosticsTag } from './bscPlugin/validation/ProgramValidator';
1✔
54
import type { ProvidedSymbolInfo, BrsFile } from './files/BrsFile';
55
import type { XmlFile } from './files/XmlFile';
56
import { SymbolTable } from './SymbolTable';
1✔
57
import { ReferenceType, TypesCreated } from './types';
1✔
58
import { Sequencer } from './common/Sequencer';
1✔
59
import { Deferred } from './deferred';
1✔
60

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

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

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

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

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

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

96
        this.createGlobalScope();
1,938✔
97

98
        this.fileFactory = new FileFactory(this);
1,938✔
99
    }
100

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

104
    /**
105
     * 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`)
106
     */
107
    public editor = new Editor();
1,938✔
108

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

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

120
        this.populateGlobalSymbolTable();
1,938✔
121
        this.globalScope.symbolTable.addSibling(this.componentsTable);
1,938✔
122

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

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

132

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

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

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

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

182
        BuiltInInterfaceAdder.getLookupTable = () => this.globalScope.symbolTable;
566,176✔
183

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

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

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

205
        for (const nodeData of Object.values(nodes) as SGNodeData[]) {
1,938✔
206
            this.recursivelyAddNodeToSymbolTable(nodeData);
186,048✔
207
        }
208

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

216
    }
217

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

226
    public diagnostics: DiagnosticManager;
227

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

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

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

241
    private currentScopeValidationOptions: ScopeValidationOptions;
242

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

248

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

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

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

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

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

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

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

294

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

582
        this.plugins.emit('beforeFileAdd', fileAddEvent);
2,614✔
583

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

587
        this.plugins.emit('afterFileAdd', fileAddEvent);
2,614✔
588

589
        return file;
2,614✔
590
    }
591

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

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

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

624
            const data = new LazyFileData(fileData);
2,610✔
625

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

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

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

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

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

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

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

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

673
                this.assignFile(file);
2,614✔
674

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

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

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

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

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

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

709
            return primaryFile;
2,610✔
710
        });
711
        return file as T;
2,610✔
712
    }
713

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

723
        assert.ok(fileParam, 'fileParam is required');
2,831✔
724

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

860
            this.dependencyGraph.remove(file.dependencyGraphKey);
218✔
861

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

869
                if (!keepSymbolInformation) {
195✔
870
                    this.fileSymbolInformation.delete(file.pkgPath);
12✔
871
                }
872
                this.crossScopeValidation.clearResolutionsForFile(file);
195✔
873
            }
874

875
            this.diagnostics.clearForFile(file.srcPath);
218✔
876

877
            //if this is a component, remove it from our components map
878
            if (isXmlFile(file)) {
218✔
879
                this.logger.debug('Unregistering component', file.srcPath);
16✔
880

881
                this.unregisterComponent(file);
16✔
882
            }
883
            this.logger.debug('Disposing file', file.srcPath);
218✔
884

885
            //dispose any disposable things on the file
886
            for (const disposable of file?.disposables ?? []) {
218!
887
                disposable();
211✔
888
            }
889
            //dispose file
890
            file?.dispose?.();
218!
891

892
            this.plugins.emit('afterFileRemove', event);
218✔
893
        }
894
    }
895

896
    public crossScopeValidation = new CrossScopeValidator(this);
1,938✔
897

898
    private isFirstValidation = true;
1,938✔
899

900
    /**
901
     * Counter used to track which validation run is being logged
902
     */
903
    private validationRunSequence = 1;
1,938✔
904

905
    /**
906
     * How many milliseconds can pass while doing synchronous operations in validate before we register a short timeout (i.e. yield to the event loop)
907
     */
908
    private validationMinSyncDuration = 75;
1,938✔
909

910
    private validatePromise: Promise<void> | undefined;
911

912

913
    private validationDetails: {
1,938✔
914
        brsFilesValidated: BrsFile[];
915
        xmlFilesValidated: XmlFile[];
916
        changedSymbols: Map<SymbolTypeFlag, Set<string>>;
917
        changedComponentTypes: string[];
918
        scopesToValidate: Scope[];
919
        filesToBeValidatedInScopeContext: Set<BscFile>;
920

921
    } = {
922
            brsFilesValidated: [],
923
            xmlFilesValidated: [],
924
            changedSymbols: new Map<SymbolTypeFlag, Set<string>>(),
925
            changedComponentTypes: [],
926
            scopesToValidate: [],
927
            filesToBeValidatedInScopeContext: new Set<BscFile>()
928
        };
929

930
    /**
931
     * Traverse the entire project, and validate all scopes
932
     */
933
    public validate(): void;
934
    public validate(options: { async: false; cancellationToken?: CancellationToken }): void;
935
    public validate(options: { async: true; cancellationToken?: CancellationToken }): Promise<void>;
936
    public validate(options?: { async?: boolean; cancellationToken?: CancellationToken }) {
937
        const validationRunId = this.validationRunSequence++;
1,507✔
938

939
        let previousValidationPromise = this.validatePromise;
1,507✔
940
        const deferred = new Deferred();
1,507✔
941

942
        if (options?.async) {
1,507✔
943
            //we're async, so create a new promise chain to resolve after this validation is done
944
            this.validatePromise = Promise.resolve(previousValidationPromise).then(() => {
127✔
945
                return deferred.promise;
127✔
946
            });
947

948
            //we are not async but there's a pending promise, then we cannot run this validation
949
        } else if (previousValidationPromise !== undefined) {
1,380!
NEW
950
            throw new Error('Cannot run synchronous validation while an async validation is in progress');
×
951
        }
952

953
        let beforeProgramValidateWasEmitted = false;
1,507✔
954

955
        const brsFilesValidated: BrsFile[] = this.validationDetails.brsFilesValidated;
1,507✔
956
        const xmlFilesValidated: XmlFile[] = this.validationDetails.xmlFilesValidated;
1,507✔
957
        const changedSymbols = this.validationDetails.changedSymbols;
1,507✔
958
        const changedComponentTypes = this.validationDetails.changedComponentTypes;
1,507✔
959
        const scopesToValidate = this.validationDetails.scopesToValidate;
1,507✔
960
        const filesToBeValidatedInScopeContext = this.validationDetails.filesToBeValidatedInScopeContext;
1,507✔
961

962
        //validate every file
963

964
        let logValidateEnd = (status?: string) => { };
1,507✔
965

966
        //will be populated later on during the correspnding sequencer event
967
        let filesToProcess: BscFile[];
968

969
        const sequencer = new Sequencer({
1,507✔
970
            name: 'program.validate',
971
            cancellationToken: options?.cancellationToken ?? new CancellationTokenSource().token,
9,042✔
972
            minSyncDuration: this.validationMinSyncDuration
973
        });
974
        //this sequencer allows us to run in both sync and async mode, depending on whether options.async is enabled.
975
        //We use this to prevent starving the CPU during long validate cycles when running in a language server context
976
        sequencer
1,507✔
977
            .once('wait for previous run', () => {
978
                //if running in async mode, return the previous validation promise to ensure we're only running one at a time
979
                if (options?.async) {
1,507✔
980
                    return previousValidationPromise;
127✔
981
                }
982
            })
983
            .once('before and on programValidate', () => {
984
                logValidateEnd = this.logger.timeStart(LogLevel.log, `Validating project${(this.logger.logLevel as LogLevel) > LogLevel.log ? ` (run ${validationRunId})` : ''}`);
1,504!
985
                this.diagnostics.clearForTag(ProgramValidatorDiagnosticsTag);
1,504✔
986
                this.plugins.emit('beforeProgramValidate', {
1,504✔
987
                    program: this
988
                });
989
                beforeProgramValidateWasEmitted = true;
1,504✔
990
                this.plugins.emit('onProgramValidate', {
1,504✔
991
                    program: this
992
                });
993
            })
994
            //handle some component symbol stuff
995
            .forEach('addDeferredComponentTypeSymbolCreation',
996
                () => {
997
                    filesToProcess = Object.values(this.files).sort(firstBy(x => x.srcPath)).filter(x => !x.isValidated);
4,292✔
998
                    for (const file of filesToProcess) {
1,504✔
999
                        filesToBeValidatedInScopeContext.add(file);
2,182✔
1000
                    }
1001

1002
                    //return the list of files that need to be processed
1003
                    return filesToProcess;
1,504✔
1004
                }, (file) => {
1005
                    // cast a wide net for potential changes in components
1006
                    if (isXmlFile(file)) {
2,181✔
1007
                        this.addDeferredComponentTypeSymbolCreation(file);
392✔
1008
                    } else if (isBrsFile(file)) {
1,789!
1009
                        for (const scope of this.getScopesForFile(file)) {
1,789✔
1010
                            if (isXmlScope(scope)) {
2,065✔
1011
                                this.addDeferredComponentTypeSymbolCreation(scope.xmlFile);
626✔
1012
                            }
1013
                        }
1014
                    }
1015
                }
1016
            )
1017
            .once('addComponentReferenceTypes', () => {
1018
                // Create reference component types for any component that changes
1019
                for (let [componentKey, componentName] of this.componentSymbolsToUpdate.entries()) {
1,501✔
1020
                    this.addComponentReferenceType(componentKey, componentName);
529✔
1021
                }
1022
            })
1023
            .forEach('beforeFileValidate', () => filesToProcess, (file) => {
1,501✔
1024
                //run the beforeFilevalidate event for every unvalidated file
1025
                this.plugins.emit('beforeFileValidate', {
2,181✔
1026
                    program: this,
1027
                    file: file
1028
                });
1029
            })
1030
            .forEach('onFileValidate', () => filesToProcess, (file) => {
1,501✔
1031
                //run the onFileValidate event for every unvalidated file
1032
                this.plugins.emit('onFileValidate', {
2,181✔
1033
                    program: this,
1034
                    file: file
1035
                });
1036
                file.isValidated = true;
2,181✔
1037
                if (isBrsFile(file)) {
2,181✔
1038
                    brsFilesValidated.push(file);
1,789✔
1039
                } else if (isXmlFile(file)) {
392!
1040
                    xmlFilesValidated.push(file);
392✔
1041
                }
1042
            })
1043
            .forEach('afterFileValidate', () => filesToProcess, (file) => {
1,501✔
1044
                //run the onFileValidate event for every unvalidated file
1045
                this.plugins.emit('afterFileValidate', {
2,181✔
1046
                    program: this,
1047
                    file: file
1048
                });
1049
            })
1050
            .once('Build component types for any component that changes', () => {
1051
                this.logger.time(LogLevel.info, ['Build component types'], () => {
1,500✔
1052
                    for (let [componentKey, componentName] of this.componentSymbolsToUpdate.entries()) {
1,500✔
1053
                        if (this.updateComponentSymbolInGlobalScope(componentKey, componentName)) {
529✔
1054
                            changedComponentTypes.push(util.getSgNodeTypeName(componentName).toLowerCase());
383✔
1055
                        }
1056
                    }
1057
                    this.componentSymbolsToUpdate.clear();
1,500✔
1058
                });
1059
            })
1060
            .once('track and update type-time and runtime symbol dependencies and changes', () => {
1061
                const changedSymbolsMapArr = [...brsFilesValidated, ...xmlFilesValidated]?.map(f => {
1,500!
1062
                    if (isBrsFile(f)) {
2,181✔
1063
                        return f.providedSymbols.changes;
1,789✔
1064
                    }
1065
                    return null;
392✔
1066
                }).filter(x => x);
2,181✔
1067

1068
                // update the map of typetime dependencies
1069
                for (const file of brsFilesValidated) {
1,500✔
1070
                    for (const [symbolName, provided] of file.providedSymbols.symbolMap.get(SymbolTypeFlag.typetime).entries()) {
1,789✔
1071
                        // clear existing dependencies
1072
                        for (const values of this.symbolDependencies.values()) {
669✔
1073
                            values.delete(symbolName);
62✔
1074
                        }
1075

1076
                        // map types to the set of types that depend upon them
1077
                        for (const dependentSymbol of provided.requiredSymbolNames?.values() ?? []) {
669!
1078
                            const dependentSymbolLower = dependentSymbol.toLowerCase();
185✔
1079
                            if (!this.symbolDependencies.has(dependentSymbolLower)) {
185✔
1080
                                this.symbolDependencies.set(dependentSymbolLower, new Set<string>());
163✔
1081
                            }
1082
                            const symbolsDependentUpon = this.symbolDependencies.get(dependentSymbolLower);
185✔
1083
                            symbolsDependentUpon.add(symbolName);
185✔
1084
                        }
1085
                    }
1086
                }
1087

1088
                for (const flag of [SymbolTypeFlag.runtime, SymbolTypeFlag.typetime]) {
1,500✔
1089
                    const changedSymbolsSetArr = changedSymbolsMapArr.map(symMap => symMap.get(flag));
3,578✔
1090
                    const changedSymbolSet = new Set<string>();
3,000✔
1091
                    for (const changeSet of changedSymbolsSetArr) {
3,000✔
1092
                        for (const change of changeSet) {
3,578✔
1093
                            changedSymbolSet.add(change);
3,560✔
1094
                        }
1095
                    }
1096
                    if (!changedSymbols.has(flag)) {
3,000✔
1097
                        changedSymbols.set(flag, changedSymbolSet);
2,996✔
1098
                    } else {
1099
                        changedSymbols.set(flag, new Set([...changedSymbols.get(flag), ...changedSymbolSet]));
4✔
1100
                    }
1101
                }
1102

1103
                // update changed symbol set with any changed component
1104
                for (const changedComponentType of changedComponentTypes) {
1,500✔
1105
                    changedSymbols.get(SymbolTypeFlag.typetime).add(changedComponentType);
383✔
1106
                }
1107

1108
                // Add any additional types that depend on a changed type
1109
                // as each iteration of the loop might add new types, need to keep checking until nothing new is added
1110
                const dependentTypesChanged = new Set<string>();
1,500✔
1111
                let foundDependentTypes = false;
1,500✔
1112
                const changedTypeSymbols = changedSymbols.get(SymbolTypeFlag.typetime);
1,500✔
1113
                do {
1,500✔
1114
                    foundDependentTypes = false;
1,506✔
1115
                    const allChangedTypesSofar = [...Array.from(changedTypeSymbols), ...Array.from(dependentTypesChanged)];
1,506✔
1116
                    for (const changedSymbol of allChangedTypesSofar) {
1,506✔
1117
                        const symbolsDependentUponChangedSymbol = this.symbolDependencies.get(changedSymbol) ?? [];
1,055✔
1118
                        for (const symbolName of symbolsDependentUponChangedSymbol) {
1,055✔
1119
                            if (!changedTypeSymbols.has(symbolName) && !dependentTypesChanged.has(symbolName)) {
189✔
1120
                                foundDependentTypes = true;
6✔
1121
                                dependentTypesChanged.add(symbolName);
6✔
1122
                            }
1123
                        }
1124
                    }
1125
                } while (foundDependentTypes);
1126

1127
                changedSymbols.set(SymbolTypeFlag.typetime, new Set([...changedSymbols.get(SymbolTypeFlag.typetime), ...changedTypeSymbols, ...dependentTypesChanged]));
1,500✔
1128

1129
                // can reset filesValidatedList, because they are no longer needed
1130
                this.validationDetails.brsFilesValidated = [];
1,500✔
1131
                this.validationDetails.xmlFilesValidated = [];
1,500✔
1132
            })
1133
            .once('tracks changed symbols and prepares files and scopes for validation.', () => {
1134
                if (this.options.logLevel === LogLevel.debug) {
1,500!
NEW
1135
                    const changedRuntime = Array.from(changedSymbols.get(SymbolTypeFlag.runtime)).sort();
×
NEW
1136
                    this.logger.debug('Changed Symbols (runTime):', changedRuntime.join(', '));
×
NEW
1137
                    const changedTypetime = Array.from(changedSymbols.get(SymbolTypeFlag.typetime)).sort();
×
NEW
1138
                    this.logger.debug('Changed Symbols (typeTime):', changedTypetime.join(', '));
×
1139
                }
1140

1141
                const scopesToCheck = this.getScopesForCrossScopeValidation(changedComponentTypes.length > 0);
1,500✔
1142
                this.crossScopeValidation.buildComponentsMap();
1,500✔
1143
                this.crossScopeValidation.addDiagnosticsForScopes(scopesToCheck);
1,500✔
1144
                const filesToRevalidate = this.crossScopeValidation.getFilesRequiringChangedSymbol(scopesToCheck, changedSymbols);
1,500✔
1145
                for (const file of filesToRevalidate) {
1,500✔
1146
                    filesToBeValidatedInScopeContext.add(file);
420✔
1147
                }
1148

1149
                this.currentScopeValidationOptions = {
1,500✔
1150
                    filesToBeValidatedInScopeContext: filesToBeValidatedInScopeContext,
1151
                    changedSymbols: changedSymbols,
1152
                    changedFiles: Array.from(filesToBeValidatedInScopeContext),
1153
                    initialValidation: this.isFirstValidation
1154
                };
1155

1156
                //can reset changedComponent types
1157
                this.validationDetails.changedComponentTypes = [];
1,500✔
1158
            })
1159
            .forEach('invalidate affected scopes', () => filesToBeValidatedInScopeContext, (file) => {
1,500✔
1160
                if (isBrsFile(file)) {
2,311✔
1161
                    file.validationSegmenter.unValidateAllSegments();
1,919✔
1162
                    for (const scope of this.getScopesForFile(file)) {
1,919✔
1163
                        scope.invalidate();
2,196✔
1164
                    }
1165
                }
1166
            })
1167
            .forEach('validate scopes', () => this.getSortedScopeNames(), (scopeName) => {
1,500✔
1168
                //sort the scope names so we get consistent results
1169
                let scope = this.scopes[scopeName];
3,431✔
1170
                if (scope.shouldValidate(this.currentScopeValidationOptions)) {
3,431✔
1171
                    scopesToValidate.push(scope);
1,872✔
1172
                    this.plugins.emit('beforeScopeValidate', {
1,872✔
1173
                        program: this,
1174
                        scope: scope
1175
                    });
1176
                }
1177
            })
1178
            .forEach('validate scope', () => this.getSortedScopeNames(), (scopeName) => {
1,498✔
1179
                //sort the scope names so we get consistent results
1180
                let scope = this.scopes[scopeName];
3,426✔
1181
                scope.validate(this.currentScopeValidationOptions);
3,426✔
1182
            })
1183
            .forEach('afterScopeValidate', () => scopesToValidate, (scope) => {
1,494✔
1184
                this.plugins.emit('afterScopeValidate', {
1,868✔
1185
                    program: this,
1186
                    scope: scope
1187
                });
1188
            })
1189
            .once('detect duplicate component names', () => {
1190
                this.detectDuplicateComponentNames();
1,493✔
1191
                this.isFirstValidation = false;
1,493✔
1192

1193
                // can reset other validation details
1194
                this.validationDetails.changedSymbols = new Map<SymbolTypeFlag, Set<string>>();
1,493✔
1195
                this.validationDetails.scopesToValidate = [];
1,493✔
1196
                this.validationDetails.filesToBeValidatedInScopeContext = new Set<BscFile>();
1,493✔
1197

1198
            })
1199
            .onCancel(() => {
1200
                logValidateEnd('cancelled');
14✔
1201
            })
1202
            .onSuccess(() => {
1203
                logValidateEnd();
1,493✔
1204
            })
1205
            .onComplete(() => {
1206
                //if we emitted the beforeProgramValidate hook, emit the afterProgramValidate hook as well
1207
                if (beforeProgramValidateWasEmitted) {
1,507✔
1208
                    const wasCancelled = options?.cancellationToken?.isCancellationRequested ?? false;
1,504✔
1209
                    this.plugins.emit('afterProgramValidate', {
1,504✔
1210
                        program: this,
1211
                        wasCancelled: wasCancelled
1212
                    });
1213
                }
1214

1215
                //log all the sequencer timing metrics if `info` logging is enabled
1216
                this.logger.info(
1,507✔
1217
                    sequencer.formatMetrics({
1218
                        header: 'Program.validate metrics:',
1219
                        //only include loop iterations if `debug` logging is enabled
1220
                        includeLoopIterations: this.logger.isLogLevelEnabled(LogLevel.debug)
1221
                    })
1222
                );
1223

1224
                //regardless of the success of the validation, mark this run as complete
1225
                deferred.resolve();
1,507✔
1226
                //clear the validatePromise which means we're no longer running a validation
1227
                this.validatePromise = undefined;
1,507✔
1228
            });
1229

1230
        //run the sequencer in async mode if enabled
1231
        if (options?.async) {
1,507✔
1232
            return sequencer.run();
127✔
1233

1234
            //run the sequencer in sync mode
1235
        } else {
1236
            return sequencer.runSync();
1,380✔
1237
        }
1238
    }
1239

1240
    protected logValidationMetrics(metrics: Record<string, number | string>) {
UNCOV
1241
        let logs = [] as string[];
×
UNCOV
1242
        for (const key in metrics) {
×
UNCOV
1243
            logs.push(`${key}=${chalk.yellow(metrics[key].toString())}`);
×
1244
        }
UNCOV
1245
        this.logger.info(`Validation Metrics: ${logs.join(', ')}`);
×
1246
    }
1247

1248
    private getScopesForCrossScopeValidation(someComponentTypeChanged = false) {
×
1249
        const scopesForCrossScopeValidation = [];
1,500✔
1250
        for (let scopeName of this.getSortedScopeNames()) {
1,500✔
1251
            let scope = this.scopes[scopeName];
3,431✔
1252
            if (this.globalScope !== scope && (someComponentTypeChanged || !scope.isValidated)) {
3,431✔
1253
                scopesForCrossScopeValidation.push(scope);
1,888✔
1254
            }
1255
        }
1256
        return scopesForCrossScopeValidation;
1,500✔
1257
    }
1258

1259
    /**
1260
     * Flag all duplicate component names
1261
     */
1262
    private detectDuplicateComponentNames() {
1263
        const componentsByName = Object.keys(this.files).reduce<Record<string, XmlFile[]>>((map, filePath) => {
1,493✔
1264
            const file = this.files[filePath];
2,556✔
1265
            //if this is an XmlFile, and it has a valid `componentName` property
1266
            if (isXmlFile(file) && file.componentName?.text) {
2,556✔
1267
                let lowerName = file.componentName.text.toLowerCase();
556✔
1268
                if (!map[lowerName]) {
556✔
1269
                    map[lowerName] = [];
553✔
1270
                }
1271
                map[lowerName].push(file);
556✔
1272
            }
1273
            return map;
2,556✔
1274
        }, {});
1275

1276
        for (let name in componentsByName) {
1,493✔
1277
            const xmlFiles = componentsByName[name];
553✔
1278
            //add diagnostics for every duplicate component with this name
1279
            if (xmlFiles.length > 1) {
553✔
1280
                for (let xmlFile of xmlFiles) {
3✔
1281
                    const { componentName } = xmlFile;
6✔
1282
                    this.diagnostics.register({
6✔
1283
                        ...DiagnosticMessages.duplicateComponentName(componentName.text),
1284
                        location: xmlFile.componentName.location,
1285
                        relatedInformation: xmlFiles.filter(x => x !== xmlFile).map(x => {
12✔
1286
                            return {
6✔
1287
                                location: x.componentName.location,
1288
                                message: 'Also defined here'
1289
                            };
1290
                        })
1291
                    }, { tags: [ProgramValidatorDiagnosticsTag] });
1292
                }
1293
            }
1294
        }
1295
    }
1296

1297
    /**
1298
     * Get the files for a list of filePaths
1299
     * @param filePaths can be an array of srcPath or a destPath strings
1300
     * @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
1301
     */
1302
    public getFiles<T extends BscFile>(filePaths: string[], normalizePath = true) {
29✔
1303
        return filePaths
29✔
1304
            .map(filePath => this.getFile(filePath, normalizePath))
39✔
1305
            .filter(file => file !== undefined) as T[];
39✔
1306
    }
1307

1308
    private getFilePathCache = new Map<string, { path: string; isDestMap?: boolean }>();
1,938✔
1309

1310
    /**
1311
     * Get the file at the given path
1312
     * @param filePath can be a srcPath or a destPath
1313
     * @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
1314
     */
1315
    public getFile<T extends BscFile>(filePath: string, normalizePath = true) {
19,549✔
1316
        if (this.getFilePathCache.has(filePath)) {
26,426✔
1317
            const cachedFilePath = this.getFilePathCache.get(filePath);
15,626✔
1318
            if (cachedFilePath.isDestMap) {
15,626✔
1319
                return this.destMap.get(
12,965✔
1320
                    cachedFilePath.path
1321
                ) as T;
1322
            }
1323
            return this.files[
2,661✔
1324
                cachedFilePath.path
1325
            ] as T;
1326
        }
1327
        if (typeof filePath !== 'string') {
10,800✔
1328
            return undefined;
3,624✔
1329
            //is the path absolute (or the `virtual:` prefix)
1330
        } else if (/^(?:(?:virtual:[\/\\])|(?:\w:)|(?:[\/\\]))/gmi.exec(filePath)) {
7,176✔
1331
            const standardizedPath = (normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase();
3,437!
1332
            this.getFilePathCache.set(filePath, { path: standardizedPath });
3,437✔
1333

1334
            return this.files[
3,437✔
1335
                standardizedPath
1336
            ] as T;
1337
        } else if (util.isUriLike(filePath)) {
3,739✔
1338
            const path = URI.parse(filePath).fsPath;
572✔
1339
            const standardizedPath = (normalizePath ? util.standardizePath(path) : path).toLowerCase();
572!
1340
            this.getFilePathCache.set(filePath, { path: standardizedPath });
572✔
1341

1342
            return this.files[
572✔
1343
                standardizedPath
1344
            ] as T;
1345
        } else {
1346
            const standardizedPath = (normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase();
3,167✔
1347
            this.getFilePathCache.set(filePath, { path: standardizedPath, isDestMap: true });
3,167✔
1348
            return this.destMap.get(
3,167✔
1349
                standardizedPath
1350
            ) as T;
1351
        }
1352
    }
1353

1354
    private sortedScopeNames: string[] = undefined;
1,938✔
1355

1356
    /**
1357
     * Gets a sorted list of all scopeNames, always beginning with "global", "source", then any others in alphabetical order
1358
     */
1359
    private getSortedScopeNames() {
1360
        if (!this.sortedScopeNames) {
13,196✔
1361
            this.sortedScopeNames = Object.keys(this.scopes).sort((a, b) => {
1,426✔
1362
                if (a === 'global') {
2,076!
UNCOV
1363
                    return -1;
×
1364
                } else if (b === 'global') {
2,076✔
1365
                    return 1;
1,389✔
1366
                }
1367
                if (a === 'source') {
687✔
1368
                    return -1;
30✔
1369
                } else if (b === 'source') {
657✔
1370
                    return 1;
149✔
1371
                }
1372
                if (a < b) {
508✔
1373
                    return -1;
203✔
1374
                } else if (b < a) {
305!
1375
                    return 1;
305✔
1376
                }
UNCOV
1377
                return 0;
×
1378
            });
1379
        }
1380
        return this.sortedScopeNames;
13,196✔
1381
    }
1382

1383
    /**
1384
     * Get a list of all scopes the file is loaded into
1385
     * @param file the file
1386
     */
1387
    public getScopesForFile(file: BscFile | string) {
1388
        const resolvedFile = typeof file === 'string' ? this.getFile(file) : file;
4,476✔
1389

1390
        let result = [] as Scope[];
4,476✔
1391
        if (resolvedFile) {
4,476✔
1392
            const scopeKeys = this.getSortedScopeNames();
4,475✔
1393
            for (let key of scopeKeys) {
4,475✔
1394
                let scope = this.scopes[key];
40,427✔
1395

1396
                if (scope.hasFile(resolvedFile)) {
40,427✔
1397
                    result.push(scope);
5,048✔
1398
                }
1399
            }
1400
        }
1401
        return result;
4,476✔
1402
    }
1403

1404
    /**
1405
     * Get the first found scope for a file.
1406
     */
1407
    public getFirstScopeForFile(file: BscFile): Scope | undefined {
1408
        const scopeKeys = this.getSortedScopeNames();
4,223✔
1409
        for (let key of scopeKeys) {
4,223✔
1410
            let scope = this.scopes[key];
18,900✔
1411

1412
            if (scope.hasFile(file)) {
18,900✔
1413
                return scope;
3,079✔
1414
            }
1415
        }
1416
    }
1417

1418
    public getStatementsByName(name: string, originFile: BrsFile, namespaceName?: string): FileLink<Statement>[] {
1419
        let results = new Map<Statement, FileLink<Statement>>();
39✔
1420
        const filesSearched = new Set<BrsFile>();
39✔
1421
        let lowerNamespaceName = namespaceName?.toLowerCase();
39✔
1422
        let lowerName = name?.toLowerCase();
39!
1423

1424
        function addToResults(statement: FunctionStatement | MethodStatement, file: BrsFile) {
1425
            let parentNamespaceName = statement.findAncestor<NamespaceStatement>(isNamespaceStatement)?.getName(originFile.parseMode)?.toLowerCase();
98✔
1426
            if (statement.tokens.name.text.toLowerCase() === lowerName && (!lowerNamespaceName || parentNamespaceName === lowerNamespaceName)) {
98✔
1427
                if (!results.has(statement)) {
36!
1428
                    results.set(statement, { item: statement, file: file as BrsFile });
36✔
1429
                }
1430
            }
1431
        }
1432

1433
        //look through all files in scope for matches
1434
        for (const scope of this.getScopesForFile(originFile)) {
39✔
1435
            for (const file of scope.getAllFiles()) {
39✔
1436
                //skip non-brs files, or files we've already processed
1437
                if (!isBrsFile(file) || filesSearched.has(file)) {
45✔
1438
                    continue;
3✔
1439
                }
1440
                filesSearched.add(file);
42✔
1441

1442
                file.ast.walk(createVisitor({
42✔
1443
                    FunctionStatement: (statement: FunctionStatement) => {
1444
                        addToResults(statement, file);
95✔
1445
                    },
1446
                    MethodStatement: (statement: MethodStatement) => {
1447
                        addToResults(statement, file);
3✔
1448
                    }
1449
                }), {
1450
                    walkMode: WalkMode.visitStatements
1451
                });
1452
            }
1453
        }
1454
        return [...results.values()];
39✔
1455
    }
1456

1457
    public getStatementsForXmlFile(scope: XmlScope, filterName?: string): FileLink<FunctionStatement>[] {
1458
        let results = new Map<Statement, FileLink<FunctionStatement>>();
14✔
1459
        const filesSearched = new Set<BrsFile>();
14✔
1460

1461
        //get all function names for the xml file and parents
1462
        let funcNames = new Set<string>();
14✔
1463
        let currentScope = scope;
14✔
1464
        while (isXmlScope(currentScope)) {
14✔
1465
            for (let name of currentScope.xmlFile.ast.componentElement.interfaceElement?.functions.map((f) => f.name) ?? []) {
20✔
1466
                if (!filterName || name === filterName) {
20!
1467
                    funcNames.add(name);
20✔
1468
                }
1469
            }
1470
            currentScope = currentScope.getParentScope() as XmlScope;
16✔
1471
        }
1472

1473
        //look through all files in scope for matches
1474
        for (const file of scope.getOwnFiles()) {
14✔
1475
            //skip non-brs files, or files we've already processed
1476
            if (!isBrsFile(file) || filesSearched.has(file)) {
28✔
1477
                continue;
14✔
1478
            }
1479
            filesSearched.add(file);
14✔
1480

1481
            file.ast.walk(createVisitor({
14✔
1482
                FunctionStatement: (statement: FunctionStatement) => {
1483
                    if (funcNames.has(statement.tokens.name.text)) {
19!
1484
                        if (!results.has(statement)) {
19!
1485
                            results.set(statement, { item: statement, file: file });
19✔
1486
                        }
1487
                    }
1488
                }
1489
            }), {
1490
                walkMode: WalkMode.visitStatements
1491
            });
1492
        }
1493
        return [...results.values()];
14✔
1494
    }
1495

1496
    /**
1497
     * Find all available completion items at the given position
1498
     * @param filePath can be a srcPath or a destPath
1499
     * @param position the position (line & column) where completions should be found
1500
     */
1501
    public getCompletions(filePath: string, position: Position) {
1502
        let file = this.getFile(filePath);
123✔
1503
        if (!file) {
123!
UNCOV
1504
            return [];
×
1505
        }
1506

1507
        //find the scopes for this file
1508
        let scopes = this.getScopesForFile(file);
123✔
1509

1510
        //if there are no scopes, include the global scope so we at least get the built-in functions
1511
        scopes = scopes.length > 0 ? scopes : [this.globalScope];
123!
1512

1513
        const event: ProvideCompletionsEvent = {
123✔
1514
            program: this,
1515
            file: file,
1516
            scopes: scopes,
1517
            position: position,
1518
            completions: []
1519
        };
1520

1521
        this.plugins.emit('beforeProvideCompletions', event);
123✔
1522

1523
        this.plugins.emit('provideCompletions', event);
123✔
1524

1525
        this.plugins.emit('afterProvideCompletions', event);
123✔
1526

1527
        return event.completions;
123✔
1528
    }
1529

1530
    /**
1531
     * Goes through each file and builds a list of workspace symbols for the program. Used by LanguageServer's onWorkspaceSymbol functionality
1532
     */
1533
    public getWorkspaceSymbols() {
1534
        const event: ProvideWorkspaceSymbolsEvent = {
22✔
1535
            program: this,
1536
            workspaceSymbols: []
1537
        };
1538
        this.plugins.emit('beforeProvideWorkspaceSymbols', event);
22✔
1539
        this.plugins.emit('provideWorkspaceSymbols', event);
22✔
1540
        this.plugins.emit('afterProvideWorkspaceSymbols', event);
22✔
1541
        return event.workspaceSymbols;
22✔
1542
    }
1543

1544
    /**
1545
     * Given a position in a file, if the position is sitting on some type of identifier,
1546
     * go to the definition of that identifier (where this thing was first defined)
1547
     */
1548
    public getDefinition(srcPath: string, position: Position): Location[] {
1549
        let file = this.getFile(srcPath);
18✔
1550
        if (!file) {
18!
UNCOV
1551
            return [];
×
1552
        }
1553

1554
        const event: ProvideDefinitionEvent = {
18✔
1555
            program: this,
1556
            file: file,
1557
            position: position,
1558
            definitions: []
1559
        };
1560

1561
        this.plugins.emit('beforeProvideDefinition', event);
18✔
1562
        this.plugins.emit('provideDefinition', event);
18✔
1563
        this.plugins.emit('afterProvideDefinition', event);
18✔
1564
        return event.definitions;
18✔
1565
    }
1566

1567
    /**
1568
     * Get hover information for a file and position
1569
     */
1570
    public getHover(srcPath: string, position: Position): Hover[] {
1571
        let file = this.getFile(srcPath);
69✔
1572
        let result: Hover[];
1573
        if (file) {
69!
1574
            const event = {
69✔
1575
                program: this,
1576
                file: file,
1577
                position: position,
1578
                scopes: this.getScopesForFile(file),
1579
                hovers: []
1580
            } as ProvideHoverEvent;
1581
            this.plugins.emit('beforeProvideHover', event);
69✔
1582
            this.plugins.emit('provideHover', event);
69✔
1583
            this.plugins.emit('afterProvideHover', event);
69✔
1584
            result = event.hovers;
69✔
1585
        }
1586

1587
        return result ?? [];
69!
1588
    }
1589

1590
    /**
1591
     * Get full list of document symbols for a file
1592
     * @param srcPath path to the file
1593
     */
1594
    public getDocumentSymbols(srcPath: string): DocumentSymbol[] | undefined {
1595
        let file = this.getFile(srcPath);
24✔
1596
        if (file) {
24!
1597
            const event: ProvideDocumentSymbolsEvent = {
24✔
1598
                program: this,
1599
                file: file,
1600
                documentSymbols: []
1601
            };
1602
            this.plugins.emit('beforeProvideDocumentSymbols', event);
24✔
1603
            this.plugins.emit('provideDocumentSymbols', event);
24✔
1604
            this.plugins.emit('afterProvideDocumentSymbols', event);
24✔
1605
            return event.documentSymbols;
24✔
1606
        } else {
UNCOV
1607
            return undefined;
×
1608
        }
1609
    }
1610

1611
    /**
1612
     * Compute code actions for the given file and range
1613
     */
1614
    public getCodeActions(srcPath: string, range: Range) {
1615
        const codeActions = [] as CodeAction[];
12✔
1616
        const file = this.getFile(srcPath);
12✔
1617
        if (file) {
12✔
1618
            const fileUri = util.pathToUri(file?.srcPath);
11!
1619
            const diagnostics = this
11✔
1620
                //get all current diagnostics (filtered by diagnostic filters)
1621
                .getDiagnostics()
1622
                //only keep diagnostics related to this file
1623
                .filter(x => x.location?.uri === fileUri)
21!
1624
                //only keep diagnostics that touch this range
1625
                .filter(x => util.rangesIntersectOrTouch(x.location.range, range));
12✔
1626

1627
            const scopes = this.getScopesForFile(file);
11✔
1628

1629
            this.plugins.emit('onGetCodeActions', {
11✔
1630
                program: this,
1631
                file: file,
1632
                range: range,
1633
                diagnostics: diagnostics,
1634
                scopes: scopes,
1635
                codeActions: codeActions
1636
            });
1637
        }
1638
        return codeActions;
12✔
1639
    }
1640

1641
    /**
1642
     * Get semantic tokens for the specified file
1643
     */
1644
    public getSemanticTokens(srcPath: string): SemanticToken[] | undefined {
1645
        const file = this.getFile(srcPath);
24✔
1646
        if (file) {
24!
1647
            const result = [] as SemanticToken[];
24✔
1648
            this.plugins.emit('onGetSemanticTokens', {
24✔
1649
                program: this,
1650
                file: file,
1651
                scopes: this.getScopesForFile(file),
1652
                semanticTokens: result
1653
            });
1654
            return result;
24✔
1655
        }
1656
    }
1657

1658
    public getSignatureHelp(filepath: string, position: Position): SignatureInfoObj[] {
1659
        let file: BrsFile = this.getFile(filepath);
185✔
1660
        if (!file || !isBrsFile(file)) {
185✔
1661
            return [];
3✔
1662
        }
1663
        let callExpressionInfo = new CallExpressionInfo(file, position);
182✔
1664
        let signatureHelpUtil = new SignatureHelpUtil();
182✔
1665
        return signatureHelpUtil.getSignatureHelpItems(callExpressionInfo);
182✔
1666
    }
1667

1668
    public getReferences(srcPath: string, position: Position): Location[] {
1669
        //find the file
1670
        let file = this.getFile(srcPath);
4✔
1671

1672
        const event: ProvideReferencesEvent = {
4✔
1673
            program: this,
1674
            file: file,
1675
            position: position,
1676
            references: []
1677
        };
1678

1679
        this.plugins.emit('beforeProvideReferences', event);
4✔
1680
        this.plugins.emit('provideReferences', event);
4✔
1681
        this.plugins.emit('afterProvideReferences', event);
4✔
1682

1683
        return event.references;
4✔
1684
    }
1685

1686
    /**
1687
     * Transpile a single file and get the result as a string.
1688
     * This does not write anything to the file system.
1689
     *
1690
     * This should only be called by `LanguageServer`.
1691
     * Internal usage should call `_getTranspiledFileContents` instead.
1692
     * @param filePath can be a srcPath or a destPath
1693
     */
1694
    public async getTranspiledFileContents(filePath: string): Promise<FileTranspileResult> {
1695
        const file = this.getFile(filePath);
319✔
1696

1697
        return this.getTranspiledFileContentsPipeline.run(async () => {
319✔
1698

1699
            const result = {
319✔
1700
                destPath: file.destPath,
1701
                pkgPath: file.pkgPath,
1702
                srcPath: file.srcPath
1703
            } as FileTranspileResult;
1704

1705
            const expectedPkgPath = file.pkgPath.toLowerCase();
319✔
1706
            const expectedMapPath = `${expectedPkgPath}.map`;
319✔
1707
            const expectedTypedefPkgPath = expectedPkgPath.replace(/\.brs$/i, '.d.bs');
319✔
1708

1709
            //add a temporary plugin to tap into the file writing process
1710
            const plugin = this.plugins.addFirst({
319✔
1711
                name: 'getTranspiledFileContents',
1712
                beforeWriteFile: (event) => {
1713
                    const pkgPath = event.file.pkgPath.toLowerCase();
994✔
1714
                    switch (pkgPath) {
994✔
1715
                        //this is the actual transpiled file
1716
                        case expectedPkgPath:
994✔
1717
                            result.code = event.file.data.toString();
319✔
1718
                            break;
319✔
1719
                        //this is the sourcemap
1720
                        case expectedMapPath:
1721
                            result.map = event.file.data.toString();
170✔
1722
                            break;
170✔
1723
                        //this is the typedef
1724
                        case expectedTypedefPkgPath:
1725
                            result.typedef = event.file.data.toString();
8✔
1726
                            break;
8✔
1727
                        default:
1728
                        //no idea what this file is. just ignore it
1729
                    }
1730
                    //mark every file as processed so it they don't get written to the output directory
1731
                    event.processedFiles.add(event.file);
994✔
1732
                }
1733
            });
1734

1735
            try {
319✔
1736
                //now that the plugin has been registered, run the build with just this file
1737
                await this.build({
319✔
1738
                    files: [file]
1739
                });
1740
            } finally {
1741
                this.plugins.remove(plugin);
319✔
1742
            }
1743
            return result;
319✔
1744
        });
1745
    }
1746
    private getTranspiledFileContentsPipeline = new ActionPipeline();
1,938✔
1747

1748
    /**
1749
     * Get the absolute output path for a file
1750
     */
1751
    private getOutputPath(file: { pkgPath?: string }, stagingDir = this.getStagingDir()) {
×
1752
        return s`${stagingDir}/${file.pkgPath}`;
1,835✔
1753
    }
1754

1755
    private getStagingDir(stagingDir?: string) {
1756
        let result = stagingDir ?? this.options.stagingDir ?? this.options.stagingDir;
719✔
1757
        if (!result) {
719✔
1758
            result = rokuDeploy.getOptions(this.options as any).stagingDir;
531✔
1759
        }
1760
        result = s`${path.resolve(this.options.cwd ?? process.cwd(), result ?? '/')}`;
719!
1761
        return result;
719✔
1762
    }
1763

1764
    /**
1765
     * Prepare the program for building
1766
     * @param files the list of files that should be prepared
1767
     */
1768
    private async prepare(files: BscFile[]) {
1769
        const programEvent: PrepareProgramEvent = {
360✔
1770
            program: this,
1771
            editor: this.editor,
1772
            files: files
1773
        };
1774

1775
        //assign an editor to every file
1776
        for (const file of programEvent.files) {
360✔
1777
            //if the file doesn't have an editor yet, assign one now
1778
            if (!file.editor) {
730✔
1779
                file.editor = new Editor();
683✔
1780
            }
1781
        }
1782

1783
        //sort the entries to make transpiling more deterministic
1784
        programEvent.files.sort((a, b) => {
360✔
1785
            if (a.pkgPath < b.pkgPath) {
386✔
1786
                return -1;
324✔
1787
            } else if (a.pkgPath > b.pkgPath) {
62!
1788
                return 1;
62✔
1789
            } else {
UNCOV
1790
                return 1;
×
1791
            }
1792
        });
1793

1794
        await this.plugins.emitAsync('beforePrepareProgram', programEvent);
360✔
1795
        await this.plugins.emitAsync('prepareProgram', programEvent);
360✔
1796

1797
        const stagingDir = this.getStagingDir();
360✔
1798

1799
        const entries: TranspileObj[] = [];
360✔
1800

1801
        for (const file of files) {
360✔
1802
            const scope = this.getFirstScopeForFile(file);
730✔
1803
            //link the symbol table for all the files in this scope
1804
            scope?.linkSymbolTable();
730✔
1805

1806
            //if the file doesn't have an editor yet, assign one now
1807
            if (!file.editor) {
730!
UNCOV
1808
                file.editor = new Editor();
×
1809
            }
1810
            const event = {
730✔
1811
                program: this,
1812
                file: file,
1813
                editor: file.editor,
1814
                scope: scope,
1815
                outputPath: this.getOutputPath(file, stagingDir)
1816
            } as PrepareFileEvent & { outputPath: string };
1817

1818
            await this.plugins.emitAsync('beforePrepareFile', event);
730✔
1819
            await this.plugins.emitAsync('prepareFile', event);
730✔
1820
            await this.plugins.emitAsync('afterPrepareFile', event);
730✔
1821

1822
            //TODO remove this in v1
1823
            entries.push(event);
730✔
1824

1825
            //unlink the symbolTable so the next loop iteration can link theirs
1826
            scope?.unlinkSymbolTable();
730✔
1827
        }
1828

1829
        await this.plugins.emitAsync('afterPrepareProgram', programEvent);
360✔
1830
        return files;
360✔
1831
    }
1832

1833
    /**
1834
     * Generate the contents of every file
1835
     */
1836
    private async serialize(files: BscFile[]) {
1837

1838
        const allFiles = new Map<BscFile, SerializedFile[]>();
359✔
1839

1840
        //exclude prunable files if that option is enabled
1841
        if (this.options.pruneEmptyCodeFiles === true) {
359✔
1842
            files = files.filter(x => x.canBePruned !== true);
9✔
1843
        }
1844

1845
        const serializeProgramEvent = await this.plugins.emitAsync('beforeSerializeProgram', {
359✔
1846
            program: this,
1847
            files: files,
1848
            result: allFiles
1849
        });
1850
        await this.plugins.emitAsync('onSerializeProgram', serializeProgramEvent);
359✔
1851

1852
        // serialize each file
1853
        for (const file of files) {
359✔
1854
            let scope = this.getFirstScopeForFile(file);
727✔
1855

1856
            //if the file doesn't have a scope, create a temporary scope for the file so it can depend on scope-level items
1857
            if (!scope) {
727✔
1858
                scope = new Scope(`temporary-for-${file.pkgPath}`, this);
370✔
1859
                scope.getAllFiles = () => [file];
3,317✔
1860
                scope.getOwnFiles = scope.getAllFiles;
370✔
1861
            }
1862

1863
            //link the symbol table for all the files in this scope
1864
            scope?.linkSymbolTable();
727!
1865
            const event: SerializeFileEvent = {
727✔
1866
                program: this,
1867
                file: file,
1868
                scope: scope,
1869
                result: allFiles
1870
            };
1871
            await this.plugins.emitAsync('beforeSerializeFile', event);
727✔
1872
            await this.plugins.emitAsync('serializeFile', event);
727✔
1873
            await this.plugins.emitAsync('afterSerializeFile', event);
727✔
1874
            //unlink the symbolTable so the next loop iteration can link theirs
1875
            scope?.unlinkSymbolTable();
727!
1876
        }
1877

1878
        this.plugins.emit('afterSerializeProgram', serializeProgramEvent);
359✔
1879

1880
        return allFiles;
359✔
1881
    }
1882

1883
    /**
1884
     * Write the entire project to disk
1885
     */
1886
    private async write(stagingDir: string, files: Map<BscFile, SerializedFile[]>) {
1887
        const programEvent = await this.plugins.emitAsync('beforeWriteProgram', {
359✔
1888
            program: this,
1889
            files: files,
1890
            stagingDir: stagingDir
1891
        });
1892
        //empty the staging directory
1893
        await fsExtra.emptyDir(stagingDir);
359✔
1894

1895
        const serializedFiles = [...files]
359✔
1896
            .map(([, serializedFiles]) => serializedFiles)
727✔
1897
            .flat();
1898

1899
        //write all the files to disk (asynchronously)
1900
        await Promise.all(
359✔
1901
            serializedFiles.map(async (file) => {
1902
                const event = await this.plugins.emitAsync('beforeWriteFile', {
1,105✔
1903
                    program: this,
1904
                    file: file,
1905
                    outputPath: this.getOutputPath(file, stagingDir),
1906
                    processedFiles: new Set<SerializedFile>()
1907
                });
1908

1909
                await this.plugins.emitAsync('writeFile', event);
1,105✔
1910

1911
                await this.plugins.emitAsync('afterWriteFile', event);
1,105✔
1912
            })
1913
        );
1914

1915
        await this.plugins.emitAsync('afterWriteProgram', programEvent);
359✔
1916
    }
1917

1918
    private buildPipeline = new ActionPipeline();
1,938✔
1919

1920
    /**
1921
     * Build the project. This transpiles/transforms/copies all files and moves them to the staging directory
1922
     * @param options the list of options used to build the program
1923
     */
1924
    public async build(options?: ProgramBuildOptions) {
1925
        //run a single build at a time
1926
        await this.buildPipeline.run(async () => {
359✔
1927
            const stagingDir = this.getStagingDir(options?.stagingDir);
359✔
1928

1929
            const event = await this.plugins.emitAsync('beforeBuildProgram', {
359✔
1930
                program: this,
1931
                editor: this.editor,
1932
                files: options?.files ?? Object.values(this.files)
2,154✔
1933
            });
1934

1935
            //prepare the program (and files) for building
1936
            event.files = await this.prepare(event.files);
359✔
1937

1938
            //stage the entire program
1939
            const serializedFilesByFile = await this.serialize(event.files);
359✔
1940

1941
            await this.write(stagingDir, serializedFilesByFile);
359✔
1942

1943
            await this.plugins.emitAsync('afterBuildProgram', event);
359✔
1944

1945
            //undo all edits for the program
1946
            this.editor.undoAll();
359✔
1947
            //undo all edits for each file
1948
            for (const file of event.files) {
359✔
1949
                file.editor.undoAll();
728✔
1950
            }
1951
        });
1952

1953
        console.log('TYPES CREATED', TypesCreated);
359✔
1954
        let totalTypesCreated = 0;
359✔
1955
        for (const key in TypesCreated) {
359✔
1956
            if (TypesCreated.hasOwnProperty(key)) {
9,326!
1957
                totalTypesCreated += TypesCreated[key];
9,326✔
1958

1959
            }
1960
        }
1961
        console.log('TOTAL TYPES CREATED', totalTypesCreated);
359✔
1962
    }
1963

1964
    /**
1965
     * Find a list of files in the program that have a function with the given name (case INsensitive)
1966
     */
1967
    public findFilesForFunction(functionName: string) {
1968
        const files = [] as BscFile[];
7✔
1969
        const lowerFunctionName = functionName.toLowerCase();
7✔
1970
        //find every file with this function defined
1971
        for (const file of Object.values(this.files)) {
7✔
1972
            if (isBrsFile(file)) {
25✔
1973
                //TODO handle namespace-relative function calls
1974
                //if the file has a function with this name
1975
                // eslint-disable-next-line @typescript-eslint/dot-notation
1976
                if (file['_cachedLookups'].functionStatementMap.get(lowerFunctionName)) {
17✔
1977
                    files.push(file);
2✔
1978
                }
1979
            }
1980
        }
1981
        return files;
7✔
1982
    }
1983

1984
    /**
1985
     * Find a list of files in the program that have a class with the given name (case INsensitive)
1986
     */
1987
    public findFilesForClass(className: string) {
1988
        const files = [] as BscFile[];
7✔
1989
        const lowerClassName = className.toLowerCase();
7✔
1990
        //find every file with this class defined
1991
        for (const file of Object.values(this.files)) {
7✔
1992
            if (isBrsFile(file)) {
25✔
1993
                //TODO handle namespace-relative classes
1994
                //if the file has a function with this name
1995

1996
                // eslint-disable-next-line @typescript-eslint/dot-notation
1997
                if (file['_cachedLookups'].classStatementMap.get(lowerClassName) !== undefined) {
17✔
1998
                    files.push(file);
1✔
1999
                }
2000
            }
2001
        }
2002
        return files;
7✔
2003
    }
2004

2005
    public findFilesForNamespace(name: string) {
2006
        const files = [] as BscFile[];
7✔
2007
        const lowerName = name.toLowerCase();
7✔
2008
        //find every file with this class defined
2009
        for (const file of Object.values(this.files)) {
7✔
2010
            if (isBrsFile(file)) {
25✔
2011

2012
                // eslint-disable-next-line @typescript-eslint/dot-notation
2013
                if (file['_cachedLookups'].namespaceStatements.find((x) => {
17✔
2014
                    const namespaceName = x.name.toLowerCase();
7✔
2015
                    return (
7✔
2016
                        //the namespace name matches exactly
2017
                        namespaceName === lowerName ||
9✔
2018
                        //the full namespace starts with the name (honoring the part boundary)
2019
                        namespaceName.startsWith(lowerName + '.')
2020
                    );
2021
                })) {
2022
                    files.push(file);
6✔
2023
                }
2024
            }
2025
        }
2026

2027
        return files;
7✔
2028
    }
2029

2030
    public findFilesForEnum(name: string) {
2031
        const files = [] as BscFile[];
8✔
2032
        const lowerName = name.toLowerCase();
8✔
2033
        //find every file with this enum defined
2034
        for (const file of Object.values(this.files)) {
8✔
2035
            if (isBrsFile(file)) {
26✔
2036
                // eslint-disable-next-line @typescript-eslint/dot-notation
2037
                if (file['_cachedLookups'].enumStatementMap.get(lowerName)) {
18✔
2038
                    files.push(file);
1✔
2039
                }
2040
            }
2041
        }
2042
        return files;
8✔
2043
    }
2044

2045
    private _manifest: Map<string, string>;
2046

2047
    /**
2048
     * Modify a parsed manifest map by reading `bs_const` and injecting values from `options.manifest.bs_const`
2049
     * @param parsedManifest The manifest map to read from and modify
2050
     */
2051
    private buildBsConstsIntoParsedManifest(parsedManifest: Map<string, string>) {
2052
        // Lift the bs_consts defined in the manifest
2053
        let bsConsts = getBsConst(parsedManifest, false);
17✔
2054

2055
        // Override or delete any bs_consts defined in the bs config
2056
        for (const key in this.options?.manifest?.bs_const) {
17!
2057
            const value = this.options.manifest.bs_const[key];
3✔
2058
            if (value === null) {
3✔
2059
                bsConsts.delete(key);
1✔
2060
            } else {
2061
                bsConsts.set(key, value);
2✔
2062
            }
2063
        }
2064

2065
        // convert the new list of bs consts back into a string for the rest of the down stream systems to use
2066
        let constString = '';
17✔
2067
        for (const [key, value] of bsConsts) {
17✔
2068
            constString += `${constString !== '' ? ';' : ''}${key}=${value.toString()}`;
8✔
2069
        }
2070

2071
        // Set the updated bs_const value
2072
        parsedManifest.set('bs_const', constString);
17✔
2073
    }
2074

2075
    /**
2076
     * Try to find and load the manifest into memory
2077
     * @param manifestFileObj A pointer to a potential manifest file object found during loading
2078
     * @param replaceIfAlreadyLoaded should we overwrite the internal `_manifest` if it already exists
2079
     */
2080
    public loadManifest(manifestFileObj?: FileObj, replaceIfAlreadyLoaded = true) {
1,573✔
2081
        //if we already have a manifest instance, and should not replace...then don't replace
2082
        if (!replaceIfAlreadyLoaded && this._manifest) {
1,581!
UNCOV
2083
            return;
×
2084
        }
2085
        let manifestPath = manifestFileObj
1,581✔
2086
            ? manifestFileObj.src
1,581✔
2087
            : path.join(this.options.rootDir, 'manifest');
2088

2089
        try {
1,581✔
2090
            // we only load this manifest once, so do it sync to improve speed downstream
2091
            const contents = fsExtra.readFileSync(manifestPath, 'utf-8');
1,581✔
2092
            const parsedManifest = parseManifest(contents);
17✔
2093
            this.buildBsConstsIntoParsedManifest(parsedManifest);
17✔
2094
            this._manifest = parsedManifest;
17✔
2095
        } catch (e) {
2096
            this._manifest = new Map();
1,564✔
2097
        }
2098
    }
2099

2100
    /**
2101
     * Get a map of the manifest information
2102
     */
2103
    public getManifest() {
2104
        if (!this._manifest) {
2,525✔
2105
            this.loadManifest();
1,572✔
2106
        }
2107
        return this._manifest;
2,525✔
2108
    }
2109

2110
    public dispose() {
2111
        this.plugins.emit('beforeProgramDispose', { program: this });
1,812✔
2112

2113
        for (let filePath in this.files) {
1,812✔
2114
            this.files[filePath]?.dispose?.();
2,299!
2115
        }
2116
        for (let name in this.scopes) {
1,812✔
2117
            this.scopes[name]?.dispose?.();
3,817!
2118
        }
2119
        this.globalScope?.dispose?.();
1,812!
2120
        this.dependencyGraph?.dispose?.();
1,812!
2121
    }
2122
}
2123

2124
export interface FileTranspileResult {
2125
    srcPath: string;
2126
    destPath: string;
2127
    pkgPath: string;
2128
    code: string;
2129
    map: string;
2130
    typedef: string;
2131
}
2132

2133

2134
class ProvideFileEventInternal<TFile extends BscFile = BscFile> implements ProvideFileEvent<TFile> {
2135
    constructor(
2136
        public program: Program,
2,610✔
2137
        public srcPath: string,
2,610✔
2138
        public destPath: string,
2,610✔
2139
        public data: LazyFileData,
2,610✔
2140
        public fileFactory: FileFactory
2,610✔
2141
    ) {
2142
        this.srcExtension = path.extname(srcPath)?.toLowerCase();
2,610!
2143
    }
2144

2145
    public srcExtension: string;
2146

2147
    public files: TFile[] = [];
2,610✔
2148
}
2149

2150
export interface ProgramBuildOptions {
2151
    /**
2152
     * The directory where the final built files should be placed. This directory will be cleared before running
2153
     */
2154
    stagingDir?: string;
2155
    /**
2156
     * An array of files to build. If omitted, the entire list of files from the program will be used instead.
2157
     * Typically you will want to leave this blank
2158
     */
2159
    files?: BscFile[];
2160
}
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