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

rokucommunity / brighterscript / #13309

22 Nov 2024 08:22PM UTC coverage: 86.806% (+0.005%) from 86.801%
#13309

push

web-flow
Merge a320d9302 into 2a6afd921

11836 of 14421 branches covered (82.07%)

Branch coverage included in aggregate %.

192 of 206 new or added lines in 26 files covered. (93.2%)

201 existing lines in 18 files now uncovered.

12869 of 14039 relevant lines covered (91.67%)

32035.69 hits per line

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

93.32
/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 } 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,791✔
80
        this.logger = logger ?? createLogger(options);
1,791✔
81
        this.plugins = plugins || new PluginInterface([], { logger: this.logger });
1,791✔
82
        this.diagnostics = diagnosticsManager || new DiagnosticManager();
1,791✔
83

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

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

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

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

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

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

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

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

131

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

160
        return nodeType;
331,335✔
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,791✔
169
        this.globalScope.symbolTable.addSymbol('double', undefined, DoubleType.instance, SymbolTypeFlag.typetime);
1,791✔
170
        this.globalScope.symbolTable.addSymbol('dynamic', undefined, DynamicType.instance, SymbolTypeFlag.typetime);
1,791✔
171
        this.globalScope.symbolTable.addSymbol('float', undefined, FloatType.instance, SymbolTypeFlag.typetime);
1,791✔
172
        this.globalScope.symbolTable.addSymbol('function', undefined, new FunctionType(), SymbolTypeFlag.typetime);
1,791✔
173
        this.globalScope.symbolTable.addSymbol('integer', undefined, IntegerType.instance, SymbolTypeFlag.typetime);
1,791✔
174
        this.globalScope.symbolTable.addSymbol('longinteger', undefined, LongIntegerType.instance, SymbolTypeFlag.typetime);
1,791✔
175
        this.globalScope.symbolTable.addSymbol('object', undefined, new ObjectType(), SymbolTypeFlag.typetime);
1,791✔
176
        this.globalScope.symbolTable.addSymbol('string', undefined, StringType.instance, SymbolTypeFlag.typetime);
1,791✔
177
        this.globalScope.symbolTable.addSymbol('void', undefined, VoidType.instance, SymbolTypeFlag.typetime);
1,791✔
178

179
        BuiltInInterfaceAdder.getLookupTable = () => this.globalScope.symbolTable;
787,354✔
180

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

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

192
        for (const componentData of Object.values(components) as BRSComponentData[]) {
1,791✔
193
            const nodeType = new InterfaceType(componentData.name);
116,415✔
194
            nodeType.addBuiltInInterfaces();
116,415✔
195
            nodeType.isBuiltIn = true;
116,415✔
196
            if (componentData.name !== 'roSGNode') {
116,415✔
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,624✔
199
            }
200
        }
201

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

206
        for (const eventData of Object.values(events) as BRSEventData[]) {
1,791✔
207
            const nodeType = new InterfaceType(eventData.name);
32,238✔
208
            nodeType.addBuiltInInterfaces();
32,238✔
209
            nodeType.isBuiltIn = true;
32,238✔
210
            this.globalScope.symbolTable.addSymbol(eventData.name, { description: eventData.description }, nodeType, SymbolTypeFlag.typetime);
32,238✔
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,791✔
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,791✔
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,791✔
237

238

239
    private componentsTable = new SymbolTable('Custom Components');
1,791✔
240

241
    public addFileSymbolInfo(file: BrsFile) {
242
        this.fileSymbolInformation.set(file.pkgPath, {
1,667✔
243
            provides: file.providedSymbols,
244
            requires: file.requiredSymbols
245
        });
246
    }
247

248
    public getFileSymbolInfo(file: BrsFile) {
249
        return this.fileSymbolInformation.get(file.pkgPath);
1,670✔
250
    }
251

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

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

264
            //default to the embedded version
265
        } else {
266
            return `${this.options.bslibDestinationDir}${path.sep}bslib.brs`;
2,347✔
267
        }
268
    }
269

270
    public get bslibPrefix() {
271
        if (this.bslibPkgPath === bslibNonAliasedRokuModulesPkgPath) {
1,737✔
272
            return 'rokucommunity_bslib';
18✔
273
        } else {
274
            return 'bslib';
1,719✔
275
        }
276
    }
277

278

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

294
    private scopes = {} as Record<string, Scope>;
1,791✔
295

296
    protected addScope(scope: Scope) {
297
        this.scopes[scope.name] = scope;
1,954✔
298
        delete this.sortedScopeNames;
1,954✔
299
    }
300

301
    protected removeScope(scope: Scope) {
302
        if (this.scopes[scope.name]) {
11!
303
            delete this.scopes[scope.name];
11✔
304
            delete this.sortedScopeNames;
11✔
305
        }
306
    }
307

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

316
    /**
317
     * Get the component with the specified name
318
     */
319
    public getComponent(componentName: string) {
320
        if (componentName) {
1,892✔
321
            //return the first compoment in the list with this name
322
            //(components are ordered in this list by destPath to ensure consistency)
323
            return this.components[componentName.toLowerCase()]?.[0];
1,878✔
324
        } else {
325
            return undefined;
14✔
326
        }
327
    }
328

329
    /**
330
     * Get the sorted names of custom components
331
     */
332
    public getSortedComponentNames() {
333
        const componentNames = Object.keys(this.components);
1,337✔
334
        componentNames.sort((a, b) => {
1,337✔
335
            if (a < b) {
703✔
336
                return -1;
279✔
337
            } else if (b < a) {
424!
338
                return 1;
424✔
339
            }
UNCOV
340
            return 0;
×
341
        });
342
        return componentNames;
1,337✔
343
    }
344

345
    /**
346
     * Keeps a set of all the components that need to have their types updated during the current validation cycle
347
     */
348
    private componentSymbolsToUpdate = new Set<{ componentKey: string; componentName: string }>();
1,791✔
349

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

376
    /**
377
     * Remove the specified component from the components map
378
     */
379
    private unregisterComponent(xmlFile: XmlFile) {
380
        const key = this.getComponentKey(xmlFile);
11✔
381
        const arr = this.components[key] || [];
11!
382
        for (let i = 0; i < arr.length; i++) {
11✔
383
            if (arr[i].file === xmlFile) {
11!
384
                arr.splice(i, 1);
11✔
385
                break;
11✔
386
            }
387
        }
388

389
        this.syncComponentDependencyGraph(arr);
11✔
390
        this.addDeferredComponentTypeSymbolCreation(xmlFile);
11✔
391
    }
392

393
    /**
394
     * Adds a component described in an XML to the set of components that needs to be updated this validation cycle.
395
     * @param xmlFile XML file with <component> tag
396
     */
397
    private addDeferredComponentTypeSymbolCreation(xmlFile: XmlFile) {
398
        this.componentSymbolsToUpdate.add({ componentKey: this.getComponentKey(xmlFile), componentName: xmlFile.componentName?.text });
410✔
399

400
    }
401

402
    private getComponentKey(xmlFile: XmlFile) {
403
        return (xmlFile.componentName?.text ?? xmlFile.pkgPath).toLowerCase();
820✔
404
    }
405

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

423
            componentScope.linkSymbolTable();
321✔
424
            const componentType = componentScope.getComponentType();
321✔
425
            if (componentType) {
321!
426
                this.componentsTable.addSymbol(symbolName, {}, componentType, SymbolTypeFlag.typetime);
321✔
427
            }
428
            componentScope.unlinkSymbolTable();
321✔
429
        }
430
    }
431

432
    /**
433
     * 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
434
     * @param componentKey key getting a component from `this.components`
435
     * @param componentName the unprefixed name of the component that will be added (e.g. 'MyLabel' NOT 'roSgNodeMyLabel')
436
     */
437
    private addComponentReferenceType(componentKey: string, componentName: string) {
438
        const symbolName = componentName ? util.getSgNodeTypeName(componentName) : undefined;
329✔
439
        if (!symbolName) {
329✔
440
            return;
7✔
441
        }
442
        const components = this.components[componentKey] || [];
322!
443
        // Remove any existing symbols that match
444
        this.globalScope.symbolTable.removeSymbol(symbolName);
322✔
445
        // There is a component that can be added - use it.
446
        if (components.length > 0) {
322✔
447

448
            const componentRefType = new ReferenceType(symbolName, symbolName, SymbolTypeFlag.typetime, () => this.componentsTable);
2,048✔
449
            if (componentRefType) {
321!
450
                this.globalScope.symbolTable.addSymbol(symbolName, {}, componentRefType, SymbolTypeFlag.typetime);
321✔
451
            }
452

453
        }
454
    }
455

456
    /**
457
     * re-attach the dependency graph with a new key for any component who changed
458
     * their position in their own named array (only matters when there are multiple
459
     * components with the same name)
460
     */
461
    private syncComponentDependencyGraph(components: Array<{ file: XmlFile; scope: XmlScope }>) {
462
        //reattach every dependency graph
463
        for (let i = 0; i < components.length; i++) {
410✔
464
            const { file, scope } = components[i];
405✔
465

466
            //attach (or re-attach) the dependencyGraph for every component whose position changed
467
            if (file.dependencyGraphIndex !== i) {
405✔
468
                file.dependencyGraphIndex = i;
401✔
469
                this.dependencyGraph.addOrReplace(file.dependencyGraphKey, file.dependencies);
401✔
470
                file.attachDependencyGraph(this.dependencyGraph);
401✔
471
                scope.attachDependencyGraph(this.dependencyGraph);
401✔
472
            }
473
        }
474
    }
475

476
    /**
477
     * Get a list of all files that are included in the project but are not referenced
478
     * by any scope in the program.
479
     */
480
    public getUnreferencedFiles() {
UNCOV
481
        let result = [] as BscFile[];
×
UNCOV
482
        for (let filePath in this.files) {
×
UNCOV
483
            let file = this.files[filePath];
×
484
            //is this file part of a scope
UNCOV
485
            if (!this.getFirstScopeForFile(file)) {
×
486
                //no scopes reference this file. add it to the list
UNCOV
487
                result.push(file);
×
488
            }
489
        }
UNCOV
490
        return result;
×
491
    }
492

493
    /**
494
     * Get the list of errors for the entire program.
495
     */
496
    public getDiagnostics() {
497
        return this.diagnostics.getDiagnostics();
1,135✔
498
    }
499

500
    /**
501
     * Determine if the specified file is loaded in this program right now.
502
     * @param filePath the absolute or relative path to the file
503
     * @param normalizePath should the provided path be normalized before use
504
     */
505
    public hasFile(filePath: string, normalizePath = true) {
2,553✔
506
        return !!this.getFile(filePath, normalizePath);
2,553✔
507
    }
508

509
    /**
510
     * roku filesystem is case INsensitive, so find the scope by key case insensitive
511
     * @param scopeName xml scope names are their `destPath`. Source scope is stored with the key `"source"`
512
     */
513
    public getScopeByName(scopeName: string): Scope | undefined {
514
        if (!scopeName) {
60!
UNCOV
515
            return undefined;
×
516
        }
517
        //most scopes are xml file pkg paths. however, the ones that are not are single names like "global" and "scope",
518
        //so it's safe to run the standardizePkgPath method
519
        scopeName = s`${scopeName}`;
60✔
520
        let key = Object.keys(this.scopes).find(x => x.toLowerCase() === scopeName.toLowerCase());
137✔
521
        return this.scopes[key!];
60✔
522
    }
523

524
    /**
525
     * Return all scopes
526
     */
527
    public getScopes() {
528
        return Object.values(this.scopes);
10✔
529
    }
530

531
    /**
532
     * Find the scope for the specified component
533
     */
534
    public getComponentScope(componentName: string) {
535
        return this.getComponent(componentName)?.scope;
448✔
536
    }
537

538
    /**
539
     * Update internal maps with this file reference
540
     */
541
    private assignFile<T extends BscFile = BscFile>(file: T) {
542
        const fileAddEvent: BeforeFileAddEvent = {
2,374✔
543
            file: file,
544
            program: this
545
        };
546

547
        this.plugins.emit('beforeFileAdd', fileAddEvent);
2,374✔
548

549
        this.files[file.srcPath.toLowerCase()] = file;
2,374✔
550
        this.destMap.set(file.destPath.toLowerCase(), file);
2,374✔
551

552
        this.plugins.emit('afterFileAdd', fileAddEvent);
2,374✔
553

554
        return file;
2,374✔
555
    }
556

557
    /**
558
     * Remove this file from internal maps
559
     */
560
    private unassignFile<T extends BscFile = BscFile>(file: T) {
561
        delete this.files[file.srcPath.toLowerCase()];
152✔
562
        this.destMap.delete(file.destPath.toLowerCase());
152✔
563
        return file;
152✔
564
    }
565

566
    /**
567
     * Load a file into the program. If that file already exists, it is replaced.
568
     * If file contents are provided, those are used, Otherwise, the file is loaded from the file system
569
     * @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:/`)
570
     * @param fileData the file contents. omit or pass `undefined` to prevent loading the data at this time
571
     */
572
    public setFile<T extends BscFile>(srcDestOrPkgPath: string, fileData?: FileData): T;
573
    /**
574
     * Load a file into the program. If that file already exists, it is replaced.
575
     * @param fileEntry an object that specifies src and dest for the file.
576
     * @param fileData the file contents. omit or pass `undefined` to prevent loading the data at this time
577
     */
578
    public setFile<T extends BscFile>(fileEntry: FileObj, fileData: FileData): T;
579
    public setFile<T extends BscFile>(fileParam: FileObj | string, fileData: FileData): T {
580
        //normalize the file paths
581
        const { srcPath, destPath } = this.getPaths(fileParam, this.options.rootDir);
2,370✔
582

583
        let file = this.logger.time(LogLevel.debug, ['Program.setFile()', chalk.green(srcPath)], () => {
2,370✔
584
            //if the file is already loaded, remove it
585
            if (this.hasFile(srcPath)) {
2,370✔
586
                this.removeFile(srcPath, true, true);
136✔
587
            }
588

589
            const data = new LazyFileData(fileData);
2,370✔
590

591
            const event = new ProvideFileEventInternal(this, srcPath, destPath, data, this.fileFactory);
2,370✔
592

593
            this.plugins.emit('beforeProvideFile', event);
2,370✔
594
            this.plugins.emit('provideFile', event);
2,370✔
595
            this.plugins.emit('afterProvideFile', event);
2,370✔
596

597
            //if no files were provided, create a AssetFile to represent it.
598
            if (event.files.length === 0) {
2,370✔
599
                event.files.push(
18✔
600
                    this.fileFactory.AssetFile({
601
                        srcPath: event.srcPath,
602
                        destPath: event.destPath,
603
                        pkgPath: event.destPath,
604
                        data: data
605
                    })
606
                );
607
            }
608

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

612
            if (!primaryFile) {
2,370!
UNCOV
613
                throw new Error(`No file provided for srcPath '${srcPath}'. Instead, received ${JSON.stringify(event.files.map(x => ({
×
614
                    type: x.type,
615
                    srcPath: x.srcPath,
616
                    destPath: x.destPath
617
                })))}`);
618
            }
619

620
            //link the virtual files to the primary file
621
            this.fileClusters.set(primaryFile.srcPath?.toLowerCase(), event.files);
2,370!
622

623
            for (const file of event.files) {
2,370✔
624
                file.srcPath = s(file.srcPath);
2,374✔
625
                if (file.destPath) {
2,374!
626
                    file.destPath = s`${util.replaceCaseInsensitive(file.destPath, this.options.rootDir, '')}`;
2,374✔
627
                }
628
                if (file.pkgPath) {
2,374✔
629
                    file.pkgPath = s`${util.replaceCaseInsensitive(file.pkgPath, this.options.rootDir, '')}`;
2,370✔
630
                } else {
631
                    file.pkgPath = file.destPath;
4✔
632
                }
633
                file.excludeFromOutput = file.excludeFromOutput === true;
2,374✔
634

635
                //set the dependencyGraph key for every file to its destPath
636
                file.dependencyGraphKey = file.destPath.toLowerCase();
2,374✔
637

638
                this.assignFile(file);
2,374✔
639

640
                //register a callback anytime this file's dependencies change
641
                if (typeof file.onDependenciesChanged === 'function') {
2,374✔
642
                    file.disposables ??= [];
2,348!
643
                    file.disposables.push(
2,348✔
644
                        this.dependencyGraph.onchange(file.dependencyGraphKey, file.onDependenciesChanged.bind(file))
645
                    );
646
                }
647

648
                //register this file (and its dependencies) with the dependency graph
649
                this.dependencyGraph.addOrReplace(file.dependencyGraphKey, file.dependencies ?? []);
2,374✔
650

651
                //if this is a `source` file, add it to the source scope's dependency list
652
                if (this.isSourceBrsFile(file)) {
2,374✔
653
                    this.createSourceScope();
1,598✔
654
                    this.dependencyGraph.addDependency('scope:source', file.dependencyGraphKey);
1,598✔
655
                }
656

657
                //if this is an xml file in the components folder, register it as a component
658
                if (this.isComponentsXmlFile(file)) {
2,374✔
659
                    //create a new scope for this xml file
660
                    let scope = new XmlScope(file, this);
399✔
661
                    this.addScope(scope);
399✔
662

663
                    //register this componet now that we have parsed it and know its component name
664
                    this.registerComponent(file, scope);
399✔
665

666
                    //notify plugins that the scope is created and the component is registered
667
                    this.plugins.emit('afterScopeCreate', {
399✔
668
                        program: this,
669
                        scope: scope
670
                    });
671
                }
672
            }
673

674
            return primaryFile;
2,370✔
675
        });
676
        return file as T;
2,370✔
677
    }
678

679
    /**
680
     * Given a srcPath, a destPath, or both, resolve whichever is missing, relative to rootDir.
681
     * @param fileParam an object representing file paths
682
     * @param rootDir must be a pre-normalized path
683
     */
684
    private getPaths(fileParam: string | FileObj | { srcPath?: string; pkgPath?: string }, rootDir: string) {
685
        let srcPath: string | undefined;
686
        let destPath: string | undefined;
687

688
        assert.ok(fileParam, 'fileParam is required');
2,525✔
689

690
        //lift the path vars from the incoming param
691
        if (typeof fileParam === 'string') {
2,525✔
692
            fileParam = this.removePkgPrefix(fileParam);
2,178✔
693
            srcPath = s`${path.resolve(rootDir, fileParam)}`;
2,178✔
694
            destPath = s`${util.replaceCaseInsensitive(srcPath, rootDir, '')}`;
2,178✔
695
        } else {
696
            let param: any = fileParam;
347✔
697

698
            if (param.src) {
347✔
699
                srcPath = s`${param.src}`;
346✔
700
            }
701
            if (param.srcPath) {
347!
UNCOV
702
                srcPath = s`${param.srcPath}`;
×
703
            }
704
            if (param.dest) {
347✔
705
                destPath = s`${this.removePkgPrefix(param.dest)}`;
346✔
706
            }
707
            if (param.pkgPath) {
347!
UNCOV
708
                destPath = s`${this.removePkgPrefix(param.pkgPath)}`;
×
709
            }
710
        }
711

712
        //if there's no srcPath, use the destPath to build an absolute srcPath
713
        if (!srcPath) {
2,525✔
714
            srcPath = s`${rootDir}/${destPath}`;
1✔
715
        }
716
        //coerce srcPath to an absolute path
717
        if (!path.isAbsolute(srcPath)) {
2,525✔
718
            srcPath = util.standardizePath(srcPath);
1✔
719
        }
720

721
        //if destPath isn't set, compute it from the other paths
722
        if (!destPath) {
2,525✔
723
            destPath = s`${util.replaceCaseInsensitive(srcPath, rootDir, '')}`;
1✔
724
        }
725

726
        assert.ok(srcPath, 'fileEntry.src is required');
2,525✔
727
        assert.ok(destPath, 'fileEntry.dest is required');
2,525✔
728

729
        return {
2,525✔
730
            srcPath: srcPath,
731
            //remove leading slash
732
            destPath: destPath.replace(/^[\/\\]+/, '')
733
        };
734
    }
735

736
    /**
737
     * Remove any leading `pkg:/` found in the path
738
     */
739
    private removePkgPrefix(path: string) {
740
        return path.replace(/^pkg:\//i, '');
2,524✔
741
    }
742

743
    /**
744
     * Is this file a .brs file found somewhere within the `pkg:/source/` folder?
745
     */
746
    private isSourceBrsFile(file: BscFile) {
747
        return !!/^(pkg:\/)?source[\/\\]/.exec(file.destPath);
2,526✔
748
    }
749

750
    /**
751
     * Is this file a .brs file found somewhere within the `pkg:/source/` folder?
752
     */
753
    private isComponentsXmlFile(file: BscFile): file is XmlFile {
754
        return isXmlFile(file) && !!/^(pkg:\/)?components[\/\\]/.exec(file.destPath);
2,374✔
755
    }
756

757
    /**
758
     * Ensure source scope is created.
759
     * Note: automatically called internally, and no-op if it exists already.
760
     */
761
    public createSourceScope() {
762
        if (!this.scopes.source) {
2,353✔
763
            const sourceScope = new Scope('source', this, 'scope:source');
1,555✔
764
            sourceScope.attachDependencyGraph(this.dependencyGraph);
1,555✔
765
            this.addScope(sourceScope);
1,555✔
766
            this.plugins.emit('afterScopeCreate', {
1,555✔
767
                program: this,
768
                scope: sourceScope
769
            });
770
        }
771
    }
772

773
    /**
774
     * Remove a set of files from the program
775
     * @param srcPaths can be an array of srcPath or destPath strings
776
     * @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
777
     */
778
    public removeFiles(srcPaths: string[], normalizePath = true) {
1✔
779
        for (let srcPath of srcPaths) {
1✔
780
            this.removeFile(srcPath, normalizePath);
1✔
781
        }
782
    }
783

784
    /**
785
     * Remove a file from the program
786
     * @param filePath can be a srcPath, a destPath, or a destPath with leading `pkg:/`
787
     * @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
788
     */
789
    public removeFile(filePath: string, normalizePath = true, keepSymbolInformation = false) {
27✔
790
        this.logger.debug('Program.removeFile()', filePath);
150✔
791
        const paths = this.getPaths(filePath, this.options.rootDir);
150✔
792

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

796
        for (const file of files) {
150✔
797
            //if a file has already been removed, nothing more needs to be done here
798
            if (!file || !this.hasFile(file.srcPath)) {
153✔
799
                continue;
1✔
800
            }
801
            this.diagnostics.clearForFile(file.srcPath);
152✔
802

803
            const event: BeforeFileRemoveEvent = { file: file, program: this };
152✔
804
            this.plugins.emit('beforeFileRemove', event);
152✔
805

806
            //if there is a scope named the same as this file's path, remove it (i.e. xml scopes)
807
            let scope = this.scopes[file.destPath];
152✔
808
            if (scope) {
152✔
809
                const scopeDisposeEvent = {
11✔
810
                    program: this,
811
                    scope: scope
812
                };
813
                this.plugins.emit('beforeScopeDispose', scopeDisposeEvent);
11✔
814
                this.plugins.emit('onScopeDispose', scopeDisposeEvent);
11✔
815
                scope.dispose();
11✔
816
                //notify dependencies of this scope that it has been removed
817
                this.dependencyGraph.remove(scope.dependencyGraphKey!);
11✔
818
                this.removeScope(this.scopes[file.destPath]);
11✔
819
                this.plugins.emit('afterScopeDispose', scopeDisposeEvent);
11✔
820
            }
821
            //remove the file from the program
822
            this.unassignFile(file);
152✔
823

824
            this.dependencyGraph.remove(file.dependencyGraphKey);
152✔
825

826
            //if this is a pkg:/source file, notify the `source` scope that it has changed
827
            if (this.isSourceBrsFile(file)) {
152✔
828
                this.dependencyGraph.removeDependency('scope:source', file.dependencyGraphKey);
126✔
829
            }
830
            if (isBrsFile(file)) {
152✔
831
                if (!keepSymbolInformation) {
135✔
832
                    this.fileSymbolInformation.delete(file.pkgPath);
8✔
833
                }
834
                this.crossScopeValidation.clearResolutionsForFile(file);
135✔
835
            }
836

837
            //if this is a component, remove it from our components map
838
            if (isXmlFile(file)) {
152✔
839
                this.unregisterComponent(file);
11✔
840
            }
841
            //dispose any disposable things on the file
842
            for (const disposable of file?.disposables ?? []) {
152!
843
                disposable();
146✔
844
            }
845
            //dispose file
846
            file?.dispose?.();
152!
847

848
            this.plugins.emit('afterFileRemove', event);
152✔
849
        }
850
    }
851

852
    public crossScopeValidation = new CrossScopeValidator(this);
1,791✔
853

854
    private isFirstValidation = true;
1,791✔
855

856
    /**
857
     * Traverse the entire project, and validate all scopes
858
     */
859
    public validate() {
860
        this.logger.time(LogLevel.log, ['Validating project'], () => {
1,337✔
861
            this.diagnostics.clearForTag(ProgramValidatorDiagnosticsTag);
1,337✔
862
            const programValidateEvent = {
1,337✔
863
                program: this
864
            };
865
            this.plugins.emit('beforeProgramValidate', programValidateEvent);
1,337✔
866
            this.plugins.emit('onProgramValidate', programValidateEvent);
1,337✔
867

868
            const metrics = {
1,337✔
869
                filesChanged: 0,
870
                filesValidated: 0,
871
                fileValidationTime: '',
872
                crossScopeValidationTime: '',
873
                scopesValidated: 0,
874
                totalLinkTime: '',
875
                totalScopeValidationTime: '',
876
                componentValidationTime: ''
877
            };
878

879
            const validationStopwatch = new Stopwatch();
1,337✔
880
            //validate every file
881
            const brsFilesValidated: BrsFile[] = [];
1,337✔
882
            const afterValidateFiles: BscFile[] = [];
1,337✔
883

884
            // Create reference component types for any component that changes
885
            this.logger.time(LogLevel.info, ['Build component types'], () => {
1,337✔
886
                for (let { componentKey, componentName } of this.componentSymbolsToUpdate) {
1,337✔
887
                    this.addComponentReferenceType(componentKey, componentName);
329✔
888
                }
889
            });
890

891

892
            metrics.fileValidationTime = validationStopwatch.getDurationTextFor(() => {
1,337✔
893
                //sort files by path so we get consistent results
894
                const files = Object.values(this.files).sort(firstBy(x => x.srcPath));
3,618✔
895
                for (const file of files) {
1,337✔
896
                    //for every unvalidated file, validate it
897
                    if (!file.isValidated) {
2,267✔
898
                        const validateFileEvent = {
1,935✔
899
                            program: this,
900
                            file: file
901
                        };
902
                        this.plugins.emit('beforeFileValidate', validateFileEvent);
1,935✔
903
                        //emit an event to allow plugins to contribute to the file validation process
904
                        this.plugins.emit('onFileValidate', validateFileEvent);
1,935✔
905
                        file.isValidated = true;
1,935✔
906
                        if (isBrsFile(file)) {
1,935✔
907
                            brsFilesValidated.push(file);
1,609✔
908
                        }
909
                        afterValidateFiles.push(file);
1,935✔
910
                    }
911
                }
912
                // AfterFileValidate is after all files have been validated
913
                for (const file of afterValidateFiles) {
1,337✔
914
                    const validateFileEvent = {
1,935✔
915
                        program: this,
916
                        file: file
917
                    };
918
                    this.plugins.emit('afterFileValidate', validateFileEvent);
1,935✔
919
                }
920
            }).durationText;
921

922
            metrics.filesChanged = afterValidateFiles.length;
1,337✔
923

924
            // Build component types for any component that changes
925
            this.logger.time(LogLevel.info, ['Build component types'], () => {
1,337✔
926
                for (let { componentKey, componentName } of this.componentSymbolsToUpdate) {
1,337✔
927
                    this.updateComponentSymbolInGlobalScope(componentKey, componentName);
329✔
928
                }
929
                this.componentSymbolsToUpdate.clear();
1,337✔
930
            });
931

932

933
            const changedSymbolsMapArr = brsFilesValidated?.map(f => {
1,337!
934
                if (isBrsFile(f)) {
1,609!
935
                    return f.providedSymbols.changes;
1,609✔
936
                }
UNCOV
937
                return null;
×
938
            }).filter(x => x);
1,609✔
939

940
            const changedSymbols = new Map<SymbolTypeFlag, Set<string>>();
1,337✔
941
            for (const flag of [SymbolTypeFlag.runtime, SymbolTypeFlag.typetime]) {
1,337✔
942
                const changedSymbolsSetArr = changedSymbolsMapArr.map(symMap => symMap.get(flag));
3,218✔
943
                changedSymbols.set(flag, new Set(...changedSymbolsSetArr));
2,674✔
944
            }
945

946
            const filesToBeValidatedInScopeContext = new Set<BscFile>(afterValidateFiles);
1,337✔
947

948
            metrics.crossScopeValidationTime = validationStopwatch.getDurationTextFor(() => {
1,337✔
949
                const scopesToCheck = this.getScopesForCrossScopeValidation();
1,337✔
950
                this.crossScopeValidation.buildComponentsMap();
1,337✔
951
                this.crossScopeValidation.addDiagnosticsForScopes(scopesToCheck);
1,337✔
952
                const filesToRevalidate = this.crossScopeValidation.getFilesRequiringChangedSymbol(scopesToCheck, changedSymbols);
1,337✔
953
                for (const file of filesToRevalidate) {
1,337✔
954
                    filesToBeValidatedInScopeContext.add(file);
178✔
955
                }
956
            }).durationText;
957

958
            metrics.filesValidated = filesToBeValidatedInScopeContext.size;
1,337✔
959

960
            let linkTime = 0;
1,337✔
961
            let validationTime = 0;
1,337✔
962
            let scopesValidated = 0;
1,337✔
963
            let changedFiles = new Set<BscFile>(afterValidateFiles);
1,337✔
964
            this.logger.time(LogLevel.info, ['Validate all scopes'], () => {
1,337✔
965
                //sort the scope names so we get consistent results
966
                const scopeNames = this.getSortedScopeNames();
1,337✔
967
                for (const file of filesToBeValidatedInScopeContext) {
1,337✔
968
                    if (isBrsFile(file)) {
2,056✔
969
                        file.validationSegmenter.unValidateAllSegments();
1,730✔
970
                    }
971
                }
972
                for (let scopeName of scopeNames) {
1,337✔
973
                    let scope = this.scopes[scopeName];
3,043✔
974
                    const scopeValidated = scope.validate({
3,043✔
975
                        filesToBeValidatedInScopeContext: filesToBeValidatedInScopeContext,
976
                        changedSymbols: changedSymbols,
977
                        changedFiles: changedFiles,
978
                        initialValidation: this.isFirstValidation
979
                    });
980
                    if (scopeValidated) {
3,043✔
981
                        scopesValidated++;
1,656✔
982
                    }
983
                    linkTime += scope.validationMetrics.linkTime;
3,043✔
984
                    validationTime += scope.validationMetrics.validationTime;
3,043✔
985
                }
986
            });
987
            metrics.scopesValidated = scopesValidated;
1,337✔
988
            validationStopwatch.totalMilliseconds = linkTime;
1,337✔
989
            metrics.totalLinkTime = validationStopwatch.getDurationText();
1,337✔
990

991
            validationStopwatch.totalMilliseconds = validationTime;
1,337✔
992
            metrics.totalScopeValidationTime = validationStopwatch.getDurationText();
1,337✔
993

994
            metrics.componentValidationTime = validationStopwatch.getDurationTextFor(() => {
1,337✔
995
                this.detectDuplicateComponentNames();
1,337✔
996
            }).durationText;
997

998
            this.logValidationMetrics(metrics);
1,337✔
999

1000
            this.isFirstValidation = false;
1,337✔
1001

1002
            this.plugins.emit('afterProgramValidate', programValidateEvent);
1,337✔
1003
        });
1004
    }
1005

1006
    // eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style
1007
    private logValidationMetrics(metrics: { [key: string]: number | string }) {
1008
        let logs = [] as string[];
1,337✔
1009
        for (const key in metrics) {
1,337✔
1010
            logs.push(`${key}=${chalk.yellow(metrics[key].toString())}`);
10,696✔
1011
        }
1012
        this.logger.info(`Validation Metrics: ${logs.join(', ')}`);
1,337✔
1013
    }
1014

1015
    private getScopesForCrossScopeValidation() {
1016
        const scopesForCrossScopeValidation = [];
1,337✔
1017
        for (let scopeName of this.getSortedScopeNames()) {
1,337✔
1018
            let scope = this.scopes[scopeName];
3,043✔
1019
            if (this.globalScope !== scope && !scope.isValidated) {
3,043✔
1020
                scopesForCrossScopeValidation.push(scope);
1,677✔
1021
            }
1022
        }
1023
        return scopesForCrossScopeValidation;
1,337✔
1024
    }
1025

1026
    /**
1027
     * Flag all duplicate component names
1028
     */
1029
    private detectDuplicateComponentNames() {
1030
        const componentsByName = Object.keys(this.files).reduce<Record<string, XmlFile[]>>((map, filePath) => {
1,337✔
1031
            const file = this.files[filePath];
2,267✔
1032
            //if this is an XmlFile, and it has a valid `componentName` property
1033
            if (isXmlFile(file) && file.componentName?.text) {
2,267✔
1034
                let lowerName = file.componentName.text.toLowerCase();
458✔
1035
                if (!map[lowerName]) {
458✔
1036
                    map[lowerName] = [];
455✔
1037
                }
1038
                map[lowerName].push(file);
458✔
1039
            }
1040
            return map;
2,267✔
1041
        }, {});
1042

1043
        for (let name in componentsByName) {
1,337✔
1044
            const xmlFiles = componentsByName[name];
455✔
1045
            //add diagnostics for every duplicate component with this name
1046
            if (xmlFiles.length > 1) {
455✔
1047
                for (let xmlFile of xmlFiles) {
3✔
1048
                    const { componentName } = xmlFile;
6✔
1049
                    this.diagnostics.register({
6✔
1050
                        ...DiagnosticMessages.duplicateComponentName(componentName.text),
1051
                        location: xmlFile.componentName.location,
1052
                        relatedInformation: xmlFiles.filter(x => x !== xmlFile).map(x => {
12✔
1053
                            return {
6✔
1054
                                location: x.componentName.location,
1055
                                message: 'Also defined here'
1056
                            };
1057
                        })
1058
                    }, { tags: [ProgramValidatorDiagnosticsTag] });
1059
                }
1060
            }
1061
        }
1062
    }
1063

1064
    /**
1065
     * Get the files for a list of filePaths
1066
     * @param filePaths can be an array of srcPath or a destPath strings
1067
     * @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
1068
     */
1069
    public getFiles<T extends BscFile>(filePaths: string[], normalizePath = true) {
29✔
1070
        return filePaths
29✔
1071
            .map(filePath => this.getFile(filePath, normalizePath))
39✔
1072
            .filter(file => file !== undefined) as T[];
39✔
1073
    }
1074

1075
    /**
1076
     * Get the file at the given path
1077
     * @param filePath can be a srcPath or a destPath
1078
     * @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
1079
     */
1080
    public getFile<T extends BscFile>(filePath: string, normalizePath = true) {
14,236✔
1081
        if (typeof filePath !== 'string') {
18,255✔
1082
            return undefined;
3,363✔
1083
            //is the path absolute (or the `virtual:` prefix)
1084
        } else if (/^(?:(?:virtual:[\/\\])|(?:\w:)|(?:[\/\\]))/gmi.exec(filePath)) {
14,892✔
1085
            return this.files[
4,578✔
1086
                (normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase()
4,578!
1087
            ] as T;
1088
        } else if (util.isUriLike(filePath)) {
10,314✔
1089
            const path = URI.parse(filePath).fsPath;
687✔
1090
            return this.files[
687✔
1091
                (normalizePath ? util.standardizePath(path) : path).toLowerCase()
687!
1092
            ] as T;
1093
        } else {
1094
            return this.destMap.get(
9,627✔
1095
                (normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase()
9,627✔
1096
            ) as T;
1097
        }
1098
    }
1099

1100
    private sortedScopeNames: string[] = undefined;
1,791✔
1101

1102
    /**
1103
     * Gets a sorted list of all scopeNames, always beginning with "global", "source", then any others in alphabetical order
1104
     */
1105
    private getSortedScopeNames() {
1106
        if (!this.sortedScopeNames) {
7,358✔
1107
            this.sortedScopeNames = Object.keys(this.scopes).sort((a, b) => {
1,292✔
1108
                if (a === 'global') {
1,855!
UNCOV
1109
                    return -1;
×
1110
                } else if (b === 'global') {
1,855✔
1111
                    return 1;
1,274✔
1112
                }
1113
                if (a === 'source') {
581✔
1114
                    return -1;
27✔
1115
                } else if (b === 'source') {
554✔
1116
                    return 1;
125✔
1117
                }
1118
                if (a < b) {
429✔
1119
                    return -1;
179✔
1120
                } else if (b < a) {
250!
1121
                    return 1;
250✔
1122
                }
UNCOV
1123
                return 0;
×
1124
            });
1125
        }
1126
        return this.sortedScopeNames;
7,358✔
1127
    }
1128

1129
    /**
1130
     * Get a list of all scopes the file is loaded into
1131
     * @param file the file
1132
     */
1133
    public getScopesForFile(file: BscFile | string) {
1134
        const resolvedFile = typeof file === 'string' ? this.getFile(file) : file;
720✔
1135

1136
        let result = [] as Scope[];
720✔
1137
        if (resolvedFile) {
720✔
1138
            const scopeKeys = this.getSortedScopeNames();
719✔
1139
            for (let key of scopeKeys) {
719✔
1140
                let scope = this.scopes[key];
1,507✔
1141

1142
                if (scope.hasFile(resolvedFile)) {
1,507✔
1143
                    result.push(scope);
733✔
1144
                }
1145
            }
1146
        }
1147
        return result;
720✔
1148
    }
1149

1150
    /**
1151
     * Get the first found scope for a file.
1152
     */
1153
    public getFirstScopeForFile(file: BscFile): Scope | undefined {
1154
        const scopeKeys = this.getSortedScopeNames();
3,965✔
1155
        for (let key of scopeKeys) {
3,965✔
1156
            let scope = this.scopes[key];
18,306✔
1157

1158
            if (scope.hasFile(file)) {
18,306✔
1159
                return scope;
2,890✔
1160
            }
1161
        }
1162
    }
1163

1164
    public getStatementsByName(name: string, originFile: BrsFile, namespaceName?: string): FileLink<Statement>[] {
1165
        let results = new Map<Statement, FileLink<Statement>>();
39✔
1166
        const filesSearched = new Set<BrsFile>();
39✔
1167
        let lowerNamespaceName = namespaceName?.toLowerCase();
39✔
1168
        let lowerName = name?.toLowerCase();
39!
1169

1170
        function addToResults(statement: FunctionStatement | MethodStatement, file: BrsFile) {
1171
            let parentNamespaceName = statement.findAncestor<NamespaceStatement>(isNamespaceStatement)?.getName(originFile.parseMode)?.toLowerCase();
98✔
1172
            if (statement.tokens.name.text.toLowerCase() === lowerName && (!lowerNamespaceName || parentNamespaceName === lowerNamespaceName)) {
98✔
1173
                if (!results.has(statement)) {
36!
1174
                    results.set(statement, { item: statement, file: file as BrsFile });
36✔
1175
                }
1176
            }
1177
        }
1178

1179
        //look through all files in scope for matches
1180
        for (const scope of this.getScopesForFile(originFile)) {
39✔
1181
            for (const file of scope.getAllFiles()) {
39✔
1182
                //skip non-brs files, or files we've already processed
1183
                if (!isBrsFile(file) || filesSearched.has(file)) {
45✔
1184
                    continue;
3✔
1185
                }
1186
                filesSearched.add(file);
42✔
1187

1188
                file.ast.walk(createVisitor({
42✔
1189
                    FunctionStatement: (statement: FunctionStatement) => {
1190
                        addToResults(statement, file);
95✔
1191
                    },
1192
                    MethodStatement: (statement: MethodStatement) => {
1193
                        addToResults(statement, file);
3✔
1194
                    }
1195
                }), {
1196
                    walkMode: WalkMode.visitStatements
1197
                });
1198
            }
1199
        }
1200
        return [...results.values()];
39✔
1201
    }
1202

1203
    public getStatementsForXmlFile(scope: XmlScope, filterName?: string): FileLink<FunctionStatement>[] {
1204
        let results = new Map<Statement, FileLink<FunctionStatement>>();
8✔
1205
        const filesSearched = new Set<BrsFile>();
8✔
1206

1207
        //get all function names for the xml file and parents
1208
        let funcNames = new Set<string>();
8✔
1209
        let currentScope = scope;
8✔
1210
        while (isXmlScope(currentScope)) {
8✔
1211
            for (let name of currentScope.xmlFile.ast.componentElement.interfaceElement?.functions.map((f) => f.name) ?? []) {
14✔
1212
                if (!filterName || name === filterName) {
14!
1213
                    funcNames.add(name);
14✔
1214
                }
1215
            }
1216
            currentScope = currentScope.getParentScope() as XmlScope;
10✔
1217
        }
1218

1219
        //look through all files in scope for matches
1220
        for (const file of scope.getOwnFiles()) {
8✔
1221
            //skip non-brs files, or files we've already processed
1222
            if (!isBrsFile(file) || filesSearched.has(file)) {
16✔
1223
                continue;
8✔
1224
            }
1225
            filesSearched.add(file);
8✔
1226

1227
            file.ast.walk(createVisitor({
8✔
1228
                FunctionStatement: (statement: FunctionStatement) => {
1229
                    if (funcNames.has(statement.tokens.name.text)) {
13!
1230
                        if (!results.has(statement)) {
13!
1231
                            results.set(statement, { item: statement, file: file });
13✔
1232
                        }
1233
                    }
1234
                }
1235
            }), {
1236
                walkMode: WalkMode.visitStatements
1237
            });
1238
        }
1239
        return [...results.values()];
8✔
1240
    }
1241

1242
    /**
1243
     * Find all available completion items at the given position
1244
     * @param filePath can be a srcPath or a destPath
1245
     * @param position the position (line & column) where completions should be found
1246
     */
1247
    public getCompletions(filePath: string, position: Position) {
1248
        let file = this.getFile(filePath);
117✔
1249
        if (!file) {
117!
UNCOV
1250
            return [];
×
1251
        }
1252

1253
        //find the scopes for this file
1254
        let scopes = this.getScopesForFile(file);
117✔
1255

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

1259
        const event: ProvideCompletionsEvent = {
117✔
1260
            program: this,
1261
            file: file,
1262
            scopes: scopes,
1263
            position: position,
1264
            completions: []
1265
        };
1266

1267
        this.plugins.emit('beforeProvideCompletions', event);
117✔
1268

1269
        this.plugins.emit('provideCompletions', event);
117✔
1270

1271
        this.plugins.emit('afterProvideCompletions', event);
117✔
1272

1273
        return event.completions;
117✔
1274
    }
1275

1276
    /**
1277
     * Goes through each file and builds a list of workspace symbols for the program. Used by LanguageServer's onWorkspaceSymbol functionality
1278
     */
1279
    public getWorkspaceSymbols() {
1280
        const event: ProvideWorkspaceSymbolsEvent = {
22✔
1281
            program: this,
1282
            workspaceSymbols: []
1283
        };
1284
        this.plugins.emit('beforeProvideWorkspaceSymbols', event);
22✔
1285
        this.plugins.emit('provideWorkspaceSymbols', event);
22✔
1286
        this.plugins.emit('afterProvideWorkspaceSymbols', event);
22✔
1287
        return event.workspaceSymbols;
22✔
1288
    }
1289

1290
    /**
1291
     * Given a position in a file, if the position is sitting on some type of identifier,
1292
     * go to the definition of that identifier (where this thing was first defined)
1293
     */
1294
    public getDefinition(srcPath: string, position: Position): Location[] {
1295
        let file = this.getFile(srcPath);
18✔
1296
        if (!file) {
18!
UNCOV
1297
            return [];
×
1298
        }
1299

1300
        const event: ProvideDefinitionEvent = {
18✔
1301
            program: this,
1302
            file: file,
1303
            position: position,
1304
            definitions: []
1305
        };
1306

1307
        this.plugins.emit('beforeProvideDefinition', event);
18✔
1308
        this.plugins.emit('provideDefinition', event);
18✔
1309
        this.plugins.emit('afterProvideDefinition', event);
18✔
1310
        return event.definitions;
18✔
1311
    }
1312

1313
    /**
1314
     * Get hover information for a file and position
1315
     */
1316
    public getHover(srcPath: string, position: Position): Hover[] {
1317
        let file = this.getFile(srcPath);
68✔
1318
        let result: Hover[];
1319
        if (file) {
68!
1320
            const event = {
68✔
1321
                program: this,
1322
                file: file,
1323
                position: position,
1324
                scopes: this.getScopesForFile(file),
1325
                hovers: []
1326
            } as ProvideHoverEvent;
1327
            this.plugins.emit('beforeProvideHover', event);
68✔
1328
            this.plugins.emit('provideHover', event);
68✔
1329
            this.plugins.emit('afterProvideHover', event);
68✔
1330
            result = event.hovers;
68✔
1331
        }
1332

1333
        return result ?? [];
68!
1334
    }
1335

1336
    /**
1337
     * Get full list of document symbols for a file
1338
     * @param srcPath path to the file
1339
     */
1340
    public getDocumentSymbols(srcPath: string): DocumentSymbol[] | undefined {
1341
        let file = this.getFile(srcPath);
18✔
1342
        if (file) {
18!
1343
            const event: ProvideDocumentSymbolsEvent = {
18✔
1344
                program: this,
1345
                file: file,
1346
                documentSymbols: []
1347
            };
1348
            this.plugins.emit('beforeProvideDocumentSymbols', event);
18✔
1349
            this.plugins.emit('provideDocumentSymbols', event);
18✔
1350
            this.plugins.emit('afterProvideDocumentSymbols', event);
18✔
1351
            return event.documentSymbols;
18✔
1352
        } else {
UNCOV
1353
            return undefined;
×
1354
        }
1355
    }
1356

1357
    /**
1358
     * Compute code actions for the given file and range
1359
     */
1360
    public getCodeActions(srcPath: string, range: Range) {
1361
        const codeActions = [] as CodeAction[];
13✔
1362
        const file = this.getFile(srcPath);
13✔
1363
        if (file) {
13✔
1364
            const fileUri = util.pathToUri(file?.srcPath);
12!
1365
            const diagnostics = this
12✔
1366
                //get all current diagnostics (filtered by diagnostic filters)
1367
                .getDiagnostics()
1368
                //only keep diagnostics related to this file
1369
                .filter(x => x.location?.uri === fileUri)
25✔
1370
                //only keep diagnostics that touch this range
1371
                .filter(x => util.rangesIntersectOrTouch(x.location.range, range));
12✔
1372

1373
            const scopes = this.getScopesForFile(file);
12✔
1374

1375
            this.plugins.emit('onGetCodeActions', {
12✔
1376
                program: this,
1377
                file: file,
1378
                range: range,
1379
                diagnostics: diagnostics,
1380
                scopes: scopes,
1381
                codeActions: codeActions
1382
            });
1383
        }
1384
        return codeActions;
13✔
1385
    }
1386

1387
    /**
1388
     * Get semantic tokens for the specified file
1389
     */
1390
    public getSemanticTokens(srcPath: string): SemanticToken[] | undefined {
1391
        const file = this.getFile(srcPath);
24✔
1392
        if (file) {
24!
1393
            const result = [] as SemanticToken[];
24✔
1394
            this.plugins.emit('onGetSemanticTokens', {
24✔
1395
                program: this,
1396
                file: file,
1397
                scopes: this.getScopesForFile(file),
1398
                semanticTokens: result
1399
            });
1400
            return result;
24✔
1401
        }
1402
    }
1403

1404
    public getSignatureHelp(filepath: string, position: Position): SignatureInfoObj[] {
1405
        let file: BrsFile = this.getFile(filepath);
185✔
1406
        if (!file || !isBrsFile(file)) {
185✔
1407
            return [];
3✔
1408
        }
1409
        let callExpressionInfo = new CallExpressionInfo(file, position);
182✔
1410
        let signatureHelpUtil = new SignatureHelpUtil();
182✔
1411
        return signatureHelpUtil.getSignatureHelpItems(callExpressionInfo);
182✔
1412
    }
1413

1414
    public getReferences(srcPath: string, position: Position): Location[] {
1415
        //find the file
1416
        let file = this.getFile(srcPath);
4✔
1417

1418
        const event: ProvideReferencesEvent = {
4✔
1419
            program: this,
1420
            file: file,
1421
            position: position,
1422
            references: []
1423
        };
1424

1425
        this.plugins.emit('beforeProvideReferences', event);
4✔
1426
        this.plugins.emit('provideReferences', event);
4✔
1427
        this.plugins.emit('afterProvideReferences', event);
4✔
1428

1429
        return event.references;
4✔
1430
    }
1431

1432
    /**
1433
     * Transpile a single file and get the result as a string.
1434
     * This does not write anything to the file system.
1435
     *
1436
     * This should only be called by `LanguageServer`.
1437
     * Internal usage should call `_getTranspiledFileContents` instead.
1438
     * @param filePath can be a srcPath or a destPath
1439
     */
1440
    public async getTranspiledFileContents(filePath: string): Promise<FileTranspileResult> {
1441
        const file = this.getFile(filePath);
306✔
1442

1443
        return this.getTranspiledFileContentsPipeline.run(async () => {
306✔
1444

1445
            const result = {
306✔
1446
                destPath: file.destPath,
1447
                pkgPath: file.pkgPath,
1448
                srcPath: file.srcPath
1449
            } as FileTranspileResult;
1450

1451
            const expectedPkgPath = file.pkgPath.toLowerCase();
306✔
1452
            const expectedMapPath = `${expectedPkgPath}.map`;
306✔
1453
            const expectedTypedefPkgPath = expectedPkgPath.replace(/\.brs$/i, '.d.bs');
306✔
1454

1455
            //add a temporary plugin to tap into the file writing process
1456
            const plugin = this.plugins.addFirst({
306✔
1457
                name: 'getTranspiledFileContents',
1458
                beforeWriteFile: (event) => {
1459
                    const pkgPath = event.file.pkgPath.toLowerCase();
968✔
1460
                    switch (pkgPath) {
968✔
1461
                        //this is the actual transpiled file
1462
                        case expectedPkgPath:
968✔
1463
                            result.code = event.file.data.toString();
306✔
1464
                            break;
306✔
1465
                        //this is the sourcemap
1466
                        case expectedMapPath:
1467
                            result.map = event.file.data.toString();
170✔
1468
                            break;
170✔
1469
                        //this is the typedef
1470
                        case expectedTypedefPkgPath:
1471
                            result.typedef = event.file.data.toString();
8✔
1472
                            break;
8✔
1473
                        default:
1474
                        //no idea what this file is. just ignore it
1475
                    }
1476
                    //mark every file as processed so it they don't get written to the output directory
1477
                    event.processedFiles.add(event.file);
968✔
1478
                }
1479
            });
1480

1481
            try {
306✔
1482
                //now that the plugin has been registered, run the build with just this file
1483
                await this.build({
306✔
1484
                    files: [file]
1485
                });
1486
            } finally {
1487
                this.plugins.remove(plugin);
306✔
1488
            }
1489
            return result;
306✔
1490
        });
1491
    }
1492
    private getTranspiledFileContentsPipeline = new ActionPipeline();
1,791✔
1493

1494
    /**
1495
     * Get the absolute output path for a file
1496
     */
1497
    private getOutputPath(file: { pkgPath?: string }, stagingDir = this.getStagingDir()) {
×
1498
        return s`${stagingDir}/${file.pkgPath}`;
1,783✔
1499
    }
1500

1501
    private getStagingDir(stagingDir?: string) {
1502
        let result = stagingDir ?? this.options.stagingDir ?? this.options.stagingDir;
693✔
1503
        if (!result) {
693✔
1504
            result = rokuDeploy.getOptions(this.options as any).stagingDir;
507✔
1505
        }
1506
        result = s`${path.resolve(this.options.cwd ?? process.cwd(), result ?? '/')}`;
693!
1507
        return result;
693✔
1508
    }
1509

1510
    /**
1511
     * Prepare the program for building
1512
     * @param files the list of files that should be prepared
1513
     */
1514
    private async prepare(files: BscFile[]) {
1515
        const programEvent: PrepareProgramEvent = {
347✔
1516
            program: this,
1517
            editor: this.editor,
1518
            files: files
1519
        };
1520

1521
        //assign an editor to every file
1522
        for (const file of programEvent.files) {
347✔
1523
            //if the file doesn't have an editor yet, assign one now
1524
            if (!file.editor) {
704✔
1525
                file.editor = new Editor();
657✔
1526
            }
1527
        }
1528

1529
        //sort the entries to make transpiling more deterministic
1530
        programEvent.files.sort((a, b) => {
347✔
1531
            if (a.pkgPath < b.pkgPath) {
371✔
1532
                return -1;
311✔
1533
            } else if (a.pkgPath > b.pkgPath) {
60!
1534
                return 1;
60✔
1535
            } else {
UNCOV
1536
                return 1;
×
1537
            }
1538
        });
1539

1540
        await this.plugins.emitAsync('beforePrepareProgram', programEvent);
347✔
1541
        await this.plugins.emitAsync('prepareProgram', programEvent);
347✔
1542

1543
        const stagingDir = this.getStagingDir();
347✔
1544

1545
        const entries: TranspileObj[] = [];
347✔
1546

1547
        for (const file of files) {
347✔
1548
            const scope = this.getFirstScopeForFile(file);
704✔
1549
            //link the symbol table for all the files in this scope
1550
            scope?.linkSymbolTable();
704✔
1551

1552
            //if the file doesn't have an editor yet, assign one now
1553
            if (!file.editor) {
704!
UNCOV
1554
                file.editor = new Editor();
×
1555
            }
1556
            const event = {
704✔
1557
                program: this,
1558
                file: file,
1559
                editor: file.editor,
1560
                scope: scope,
1561
                outputPath: this.getOutputPath(file, stagingDir)
1562
            } as PrepareFileEvent & { outputPath: string };
1563

1564
            await this.plugins.emitAsync('beforePrepareFile', event);
704✔
1565
            await this.plugins.emitAsync('prepareFile', event);
704✔
1566
            await this.plugins.emitAsync('afterPrepareFile', event);
704✔
1567

1568
            //TODO remove this in v1
1569
            entries.push(event);
704✔
1570

1571
            //unlink the symbolTable so the next loop iteration can link theirs
1572
            scope?.unlinkSymbolTable();
704✔
1573
        }
1574

1575
        await this.plugins.emitAsync('afterPrepareProgram', programEvent);
347✔
1576
        return files;
347✔
1577
    }
1578

1579
    /**
1580
     * Generate the contents of every file
1581
     */
1582
    private async serialize(files: BscFile[]) {
1583

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

1586
        //exclude prunable files if that option is enabled
1587
        if (this.options.pruneEmptyCodeFiles === true) {
346✔
1588
            files = files.filter(x => x.canBePruned !== true);
9✔
1589
        }
1590

1591
        const serializeProgramEvent = await this.plugins.emitAsync('beforeSerializeProgram', {
346✔
1592
            program: this,
1593
            files: files,
1594
            result: allFiles
1595
        });
1596
        await this.plugins.emitAsync('onSerializeProgram', serializeProgramEvent);
346✔
1597

1598
        // serialize each file
1599
        for (const file of files) {
346✔
1600
            let scope = this.getFirstScopeForFile(file);
701✔
1601

1602
            //if the file doesn't have a scope, create a temporary scope for the file so it can depend on scope-level items
1603
            if (!scope) {
701✔
1604
                scope = new Scope(`temporary-for-${file.pkgPath}`, this);
357✔
1605
                scope.getAllFiles = () => [file];
3,200✔
1606
                scope.getOwnFiles = scope.getAllFiles;
357✔
1607
            }
1608

1609
            //link the symbol table for all the files in this scope
1610
            scope?.linkSymbolTable();
701!
1611
            const event: SerializeFileEvent = {
701✔
1612
                program: this,
1613
                file: file,
1614
                scope: scope,
1615
                result: allFiles
1616
            };
1617
            await this.plugins.emitAsync('beforeSerializeFile', event);
701✔
1618
            await this.plugins.emitAsync('serializeFile', event);
701✔
1619
            await this.plugins.emitAsync('afterSerializeFile', event);
701✔
1620
            //unlink the symbolTable so the next loop iteration can link theirs
1621
            scope?.unlinkSymbolTable();
701!
1622
        }
1623

1624
        this.plugins.emit('afterSerializeProgram', serializeProgramEvent);
346✔
1625

1626
        return allFiles;
346✔
1627
    }
1628

1629
    /**
1630
     * Write the entire project to disk
1631
     */
1632
    private async write(stagingDir: string, files: Map<BscFile, SerializedFile[]>) {
1633
        const programEvent = await this.plugins.emitAsync('beforeWriteProgram', {
346✔
1634
            program: this,
1635
            files: files,
1636
            stagingDir: stagingDir
1637
        });
1638
        //empty the staging directory
1639
        await fsExtra.emptyDir(stagingDir);
346✔
1640

1641
        const serializedFiles = [...files]
346✔
1642
            .map(([, serializedFiles]) => serializedFiles)
701✔
1643
            .flat();
1644

1645
        //write all the files to disk (asynchronously)
1646
        await Promise.all(
346✔
1647
            serializedFiles.map(async (file) => {
1648
                const event = await this.plugins.emitAsync('beforeWriteFile', {
1,079✔
1649
                    program: this,
1650
                    file: file,
1651
                    outputPath: this.getOutputPath(file, stagingDir),
1652
                    processedFiles: new Set<SerializedFile>()
1653
                });
1654

1655
                await this.plugins.emitAsync('writeFile', event);
1,079✔
1656

1657
                await this.plugins.emitAsync('afterWriteFile', event);
1,079✔
1658
            })
1659
        );
1660

1661
        await this.plugins.emitAsync('afterWriteProgram', programEvent);
346✔
1662
    }
1663

1664
    private buildPipeline = new ActionPipeline();
1,791✔
1665

1666
    /**
1667
     * Build the project. This transpiles/transforms/copies all files and moves them to the staging directory
1668
     * @param options the list of options used to build the program
1669
     */
1670
    public async build(options?: ProgramBuildOptions) {
1671
        //run a single build at a time
1672
        await this.buildPipeline.run(async () => {
346✔
1673
            const stagingDir = this.getStagingDir(options?.stagingDir);
346✔
1674

1675
            const event = await this.plugins.emitAsync('beforeBuildProgram', {
346✔
1676
                program: this,
1677
                editor: this.editor,
1678
                files: options?.files ?? Object.values(this.files)
2,076✔
1679
            });
1680

1681
            //prepare the program (and files) for building
1682
            event.files = await this.prepare(event.files);
346✔
1683

1684
            //stage the entire program
1685
            const serializedFilesByFile = await this.serialize(event.files);
346✔
1686

1687
            await this.write(stagingDir, serializedFilesByFile);
346✔
1688

1689
            await this.plugins.emitAsync('afterBuildProgram', event);
346✔
1690

1691
            //undo all edits for the program
1692
            this.editor.undoAll();
346✔
1693
            //undo all edits for each file
1694
            for (const file of event.files) {
346✔
1695
                file.editor.undoAll();
702✔
1696
            }
1697
        });
1698
    }
1699

1700
    /**
1701
     * Find a list of files in the program that have a function with the given name (case INsensitive)
1702
     */
1703
    public findFilesForFunction(functionName: string) {
1704
        const files = [] as BscFile[];
7✔
1705
        const lowerFunctionName = functionName.toLowerCase();
7✔
1706
        //find every file with this function defined
1707
        for (const file of Object.values(this.files)) {
7✔
1708
            if (isBrsFile(file)) {
25✔
1709
                //TODO handle namespace-relative function calls
1710
                //if the file has a function with this name
1711
                // eslint-disable-next-line @typescript-eslint/dot-notation
1712
                if (file['_cachedLookups'].functionStatementMap.get(lowerFunctionName)) {
17✔
1713
                    files.push(file);
2✔
1714
                }
1715
            }
1716
        }
1717
        return files;
7✔
1718
    }
1719

1720
    /**
1721
     * Find a list of files in the program that have a class with the given name (case INsensitive)
1722
     */
1723
    public findFilesForClass(className: string) {
1724
        const files = [] as BscFile[];
7✔
1725
        const lowerClassName = className.toLowerCase();
7✔
1726
        //find every file with this class defined
1727
        for (const file of Object.values(this.files)) {
7✔
1728
            if (isBrsFile(file)) {
25✔
1729
                //TODO handle namespace-relative classes
1730
                //if the file has a function with this name
1731

1732
                // eslint-disable-next-line @typescript-eslint/dot-notation
1733
                if (file['_cachedLookups'].classStatementMap.get(lowerClassName) !== undefined) {
17✔
1734
                    files.push(file);
1✔
1735
                }
1736
            }
1737
        }
1738
        return files;
7✔
1739
    }
1740

1741
    public findFilesForNamespace(name: string) {
1742
        const files = [] as BscFile[];
7✔
1743
        const lowerName = name.toLowerCase();
7✔
1744
        //find every file with this class defined
1745
        for (const file of Object.values(this.files)) {
7✔
1746
            if (isBrsFile(file)) {
25✔
1747

1748
                // eslint-disable-next-line @typescript-eslint/dot-notation
1749
                if (file['_cachedLookups'].namespaceStatements.find((x) => {
17✔
1750
                    const namespaceName = x.name.toLowerCase();
7✔
1751
                    return (
7✔
1752
                        //the namespace name matches exactly
1753
                        namespaceName === lowerName ||
9✔
1754
                        //the full namespace starts with the name (honoring the part boundary)
1755
                        namespaceName.startsWith(lowerName + '.')
1756
                    );
1757
                })) {
1758
                    files.push(file);
6✔
1759
                }
1760
            }
1761
        }
1762

1763
        return files;
7✔
1764
    }
1765

1766
    public findFilesForEnum(name: string) {
1767
        const files = [] as BscFile[];
8✔
1768
        const lowerName = name.toLowerCase();
8✔
1769
        //find every file with this enum defined
1770
        for (const file of Object.values(this.files)) {
8✔
1771
            if (isBrsFile(file)) {
26✔
1772
                // eslint-disable-next-line @typescript-eslint/dot-notation
1773
                if (file['_cachedLookups'].enumStatementMap.get(lowerName)) {
18✔
1774
                    files.push(file);
1✔
1775
                }
1776
            }
1777
        }
1778
        return files;
8✔
1779
    }
1780

1781
    private _manifest: Map<string, string>;
1782

1783
    /**
1784
     * Modify a parsed manifest map by reading `bs_const` and injecting values from `options.manifest.bs_const`
1785
     * @param parsedManifest The manifest map to read from and modify
1786
     */
1787
    private buildBsConstsIntoParsedManifest(parsedManifest: Map<string, string>) {
1788
        // Lift the bs_consts defined in the manifest
1789
        let bsConsts = getBsConst(parsedManifest, false);
15✔
1790

1791
        // Override or delete any bs_consts defined in the bs config
1792
        for (const key in this.options?.manifest?.bs_const) {
15!
1793
            const value = this.options.manifest.bs_const[key];
3✔
1794
            if (value === null) {
3✔
1795
                bsConsts.delete(key);
1✔
1796
            } else {
1797
                bsConsts.set(key, value);
2✔
1798
            }
1799
        }
1800

1801
        // convert the new list of bs consts back into a string for the rest of the down stream systems to use
1802
        let constString = '';
15✔
1803
        for (const [key, value] of bsConsts) {
15✔
1804
            constString += `${constString !== '' ? ';' : ''}${key}=${value.toString()}`;
8✔
1805
        }
1806

1807
        // Set the updated bs_const value
1808
        parsedManifest.set('bs_const', constString);
15✔
1809
    }
1810

1811
    /**
1812
     * Try to find and load the manifest into memory
1813
     * @param manifestFileObj A pointer to a potential manifest file object found during loading
1814
     * @param replaceIfAlreadyLoaded should we overwrite the internal `_manifest` if it already exists
1815
     */
1816
    public loadManifest(manifestFileObj?: FileObj, replaceIfAlreadyLoaded = true) {
1,470✔
1817
        //if we already have a manifest instance, and should not replace...then don't replace
1818
        if (!replaceIfAlreadyLoaded && this._manifest) {
1,476!
UNCOV
1819
            return;
×
1820
        }
1821
        let manifestPath = manifestFileObj
1,476✔
1822
            ? manifestFileObj.src
1,476✔
1823
            : path.join(this.options.rootDir, 'manifest');
1824

1825
        try {
1,476✔
1826
            // we only load this manifest once, so do it sync to improve speed downstream
1827
            const contents = fsExtra.readFileSync(manifestPath, 'utf-8');
1,476✔
1828
            const parsedManifest = parseManifest(contents);
15✔
1829
            this.buildBsConstsIntoParsedManifest(parsedManifest);
15✔
1830
            this._manifest = parsedManifest;
15✔
1831
        } catch (e) {
1832
            this._manifest = new Map();
1,461✔
1833
        }
1834
    }
1835

1836
    /**
1837
     * Get a map of the manifest information
1838
     */
1839
    public getManifest() {
1840
        if (!this._manifest) {
2,298✔
1841
            this.loadManifest();
1,469✔
1842
        }
1843
        return this._manifest;
2,298✔
1844
    }
1845

1846
    public dispose() {
1847
        this.plugins.emit('beforeProgramDispose', { program: this });
1,643✔
1848

1849
        for (let filePath in this.files) {
1,643✔
1850
            this.files[filePath]?.dispose?.();
2,055!
1851
        }
1852
        for (let name in this.scopes) {
1,643✔
1853
            this.scopes[name]?.dispose?.();
3,473!
1854
        }
1855
        this.globalScope?.dispose?.();
1,643!
1856
        this.dependencyGraph?.dispose?.();
1,643!
1857
    }
1858
}
1859

1860
export interface FileTranspileResult {
1861
    srcPath: string;
1862
    destPath: string;
1863
    pkgPath: string;
1864
    code: string;
1865
    map: string;
1866
    typedef: string;
1867
}
1868

1869

1870
class ProvideFileEventInternal<TFile extends BscFile = BscFile> implements ProvideFileEvent<TFile> {
1871
    constructor(
1872
        public program: Program,
2,370✔
1873
        public srcPath: string,
2,370✔
1874
        public destPath: string,
2,370✔
1875
        public data: LazyFileData,
2,370✔
1876
        public fileFactory: FileFactory
2,370✔
1877
    ) {
1878
        this.srcExtension = path.extname(srcPath)?.toLowerCase();
2,370!
1879
    }
1880

1881
    public srcExtension: string;
1882

1883
    public files: TFile[] = [];
2,370✔
1884
}
1885

1886
export interface ProgramBuildOptions {
1887
    /**
1888
     * The directory where the final built files should be placed. This directory will be cleared before running
1889
     */
1890
    stagingDir?: string;
1891
    /**
1892
     * An array of files to build. If omitted, the entire list of files from the program will be used instead.
1893
     * Typically you will want to leave this blank
1894
     */
1895
    files?: BscFile[];
1896
}
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