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

rokucommunity / brighterscript / #14176

10 Apr 2025 04:25PM UTC coverage: 87.117% (-2.0%) from 89.104%
#14176

push

web-flow
Merge 2bd224618 into 2b6cc17a0

13313 of 16151 branches covered (82.43%)

Branch coverage included in aggregate %.

7993 of 8671 new or added lines in 102 files covered. (92.18%)

84 existing lines in 22 files now uncovered.

14385 of 15643 relevant lines covered (91.96%)

19746.54 hits per line

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

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

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

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

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

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

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

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

97
        this.createGlobalScope();
1,958✔
98

99
        this.fileFactory = new FileFactory(this);
1,958✔
100
    }
101

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

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

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

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

121
        this.populateGlobalSymbolTable();
1,958✔
122
        this.globalScope.symbolTable.addSibling(this.componentsTable);
1,958✔
123

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

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

133

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

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

170
        const builtInSymbolData: ExtraSymbolData = { isBuiltIn: true };
1,958✔
171

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

183
        BuiltInInterfaceAdder.getLookupTable = () => this.globalScope.symbolTable;
571,912✔
184

185
        for (const callable of globalCallables) {
1,958✔
186
            this.globalScope.symbolTable.addSymbol(callable.name, { ...builtInSymbolData, description: callable.shortDescription }, callable.type, SymbolTypeFlag.runtime);
152,724✔
187
        }
188

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

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

206
        for (const nodeData of Object.values(nodes) as SGNodeData[]) {
1,958✔
207
            this.recursivelyAddNodeToSymbolTable(nodeData);
187,968✔
208
        }
209

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

217
    }
218

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

227
    public diagnostics: DiagnosticManager;
228

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

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

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

242
    private currentScopeValidationOptions: ScopeValidationOptions;
243

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

249

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

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

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

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

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

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

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

295

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

583
        this.plugins.emit('beforeFileAdd', fileAddEvent);
2,636✔
584

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

588
        this.plugins.emit('afterFileAdd', fileAddEvent);
2,636✔
589

590
        return file;
2,636✔
591
    }
592

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

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

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

625
            const data = new LazyFileData(fileData);
2,632✔
626

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

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

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

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

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

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

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

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

674
                this.assignFile(file);
2,636✔
675

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

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

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

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

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

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

710
            return primaryFile;
2,632✔
711
        });
712
        return file as T;
2,632✔
713
    }
714

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

724
        assert.ok(fileParam, 'fileParam is required');
2,853✔
725

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

897
    public crossScopeValidation = new CrossScopeValidator(this);
1,958✔
898

899
    private isFirstValidation = true;
1,958✔
900

901
    private validationDetails: {
1,958✔
902
        brsFilesValidated: BrsFile[];
903
        xmlFilesValidated: XmlFile[];
904
        changedSymbols: Map<SymbolTypeFlag, Set<string>>;
905
        changedComponentTypes: string[];
906
        scopesToValidate: Scope[];
907
        filesToBeValidatedInScopeContext: Set<BscFile>;
908

909
    } = {
910
            brsFilesValidated: [],
911
            xmlFilesValidated: [],
912
            changedSymbols: new Map<SymbolTypeFlag, Set<string>>(),
913
            changedComponentTypes: [],
914
            scopesToValidate: [],
915
            filesToBeValidatedInScopeContext: new Set<BscFile>()
916
        };
917

918
    /**
919
     * Counter used to track which validation run is being logged
920
     */
921
    private validationRunSequence = 1;
1,958✔
922

923
    /**
924
     * How many milliseconds can pass while doing synchronous operations in validate before we register a short timeout (i.e. yield to the event loop)
925
     */
926
    private validationMinSyncDuration = 75;
1,958✔
927

928
    private validatePromise: Promise<void> | undefined;
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,523✔
938

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

942
        if (options?.async) {
1,523✔
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,396!
950
            throw new Error('Cannot run synchronous validation while an async validation is in progress');
×
951
        }
952

953
        let beforeProgramValidateWasEmitted = false;
1,523✔
954

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

962
        //validate every file
963

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

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

969
        const sequencer = new Sequencer({
1,523✔
970
            name: 'program.validate',
971
            cancellationToken: options?.cancellationToken ?? new CancellationTokenSource().token,
9,138✔
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,523✔
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,523✔
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,520!
985
                this.diagnostics.clearForTag(ProgramValidatorDiagnosticsTag);
1,520✔
986
                this.plugins.emit('beforeProgramValidate', {
1,520✔
987
                    program: this
988
                });
989
                beforeProgramValidateWasEmitted = true;
1,520✔
990
                this.plugins.emit('onProgramValidate', {
1,520✔
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,274✔
998
                    for (const file of filesToProcess) {
1,520✔
999
                        filesToBeValidatedInScopeContext.add(file);
2,200✔
1000
                    }
1001

1002
                    //return the list of files that need to be processed
1003
                    return filesToProcess;
1,520✔
1004
                }, (file) => {
1005
                    // cast a wide net for potential changes in components
1006
                    if (isXmlFile(file)) {
2,199✔
1007
                        this.addDeferredComponentTypeSymbolCreation(file);
393✔
1008
                    } else if (isBrsFile(file)) {
1,806!
1009
                        for (const scope of this.getScopesForFile(file)) {
1,806✔
1010
                            if (isXmlScope(scope)) {
2,082✔
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,517✔
1020
                    this.addComponentReferenceType(componentKey, componentName);
530✔
1021
                }
1022
            })
1023
            .forEach('beforeFileValidate', () => filesToProcess, (file) => {
1,517✔
1024
                //run the beforeFilevalidate event for every unvalidated file
1025
                this.plugins.emit('beforeFileValidate', {
2,199✔
1026
                    program: this,
1027
                    file: file
1028
                });
1029
            })
1030
            .forEach('onFileValidate', () => filesToProcess, (file) => {
1,517✔
1031
                //run the onFileValidate event for every unvalidated file
1032
                this.plugins.emit('onFileValidate', {
2,199✔
1033
                    program: this,
1034
                    file: file
1035
                });
1036
                file.isValidated = true;
2,199✔
1037
                if (isBrsFile(file)) {
2,199✔
1038
                    brsFilesValidated.push(file);
1,806✔
1039
                } else if (isXmlFile(file)) {
393!
1040
                    xmlFilesValidated.push(file);
393✔
1041
                }
1042
            })
1043
            .forEach('afterFileValidate', () => filesToProcess, (file) => {
1,517✔
1044
                //run the onFileValidate event for every unvalidated file
1045
                this.plugins.emit('afterFileValidate', {
2,199✔
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,516✔
1052
                    for (let [componentKey, componentName] of this.componentSymbolsToUpdate.entries()) {
1,516✔
1053
                        if (this.updateComponentSymbolInGlobalScope(componentKey, componentName)) {
530✔
1054
                            changedComponentTypes.push(util.getSgNodeTypeName(componentName).toLowerCase());
384✔
1055
                        }
1056
                    }
1057
                    this.componentSymbolsToUpdate.clear();
1,516✔
1058
                });
1059
            })
1060
            .once('track and update type-time and runtime symbol dependencies and changes', () => {
1061
                const changedSymbolsMapArr = [...brsFilesValidated, ...xmlFilesValidated]?.map(f => {
1,516!
1062
                    if (isBrsFile(f)) {
2,199✔
1063
                        return f.providedSymbols.changes;
1,806✔
1064
                    }
1065
                    return null;
393✔
1066
                }).filter(x => x);
2,199✔
1067

1068
                // update the map of typetime dependencies
1069
                for (const file of brsFilesValidated) {
1,516✔
1070
                    for (const [symbolName, provided] of file.providedSymbols.symbolMap.get(SymbolTypeFlag.typetime).entries()) {
1,806✔
1071
                        // clear existing dependencies
1072
                        for (const values of this.symbolDependencies.values()) {
674✔
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() ?? []) {
674!
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,516✔
1089
                    const changedSymbolsSetArr = changedSymbolsMapArr.map(symMap => symMap.get(flag));
3,612✔
1090
                    const changedSymbolSet = new Set<string>();
3,032✔
1091
                    for (const changeSet of changedSymbolsSetArr) {
3,032✔
1092
                        for (const change of changeSet) {
3,612✔
1093
                            changedSymbolSet.add(change);
3,588✔
1094
                        }
1095
                    }
1096
                    if (!changedSymbols.has(flag)) {
3,032✔
1097
                        changedSymbols.set(flag, changedSymbolSet);
3,028✔
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,516✔
1105
                    changedSymbols.get(SymbolTypeFlag.typetime).add(changedComponentType);
384✔
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,516✔
1111
                let foundDependentTypes = false;
1,516✔
1112
                const changedTypeSymbols = changedSymbols.get(SymbolTypeFlag.typetime);
1,516✔
1113
                do {
1,516✔
1114
                    foundDependentTypes = false;
1,522✔
1115
                    const allChangedTypesSofar = [...Array.from(changedTypeSymbols), ...Array.from(dependentTypesChanged)];
1,522✔
1116
                    for (const changedSymbol of allChangedTypesSofar) {
1,522✔
1117
                        const symbolsDependentUponChangedSymbol = this.symbolDependencies.get(changedSymbol) ?? [];
1,061✔
1118
                        for (const symbolName of symbolsDependentUponChangedSymbol) {
1,061✔
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,516✔
1128

1129
                // can reset filesValidatedList, because they are no longer needed
1130
                this.validationDetails.brsFilesValidated = [];
1,516✔
1131
                this.validationDetails.xmlFilesValidated = [];
1,516✔
1132
            })
1133
            .once('tracks changed symbols and prepares files and scopes for validation.', () => {
1134
                if (this.options.logLevel === LogLevel.debug) {
1,516!
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,516✔
1142
                this.crossScopeValidation.buildComponentsMap();
1,516✔
1143
                this.crossScopeValidation.addDiagnosticsForScopes(scopesToCheck);
1,516✔
1144
                const filesToRevalidate = this.crossScopeValidation.getFilesRequiringChangedSymbol(scopesToCheck, changedSymbols);
1,516✔
1145
                for (const file of filesToRevalidate) {
1,516✔
1146
                    filesToBeValidatedInScopeContext.add(file);
420✔
1147
                }
1148

1149
                this.currentScopeValidationOptions = {
1,516✔
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,516✔
1158
            })
1159
            .forEach('invalidate affected scopes', () => filesToBeValidatedInScopeContext, (file) => {
1,516✔
1160
                if (isBrsFile(file)) {
2,329✔
1161
                    file.validationSegmenter.unValidateAllSegments();
1,936✔
1162
                    for (const scope of this.getScopesForFile(file)) {
1,936✔
1163
                        scope.invalidate();
2,213✔
1164
                    }
1165
                }
1166
            })
1167
            .forEach('validate scopes', () => this.getSortedScopeNames(), (scopeName) => {
1,516✔
1168
                //sort the scope names so we get consistent results
1169
                let scope = this.scopes[scopeName];
3,464✔
1170
                if (scope.shouldValidate(this.currentScopeValidationOptions)) {
3,464✔
1171
                    scopesToValidate.push(scope);
1,889✔
1172
                    this.plugins.emit('beforeScopeValidate', {
1,889✔
1173
                        program: this,
1174
                        scope: scope
1175
                    });
1176
                }
1177
            })
1178
            .forEach('validate scope', () => this.getSortedScopeNames(), (scopeName) => {
1,514✔
1179
                //sort the scope names so we get consistent results
1180
                let scope = this.scopes[scopeName];
3,459✔
1181
                scope.validate(this.currentScopeValidationOptions);
3,459✔
1182
            })
1183
            .forEach('afterScopeValidate', () => scopesToValidate, (scope) => {
1,510✔
1184
                this.plugins.emit('afterScopeValidate', {
1,885✔
1185
                    program: this,
1186
                    scope: scope
1187
                });
1188
            })
1189
            .once('detect duplicate component names', () => {
1190
                this.detectDuplicateComponentNames();
1,509✔
1191
                this.isFirstValidation = false;
1,509✔
1192

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

1198
            })
1199
            .onCancel(() => {
1200
                logValidateEnd('cancelled');
14✔
1201
            })
1202
            .onSuccess(() => {
1203
                logValidateEnd();
1,509✔
1204
            })
1205
            .onComplete(() => {
1206
                //if we emitted the beforeProgramValidate hook, emit the afterProgramValidate hook as well
1207
                if (beforeProgramValidateWasEmitted) {
1,523✔
1208
                    const wasCancelled = options?.cancellationToken?.isCancellationRequested ?? false;
1,520✔
1209
                    this.plugins.emit('afterProgramValidate', {
1,520✔
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,523✔
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,523✔
1226
                //clear the validatePromise which means we're no longer running a validation
1227
                this.validatePromise = undefined;
1,523✔
1228
            });
1229

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

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

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

1248
    private getScopesForCrossScopeValidation(someComponentTypeChanged = false) {
×
1249
        const scopesForCrossScopeValidation = [];
1,516✔
1250
        for (let scopeName of this.getSortedScopeNames()) {
1,516✔
1251
            let scope = this.scopes[scopeName];
3,464✔
1252
            if (this.globalScope !== scope && (someComponentTypeChanged || !scope.isValidated)) {
3,464✔
1253
                scopesForCrossScopeValidation.push(scope);
1,905✔
1254
            }
1255
        }
1256
        return scopesForCrossScopeValidation;
1,516✔
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,509✔
1264
            const file = this.files[filePath];
2,574✔
1265
            //if this is an XmlFile, and it has a valid `componentName` property
1266
            if (isXmlFile(file) && file.componentName?.text) {
2,574✔
1267
                let lowerName = file.componentName.text.toLowerCase();
557✔
1268
                if (!map[lowerName]) {
557✔
1269
                    map[lowerName] = [];
554✔
1270
                }
1271
                map[lowerName].push(file);
557✔
1272
            }
1273
            return map;
2,574✔
1274
        }, {});
1275

1276
        for (let name in componentsByName) {
1,509✔
1277
            const xmlFiles = componentsByName[name];
554✔
1278
            //add diagnostics for every duplicate component with this name
1279
            if (xmlFiles.length > 1) {
554✔
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,958✔
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,784✔
1316
        if (this.getFilePathCache.has(filePath)) {
26,683✔
1317
            const cachedFilePath = this.getFilePathCache.get(filePath);
15,767✔
1318
            if (cachedFilePath.isDestMap) {
15,767✔
1319
                return this.destMap.get(
13,087✔
1320
                    cachedFilePath.path
1321
                ) as T;
1322
            }
1323
            return this.files[
2,680✔
1324
                cachedFilePath.path
1325
            ] as T;
1326
        }
1327
        if (typeof filePath !== 'string') {
10,916✔
1328
            return undefined;
3,655✔
1329
            //is the path absolute (or the `virtual:` prefix)
1330
        } else if (/^(?:(?:virtual:[\/\\])|(?:\w:)|(?:[\/\\]))/gmi.exec(filePath)) {
7,261✔
1331
            const standardizedPath = (normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase();
3,479!
1332
            this.getFilePathCache.set(filePath, { path: standardizedPath });
3,479✔
1333

1334
            return this.files[
3,479✔
1335
                standardizedPath
1336
            ] as T;
1337
        } else if (util.isUriLike(filePath)) {
3,782✔
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,210✔
1347
            this.getFilePathCache.set(filePath, { path: standardizedPath, isDestMap: true });
3,210✔
1348
            return this.destMap.get(
3,210✔
1349
                standardizedPath
1350
            ) as T;
1351
        }
1352
    }
1353

1354
    private sortedScopeNames: string[] = undefined;
1,958✔
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,115✔
1361
            this.sortedScopeNames = Object.keys(this.scopes).sort((a, b) => {
1,445✔
1362
                if (a === 'global') {
2,090!
NEW
1363
                    return -1;
×
1364
                } else if (b === 'global') {
2,090✔
1365
                    return 1;
1,410✔
1366
                }
1367
                if (a === 'source') {
680✔
1368
                    return -1;
30✔
1369
                } else if (b === 'source') {
650✔
1370
                    return 1;
150✔
1371
                }
1372
                if (a < b) {
500✔
1373
                    return -1;
211✔
1374
                } else if (b < a) {
289!
1375
                    return 1;
289✔
1376
                }
NEW
1377
                return 0;
×
1378
            });
1379
        }
1380
        return this.sortedScopeNames;
13,115✔
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,282✔
1389

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

1396
                if (scope.hasFile(resolvedFile)) {
40,004✔
1397
                    result.push(scope);
4,850✔
1398
                }
1399
            }
1400
        }
1401
        return result;
4,282✔
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,288✔
1409
        for (let key of scopeKeys) {
4,288✔
1410
            let scope = this.scopes[key];
19,030✔
1411

1412
            if (scope.hasFile(file)) {
19,030✔
1413
                return scope;
3,120✔
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);
126✔
1503
        if (!file) {
126!
1504
            return [];
×
1505
        }
1506

1507
        const event: ProvideCompletionsEvent = {
126✔
1508
            program: this,
1509
            file: file,
1510
            scopes: this.getScopesForFile(file),
1511
            position: position,
1512
            completions: []
1513
        };
1514

1515
        this.plugins.emit('beforeProvideCompletions', event);
126✔
1516

1517
        this.plugins.emit('provideCompletions', event);
126✔
1518

1519
        this.plugins.emit('afterProvideCompletions', event);
126✔
1520

1521
        return event.completions;
126✔
1522
    }
1523

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

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

1548
        const event: ProvideDefinitionEvent = {
18✔
1549
            program: this,
1550
            file: file,
1551
            position: position,
1552
            definitions: []
1553
        };
1554

1555
        this.plugins.emit('beforeProvideDefinition', event);
18✔
1556
        this.plugins.emit('provideDefinition', event);
18✔
1557
        this.plugins.emit('afterProvideDefinition', event);
18✔
1558
        return event.definitions;
18✔
1559
    }
1560

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

1581
        return result ?? [];
73!
1582
    }
1583

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

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

1621
            const scopes = this.getScopesForFile(file);
11✔
1622

1623
            this.plugins.emit('onGetCodeActions', {
11✔
1624
                program: this,
1625
                file: file,
1626
                range: range,
1627
                diagnostics: diagnostics,
1628
                scopes: scopes,
1629
                codeActions: codeActions
1630
            });
1631
        }
1632
        return codeActions;
12✔
1633
    }
1634

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

1652
    public getSignatureHelp(filePath: string, position: Position): SignatureInfoObj[] {
1653
        let file: BrsFile = this.getFile(filePath);
185✔
1654
        if (!file || !isBrsFile(file)) {
185✔
1655
            return [];
3✔
1656
        }
1657
        let callExpressionInfo = new CallExpressionInfo(file, position);
182✔
1658
        let signatureHelpUtil = new SignatureHelpUtil();
182✔
1659
        return signatureHelpUtil.getSignatureHelpItems(callExpressionInfo);
182✔
1660
    }
1661

1662
    public getReferences(srcPath: string, position: Position): Location[] {
1663
        //find the file
1664
        let file = this.getFile(srcPath);
4✔
1665

1666
        const event: ProvideReferencesEvent = {
4✔
1667
            program: this,
1668
            file: file,
1669
            position: position,
1670
            references: []
1671
        };
1672

1673
        this.plugins.emit('beforeProvideReferences', event);
4✔
1674
        this.plugins.emit('provideReferences', event);
4✔
1675
        this.plugins.emit('afterProvideReferences', event);
4✔
1676

1677
        return event.references;
4✔
1678
    }
1679

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

1691
        return this.getTranspiledFileContentsPipeline.run(async () => {
327✔
1692

1693
            const result = {
327✔
1694
                destPath: file.destPath,
1695
                pkgPath: file.pkgPath,
1696
                srcPath: file.srcPath
1697
            } as FileTranspileResult;
1698

1699
            const expectedPkgPath = file.pkgPath.toLowerCase();
327✔
1700
            const expectedMapPath = `${expectedPkgPath}.map`;
327✔
1701
            const expectedTypedefPkgPath = expectedPkgPath.replace(/\.brs$/i, '.d.bs');
327✔
1702

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

1729
            try {
327✔
1730
                //now that the plugin has been registered, run the build with just this file
1731
                await this.build({
327✔
1732
                    files: [file]
1733
                });
1734
            } finally {
1735
                this.plugins.remove(plugin);
327✔
1736
            }
1737
            return result;
327✔
1738
        });
1739
    }
1740
    private getTranspiledFileContentsPipeline = new ActionPipeline();
1,958✔
1741

1742
    /**
1743
     * Get the absolute output path for a file
1744
     */
1745
    private getOutputPath(file: { pkgPath?: string }, stagingDir = this.getStagingDir()) {
×
1746
        return s`${stagingDir}/${file.pkgPath}`;
1,875✔
1747
    }
1748

1749
    private getStagingDir(stagingDir?: string) {
1750
        let result = stagingDir ?? this.options.stagingDir ?? this.options.stagingDir;
735✔
1751
        if (!result) {
735✔
1752
            result = rokuDeploy.getOptions(this.options as any).stagingDir;
547✔
1753
        }
1754
        result = s`${path.resolve(this.options.cwd ?? process.cwd(), result ?? '/')}`;
735!
1755
        return result;
735✔
1756
    }
1757

1758
    /**
1759
     * Prepare the program for building
1760
     * @param files the list of files that should be prepared
1761
     */
1762
    private async prepare(files: BscFile[]) {
1763
        const programEvent: PrepareProgramEvent = {
368✔
1764
            program: this,
1765
            editor: this.editor,
1766
            files: files
1767
        };
1768

1769
        //assign an editor to every file
1770
        for (const file of programEvent.files) {
368✔
1771
            //if the file doesn't have an editor yet, assign one now
1772
            if (!file.editor) {
746✔
1773
                file.editor = new Editor();
699✔
1774
            }
1775
        }
1776

1777
        //sort the entries to make transpiling more deterministic
1778
        programEvent.files.sort((a, b) => {
368✔
1779
            if (a.pkgPath < b.pkgPath) {
393✔
1780
                return -1;
333✔
1781
            } else if (a.pkgPath > b.pkgPath) {
60!
1782
                return 1;
60✔
1783
            } else {
NEW
1784
                return 1;
×
1785
            }
1786
        });
1787

1788
        await this.plugins.emitAsync('beforePrepareProgram', programEvent);
368✔
1789
        await this.plugins.emitAsync('prepareProgram', programEvent);
368✔
1790

1791
        const stagingDir = this.getStagingDir();
368✔
1792

1793
        const entries: TranspileObj[] = [];
368✔
1794

1795
        for (const file of files) {
368✔
1796
            const scope = this.getFirstScopeForFile(file);
746✔
1797
            //link the symbol table for all the files in this scope
1798
            scope?.linkSymbolTable();
746✔
1799

1800
            //if the file doesn't have an editor yet, assign one now
1801
            if (!file.editor) {
746!
NEW
1802
                file.editor = new Editor();
×
1803
            }
1804
            const event = {
746✔
1805
                program: this,
1806
                file: file,
1807
                editor: file.editor,
1808
                scope: scope,
1809
                outputPath: this.getOutputPath(file, stagingDir)
1810
            } as PrepareFileEvent & { outputPath: string };
1811

1812
            await this.plugins.emitAsync('beforePrepareFile', event);
746✔
1813
            await this.plugins.emitAsync('prepareFile', event);
746✔
1814
            await this.plugins.emitAsync('afterPrepareFile', event);
746✔
1815

1816
            //TODO remove this in v1
1817
            entries.push(event);
746✔
1818

1819
            //unlink the symbolTable so the next loop iteration can link theirs
1820
            scope?.unlinkSymbolTable();
746✔
1821
        }
1822

1823
        await this.plugins.emitAsync('afterPrepareProgram', programEvent);
368✔
1824
        return files;
368✔
1825
    }
1826

1827
    /**
1828
     * Generate the contents of every file
1829
     */
1830
    private async serialize(files: BscFile[]) {
1831

1832
        const allFiles = new Map<BscFile, SerializedFile[]>();
367✔
1833

1834
        //exclude prunable files if that option is enabled
1835
        if (this.options.pruneEmptyCodeFiles === true) {
367✔
1836
            files = files.filter(x => x.canBePruned !== true);
9✔
1837
        }
1838

1839
        const serializeProgramEvent = await this.plugins.emitAsync('beforeSerializeProgram', {
367✔
1840
            program: this,
1841
            files: files,
1842
            result: allFiles
1843
        });
1844
        await this.plugins.emitAsync('onSerializeProgram', serializeProgramEvent);
367✔
1845

1846
        // serialize each file
1847
        for (const file of files) {
367✔
1848
            let scope = this.getFirstScopeForFile(file);
743✔
1849

1850
            //if the file doesn't have a scope, create a temporary scope for the file so it can depend on scope-level items
1851
            if (!scope) {
743✔
1852
                scope = new Scope(`temporary-for-${file.pkgPath}`, this);
378✔
1853
                scope.getAllFiles = () => [file];
3,389✔
1854
                scope.getOwnFiles = scope.getAllFiles;
378✔
1855
            }
1856

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

1872
        this.plugins.emit('afterSerializeProgram', serializeProgramEvent);
367✔
1873

1874
        return allFiles;
367✔
1875
    }
1876

1877
    /**
1878
     * Write the entire project to disk
1879
     */
1880
    private async write(stagingDir: string, files: Map<BscFile, SerializedFile[]>) {
1881
        const programEvent = await this.plugins.emitAsync('beforeWriteProgram', {
367✔
1882
            program: this,
1883
            files: files,
1884
            stagingDir: stagingDir
1885
        });
1886
        //empty the staging directory
1887
        await fsExtra.emptyDir(stagingDir);
367✔
1888

1889
        const serializedFiles = [...files]
367✔
1890
            .map(([, serializedFiles]) => serializedFiles)
743✔
1891
            .flat();
1892

1893
        //write all the files to disk (asynchronously)
1894
        await Promise.all(
367✔
1895
            serializedFiles.map(async (file) => {
1896
                const event = await this.plugins.emitAsync('beforeWriteFile', {
1,129✔
1897
                    program: this,
1898
                    file: file,
1899
                    outputPath: this.getOutputPath(file, stagingDir),
1900
                    processedFiles: new Set<SerializedFile>()
1901
                });
1902

1903
                await this.plugins.emitAsync('writeFile', event);
1,129✔
1904

1905
                await this.plugins.emitAsync('afterWriteFile', event);
1,129✔
1906
            })
1907
        );
1908

1909
        await this.plugins.emitAsync('afterWriteProgram', programEvent);
367✔
1910
    }
1911

1912
    private buildPipeline = new ActionPipeline();
1,958✔
1913

1914
    /**
1915
     * Build the project. This transpiles/transforms/copies all files and moves them to the staging directory
1916
     * @param options the list of options used to build the program
1917
     */
1918
    public async build(options?: ProgramBuildOptions) {
1919
        //run a single build at a time
1920
        await this.buildPipeline.run(async () => {
367✔
1921
            const stagingDir = this.getStagingDir(options?.stagingDir);
367✔
1922

1923
            const event = await this.plugins.emitAsync('beforeBuildProgram', {
367✔
1924
                program: this,
1925
                editor: this.editor,
1926
                files: options?.files ?? Object.values(this.files)
2,202✔
1927
            });
1928

1929
            //prepare the program (and files) for building
1930
            event.files = await this.prepare(event.files);
367✔
1931

1932
            //stage the entire program
1933
            const serializedFilesByFile = await this.serialize(event.files);
367✔
1934

1935
            await this.write(stagingDir, serializedFilesByFile);
367✔
1936

1937
            await this.plugins.emitAsync('afterBuildProgram', event);
367✔
1938

1939
            //undo all edits for the program
1940
            this.editor.undoAll();
367✔
1941
            //undo all edits for each file
1942
            for (const file of event.files) {
367✔
1943
                file.editor.undoAll();
744✔
1944
            }
1945
        });
1946

1947
        this.logger.debug('Types Created', TypesCreated);
367✔
1948
        let totalTypesCreated = 0;
367✔
1949
        for (const key in TypesCreated) {
367✔
1950
            if (TypesCreated.hasOwnProperty(key)) {
9,534!
1951
                totalTypesCreated += TypesCreated[key];
9,534✔
1952

1953
            }
1954
        }
1955
        this.logger.info('Total Types Created', totalTypesCreated);
367✔
1956
    }
1957

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

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

1990
                // eslint-disable-next-line @typescript-eslint/dot-notation
1991
                if (file['_cachedLookups'].classStatementMap.get(lowerClassName) !== undefined) {
17✔
1992
                    files.push(file);
1✔
1993
                }
1994
            }
1995
        }
1996
        return files;
7✔
1997
    }
1998

1999
    public findFilesForNamespace(name: string) {
2000
        const files = [] as BscFile[];
7✔
2001
        const lowerName = name.toLowerCase();
7✔
2002
        //find every file with this class defined
2003
        for (const file of Object.values(this.files)) {
7✔
2004
            if (isBrsFile(file)) {
25✔
2005

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

2021
        return files;
7✔
2022
    }
2023

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

2039
    private _manifest: Map<string, string>;
2040

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

2049
        // Override or delete any bs_consts defined in the bs config
2050
        for (const key in this.options?.manifest?.bs_const) {
17!
2051
            const value = this.options.manifest.bs_const[key];
3✔
2052
            if (value === null) {
3✔
2053
                bsConsts.delete(key);
1✔
2054
            } else {
2055
                bsConsts.set(key, value);
2✔
2056
            }
2057
        }
2058

2059
        // convert the new list of bs consts back into a string for the rest of the down stream systems to use
2060
        let constString = '';
17✔
2061
        for (const [key, value] of bsConsts) {
17✔
2062
            constString += `${constString !== '' ? ';' : ''}${key}=${value.toString()}`;
8✔
2063
        }
2064

2065
        // Set the updated bs_const value
2066
        parsedManifest.set('bs_const', constString);
17✔
2067
    }
2068

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

2083
        try {
1,601✔
2084
            // we only load this manifest once, so do it sync to improve speed downstream
2085
            const contents = fsExtra.readFileSync(manifestPath, 'utf-8');
1,601✔
2086
            const parsedManifest = parseManifest(contents);
17✔
2087
            this.buildBsConstsIntoParsedManifest(parsedManifest);
17✔
2088
            this._manifest = parsedManifest;
17✔
2089
        } catch (e) {
2090
            this._manifest = new Map();
1,584✔
2091
        }
2092
    }
2093

2094
    /**
2095
     * Get a map of the manifest information
2096
     */
2097
    public getManifest() {
2098
        if (!this._manifest) {
2,555✔
2099
            this.loadManifest();
1,592✔
2100
        }
2101
        return this._manifest;
2,555✔
2102
    }
2103

2104
    public dispose() {
2105
        this.plugins.emit('beforeProgramDispose', { program: this });
1,833✔
2106

2107
        for (let filePath in this.files) {
1,833✔
2108
            this.files[filePath]?.dispose?.();
2,322!
2109
        }
2110
        for (let name in this.scopes) {
1,833✔
2111
            this.scopes[name]?.dispose?.();
3,860!
2112
        }
2113
        this.globalScope?.dispose?.();
1,833!
2114
        this.dependencyGraph?.dispose?.();
1,833!
2115
    }
2116
}
2117

2118
export interface FileTranspileResult {
2119
    srcPath: string;
2120
    destPath: string;
2121
    pkgPath: string;
2122
    code: string;
2123
    map: string;
2124
    typedef: string;
2125
}
2126

2127

2128
class ProvideFileEventInternal<TFile extends BscFile = BscFile> implements ProvideFileEvent<TFile> {
2129
    constructor(
2130
        public program: Program,
2,632✔
2131
        public srcPath: string,
2,632✔
2132
        public destPath: string,
2,632✔
2133
        public data: LazyFileData,
2,632✔
2134
        public fileFactory: FileFactory
2,632✔
2135
    ) {
2136
        this.srcExtension = path.extname(srcPath)?.toLowerCase();
2,632!
2137
    }
2138

2139
    public srcExtension: string;
2140

2141
    public files: TFile[] = [];
2,632✔
2142
}
2143

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