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

rokucommunity / brighterscript / #13320

25 Nov 2024 02:52PM UTC coverage: 86.872%. Remained the same
#13320

push

web-flow
Merge d9b225566 into 2a6afd921

11934 of 14527 branches covered (82.15%)

Branch coverage included in aggregate %.

300 of 316 new or added lines in 31 files covered. (94.94%)

240 existing lines in 20 files now uncovered.

12960 of 14129 relevant lines covered (91.73%)

32482.33 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

131

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

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

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

179
        BuiltInInterfaceAdder.getLookupTable = () => this.globalScope.symbolTable;
789,597✔
180

181
        for (const callable of globalCallables) {
1,794✔
182
            this.globalScope.symbolTable.addSymbol(callable.name, { description: callable.shortDescription }, callable.type, SymbolTypeFlag.runtime);
139,932✔
183
        }
184

185
        for (const ifaceData of Object.values(interfaces) as BRSInterfaceData[]) {
1,794✔
186
            const nodeType = new InterfaceType(ifaceData.name);
157,872✔
187
            nodeType.addBuiltInInterfaces();
157,872✔
188
            nodeType.isBuiltIn = true;
157,872✔
189
            this.globalScope.symbolTable.addSymbol(ifaceData.name, { description: ifaceData.description }, nodeType, SymbolTypeFlag.typetime);
157,872✔
190
        }
191

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

202
        for (const nodeData of Object.values(nodes) as SGNodeData[]) {
1,794✔
203
            this.recursivelyAddNodeToSymbolTable(nodeData);
172,224✔
204
        }
205

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

213
    }
214

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

223
    public diagnostics: DiagnosticManager;
224

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

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

236
    private fileSymbolInformation = new Map<string, { provides: ProvidedSymbolInfo; requires: UnresolvedSymbol[] }>();
1,794✔
237

238

239
    /**
240
     *  Map of typetime symbols which depend upon the key symbol
241
     */
242
    private symbolDependencies = new Map<string, Set<string>>();
1,794✔
243

244

245
    private componentsTable = new SymbolTable('Custom Components');
1,794✔
246

247
    public addFileSymbolInfo(file: BrsFile) {
248
        this.fileSymbolInformation.set(file.pkgPath, {
1,674✔
249
            provides: file.providedSymbols,
250
            requires: file.requiredSymbols
251
        });
252
    }
253

254
    public getFileSymbolInfo(file: BrsFile) {
255
        return this.fileSymbolInformation.get(file.pkgPath);
1,677✔
256
    }
257

258
    /**
259
     * The path to bslib.brs (the BrightScript runtime for certain BrighterScript features)
260
     */
261
    public get bslibPkgPath() {
262
        //if there's an aliased (preferred) version of bslib from roku_modules loaded into the program, use that
263
        if (this.getFile(bslibAliasedRokuModulesPkgPath)) {
2,382✔
264
            return bslibAliasedRokuModulesPkgPath;
11✔
265

266
            //if there's a non-aliased version of bslib from roku_modules, use that
267
        } else if (this.getFile(bslibNonAliasedRokuModulesPkgPath)) {
2,371✔
268
            return bslibNonAliasedRokuModulesPkgPath;
24✔
269

270
            //default to the embedded version
271
        } else {
272
            return `${this.options.bslibDestinationDir}${path.sep}bslib.brs`;
2,347✔
273
        }
274
    }
275

276
    public get bslibPrefix() {
277
        if (this.bslibPkgPath === bslibNonAliasedRokuModulesPkgPath) {
1,737✔
278
            return 'rokucommunity_bslib';
18✔
279
        } else {
280
            return 'bslib';
1,719✔
281
        }
282
    }
283

284

285
    /**
286
     * A map of every file loaded into this program, indexed by its original file location
287
     */
288
    public files = {} as Record<string, BscFile>;
1,794✔
289
    /**
290
     * A map of every file loaded into this program, indexed by its destPath
291
     */
292
    private destMap = new Map<string, BscFile>();
1,794✔
293
    /**
294
     * Plugins can contribute multiple virtual files for a single physical file.
295
     * This collection links the virtual files back to the physical file that produced them.
296
     * The key is the standardized and lower-cased srcPath
297
     */
298
    private fileClusters = new Map<string, BscFile[]>();
1,794✔
299

300
    private scopes = {} as Record<string, Scope>;
1,794✔
301

302
    protected addScope(scope: Scope) {
303
        this.scopes[scope.name] = scope;
1,962✔
304
        delete this.sortedScopeNames;
1,962✔
305
    }
306

307
    protected removeScope(scope: Scope) {
308
        if (this.scopes[scope.name]) {
13!
309
            delete this.scopes[scope.name];
13✔
310
            delete this.sortedScopeNames;
13✔
311
        }
312
    }
313

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

322
    /**
323
     * Get the component with the specified name
324
     */
325
    public getComponent(componentName: string) {
326
        if (componentName) {
2,620✔
327
            //return the first compoment in the list with this name
328
            //(components are ordered in this list by destPath to ensure consistency)
329
            return this.components[componentName.toLowerCase()]?.[0];
2,606✔
330
        } else {
331
            return undefined;
14✔
332
        }
333
    }
334

335
    /**
336
     * Get the sorted names of custom components
337
     */
338
    public getSortedComponentNames() {
339
        const componentNames = Object.keys(this.components);
1,343✔
340
        componentNames.sort((a, b) => {
1,343✔
341
            if (a < b) {
705✔
342
                return -1;
279✔
343
            } else if (b < a) {
426!
344
                return 1;
426✔
345
            }
UNCOV
346
            return 0;
×
347
        });
348
        return componentNames;
1,343✔
349
    }
350

351
    /**
352
     * Keeps a set of all the components that need to have their types updated during the current validation cycle
353
     */
354
    private componentSymbolsToUpdate = new Set<{ componentKey: string; componentName: string }>();
1,794✔
355

356
    /**
357
     * Register (or replace) the reference to a component in the component map
358
     */
359
    private registerComponent(xmlFile: XmlFile, scope: XmlScope) {
360
        const key = this.getComponentKey(xmlFile);
404✔
361
        if (!this.components[key]) {
404✔
362
            this.components[key] = [];
390✔
363
        }
364
        this.components[key].push({
404✔
365
            file: xmlFile,
366
            scope: scope
367
        });
368
        this.components[key].sort((a, b) => {
404✔
369
            const pathA = a.file.destPath.toLowerCase();
5✔
370
            const pathB = b.file.destPath.toLowerCase();
5✔
371
            if (pathA < pathB) {
5✔
372
                return -1;
1✔
373
            } else if (pathA > pathB) {
4!
374
                return 1;
4✔
375
            }
UNCOV
376
            return 0;
×
377
        });
378
        this.syncComponentDependencyGraph(this.components[key]);
404✔
379
        this.addDeferredComponentTypeSymbolCreation(xmlFile);
404✔
380
    }
381

382
    /**
383
     * Remove the specified component from the components map
384
     */
385
    private unregisterComponent(xmlFile: XmlFile) {
386
        const key = this.getComponentKey(xmlFile);
13✔
387
        const arr = this.components[key] || [];
13!
388
        for (let i = 0; i < arr.length; i++) {
13✔
389
            if (arr[i].file === xmlFile) {
13!
390
                arr.splice(i, 1);
13✔
391
                break;
13✔
392
            }
393
        }
394

395
        this.syncComponentDependencyGraph(arr);
13✔
396
        this.addDeferredComponentTypeSymbolCreation(xmlFile);
13✔
397
    }
398

399
    /**
400
     * Adds a component described in an XML to the set of components that needs to be updated this validation cycle.
401
     * @param xmlFile XML file with <component> tag
402
     */
403
    private addDeferredComponentTypeSymbolCreation(xmlFile: XmlFile) {
404
        this.componentSymbolsToUpdate.add({ componentKey: this.getComponentKey(xmlFile), componentName: xmlFile.componentName?.text });
417✔
405

406
    }
407

408
    private getComponentKey(xmlFile: XmlFile) {
409
        return (xmlFile.componentName?.text ?? xmlFile.pkgPath).toLowerCase();
834✔
410
    }
411

412
    /**
413
     * Resolves symbol table with the first component in this.components to have the same name as the component in the file
414
     * @param componentKey key getting a component from `this.components`
415
     * @param componentName the unprefixed name of the component that will be added (e.g. 'MyLabel' NOT 'roSgNodeMyLabel')
416
     */
417
    private updateComponentSymbolInGlobalScope(componentKey: string, componentName: string) {
418
        const symbolName = componentName ? util.getSgNodeTypeName(componentName) : undefined;
336✔
419
        if (!symbolName) {
336✔
420
            return;
7✔
421
        }
422
        const components = this.components[componentKey] || [];
329!
423
        const previousComponentType = this.componentsTable.getSymbolType(symbolName, { flags: SymbolTypeFlag.typetime });
329✔
424
        // Remove any existing symbols that match
425
        this.componentsTable.removeSymbol(symbolName);
329✔
426
        if (components.length > 0) {
329✔
427
            // There is a component that can be added - use it.
428
            const componentScope = components[0].scope;
328✔
429

430
            componentScope.linkSymbolTable();
328✔
431
            const componentType = componentScope.getComponentType();
328✔
432
            if (componentType) {
328!
433
                this.componentsTable.addSymbol(symbolName, {}, componentType, SymbolTypeFlag.typetime);
328✔
434
            }
435
            const isComponentTypeDifferent = !previousComponentType || isReferenceType(previousComponentType) || !componentType.isEqual(previousComponentType);
328✔
436
            componentScope.unlinkSymbolTable();
328✔
437

438
            return isComponentTypeDifferent;
328✔
439

440
        }
441
        // There was a previous component type, but no new one, so it's different
442
        return !!previousComponentType;
1✔
443
    }
444

445
    /**
446
     * 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
447
     * @param componentKey key getting a component from `this.components`
448
     * @param componentName the unprefixed name of the component that will be added (e.g. 'MyLabel' NOT 'roSgNodeMyLabel')
449
     */
450
    private addComponentReferenceType(componentKey: string, componentName: string) {
451
        const symbolName = componentName ? util.getSgNodeTypeName(componentName) : undefined;
336✔
452
        if (!symbolName) {
336✔
453
            return;
7✔
454
        }
455
        const components = this.components[componentKey] || [];
329!
456
        // Remove any existing symbols that match
457
        this.componentsTable.removeSymbol(symbolName);
329✔
458
        // There is a component that can be added - use it.
459
        if (components.length > 0) {
329✔
460

461
            const componentRefType = new ReferenceType(symbolName, symbolName, SymbolTypeFlag.typetime, () => this.componentsTable);
1,673✔
462
            if (componentRefType) {
328!
463
                this.componentsTable.addSymbol(symbolName, {}, componentRefType, SymbolTypeFlag.typetime);
328✔
464
            }
465
        }
466
    }
467

468
    /**
469
     * re-attach the dependency graph with a new key for any component who changed
470
     * their position in their own named array (only matters when there are multiple
471
     * components with the same name)
472
     */
473
    private syncComponentDependencyGraph(components: Array<{ file: XmlFile; scope: XmlScope }>) {
474
        //reattach every dependency graph
475
        for (let i = 0; i < components.length; i++) {
417✔
476
            const { file, scope } = components[i];
410✔
477

478
            //attach (or re-attach) the dependencyGraph for every component whose position changed
479
            if (file.dependencyGraphIndex !== i) {
410✔
480
                file.dependencyGraphIndex = i;
406✔
481
                this.dependencyGraph.addOrReplace(file.dependencyGraphKey, file.dependencies);
406✔
482
                file.attachDependencyGraph(this.dependencyGraph);
406✔
483
                scope.attachDependencyGraph(this.dependencyGraph);
406✔
484
            }
485
        }
486
    }
487

488
    /**
489
     * Get a list of all files that are included in the project but are not referenced
490
     * by any scope in the program.
491
     */
492
    public getUnreferencedFiles() {
UNCOV
493
        let result = [] as BscFile[];
×
UNCOV
494
        for (let filePath in this.files) {
×
UNCOV
495
            let file = this.files[filePath];
×
496
            //is this file part of a scope
UNCOV
497
            if (!this.getFirstScopeForFile(file)) {
×
498
                //no scopes reference this file. add it to the list
UNCOV
499
                result.push(file);
×
500
            }
501
        }
UNCOV
502
        return result;
×
503
    }
504

505
    /**
506
     * Get the list of errors for the entire program.
507
     */
508
    public getDiagnostics() {
509
        return this.diagnostics.getDiagnostics();
1,141✔
510
    }
511

512
    /**
513
     * Determine if the specified file is loaded in this program right now.
514
     * @param filePath the absolute or relative path to the file
515
     * @param normalizePath should the provided path be normalized before use
516
     */
517
    public hasFile(filePath: string, normalizePath = true) {
2,568✔
518
        return !!this.getFile(filePath, normalizePath);
2,568✔
519
    }
520

521
    /**
522
     * roku filesystem is case INsensitive, so find the scope by key case insensitive
523
     * @param scopeName xml scope names are their `destPath`. Source scope is stored with the key `"source"`
524
     */
525
    public getScopeByName(scopeName: string): Scope | undefined {
526
        if (!scopeName) {
60!
UNCOV
527
            return undefined;
×
528
        }
529
        //most scopes are xml file pkg paths. however, the ones that are not are single names like "global" and "scope",
530
        //so it's safe to run the standardizePkgPath method
531
        scopeName = s`${scopeName}`;
60✔
532
        let key = Object.keys(this.scopes).find(x => x.toLowerCase() === scopeName.toLowerCase());
137✔
533
        return this.scopes[key!];
60✔
534
    }
535

536
    /**
537
     * Return all scopes
538
     */
539
    public getScopes() {
540
        return Object.values(this.scopes);
10✔
541
    }
542

543
    /**
544
     * Find the scope for the specified component
545
     */
546
    public getComponentScope(componentName: string) {
547
        return this.getComponent(componentName)?.scope;
729✔
548
    }
549

550
    /**
551
     * Update internal maps with this file reference
552
     */
553
    private assignFile<T extends BscFile = BscFile>(file: T) {
554
        const fileAddEvent: BeforeFileAddEvent = {
2,386✔
555
            file: file,
556
            program: this
557
        };
558

559
        this.plugins.emit('beforeFileAdd', fileAddEvent);
2,386✔
560

561
        this.files[file.srcPath.toLowerCase()] = file;
2,386✔
562
        this.destMap.set(file.destPath.toLowerCase(), file);
2,386✔
563

564
        this.plugins.emit('afterFileAdd', fileAddEvent);
2,386✔
565

566
        return file;
2,386✔
567
    }
568

569
    /**
570
     * Remove this file from internal maps
571
     */
572
    private unassignFile<T extends BscFile = BscFile>(file: T) {
573
        delete this.files[file.srcPath.toLowerCase()];
155✔
574
        this.destMap.delete(file.destPath.toLowerCase());
155✔
575
        return file;
155✔
576
    }
577

578
    /**
579
     * Load a file into the program. If that file already exists, it is replaced.
580
     * If file contents are provided, those are used, Otherwise, the file is loaded from the file system
581
     * @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:/`)
582
     * @param fileData the file contents. omit or pass `undefined` to prevent loading the data at this time
583
     */
584
    public setFile<T extends BscFile>(srcDestOrPkgPath: string, fileData?: FileData): T;
585
    /**
586
     * Load a file into the program. If that file already exists, it is replaced.
587
     * @param fileEntry an object that specifies src and dest for the file.
588
     * @param fileData the file contents. omit or pass `undefined` to prevent loading the data at this time
589
     */
590
    public setFile<T extends BscFile>(fileEntry: FileObj, fileData: FileData): T;
591
    public setFile<T extends BscFile>(fileParam: FileObj | string, fileData: FileData): T {
592
        //normalize the file paths
593
        const { srcPath, destPath } = this.getPaths(fileParam, this.options.rootDir);
2,382✔
594

595
        let file = this.logger.time(LogLevel.debug, ['Program.setFile()', chalk.green(srcPath)], () => {
2,382✔
596
            //if the file is already loaded, remove it
597
            if (this.hasFile(srcPath)) {
2,382✔
598
                this.removeFile(srcPath, true, true);
139✔
599
            }
600

601
            const data = new LazyFileData(fileData);
2,382✔
602

603
            const event = new ProvideFileEventInternal(this, srcPath, destPath, data, this.fileFactory);
2,382✔
604

605
            this.plugins.emit('beforeProvideFile', event);
2,382✔
606
            this.plugins.emit('provideFile', event);
2,382✔
607
            this.plugins.emit('afterProvideFile', event);
2,382✔
608

609
            //if no files were provided, create a AssetFile to represent it.
610
            if (event.files.length === 0) {
2,382✔
611
                event.files.push(
18✔
612
                    this.fileFactory.AssetFile({
613
                        srcPath: event.srcPath,
614
                        destPath: event.destPath,
615
                        pkgPath: event.destPath,
616
                        data: data
617
                    })
618
                );
619
            }
620

621
            //find the file instance for the srcPath that triggered this action.
622
            const primaryFile = event.files.find(x => x.srcPath === srcPath);
2,382✔
623

624
            if (!primaryFile) {
2,382!
UNCOV
625
                throw new Error(`No file provided for srcPath '${srcPath}'. Instead, received ${JSON.stringify(event.files.map(x => ({
×
626
                    type: x.type,
627
                    srcPath: x.srcPath,
628
                    destPath: x.destPath
629
                })))}`);
630
            }
631

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

635
            for (const file of event.files) {
2,382✔
636
                file.srcPath = s(file.srcPath);
2,386✔
637
                if (file.destPath) {
2,386!
638
                    file.destPath = s`${util.replaceCaseInsensitive(file.destPath, this.options.rootDir, '')}`;
2,386✔
639
                }
640
                if (file.pkgPath) {
2,386✔
641
                    file.pkgPath = s`${util.replaceCaseInsensitive(file.pkgPath, this.options.rootDir, '')}`;
2,382✔
642
                } else {
643
                    file.pkgPath = file.destPath;
4✔
644
                }
645
                file.excludeFromOutput = file.excludeFromOutput === true;
2,386✔
646

647
                //set the dependencyGraph key for every file to its destPath
648
                file.dependencyGraphKey = file.destPath.toLowerCase();
2,386✔
649

650
                this.assignFile(file);
2,386✔
651

652
                //register a callback anytime this file's dependencies change
653
                if (typeof file.onDependenciesChanged === 'function') {
2,386✔
654
                    file.disposables ??= [];
2,360!
655
                    file.disposables.push(
2,360✔
656
                        this.dependencyGraph.onchange(file.dependencyGraphKey, file.onDependenciesChanged.bind(file))
657
                    );
658
                }
659

660
                //register this file (and its dependencies) with the dependency graph
661
                this.dependencyGraph.addOrReplace(file.dependencyGraphKey, file.dependencies ?? []);
2,386✔
662

663
                //if this is a `source` file, add it to the source scope's dependency list
664
                if (this.isSourceBrsFile(file)) {
2,386✔
665
                    this.createSourceScope();
1,602✔
666
                    this.dependencyGraph.addDependency('scope:source', file.dependencyGraphKey);
1,602✔
667
                }
668

669
                //if this is an xml file in the components folder, register it as a component
670
                if (this.isComponentsXmlFile(file)) {
2,386✔
671
                    //create a new scope for this xml file
672
                    let scope = new XmlScope(file, this);
404✔
673
                    this.addScope(scope);
404✔
674

675
                    //register this componet now that we have parsed it and know its component name
676
                    this.registerComponent(file, scope);
404✔
677

678
                    //notify plugins that the scope is created and the component is registered
679
                    this.plugins.emit('afterScopeCreate', {
404✔
680
                        program: this,
681
                        scope: scope
682
                    });
683
                }
684
            }
685

686
            return primaryFile;
2,382✔
687
        });
688
        return file as T;
2,382✔
689
    }
690

691
    /**
692
     * Given a srcPath, a destPath, or both, resolve whichever is missing, relative to rootDir.
693
     * @param fileParam an object representing file paths
694
     * @param rootDir must be a pre-normalized path
695
     */
696
    private getPaths(fileParam: string | FileObj | { srcPath?: string; pkgPath?: string }, rootDir: string) {
697
        let srcPath: string | undefined;
698
        let destPath: string | undefined;
699

700
        assert.ok(fileParam, 'fileParam is required');
2,540✔
701

702
        //lift the path vars from the incoming param
703
        if (typeof fileParam === 'string') {
2,540✔
704
            fileParam = this.removePkgPrefix(fileParam);
2,193✔
705
            srcPath = s`${path.resolve(rootDir, fileParam)}`;
2,193✔
706
            destPath = s`${util.replaceCaseInsensitive(srcPath, rootDir, '')}`;
2,193✔
707
        } else {
708
            let param: any = fileParam;
347✔
709

710
            if (param.src) {
347✔
711
                srcPath = s`${param.src}`;
346✔
712
            }
713
            if (param.srcPath) {
347!
UNCOV
714
                srcPath = s`${param.srcPath}`;
×
715
            }
716
            if (param.dest) {
347✔
717
                destPath = s`${this.removePkgPrefix(param.dest)}`;
346✔
718
            }
719
            if (param.pkgPath) {
347!
UNCOV
720
                destPath = s`${this.removePkgPrefix(param.pkgPath)}`;
×
721
            }
722
        }
723

724
        //if there's no srcPath, use the destPath to build an absolute srcPath
725
        if (!srcPath) {
2,540✔
726
            srcPath = s`${rootDir}/${destPath}`;
1✔
727
        }
728
        //coerce srcPath to an absolute path
729
        if (!path.isAbsolute(srcPath)) {
2,540✔
730
            srcPath = util.standardizePath(srcPath);
1✔
731
        }
732

733
        //if destPath isn't set, compute it from the other paths
734
        if (!destPath) {
2,540✔
735
            destPath = s`${util.replaceCaseInsensitive(srcPath, rootDir, '')}`;
1✔
736
        }
737

738
        assert.ok(srcPath, 'fileEntry.src is required');
2,540✔
739
        assert.ok(destPath, 'fileEntry.dest is required');
2,540✔
740

741
        return {
2,540✔
742
            srcPath: srcPath,
743
            //remove leading slash
744
            destPath: destPath.replace(/^[\/\\]+/, '')
745
        };
746
    }
747

748
    /**
749
     * Remove any leading `pkg:/` found in the path
750
     */
751
    private removePkgPrefix(path: string) {
752
        return path.replace(/^pkg:\//i, '');
2,539✔
753
    }
754

755
    /**
756
     * Is this file a .brs file found somewhere within the `pkg:/source/` folder?
757
     */
758
    private isSourceBrsFile(file: BscFile) {
759
        return !!/^(pkg:\/)?source[\/\\]/.exec(file.destPath);
2,541✔
760
    }
761

762
    /**
763
     * Is this file a .brs file found somewhere within the `pkg:/source/` folder?
764
     */
765
    private isComponentsXmlFile(file: BscFile): file is XmlFile {
766
        return isXmlFile(file) && !!/^(pkg:\/)?components[\/\\]/.exec(file.destPath);
2,386✔
767
    }
768

769
    /**
770
     * Ensure source scope is created.
771
     * Note: automatically called internally, and no-op if it exists already.
772
     */
773
    public createSourceScope() {
774
        if (!this.scopes.source) {
2,360✔
775
            const sourceScope = new Scope('source', this, 'scope:source');
1,558✔
776
            sourceScope.attachDependencyGraph(this.dependencyGraph);
1,558✔
777
            this.addScope(sourceScope);
1,558✔
778
            this.plugins.emit('afterScopeCreate', {
1,558✔
779
                program: this,
780
                scope: sourceScope
781
            });
782
        }
783
    }
784

785
    /**
786
     * Remove a set of files from the program
787
     * @param srcPaths can be an array of srcPath or destPath strings
788
     * @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
789
     */
790
    public removeFiles(srcPaths: string[], normalizePath = true) {
1✔
791
        for (let srcPath of srcPaths) {
1✔
792
            this.removeFile(srcPath, normalizePath);
1✔
793
        }
794
    }
795

796
    /**
797
     * Remove a file from the program
798
     * @param filePath can be a srcPath, a destPath, or a destPath with leading `pkg:/`
799
     * @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
800
     */
801
    public removeFile(filePath: string, normalizePath = true, keepSymbolInformation = false) {
27✔
802
        this.logger.debug('Program.removeFile()', filePath);
153✔
803
        const paths = this.getPaths(filePath, this.options.rootDir);
153✔
804

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

808
        for (const file of files) {
153✔
809
            //if a file has already been removed, nothing more needs to be done here
810
            if (!file || !this.hasFile(file.srcPath)) {
156✔
811
                continue;
1✔
812
            }
813
            this.diagnostics.clearForFile(file.srcPath);
155✔
814

815
            const event: BeforeFileRemoveEvent = { file: file, program: this };
155✔
816
            this.plugins.emit('beforeFileRemove', event);
155✔
817

818
            //if there is a scope named the same as this file's path, remove it (i.e. xml scopes)
819
            let scope = this.scopes[file.destPath];
155✔
820
            if (scope) {
155✔
821
                const scopeDisposeEvent = {
13✔
822
                    program: this,
823
                    scope: scope
824
                };
825
                this.plugins.emit('beforeScopeDispose', scopeDisposeEvent);
13✔
826
                this.plugins.emit('onScopeDispose', scopeDisposeEvent);
13✔
827
                scope.dispose();
13✔
828
                //notify dependencies of this scope that it has been removed
829
                this.dependencyGraph.remove(scope.dependencyGraphKey!);
13✔
830
                this.removeScope(this.scopes[file.destPath]);
13✔
831
                this.plugins.emit('afterScopeDispose', scopeDisposeEvent);
13✔
832
            }
833
            //remove the file from the program
834
            this.unassignFile(file);
155✔
835

836
            this.dependencyGraph.remove(file.dependencyGraphKey);
155✔
837

838
            //if this is a pkg:/source file, notify the `source` scope that it has changed
839
            if (this.isSourceBrsFile(file)) {
155✔
840
                this.dependencyGraph.removeDependency('scope:source', file.dependencyGraphKey);
127✔
841
            }
842
            if (isBrsFile(file)) {
155✔
843
                if (!keepSymbolInformation) {
136✔
844
                    this.fileSymbolInformation.delete(file.pkgPath);
8✔
845
                }
846
                this.crossScopeValidation.clearResolutionsForFile(file);
136✔
847
            }
848

849
            //if this is a component, remove it from our components map
850
            if (isXmlFile(file)) {
155✔
851
                this.unregisterComponent(file);
13✔
852
            }
853
            //dispose any disposable things on the file
854
            for (const disposable of file?.disposables ?? []) {
155!
855
                disposable();
149✔
856
            }
857
            //dispose file
858
            file?.dispose?.();
155!
859

860
            this.plugins.emit('afterFileRemove', event);
155✔
861
        }
862
    }
863

864
    public crossScopeValidation = new CrossScopeValidator(this);
1,794✔
865

866
    private isFirstValidation = true;
1,794✔
867

868
    /**
869
     * Traverse the entire project, and validate all scopes
870
     */
871
    public validate() {
872
        this.logger.time(LogLevel.log, ['Validating project'], () => {
1,343✔
873
            this.diagnostics.clearForTag(ProgramValidatorDiagnosticsTag);
1,343✔
874
            const programValidateEvent = {
1,343✔
875
                program: this
876
            };
877
            this.plugins.emit('beforeProgramValidate', programValidateEvent);
1,343✔
878
            this.plugins.emit('onProgramValidate', programValidateEvent);
1,343✔
879

880
            const metrics = {
1,343✔
881
                filesChanged: 0,
882
                filesValidated: 0,
883
                fileValidationTime: '',
884
                crossScopeValidationTime: '',
885
                scopesValidated: 0,
886
                totalLinkTime: '',
887
                totalScopeValidationTime: '',
888
                componentValidationTime: ''
889
            };
890

891
            const validationStopwatch = new Stopwatch();
1,343✔
892
            //validate every file
893
            const brsFilesValidated: BrsFile[] = [];
1,343✔
894
            const xmlFilesValidated: XmlFile[] = [];
1,343✔
895

896
            const afterValidateFiles: BscFile[] = [];
1,343✔
897

898
            // Create reference component types for any component that changes
899
            this.logger.time(LogLevel.info, ['Build component types'], () => {
1,343✔
900
                for (let { componentKey, componentName } of this.componentSymbolsToUpdate) {
1,343✔
901
                    this.addComponentReferenceType(componentKey, componentName);
336✔
902
                }
903
            });
904

905

906
            metrics.fileValidationTime = validationStopwatch.getDurationTextFor(() => {
1,343✔
907
                //sort files by path so we get consistent results
908
                const files = Object.values(this.files).sort(firstBy(x => x.srcPath));
3,662✔
909
                for (const file of files) {
1,343✔
910
                    //for every unvalidated file, validate it
911
                    if (!file.isValidated) {
2,285✔
912
                        const validateFileEvent = {
1,947✔
913
                            program: this,
914
                            file: file
915
                        };
916
                        this.plugins.emit('beforeFileValidate', validateFileEvent);
1,947✔
917
                        //emit an event to allow plugins to contribute to the file validation process
918
                        this.plugins.emit('onFileValidate', validateFileEvent);
1,947✔
919
                        file.isValidated = true;
1,947✔
920
                        if (isBrsFile(file)) {
1,947✔
921
                            brsFilesValidated.push(file);
1,616✔
922
                        } else if (isXmlFile(file)) {
331!
923
                            xmlFilesValidated.push(file);
331✔
924
                        }
925
                        afterValidateFiles.push(file);
1,947✔
926
                    }
927
                }
928
                // AfterFileValidate is after all files have been validated
929
                for (const file of afterValidateFiles) {
1,343✔
930
                    const validateFileEvent = {
1,947✔
931
                        program: this,
932
                        file: file
933
                    };
934
                    this.plugins.emit('afterFileValidate', validateFileEvent);
1,947✔
935
                }
936
            }).durationText;
937

938
            metrics.filesChanged = afterValidateFiles.length;
1,343✔
939

940
            const changedComponentTypes: string[] = [];
1,343✔
941

942
            // Build component types for any component that changes
943
            this.logger.time(LogLevel.info, ['Build component types'], () => {
1,343✔
944
                for (let { componentKey, componentName } of this.componentSymbolsToUpdate) {
1,343✔
945
                    if (this.updateComponentSymbolInGlobalScope(componentKey, componentName)) {
336✔
946
                        changedComponentTypes.push(util.getSgNodeTypeName(componentName).toLowerCase());
321✔
947
                    }
948
                }
949
                this.componentSymbolsToUpdate.clear();
1,343✔
950
            });
951

952
            const changedSymbolsMapArr = [...brsFilesValidated, ...xmlFilesValidated]?.map(f => {
1,343!
953
                if (isBrsFile(f)) {
1,947✔
954
                    return f.providedSymbols.changes;
1,616✔
955
                }
956
                return null;
331✔
957
            }).filter(x => x);
1,947✔
958

959

960
            // update the map of typetime dependencies
961
            for (const file of brsFilesValidated) {
1,343✔
962
                for (const [symbolName, provided] of file.providedSymbols.symbolMap.get(SymbolTypeFlag.typetime).entries()) {
1,616✔
963
                    // clear existing dependencies
964
                    for (const values of this.symbolDependencies.values()) {
633✔
965
                        values.delete(symbolName);
59✔
966
                    }
967

968
                    // map types to the set of types that depend upon them
969
                    for (const dependentSymbol of provided.requiredSymbolNames?.values() ?? []) {
633!
970
                        const dependentSymbolLower = dependentSymbol.toLowerCase();
166✔
971
                        if (!this.symbolDependencies.has(dependentSymbolLower)) {
166✔
972
                            this.symbolDependencies.set(dependentSymbolLower, new Set<string>());
146✔
973
                        }
974
                        const symbolsDependentUpon = this.symbolDependencies.get(dependentSymbolLower);
166✔
975
                        symbolsDependentUpon.add(symbolName);
166✔
976
                    }
977
                }
978
            }
979

980
            // get set of changed symbols
981
            const changedSymbols = new Map<SymbolTypeFlag, Set<string>>();
1,343✔
982
            for (const flag of [SymbolTypeFlag.runtime, SymbolTypeFlag.typetime]) {
1,343✔
983
                const changedSymbolsSetArr = changedSymbolsMapArr.map(symMap => symMap.get(flag));
3,232✔
984
                const changedSymbolSet = new Set<string>();
2,686✔
985
                for (const changeSet of changedSymbolsSetArr) {
2,686✔
986
                    for (const change of changeSet) {
3,232✔
987
                        changedSymbolSet.add(change);
3,301✔
988
                    }
989
                }
990
                changedSymbols.set(flag, changedSymbolSet);
2,686✔
991
            }
992

993
            // update changed symbol set with any changed component
994
            for (const changedComponentType of changedComponentTypes) {
1,343✔
995
                changedSymbols.get(SymbolTypeFlag.typetime).add(changedComponentType);
321✔
996
            }
997

998
            // Add any additional types that depend on a changed type
999
            // as each interation of the loop might add new types, need to keep checking until nothing new is added
1000
            const dependentTypesChanged = new Set<string>();
1,343✔
1001
            let foundDependentTypes = false;
1,343✔
1002
            const changedTypeSymbols = changedSymbols.get(SymbolTypeFlag.typetime);
1,343✔
1003
            do {
1,343✔
1004
                foundDependentTypes = false;
1,347✔
1005
                for (const changedSymbol of changedTypeSymbols) {
1,347✔
1006
                    const symbolsDependentUponChangedSymbol = this.symbolDependencies.get(changedSymbol) ?? [];
950✔
1007
                    for (const symbolName of symbolsDependentUponChangedSymbol) {
950✔
1008
                        if (!changedTypeSymbols.has(symbolName) && !dependentTypesChanged.has(symbolName)) {
166✔
1009
                            foundDependentTypes = true;
4✔
1010
                            dependentTypesChanged.add(symbolName);
4✔
1011
                        }
1012
                    }
1013
                }
1014
            } while (foundDependentTypes);
1015

1016
            changedSymbols.set(SymbolTypeFlag.typetime, new Set([...changedTypeSymbols, ...dependentTypesChanged]));
1,343✔
1017

1018
            const filesToBeValidatedInScopeContext = new Set<BscFile>(afterValidateFiles);
1,343✔
1019

1020
            metrics.crossScopeValidationTime = validationStopwatch.getDurationTextFor(() => {
1,343✔
1021
                const scopesToCheck = this.getScopesForCrossScopeValidation(changedComponentTypes.length > 0);
1,343✔
1022
                this.crossScopeValidation.buildComponentsMap();
1,343✔
1023
                this.crossScopeValidation.addDiagnosticsForScopes(scopesToCheck);
1,343✔
1024
                const filesToRevalidate = this.crossScopeValidation.getFilesRequiringChangedSymbol(scopesToCheck, changedSymbols);
1,343✔
1025
                for (const file of filesToRevalidate) {
1,343✔
1026
                    filesToBeValidatedInScopeContext.add(file);
404✔
1027
                }
1028
            }).durationText;
1029

1030
            metrics.filesValidated = filesToBeValidatedInScopeContext.size;
1,343✔
1031

1032
            let linkTime = 0;
1,343✔
1033
            let validationTime = 0;
1,343✔
1034
            let scopesValidated = 0;
1,343✔
1035
            let changedFiles = new Set<BscFile>(afterValidateFiles);
1,343✔
1036
            this.logger.time(LogLevel.info, ['Validate all scopes'], () => {
1,343✔
1037
                //sort the scope names so we get consistent results
1038
                const scopeNames = this.getSortedScopeNames();
1,343✔
1039
                for (const file of filesToBeValidatedInScopeContext) {
1,343✔
1040
                    if (isBrsFile(file)) {
2,073✔
1041
                        file.validationSegmenter.unValidateAllSegments();
1,742✔
1042
                        for (const scope of this.getScopesForFile(file)) {
1,742✔
1043
                            scope.invalidate();
2,038✔
1044
                        }
1045
                    }
1046
                }
1047
                for (let scopeName of scopeNames) {
1,343✔
1048
                    let scope = this.scopes[scopeName];
3,061✔
1049
                    const scopeValidated = scope.validate({
3,061✔
1050
                        filesToBeValidatedInScopeContext: filesToBeValidatedInScopeContext,
1051
                        changedSymbols: changedSymbols,
1052
                        changedFiles: changedFiles,
1053
                        initialValidation: this.isFirstValidation
1054
                    });
1055
                    if (scopeValidated) {
3,061✔
1056
                        scopesValidated++;
1,667✔
1057
                    }
1058
                    linkTime += scope.validationMetrics.linkTime;
3,061✔
1059
                    validationTime += scope.validationMetrics.validationTime;
3,061✔
1060
                }
1061
            });
1062
            metrics.scopesValidated = scopesValidated;
1,343✔
1063
            validationStopwatch.totalMilliseconds = linkTime;
1,343✔
1064
            metrics.totalLinkTime = validationStopwatch.getDurationText();
1,343✔
1065

1066
            validationStopwatch.totalMilliseconds = validationTime;
1,343✔
1067
            metrics.totalScopeValidationTime = validationStopwatch.getDurationText();
1,343✔
1068

1069
            metrics.componentValidationTime = validationStopwatch.getDurationTextFor(() => {
1,343✔
1070
                this.detectDuplicateComponentNames();
1,343✔
1071
            }).durationText;
1072

1073
            this.logValidationMetrics(metrics);
1,343✔
1074

1075
            this.isFirstValidation = false;
1,343✔
1076

1077
            this.plugins.emit('afterProgramValidate', programValidateEvent);
1,343✔
1078
        });
1079
    }
1080

1081
    // eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style
1082
    private logValidationMetrics(metrics: { [key: string]: number | string }) {
1083
        let logs = [] as string[];
1,343✔
1084
        for (const key in metrics) {
1,343✔
1085
            logs.push(`${key}=${chalk.yellow(metrics[key].toString())}`);
10,744✔
1086
        }
1087
        this.logger.info(`Validation Metrics: ${logs.join(', ')}`);
1,343✔
1088
    }
1089

1090
    private getScopesForCrossScopeValidation(someComponentTypeChanged = false) {
×
1091
        const scopesForCrossScopeValidation = [];
1,343✔
1092
        for (let scopeName of this.getSortedScopeNames()) {
1,343✔
1093
            let scope = this.scopes[scopeName];
3,061✔
1094
            if (this.globalScope !== scope && (someComponentTypeChanged || !scope.isValidated)) {
3,061✔
1095
                scopesForCrossScopeValidation.push(scope);
1,694✔
1096
            }
1097
        }
1098
        return scopesForCrossScopeValidation;
1,343✔
1099
    }
1100

1101
    /**
1102
     * Flag all duplicate component names
1103
     */
1104
    private detectDuplicateComponentNames() {
1105
        const componentsByName = Object.keys(this.files).reduce<Record<string, XmlFile[]>>((map, filePath) => {
1,343✔
1106
            const file = this.files[filePath];
2,285✔
1107
            //if this is an XmlFile, and it has a valid `componentName` property
1108
            if (isXmlFile(file) && file.componentName?.text) {
2,285✔
1109
                let lowerName = file.componentName.text.toLowerCase();
464✔
1110
                if (!map[lowerName]) {
464✔
1111
                    map[lowerName] = [];
461✔
1112
                }
1113
                map[lowerName].push(file);
464✔
1114
            }
1115
            return map;
2,285✔
1116
        }, {});
1117

1118
        for (let name in componentsByName) {
1,343✔
1119
            const xmlFiles = componentsByName[name];
461✔
1120
            //add diagnostics for every duplicate component with this name
1121
            if (xmlFiles.length > 1) {
461✔
1122
                for (let xmlFile of xmlFiles) {
3✔
1123
                    const { componentName } = xmlFile;
6✔
1124
                    this.diagnostics.register({
6✔
1125
                        ...DiagnosticMessages.duplicateComponentName(componentName.text),
1126
                        location: xmlFile.componentName.location,
1127
                        relatedInformation: xmlFiles.filter(x => x !== xmlFile).map(x => {
12✔
1128
                            return {
6✔
1129
                                location: x.componentName.location,
1130
                                message: 'Also defined here'
1131
                            };
1132
                        })
1133
                    }, { tags: [ProgramValidatorDiagnosticsTag] });
1134
                }
1135
            }
1136
        }
1137
    }
1138

1139
    /**
1140
     * Get the files for a list of filePaths
1141
     * @param filePaths can be an array of srcPath or a destPath strings
1142
     * @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
1143
     */
1144
    public getFiles<T extends BscFile>(filePaths: string[], normalizePath = true) {
29✔
1145
        return filePaths
29✔
1146
            .map(filePath => this.getFile(filePath, normalizePath))
39✔
1147
            .filter(file => file !== undefined) as T[];
39✔
1148
    }
1149

1150
    /**
1151
     * Get the file at the given path
1152
     * @param filePath can be a srcPath or a destPath
1153
     * @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
1154
     */
1155
    public getFile<T extends BscFile>(filePath: string, normalizePath = true) {
17,479✔
1156
        if (typeof filePath !== 'string') {
23,975✔
1157
            return undefined;
3,378✔
1158
            //is the path absolute (or the `virtual:` prefix)
1159
        } else if (/^(?:(?:virtual:[\/\\])|(?:\w:)|(?:[\/\\]))/gmi.exec(filePath)) {
20,597✔
1160
            return this.files[
4,593✔
1161
                (normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase()
4,593!
1162
            ] as T;
1163
        } else if (util.isUriLike(filePath)) {
16,004✔
1164
            const path = URI.parse(filePath).fsPath;
690✔
1165
            return this.files[
690✔
1166
                (normalizePath ? util.standardizePath(path) : path).toLowerCase()
690!
1167
            ] as T;
1168
        } else {
1169
            return this.destMap.get(
15,314✔
1170
                (normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase()
15,314✔
1171
            ) as T;
1172
        }
1173
    }
1174

1175
    private sortedScopeNames: string[] = undefined;
1,794✔
1176

1177
    /**
1178
     * Gets a sorted list of all scopeNames, always beginning with "global", "source", then any others in alphabetical order
1179
     */
1180
    private getSortedScopeNames() {
1181
        if (!this.sortedScopeNames) {
9,124✔
1182
            this.sortedScopeNames = Object.keys(this.scopes).sort((a, b) => {
1,297✔
1183
                if (a === 'global') {
1,868!
UNCOV
1184
                    return -1;
×
1185
                } else if (b === 'global') {
1,868✔
1186
                    return 1;
1,279✔
1187
                }
1188
                if (a === 'source') {
589✔
1189
                    return -1;
27✔
1190
                } else if (b === 'source') {
562✔
1191
                    return 1;
130✔
1192
                }
1193
                if (a < b) {
432✔
1194
                    return -1;
181✔
1195
                } else if (b < a) {
251!
1196
                    return 1;
251✔
1197
                }
UNCOV
1198
                return 0;
×
1199
            });
1200
        }
1201
        return this.sortedScopeNames;
9,124✔
1202
    }
1203

1204
    /**
1205
     * Get a list of all scopes the file is loaded into
1206
     * @param file the file
1207
     */
1208
    public getScopesForFile(file: BscFile | string) {
1209
        const resolvedFile = typeof file === 'string' ? this.getFile(file) : file;
2,462✔
1210

1211
        let result = [] as Scope[];
2,462✔
1212
        if (resolvedFile) {
2,462✔
1213
            const scopeKeys = this.getSortedScopeNames();
2,461✔
1214
            for (let key of scopeKeys) {
2,461✔
1215
                let scope = this.scopes[key];
25,607✔
1216

1217
                if (scope.hasFile(resolvedFile)) {
25,607✔
1218
                    result.push(scope);
2,771✔
1219
                }
1220
            }
1221
        }
1222
        return result;
2,462✔
1223
    }
1224

1225
    /**
1226
     * Get the first found scope for a file.
1227
     */
1228
    public getFirstScopeForFile(file: BscFile): Scope | undefined {
1229
        const scopeKeys = this.getSortedScopeNames();
3,977✔
1230
        for (let key of scopeKeys) {
3,977✔
1231
            let scope = this.scopes[key];
18,340✔
1232

1233
            if (scope.hasFile(file)) {
18,340✔
1234
                return scope;
2,902✔
1235
            }
1236
        }
1237
    }
1238

1239
    public getStatementsByName(name: string, originFile: BrsFile, namespaceName?: string): FileLink<Statement>[] {
1240
        let results = new Map<Statement, FileLink<Statement>>();
39✔
1241
        const filesSearched = new Set<BrsFile>();
39✔
1242
        let lowerNamespaceName = namespaceName?.toLowerCase();
39✔
1243
        let lowerName = name?.toLowerCase();
39!
1244

1245
        function addToResults(statement: FunctionStatement | MethodStatement, file: BrsFile) {
1246
            let parentNamespaceName = statement.findAncestor<NamespaceStatement>(isNamespaceStatement)?.getName(originFile.parseMode)?.toLowerCase();
98✔
1247
            if (statement.tokens.name.text.toLowerCase() === lowerName && (!lowerNamespaceName || parentNamespaceName === lowerNamespaceName)) {
98✔
1248
                if (!results.has(statement)) {
36!
1249
                    results.set(statement, { item: statement, file: file as BrsFile });
36✔
1250
                }
1251
            }
1252
        }
1253

1254
        //look through all files in scope for matches
1255
        for (const scope of this.getScopesForFile(originFile)) {
39✔
1256
            for (const file of scope.getAllFiles()) {
39✔
1257
                //skip non-brs files, or files we've already processed
1258
                if (!isBrsFile(file) || filesSearched.has(file)) {
45✔
1259
                    continue;
3✔
1260
                }
1261
                filesSearched.add(file);
42✔
1262

1263
                file.ast.walk(createVisitor({
42✔
1264
                    FunctionStatement: (statement: FunctionStatement) => {
1265
                        addToResults(statement, file);
95✔
1266
                    },
1267
                    MethodStatement: (statement: MethodStatement) => {
1268
                        addToResults(statement, file);
3✔
1269
                    }
1270
                }), {
1271
                    walkMode: WalkMode.visitStatements
1272
                });
1273
            }
1274
        }
1275
        return [...results.values()];
39✔
1276
    }
1277

1278
    public getStatementsForXmlFile(scope: XmlScope, filterName?: string): FileLink<FunctionStatement>[] {
1279
        let results = new Map<Statement, FileLink<FunctionStatement>>();
8✔
1280
        const filesSearched = new Set<BrsFile>();
8✔
1281

1282
        //get all function names for the xml file and parents
1283
        let funcNames = new Set<string>();
8✔
1284
        let currentScope = scope;
8✔
1285
        while (isXmlScope(currentScope)) {
8✔
1286
            for (let name of currentScope.xmlFile.ast.componentElement.interfaceElement?.functions.map((f) => f.name) ?? []) {
14✔
1287
                if (!filterName || name === filterName) {
14!
1288
                    funcNames.add(name);
14✔
1289
                }
1290
            }
1291
            currentScope = currentScope.getParentScope() as XmlScope;
10✔
1292
        }
1293

1294
        //look through all files in scope for matches
1295
        for (const file of scope.getOwnFiles()) {
8✔
1296
            //skip non-brs files, or files we've already processed
1297
            if (!isBrsFile(file) || filesSearched.has(file)) {
16✔
1298
                continue;
8✔
1299
            }
1300
            filesSearched.add(file);
8✔
1301

1302
            file.ast.walk(createVisitor({
8✔
1303
                FunctionStatement: (statement: FunctionStatement) => {
1304
                    if (funcNames.has(statement.tokens.name.text)) {
13!
1305
                        if (!results.has(statement)) {
13!
1306
                            results.set(statement, { item: statement, file: file });
13✔
1307
                        }
1308
                    }
1309
                }
1310
            }), {
1311
                walkMode: WalkMode.visitStatements
1312
            });
1313
        }
1314
        return [...results.values()];
8✔
1315
    }
1316

1317
    /**
1318
     * Find all available completion items at the given position
1319
     * @param filePath can be a srcPath or a destPath
1320
     * @param position the position (line & column) where completions should be found
1321
     */
1322
    public getCompletions(filePath: string, position: Position) {
1323
        let file = this.getFile(filePath);
117✔
1324
        if (!file) {
117!
UNCOV
1325
            return [];
×
1326
        }
1327

1328
        //find the scopes for this file
1329
        let scopes = this.getScopesForFile(file);
117✔
1330

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

1334
        const event: ProvideCompletionsEvent = {
117✔
1335
            program: this,
1336
            file: file,
1337
            scopes: scopes,
1338
            position: position,
1339
            completions: []
1340
        };
1341

1342
        this.plugins.emit('beforeProvideCompletions', event);
117✔
1343

1344
        this.plugins.emit('provideCompletions', event);
117✔
1345

1346
        this.plugins.emit('afterProvideCompletions', event);
117✔
1347

1348
        return event.completions;
117✔
1349
    }
1350

1351
    /**
1352
     * Goes through each file and builds a list of workspace symbols for the program. Used by LanguageServer's onWorkspaceSymbol functionality
1353
     */
1354
    public getWorkspaceSymbols() {
1355
        const event: ProvideWorkspaceSymbolsEvent = {
22✔
1356
            program: this,
1357
            workspaceSymbols: []
1358
        };
1359
        this.plugins.emit('beforeProvideWorkspaceSymbols', event);
22✔
1360
        this.plugins.emit('provideWorkspaceSymbols', event);
22✔
1361
        this.plugins.emit('afterProvideWorkspaceSymbols', event);
22✔
1362
        return event.workspaceSymbols;
22✔
1363
    }
1364

1365
    /**
1366
     * Given a position in a file, if the position is sitting on some type of identifier,
1367
     * go to the definition of that identifier (where this thing was first defined)
1368
     */
1369
    public getDefinition(srcPath: string, position: Position): Location[] {
1370
        let file = this.getFile(srcPath);
18✔
1371
        if (!file) {
18!
UNCOV
1372
            return [];
×
1373
        }
1374

1375
        const event: ProvideDefinitionEvent = {
18✔
1376
            program: this,
1377
            file: file,
1378
            position: position,
1379
            definitions: []
1380
        };
1381

1382
        this.plugins.emit('beforeProvideDefinition', event);
18✔
1383
        this.plugins.emit('provideDefinition', event);
18✔
1384
        this.plugins.emit('afterProvideDefinition', event);
18✔
1385
        return event.definitions;
18✔
1386
    }
1387

1388
    /**
1389
     * Get hover information for a file and position
1390
     */
1391
    public getHover(srcPath: string, position: Position): Hover[] {
1392
        let file = this.getFile(srcPath);
68✔
1393
        let result: Hover[];
1394
        if (file) {
68!
1395
            const event = {
68✔
1396
                program: this,
1397
                file: file,
1398
                position: position,
1399
                scopes: this.getScopesForFile(file),
1400
                hovers: []
1401
            } as ProvideHoverEvent;
1402
            this.plugins.emit('beforeProvideHover', event);
68✔
1403
            this.plugins.emit('provideHover', event);
68✔
1404
            this.plugins.emit('afterProvideHover', event);
68✔
1405
            result = event.hovers;
68✔
1406
        }
1407

1408
        return result ?? [];
68!
1409
    }
1410

1411
    /**
1412
     * Get full list of document symbols for a file
1413
     * @param srcPath path to the file
1414
     */
1415
    public getDocumentSymbols(srcPath: string): DocumentSymbol[] | undefined {
1416
        let file = this.getFile(srcPath);
18✔
1417
        if (file) {
18!
1418
            const event: ProvideDocumentSymbolsEvent = {
18✔
1419
                program: this,
1420
                file: file,
1421
                documentSymbols: []
1422
            };
1423
            this.plugins.emit('beforeProvideDocumentSymbols', event);
18✔
1424
            this.plugins.emit('provideDocumentSymbols', event);
18✔
1425
            this.plugins.emit('afterProvideDocumentSymbols', event);
18✔
1426
            return event.documentSymbols;
18✔
1427
        } else {
UNCOV
1428
            return undefined;
×
1429
        }
1430
    }
1431

1432
    /**
1433
     * Compute code actions for the given file and range
1434
     */
1435
    public getCodeActions(srcPath: string, range: Range) {
1436
        const codeActions = [] as CodeAction[];
13✔
1437
        const file = this.getFile(srcPath);
13✔
1438
        if (file) {
13✔
1439
            const fileUri = util.pathToUri(file?.srcPath);
12!
1440
            const diagnostics = this
12✔
1441
                //get all current diagnostics (filtered by diagnostic filters)
1442
                .getDiagnostics()
1443
                //only keep diagnostics related to this file
1444
                .filter(x => x.location?.uri === fileUri)
25✔
1445
                //only keep diagnostics that touch this range
1446
                .filter(x => util.rangesIntersectOrTouch(x.location.range, range));
12✔
1447

1448
            const scopes = this.getScopesForFile(file);
12✔
1449

1450
            this.plugins.emit('onGetCodeActions', {
12✔
1451
                program: this,
1452
                file: file,
1453
                range: range,
1454
                diagnostics: diagnostics,
1455
                scopes: scopes,
1456
                codeActions: codeActions
1457
            });
1458
        }
1459
        return codeActions;
13✔
1460
    }
1461

1462
    /**
1463
     * Get semantic tokens for the specified file
1464
     */
1465
    public getSemanticTokens(srcPath: string): SemanticToken[] | undefined {
1466
        const file = this.getFile(srcPath);
24✔
1467
        if (file) {
24!
1468
            const result = [] as SemanticToken[];
24✔
1469
            this.plugins.emit('onGetSemanticTokens', {
24✔
1470
                program: this,
1471
                file: file,
1472
                scopes: this.getScopesForFile(file),
1473
                semanticTokens: result
1474
            });
1475
            return result;
24✔
1476
        }
1477
    }
1478

1479
    public getSignatureHelp(filepath: string, position: Position): SignatureInfoObj[] {
1480
        let file: BrsFile = this.getFile(filepath);
185✔
1481
        if (!file || !isBrsFile(file)) {
185✔
1482
            return [];
3✔
1483
        }
1484
        let callExpressionInfo = new CallExpressionInfo(file, position);
182✔
1485
        let signatureHelpUtil = new SignatureHelpUtil();
182✔
1486
        return signatureHelpUtil.getSignatureHelpItems(callExpressionInfo);
182✔
1487
    }
1488

1489
    public getReferences(srcPath: string, position: Position): Location[] {
1490
        //find the file
1491
        let file = this.getFile(srcPath);
4✔
1492

1493
        const event: ProvideReferencesEvent = {
4✔
1494
            program: this,
1495
            file: file,
1496
            position: position,
1497
            references: []
1498
        };
1499

1500
        this.plugins.emit('beforeProvideReferences', event);
4✔
1501
        this.plugins.emit('provideReferences', event);
4✔
1502
        this.plugins.emit('afterProvideReferences', event);
4✔
1503

1504
        return event.references;
4✔
1505
    }
1506

1507
    /**
1508
     * Transpile a single file and get the result as a string.
1509
     * This does not write anything to the file system.
1510
     *
1511
     * This should only be called by `LanguageServer`.
1512
     * Internal usage should call `_getTranspiledFileContents` instead.
1513
     * @param filePath can be a srcPath or a destPath
1514
     */
1515
    public async getTranspiledFileContents(filePath: string): Promise<FileTranspileResult> {
1516
        const file = this.getFile(filePath);
306✔
1517

1518
        return this.getTranspiledFileContentsPipeline.run(async () => {
306✔
1519

1520
            const result = {
306✔
1521
                destPath: file.destPath,
1522
                pkgPath: file.pkgPath,
1523
                srcPath: file.srcPath
1524
            } as FileTranspileResult;
1525

1526
            const expectedPkgPath = file.pkgPath.toLowerCase();
306✔
1527
            const expectedMapPath = `${expectedPkgPath}.map`;
306✔
1528
            const expectedTypedefPkgPath = expectedPkgPath.replace(/\.brs$/i, '.d.bs');
306✔
1529

1530
            //add a temporary plugin to tap into the file writing process
1531
            const plugin = this.plugins.addFirst({
306✔
1532
                name: 'getTranspiledFileContents',
1533
                beforeWriteFile: (event) => {
1534
                    const pkgPath = event.file.pkgPath.toLowerCase();
968✔
1535
                    switch (pkgPath) {
968✔
1536
                        //this is the actual transpiled file
1537
                        case expectedPkgPath:
968✔
1538
                            result.code = event.file.data.toString();
306✔
1539
                            break;
306✔
1540
                        //this is the sourcemap
1541
                        case expectedMapPath:
1542
                            result.map = event.file.data.toString();
170✔
1543
                            break;
170✔
1544
                        //this is the typedef
1545
                        case expectedTypedefPkgPath:
1546
                            result.typedef = event.file.data.toString();
8✔
1547
                            break;
8✔
1548
                        default:
1549
                        //no idea what this file is. just ignore it
1550
                    }
1551
                    //mark every file as processed so it they don't get written to the output directory
1552
                    event.processedFiles.add(event.file);
968✔
1553
                }
1554
            });
1555

1556
            try {
306✔
1557
                //now that the plugin has been registered, run the build with just this file
1558
                await this.build({
306✔
1559
                    files: [file]
1560
                });
1561
            } finally {
1562
                this.plugins.remove(plugin);
306✔
1563
            }
1564
            return result;
306✔
1565
        });
1566
    }
1567
    private getTranspiledFileContentsPipeline = new ActionPipeline();
1,794✔
1568

1569
    /**
1570
     * Get the absolute output path for a file
1571
     */
1572
    private getOutputPath(file: { pkgPath?: string }, stagingDir = this.getStagingDir()) {
×
1573
        return s`${stagingDir}/${file.pkgPath}`;
1,783✔
1574
    }
1575

1576
    private getStagingDir(stagingDir?: string) {
1577
        let result = stagingDir ?? this.options.stagingDir ?? this.options.stagingDir;
693✔
1578
        if (!result) {
693✔
1579
            result = rokuDeploy.getOptions(this.options as any).stagingDir;
507✔
1580
        }
1581
        result = s`${path.resolve(this.options.cwd ?? process.cwd(), result ?? '/')}`;
693!
1582
        return result;
693✔
1583
    }
1584

1585
    /**
1586
     * Prepare the program for building
1587
     * @param files the list of files that should be prepared
1588
     */
1589
    private async prepare(files: BscFile[]) {
1590
        const programEvent: PrepareProgramEvent = {
347✔
1591
            program: this,
1592
            editor: this.editor,
1593
            files: files
1594
        };
1595

1596
        //assign an editor to every file
1597
        for (const file of programEvent.files) {
347✔
1598
            //if the file doesn't have an editor yet, assign one now
1599
            if (!file.editor) {
704✔
1600
                file.editor = new Editor();
657✔
1601
            }
1602
        }
1603

1604
        //sort the entries to make transpiling more deterministic
1605
        programEvent.files.sort((a, b) => {
347✔
1606
            if (a.pkgPath < b.pkgPath) {
372✔
1607
                return -1;
312✔
1608
            } else if (a.pkgPath > b.pkgPath) {
60!
1609
                return 1;
60✔
1610
            } else {
UNCOV
1611
                return 1;
×
1612
            }
1613
        });
1614

1615
        await this.plugins.emitAsync('beforePrepareProgram', programEvent);
347✔
1616
        await this.plugins.emitAsync('prepareProgram', programEvent);
347✔
1617

1618
        const stagingDir = this.getStagingDir();
347✔
1619

1620
        const entries: TranspileObj[] = [];
347✔
1621

1622
        for (const file of files) {
347✔
1623
            const scope = this.getFirstScopeForFile(file);
704✔
1624
            //link the symbol table for all the files in this scope
1625
            scope?.linkSymbolTable();
704✔
1626

1627
            //if the file doesn't have an editor yet, assign one now
1628
            if (!file.editor) {
704!
UNCOV
1629
                file.editor = new Editor();
×
1630
            }
1631
            const event = {
704✔
1632
                program: this,
1633
                file: file,
1634
                editor: file.editor,
1635
                scope: scope,
1636
                outputPath: this.getOutputPath(file, stagingDir)
1637
            } as PrepareFileEvent & { outputPath: string };
1638

1639
            await this.plugins.emitAsync('beforePrepareFile', event);
704✔
1640
            await this.plugins.emitAsync('prepareFile', event);
704✔
1641
            await this.plugins.emitAsync('afterPrepareFile', event);
704✔
1642

1643
            //TODO remove this in v1
1644
            entries.push(event);
704✔
1645

1646
            //unlink the symbolTable so the next loop iteration can link theirs
1647
            scope?.unlinkSymbolTable();
704✔
1648
        }
1649

1650
        await this.plugins.emitAsync('afterPrepareProgram', programEvent);
347✔
1651
        return files;
347✔
1652
    }
1653

1654
    /**
1655
     * Generate the contents of every file
1656
     */
1657
    private async serialize(files: BscFile[]) {
1658

1659
        const allFiles = new Map<BscFile, SerializedFile[]>();
346✔
1660

1661
        //exclude prunable files if that option is enabled
1662
        if (this.options.pruneEmptyCodeFiles === true) {
346✔
1663
            files = files.filter(x => x.canBePruned !== true);
9✔
1664
        }
1665

1666
        const serializeProgramEvent = await this.plugins.emitAsync('beforeSerializeProgram', {
346✔
1667
            program: this,
1668
            files: files,
1669
            result: allFiles
1670
        });
1671
        await this.plugins.emitAsync('onSerializeProgram', serializeProgramEvent);
346✔
1672

1673
        // serialize each file
1674
        for (const file of files) {
346✔
1675
            let scope = this.getFirstScopeForFile(file);
701✔
1676

1677
            //if the file doesn't have a scope, create a temporary scope for the file so it can depend on scope-level items
1678
            if (!scope) {
701✔
1679
                scope = new Scope(`temporary-for-${file.pkgPath}`, this);
357✔
1680
                scope.getAllFiles = () => [file];
3,200✔
1681
                scope.getOwnFiles = scope.getAllFiles;
357✔
1682
            }
1683

1684
            //link the symbol table for all the files in this scope
1685
            scope?.linkSymbolTable();
701!
1686
            const event: SerializeFileEvent = {
701✔
1687
                program: this,
1688
                file: file,
1689
                scope: scope,
1690
                result: allFiles
1691
            };
1692
            await this.plugins.emitAsync('beforeSerializeFile', event);
701✔
1693
            await this.plugins.emitAsync('serializeFile', event);
701✔
1694
            await this.plugins.emitAsync('afterSerializeFile', event);
701✔
1695
            //unlink the symbolTable so the next loop iteration can link theirs
1696
            scope?.unlinkSymbolTable();
701!
1697
        }
1698

1699
        this.plugins.emit('afterSerializeProgram', serializeProgramEvent);
346✔
1700

1701
        return allFiles;
346✔
1702
    }
1703

1704
    /**
1705
     * Write the entire project to disk
1706
     */
1707
    private async write(stagingDir: string, files: Map<BscFile, SerializedFile[]>) {
1708
        const programEvent = await this.plugins.emitAsync('beforeWriteProgram', {
346✔
1709
            program: this,
1710
            files: files,
1711
            stagingDir: stagingDir
1712
        });
1713
        //empty the staging directory
1714
        await fsExtra.emptyDir(stagingDir);
346✔
1715

1716
        const serializedFiles = [...files]
346✔
1717
            .map(([, serializedFiles]) => serializedFiles)
701✔
1718
            .flat();
1719

1720
        //write all the files to disk (asynchronously)
1721
        await Promise.all(
346✔
1722
            serializedFiles.map(async (file) => {
1723
                const event = await this.plugins.emitAsync('beforeWriteFile', {
1,079✔
1724
                    program: this,
1725
                    file: file,
1726
                    outputPath: this.getOutputPath(file, stagingDir),
1727
                    processedFiles: new Set<SerializedFile>()
1728
                });
1729

1730
                await this.plugins.emitAsync('writeFile', event);
1,079✔
1731

1732
                await this.plugins.emitAsync('afterWriteFile', event);
1,079✔
1733
            })
1734
        );
1735

1736
        await this.plugins.emitAsync('afterWriteProgram', programEvent);
346✔
1737
    }
1738

1739
    private buildPipeline = new ActionPipeline();
1,794✔
1740

1741
    /**
1742
     * Build the project. This transpiles/transforms/copies all files and moves them to the staging directory
1743
     * @param options the list of options used to build the program
1744
     */
1745
    public async build(options?: ProgramBuildOptions) {
1746
        //run a single build at a time
1747
        await this.buildPipeline.run(async () => {
346✔
1748
            const stagingDir = this.getStagingDir(options?.stagingDir);
346✔
1749

1750
            const event = await this.plugins.emitAsync('beforeBuildProgram', {
346✔
1751
                program: this,
1752
                editor: this.editor,
1753
                files: options?.files ?? Object.values(this.files)
2,076✔
1754
            });
1755

1756
            //prepare the program (and files) for building
1757
            event.files = await this.prepare(event.files);
346✔
1758

1759
            //stage the entire program
1760
            const serializedFilesByFile = await this.serialize(event.files);
346✔
1761

1762
            await this.write(stagingDir, serializedFilesByFile);
346✔
1763

1764
            await this.plugins.emitAsync('afterBuildProgram', event);
346✔
1765

1766
            //undo all edits for the program
1767
            this.editor.undoAll();
346✔
1768
            //undo all edits for each file
1769
            for (const file of event.files) {
346✔
1770
                file.editor.undoAll();
702✔
1771
            }
1772
        });
1773
    }
1774

1775
    /**
1776
     * Find a list of files in the program that have a function with the given name (case INsensitive)
1777
     */
1778
    public findFilesForFunction(functionName: string) {
1779
        const files = [] as BscFile[];
7✔
1780
        const lowerFunctionName = functionName.toLowerCase();
7✔
1781
        //find every file with this function defined
1782
        for (const file of Object.values(this.files)) {
7✔
1783
            if (isBrsFile(file)) {
25✔
1784
                //TODO handle namespace-relative function calls
1785
                //if the file has a function with this name
1786
                // eslint-disable-next-line @typescript-eslint/dot-notation
1787
                if (file['_cachedLookups'].functionStatementMap.get(lowerFunctionName)) {
17✔
1788
                    files.push(file);
2✔
1789
                }
1790
            }
1791
        }
1792
        return files;
7✔
1793
    }
1794

1795
    /**
1796
     * Find a list of files in the program that have a class with the given name (case INsensitive)
1797
     */
1798
    public findFilesForClass(className: string) {
1799
        const files = [] as BscFile[];
7✔
1800
        const lowerClassName = className.toLowerCase();
7✔
1801
        //find every file with this class defined
1802
        for (const file of Object.values(this.files)) {
7✔
1803
            if (isBrsFile(file)) {
25✔
1804
                //TODO handle namespace-relative classes
1805
                //if the file has a function with this name
1806

1807
                // eslint-disable-next-line @typescript-eslint/dot-notation
1808
                if (file['_cachedLookups'].classStatementMap.get(lowerClassName) !== undefined) {
17✔
1809
                    files.push(file);
1✔
1810
                }
1811
            }
1812
        }
1813
        return files;
7✔
1814
    }
1815

1816
    public findFilesForNamespace(name: string) {
1817
        const files = [] as BscFile[];
7✔
1818
        const lowerName = name.toLowerCase();
7✔
1819
        //find every file with this class defined
1820
        for (const file of Object.values(this.files)) {
7✔
1821
            if (isBrsFile(file)) {
25✔
1822

1823
                // eslint-disable-next-line @typescript-eslint/dot-notation
1824
                if (file['_cachedLookups'].namespaceStatements.find((x) => {
17✔
1825
                    const namespaceName = x.name.toLowerCase();
7✔
1826
                    return (
7✔
1827
                        //the namespace name matches exactly
1828
                        namespaceName === lowerName ||
9✔
1829
                        //the full namespace starts with the name (honoring the part boundary)
1830
                        namespaceName.startsWith(lowerName + '.')
1831
                    );
1832
                })) {
1833
                    files.push(file);
6✔
1834
                }
1835
            }
1836
        }
1837

1838
        return files;
7✔
1839
    }
1840

1841
    public findFilesForEnum(name: string) {
1842
        const files = [] as BscFile[];
8✔
1843
        const lowerName = name.toLowerCase();
8✔
1844
        //find every file with this enum defined
1845
        for (const file of Object.values(this.files)) {
8✔
1846
            if (isBrsFile(file)) {
26✔
1847
                // eslint-disable-next-line @typescript-eslint/dot-notation
1848
                if (file['_cachedLookups'].enumStatementMap.get(lowerName)) {
18✔
1849
                    files.push(file);
1✔
1850
                }
1851
            }
1852
        }
1853
        return files;
8✔
1854
    }
1855

1856
    private _manifest: Map<string, string>;
1857

1858
    /**
1859
     * Modify a parsed manifest map by reading `bs_const` and injecting values from `options.manifest.bs_const`
1860
     * @param parsedManifest The manifest map to read from and modify
1861
     */
1862
    private buildBsConstsIntoParsedManifest(parsedManifest: Map<string, string>) {
1863
        // Lift the bs_consts defined in the manifest
1864
        let bsConsts = getBsConst(parsedManifest, false);
15✔
1865

1866
        // Override or delete any bs_consts defined in the bs config
1867
        for (const key in this.options?.manifest?.bs_const) {
15!
1868
            const value = this.options.manifest.bs_const[key];
3✔
1869
            if (value === null) {
3✔
1870
                bsConsts.delete(key);
1✔
1871
            } else {
1872
                bsConsts.set(key, value);
2✔
1873
            }
1874
        }
1875

1876
        // convert the new list of bs consts back into a string for the rest of the down stream systems to use
1877
        let constString = '';
15✔
1878
        for (const [key, value] of bsConsts) {
15✔
1879
            constString += `${constString !== '' ? ';' : ''}${key}=${value.toString()}`;
8✔
1880
        }
1881

1882
        // Set the updated bs_const value
1883
        parsedManifest.set('bs_const', constString);
15✔
1884
    }
1885

1886
    /**
1887
     * Try to find and load the manifest into memory
1888
     * @param manifestFileObj A pointer to a potential manifest file object found during loading
1889
     * @param replaceIfAlreadyLoaded should we overwrite the internal `_manifest` if it already exists
1890
     */
1891
    public loadManifest(manifestFileObj?: FileObj, replaceIfAlreadyLoaded = true) {
1,473✔
1892
        //if we already have a manifest instance, and should not replace...then don't replace
1893
        if (!replaceIfAlreadyLoaded && this._manifest) {
1,479!
UNCOV
1894
            return;
×
1895
        }
1896
        let manifestPath = manifestFileObj
1,479✔
1897
            ? manifestFileObj.src
1,479✔
1898
            : path.join(this.options.rootDir, 'manifest');
1899

1900
        try {
1,479✔
1901
            // we only load this manifest once, so do it sync to improve speed downstream
1902
            const contents = fsExtra.readFileSync(manifestPath, 'utf-8');
1,479✔
1903
            const parsedManifest = parseManifest(contents);
15✔
1904
            this.buildBsConstsIntoParsedManifest(parsedManifest);
15✔
1905
            this._manifest = parsedManifest;
15✔
1906
        } catch (e) {
1907
            this._manifest = new Map();
1,464✔
1908
        }
1909
    }
1910

1911
    /**
1912
     * Get a map of the manifest information
1913
     */
1914
    public getManifest() {
1915
        if (!this._manifest) {
2,305✔
1916
            this.loadManifest();
1,472✔
1917
        }
1918
        return this._manifest;
2,305✔
1919
    }
1920

1921
    public dispose() {
1922
        this.plugins.emit('beforeProgramDispose', { program: this });
1,646✔
1923

1924
        for (let filePath in this.files) {
1,646✔
1925
            this.files[filePath]?.dispose?.();
2,064!
1926
        }
1927
        for (let name in this.scopes) {
1,646✔
1928
            this.scopes[name]?.dispose?.();
3,482!
1929
        }
1930
        this.globalScope?.dispose?.();
1,646!
1931
        this.dependencyGraph?.dispose?.();
1,646!
1932
    }
1933
}
1934

1935
export interface FileTranspileResult {
1936
    srcPath: string;
1937
    destPath: string;
1938
    pkgPath: string;
1939
    code: string;
1940
    map: string;
1941
    typedef: string;
1942
}
1943

1944

1945
class ProvideFileEventInternal<TFile extends BscFile = BscFile> implements ProvideFileEvent<TFile> {
1946
    constructor(
1947
        public program: Program,
2,382✔
1948
        public srcPath: string,
2,382✔
1949
        public destPath: string,
2,382✔
1950
        public data: LazyFileData,
2,382✔
1951
        public fileFactory: FileFactory
2,382✔
1952
    ) {
1953
        this.srcExtension = path.extname(srcPath)?.toLowerCase();
2,382!
1954
    }
1955

1956
    public srcExtension: string;
1957

1958
    public files: TFile[] = [];
2,382✔
1959
}
1960

1961
export interface ProgramBuildOptions {
1962
    /**
1963
     * The directory where the final built files should be placed. This directory will be cleared before running
1964
     */
1965
    stagingDir?: string;
1966
    /**
1967
     * An array of files to build. If omitted, the entire list of files from the program will be used instead.
1968
     * Typically you will want to leave this blank
1969
     */
1970
    files?: BscFile[];
1971
}
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

© 2025 Coveralls, Inc