forked from rokucommunity/brighterscript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.ts
More file actions
1432 lines (1262 loc) · 53.2 KB
/
Program.ts
File metadata and controls
1432 lines (1262 loc) · 53.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as assert from 'assert';
import * as fsExtra from 'fs-extra';
import * as path from 'path';
import type { CodeAction, CompletionItem, Position, Range, SignatureInformation, Location } from 'vscode-languageserver';
import { CompletionItemKind } from 'vscode-languageserver';
import type { BsConfig } from './BsConfig';
import { Scope } from './Scope';
import { DiagnosticMessages } from './DiagnosticMessages';
import { BrsFile } from './files/BrsFile';
import { XmlFile } from './files/XmlFile';
import type { BsDiagnostic, File, FileReference, FileObj, BscFile, SemanticToken, AfterFileTranspileEvent, FileLink, ProvideHoverEvent, ProvideCompletionsEvent, Hover } from './interfaces';
import { standardizePath as s, util } from './util';
import { XmlScope } from './XmlScope';
import { DiagnosticFilterer } from './DiagnosticFilterer';
import { DependencyGraph } from './DependencyGraph';
import { Logger, LogLevel } from './Logger';
import chalk from 'chalk';
import { globalFile } from './globalCallables';
import { parseManifest, getBsConst } from './preprocessor/Manifest';
import { URI } from 'vscode-uri';
import PluginInterface from './PluginInterface';
import { isBrsFile, isXmlFile, isXmlScope, isNamespaceStatement } from './astUtils/reflection';
import type { FunctionStatement, NamespaceStatement } from './parser/Statement';
import { BscPlugin } from './bscPlugin/BscPlugin';
import { AstEditor } from './astUtils/AstEditor';
import type { SourceMapGenerator } from 'source-map';
import { rokuDeploy } from 'roku-deploy';
import type { Statement } from './parser/AstNode';
import { CallExpressionInfo } from './bscPlugin/CallExpressionInfo';
import { SignatureHelpUtil } from './bscPlugin/SignatureHelpUtil';
import { DiagnosticSeverityAdjuster } from './DiagnosticSeverityAdjuster';
const startOfSourcePkgPath = `source${path.sep}`;
const bslibNonAliasedRokuModulesPkgPath = s`source/roku_modules/rokucommunity_bslib/bslib.brs`;
const bslibAliasedRokuModulesPkgPath = s`source/roku_modules/bslib/bslib.brs`;
export interface SourceObj {
/**
* @deprecated use `srcPath` instead
*/
pathAbsolute: string;
srcPath: string;
source: string;
definitions?: string;
}
export interface TranspileObj {
file: BscFile;
outputPath: string;
}
export interface SignatureInfoObj {
index: number;
key: string;
signature: SignatureInformation;
}
export class Program {
constructor(
/**
* The root directory for this program
*/
public options: BsConfig,
logger?: Logger,
plugins?: PluginInterface
) {
this.options = util.normalizeConfig(options);
this.logger = logger || new Logger(options.logLevel as LogLevel);
this.plugins = plugins || new PluginInterface([], { logger: this.logger });
//inject the bsc plugin as the first plugin in the stack.
this.plugins.addFirst(new BscPlugin());
//normalize the root dir path
this.options.rootDir = util.getRootDir(this.options);
this.createGlobalScope();
}
public logger: Logger;
private createGlobalScope() {
//create the 'global' scope
this.globalScope = new Scope('global', this, 'scope:global');
this.globalScope.attachDependencyGraph(this.dependencyGraph);
this.scopes.global = this.globalScope;
//hardcode the files list for global scope to only contain the global file
this.globalScope.getAllFiles = () => [globalFile];
this.globalScope.validate();
//for now, disable validation of global scope because the global files have some duplicate method declarations
this.globalScope.getDiagnostics = () => [];
//TODO we might need to fix this because the isValidated clears stuff now
(this.globalScope as any).isValidated = true;
}
/**
* A graph of all files and their dependencies.
* For example:
* File.xml -> [lib1.brs, lib2.brs]
* lib2.brs -> [lib3.brs] //via an import statement
*/
private dependencyGraph = new DependencyGraph();
private diagnosticFilterer = new DiagnosticFilterer();
private diagnosticAdjuster = new DiagnosticSeverityAdjuster();
/**
* A scope that contains all built-in global functions.
* All scopes should directly or indirectly inherit from this scope
*/
public globalScope: Scope;
/**
* Plugins which can provide extra diagnostics or transform AST
*/
public plugins: PluginInterface;
/**
* A set of diagnostics. This does not include any of the scope diagnostics.
* Should only be set from `this.validate()`
*/
private diagnostics = [] as BsDiagnostic[];
/**
* The path to bslib.brs (the BrightScript runtime for certain BrighterScript features)
*/
public get bslibPkgPath() {
//if there's an aliased (preferred) version of bslib from roku_modules loaded into the program, use that
if (this.getFile(bslibAliasedRokuModulesPkgPath)) {
return bslibAliasedRokuModulesPkgPath;
//if there's a non-aliased version of bslib from roku_modules, use that
} else if (this.getFile(bslibNonAliasedRokuModulesPkgPath)) {
return bslibNonAliasedRokuModulesPkgPath;
//default to the embedded version
} else {
return `${this.options.bslibDestinationDir}${path.sep}bslib.brs`;
}
}
public get bslibPrefix() {
if (this.bslibPkgPath === bslibNonAliasedRokuModulesPkgPath) {
return 'rokucommunity_bslib';
} else {
return 'bslib';
}
}
/**
* A map of every file loaded into this program, indexed by its original file location
*/
public files = {} as Record<string, BscFile>;
private pkgMap = {} as Record<string, BscFile>;
private scopes = {} as Record<string, Scope>;
protected addScope(scope: Scope) {
this.scopes[scope.name] = scope;
}
/**
* A map of every component currently loaded into the program, indexed by the component name.
* It is a compile-time error to have multiple components with the same name. However, we store an array of components
* by name so we can provide a better developer expreience. You shouldn't be directly accessing this array,
* but if you do, only ever use the component at index 0.
*/
private components = {} as Record<string, { file: XmlFile; scope: XmlScope }[]>;
/**
* Get the component with the specified name
*/
public getComponent(componentName: string) {
if (componentName) {
//return the first compoment in the list with this name
//(components are ordered in this list by pkgPath to ensure consistency)
return this.components[componentName.toLowerCase()]?.[0];
} else {
return undefined;
}
}
/**
* Register (or replace) the reference to a component in the component map
*/
private registerComponent(xmlFile: XmlFile, scope: XmlScope) {
const key = (xmlFile.componentName?.text ?? xmlFile.pkgPath).toLowerCase();
if (!this.components[key]) {
this.components[key] = [];
}
this.components[key].push({
file: xmlFile,
scope: scope
});
this.components[key].sort((a, b) => {
const pathA = a.file.pkgPath.toLowerCase();
const pathB = b.file.pkgPath.toLowerCase();
if (pathA < pathB) {
return -1;
} else if (pathA > pathB) {
return 1;
}
return 0;
});
this.syncComponentDependencyGraph(this.components[key]);
}
/**
* Remove the specified component from the components map
*/
private unregisterComponent(xmlFile: XmlFile) {
const key = (xmlFile.componentName?.text ?? xmlFile.pkgPath).toLowerCase();
const arr = this.components[key] || [];
for (let i = 0; i < arr.length; i++) {
if (arr[i].file === xmlFile) {
arr.splice(i, 1);
break;
}
}
this.syncComponentDependencyGraph(arr);
}
/**
* re-attach the dependency graph with a new key for any component who changed
* their position in their own named array (only matters when there are multiple
* components with the same name)
*/
private syncComponentDependencyGraph(components: Array<{ file: XmlFile; scope: XmlScope }>) {
//reattach every dependency graph
for (let i = 0; i < components.length; i++) {
const { file, scope } = components[i];
//attach (or re-attach) the dependencyGraph for every component whose position changed
if (file.dependencyGraphIndex !== i) {
file.dependencyGraphIndex = i;
file.attachDependencyGraph(this.dependencyGraph);
scope.attachDependencyGraph(this.dependencyGraph);
}
}
}
/**
* Get a list of all files that are included in the project but are not referenced
* by any scope in the program.
*/
public getUnreferencedFiles() {
let result = [] as File[];
for (let filePath in this.files) {
let file = this.files[filePath];
//is this file part of a scope
if (!this.getFirstScopeForFile(file)) {
//no scopes reference this file. add it to the list
result.push(file);
}
}
return result;
}
/**
* Get the list of errors for the entire program. It's calculated on the fly
* by walking through every file, so call this sparingly.
*/
public getDiagnostics() {
return this.logger.time(LogLevel.info, ['Program.getDiagnostics()'], () => {
let diagnostics = [...this.diagnostics];
//get the diagnostics from all scopes
for (let scopeName in this.scopes) {
let scope = this.scopes[scopeName];
diagnostics.push(
...scope.getDiagnostics()
);
}
//get the diagnostics from all unreferenced files
let unreferencedFiles = this.getUnreferencedFiles();
for (let file of unreferencedFiles) {
diagnostics.push(
...file.getDiagnostics()
);
}
const filteredDiagnostics = this.logger.time(LogLevel.debug, ['filter diagnostics'], () => {
//filter out diagnostics based on our diagnostic filters
let finalDiagnostics = this.diagnosticFilterer.filter({
...this.options,
rootDir: this.options.rootDir
}, diagnostics);
return finalDiagnostics;
});
this.logger.time(LogLevel.debug, ['adjust diagnostics severity'], () => {
this.diagnosticAdjuster.adjust(this.options, diagnostics);
});
this.logger.info(`diagnostic counts: total=${chalk.yellow(diagnostics.length.toString())}, after filter=${chalk.yellow(filteredDiagnostics.length.toString())}`);
return filteredDiagnostics;
});
}
public addDiagnostics(diagnostics: BsDiagnostic[]) {
this.diagnostics.push(...diagnostics);
}
/**
* Determine if the specified file is loaded in this program right now.
* @param filePath the absolute or relative path to the file
* @param normalizePath should the provided path be normalized before use
*/
public hasFile(filePath: string, normalizePath = true) {
return !!this.getFile(filePath, normalizePath);
}
public getPkgPath(...args: any[]): any { //eslint-disable-line
throw new Error('Not implemented');
}
/**
* roku filesystem is case INsensitive, so find the scope by key case insensitive
*/
public getScopeByName(scopeName: string) {
if (!scopeName) {
return undefined;
}
//most scopes are xml file pkg paths. however, the ones that are not are single names like "global" and "scope",
//so it's safe to run the standardizePkgPath method
scopeName = s`${scopeName}`;
let key = Object.keys(this.scopes).find(x => x.toLowerCase() === scopeName.toLowerCase());
return this.scopes[key];
}
/**
* Return all scopes
*/
public getScopes() {
return Object.values(this.scopes);
}
/**
* Find the scope for the specified component
*/
public getComponentScope(componentName: string) {
return this.getComponent(componentName)?.scope;
}
/**
* Update internal maps with this file reference
*/
private assignFile<T extends BscFile = BscFile>(file: T) {
this.files[file.srcPath.toLowerCase()] = file;
this.pkgMap[file.pkgPath.toLowerCase()] = file;
return file;
}
/**
* Remove this file from internal maps
*/
private unassignFile<T extends BscFile = BscFile>(file: T) {
delete this.files[file.srcPath.toLowerCase()];
delete this.pkgMap[file.pkgPath.toLowerCase()];
return file;
}
/**
* Load a file into the program. If that file already exists, it is replaced.
* If file contents are provided, those are used, Otherwise, the file is loaded from the file system
* @param srcPath the file path relative to the root dir
* @param fileContents the file contents
* @deprecated use `setFile` instead
*/
public addOrReplaceFile<T extends BscFile>(srcPath: string, fileContents: string): T;
/**
* Load a file into the program. If that file already exists, it is replaced.
* @param fileEntry an object that specifies src and dest for the file.
* @param fileContents the file contents. If not provided, the file will be loaded from disk
* @deprecated use `setFile` instead
*/
public addOrReplaceFile<T extends BscFile>(fileEntry: FileObj, fileContents: string): T;
public addOrReplaceFile<T extends BscFile>(fileParam: FileObj | string, fileContents: string): T {
return this.setFile<T>(fileParam as any, fileContents);
}
/**
* Load a file into the program. If that file already exists, it is replaced.
* If file contents are provided, those are used, Otherwise, the file is loaded from the file system
* @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:/`)
* @param fileContents the file contents
*/
public setFile<T extends BscFile>(srcDestOrPkgPath: string, fileContents: string): T;
/**
* Load a file into the program. If that file already exists, it is replaced.
* @param fileEntry an object that specifies src and dest for the file.
* @param fileContents the file contents. If not provided, the file will be loaded from disk
*/
public setFile<T extends BscFile>(fileEntry: FileObj, fileContents: string): T;
public setFile<T extends BscFile>(fileParam: FileObj | string, fileContents: string): T {
//normalize the file paths
const { srcPath, pkgPath } = this.getPaths(fileParam, this.options.rootDir);
let file = this.logger.time(LogLevel.debug, ['Program.setFile()', chalk.green(srcPath)], () => {
//if the file is already loaded, remove it
if (this.hasFile(srcPath)) {
this.removeFile(srcPath);
}
let fileExtension = path.extname(srcPath).toLowerCase();
let file: BscFile | undefined;
if (fileExtension === '.brs' || fileExtension === '.bs') {
//add the file to the program
const brsFile = this.assignFile(
new BrsFile(srcPath, pkgPath, this)
);
//add file to the `source` dependency list
if (brsFile.pkgPath.startsWith(startOfSourcePkgPath)) {
this.createSourceScope();
this.dependencyGraph.addDependency('scope:source', brsFile.dependencyGraphKey);
}
let sourceObj: SourceObj = {
//TODO remove `pathAbsolute` in v1
pathAbsolute: srcPath,
srcPath: srcPath,
source: fileContents
};
this.plugins.emit('beforeFileParse', sourceObj);
this.logger.time(LogLevel.debug, ['parse', chalk.green(srcPath)], () => {
brsFile.parse(sourceObj.source);
});
//notify plugins that this file has finished parsing
this.plugins.emit('afterFileParse', brsFile);
file = brsFile;
brsFile.attachDependencyGraph(this.dependencyGraph);
} else if (
//is xml file
fileExtension === '.xml' &&
//resides in the components folder (Roku will only parse xml files in the components folder)
pkgPath.toLowerCase().startsWith(util.pathSepNormalize(`components/`))
) {
//add the file to the program
const xmlFile = this.assignFile(
new XmlFile(srcPath, pkgPath, this)
);
let sourceObj: SourceObj = {
//TODO remove `pathAbsolute` in v1
pathAbsolute: srcPath,
srcPath: srcPath,
source: fileContents
};
this.plugins.emit('beforeFileParse', sourceObj);
this.logger.time(LogLevel.debug, ['parse', chalk.green(srcPath)], () => {
xmlFile.parse(sourceObj.source);
});
//notify plugins that this file has finished parsing
this.plugins.emit('afterFileParse', xmlFile);
file = xmlFile;
//create a new scope for this xml file
let scope = new XmlScope(xmlFile, this);
this.addScope(scope);
//register this compoent now that we have parsed it and know its component name
this.registerComponent(xmlFile, scope);
//notify plugins that the scope is created and the component is registered
this.plugins.emit('afterScopeCreate', scope);
} else {
//TODO do we actually need to implement this? Figure out how to handle img paths
// let genericFile = this.files[srcPath] = <any>{
// srcPath: srcPath,
// pkgPath: pkgPath,
// wasProcessed: true
// } as File;
// file = <any>genericFile;
}
return file;
});
return file as T;
}
/**
* Given a srcPath, a pkgPath, or both, resolve whichever is missing, relative to rootDir.
* @param fileParam an object representing file paths
* @param rootDir must be a pre-normalized path
*/
private getPaths(fileParam: string | FileObj | { srcPath?: string; pkgPath?: string }, rootDir: string) {
let srcPath: string;
let pkgPath: string;
assert.ok(fileParam, 'fileParam is required');
//lift the srcPath and pkgPath vars from the incoming param
if (typeof fileParam === 'string') {
fileParam = this.removePkgPrefix(fileParam);
srcPath = s`${path.resolve(rootDir, fileParam)}`;
pkgPath = s`${util.replaceCaseInsensitive(srcPath, rootDir, '')}`;
} else {
let param: any = fileParam;
if (param.src) {
srcPath = s`${param.src}`;
}
if (param.srcPath) {
srcPath = s`${param.srcPath}`;
}
if (param.dest) {
pkgPath = s`${this.removePkgPrefix(param.dest)}`;
}
if (param.pkgPath) {
pkgPath = s`${this.removePkgPrefix(param.pkgPath)}`;
}
}
//if there's no srcPath, use the pkgPath to build an absolute srcPath
if (!srcPath) {
srcPath = s`${rootDir}/${pkgPath}`;
}
//coerce srcPath to an absolute path
if (!path.isAbsolute(srcPath)) {
srcPath = util.standardizePath(srcPath);
}
//if there's no pkgPath, compute relative path from rootDir
if (!pkgPath) {
pkgPath = s`${util.replaceCaseInsensitive(srcPath, rootDir, '')}`;
}
assert.ok(srcPath, 'fileEntry.src is required');
assert.ok(pkgPath, 'fileEntry.dest is required');
return {
srcPath: srcPath,
//remove leading slash from pkgPath
pkgPath: pkgPath.replace(/^[\/\\]+/, '')
};
}
/**
* Remove any leading `pkg:/` found in the path
*/
private removePkgPrefix(path: string) {
return path.replace(/^pkg:\//i, '');
}
/**
* Ensure source scope is created.
* Note: automatically called internally, and no-op if it exists already.
*/
public createSourceScope() {
if (!this.scopes.source) {
const sourceScope = new Scope('source', this, 'scope:source');
sourceScope.attachDependencyGraph(this.dependencyGraph);
this.addScope(sourceScope);
this.plugins.emit('afterScopeCreate', sourceScope);
}
}
/**
* Find the file by its absolute path. This is case INSENSITIVE, since
* Roku is a case insensitive file system. It is an error to have multiple files
* with the same path with only case being different.
* @param srcPath the absolute path to the file
* @deprecated use `getFile` instead, which auto-detects the path type
*/
public getFileByPathAbsolute<T extends BrsFile | XmlFile>(srcPath: string) {
srcPath = s`${srcPath}`;
for (let filePath in this.files) {
if (filePath.toLowerCase() === srcPath.toLowerCase()) {
return this.files[filePath] as T;
}
}
}
/**
* Get a list of files for the given (platform-normalized) pkgPath array.
* Missing files are just ignored.
* @deprecated use `getFiles` instead, which auto-detects the path types
*/
public getFilesByPkgPaths<T extends BscFile[]>(pkgPaths: string[]) {
return pkgPaths
.map(pkgPath => this.getFileByPkgPath(pkgPath))
.filter(file => file !== undefined) as T;
}
/**
* Get a file with the specified (platform-normalized) pkg path.
* If not found, return undefined
* @deprecated use `getFile` instead, which auto-detects the path type
*/
public getFileByPkgPath<T extends BscFile>(pkgPath: string) {
return this.pkgMap[pkgPath.toLowerCase()] as T;
}
/**
* Remove a set of files from the program
* @param srcPaths can be an array of srcPath or destPath strings
* @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
*/
public removeFiles(srcPaths: string[], normalizePath = true) {
for (let srcPath of srcPaths) {
this.removeFile(srcPath, normalizePath);
}
}
/**
* Remove a file from the program
* @param filePath can be a srcPath, a pkgPath, or a destPath (same as pkgPath but without `pkg:/`)
* @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
*/
public removeFile(filePath: string, normalizePath = true) {
this.logger.debug('Program.removeFile()', filePath);
let file = this.getFile(filePath, normalizePath);
if (file) {
this.plugins.emit('beforeFileDispose', file);
//if there is a scope named the same as this file's path, remove it (i.e. xml scopes)
let scope = this.scopes[file.pkgPath];
if (scope) {
this.plugins.emit('beforeScopeDispose', scope);
scope.dispose();
//notify dependencies of this scope that it has been removed
this.dependencyGraph.remove(scope.dependencyGraphKey);
delete this.scopes[file.pkgPath];
this.plugins.emit('afterScopeDispose', scope);
}
//remove the file from the program
this.unassignFile(file);
this.dependencyGraph.remove(file.dependencyGraphKey);
//if this is a pkg:/source file, notify the `source` scope that it has changed
if (file.pkgPath.startsWith(startOfSourcePkgPath)) {
this.dependencyGraph.removeDependency('scope:source', file.dependencyGraphKey);
}
//if this is a component, remove it from our components map
if (isXmlFile(file)) {
this.unregisterComponent(file);
}
//dispose file
file?.dispose();
this.plugins.emit('afterFileDispose', file);
}
}
/**
* Traverse the entire project, and validate all scopes
*/
public validate() {
this.logger.time(LogLevel.log, ['Validating project'], () => {
this.diagnostics = [];
this.plugins.emit('beforeProgramValidate', this);
//validate every file
for (const file of Object.values(this.files)) {
//for every unvalidated file, validate it
if (!file.isValidated) {
this.plugins.emit('beforeFileValidate', {
program: this,
file: file
});
//emit an event to allow plugins to contribute to the file validation process
this.plugins.emit('onFileValidate', {
program: this,
file: file
});
//call file.validate() IF the file has that function defined
file.validate?.();
file.isValidated = true;
this.plugins.emit('afterFileValidate', file);
}
}
this.logger.time(LogLevel.info, ['Validate all scopes'], () => {
for (let scopeName in this.scopes) {
let scope = this.scopes[scopeName];
scope.linkSymbolTable();
scope.validate();
scope.unlinkSymbolTable();
}
});
this.detectDuplicateComponentNames();
this.plugins.emit('afterProgramValidate', this);
});
}
/**
* Flag all duplicate component names
*/
private detectDuplicateComponentNames() {
const componentsByName = Object.keys(this.files).reduce<Record<string, XmlFile[]>>((map, filePath) => {
const file = this.files[filePath];
//if this is an XmlFile, and it has a valid `componentName` property
if (isXmlFile(file) && file.componentName?.text) {
let lowerName = file.componentName.text.toLowerCase();
if (!map[lowerName]) {
map[lowerName] = [];
}
map[lowerName].push(file);
}
return map;
}, {});
for (let name in componentsByName) {
const xmlFiles = componentsByName[name];
//add diagnostics for every duplicate component with this name
if (xmlFiles.length > 1) {
for (let xmlFile of xmlFiles) {
const { componentName } = xmlFile;
this.diagnostics.push({
...DiagnosticMessages.duplicateComponentName(componentName.text),
range: xmlFile.componentName.range,
file: xmlFile,
relatedInformation: xmlFiles.filter(x => x !== xmlFile).map(x => {
return {
location: util.createLocation(
URI.file(xmlFile.srcPath ?? xmlFile.srcPath).toString(),
x.componentName.range
),
message: 'Also defined here'
};
})
});
}
}
}
}
/**
* Get the files for a list of filePaths
* @param filePaths can be an array of srcPath or a destPath strings
* @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
*/
public getFiles<T extends BscFile>(filePaths: string[], normalizePath = true) {
return filePaths
.map(filePath => this.getFile(filePath, normalizePath))
.filter(file => file !== undefined) as T[];
}
/**
* Get the file at the given path
* @param filePath can be a srcPath or a destPath
* @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
*/
public getFile<T extends BscFile>(filePath: string, normalizePath = true) {
if (typeof filePath !== 'string') {
return undefined;
} else if (path.isAbsolute(filePath)) {
return this.files[
(normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase()
] as T;
} else {
return this.pkgMap[
(normalizePath ? util.standardizePath(filePath) : filePath).toLowerCase()
] as T;
}
}
/**
* Get a list of all scopes the file is loaded into
* @param file the file
*/
public getScopesForFile(file: XmlFile | BrsFile | string) {
if (typeof file === 'string') {
file = this.getFile(file);
}
let result = [] as Scope[];
if (file) {
for (let key in this.scopes) {
let scope = this.scopes[key];
if (scope.hasFile(file)) {
result.push(scope);
}
}
}
return result;
}
/**
* Get the first found scope for a file.
*/
public getFirstScopeForFile(file: XmlFile | BrsFile): Scope {
for (let key in this.scopes) {
let scope = this.scopes[key];
if (scope.hasFile(file)) {
return scope;
}
}
}
public getStatementsByName(name: string, originFile: BrsFile, namespaceName?: string): FileLink<Statement>[] {
let results = new Map<Statement, FileLink<Statement>>();
const filesSearched = new Set<BrsFile>();
let lowerNamespaceName = namespaceName?.toLowerCase();
let lowerName = name?.toLowerCase();
//look through all files in scope for matches
for (const scope of this.getScopesForFile(originFile)) {
for (const file of scope.getAllFiles()) {
if (isXmlFile(file) || filesSearched.has(file)) {
continue;
}
filesSearched.add(file);
for (const statement of [...file.parser.references.functionStatements, ...file.parser.references.classStatements.flatMap((cs) => cs.methods)]) {
let parentNamespaceName = statement.findAncestor<NamespaceStatement>(isNamespaceStatement)?.getName(originFile.parseMode)?.toLowerCase();
if (statement.name.text.toLowerCase() === lowerName && (!lowerNamespaceName || parentNamespaceName === lowerNamespaceName)) {
if (!results.has(statement)) {
results.set(statement, { item: statement, file: file });
}
}
}
}
}
return [...results.values()];
}
public getStatementsForXmlFile(scope: XmlScope, filterName?: string): FileLink<FunctionStatement>[] {
let results = new Map<Statement, FileLink<FunctionStatement>>();
const filesSearched = new Set<BrsFile>();
//get all function names for the xml file and parents
let funcNames = new Set<string>();
let currentScope = scope;
while (isXmlScope(currentScope)) {
for (let name of currentScope.xmlFile.ast.component.api?.functions.map((f) => f.name) ?? []) {
if (!filterName || name === filterName) {
funcNames.add(name);
}
}
currentScope = currentScope.getParentScope() as XmlScope;
}
//look through all files in scope for matches
for (const file of scope.getOwnFiles()) {
if (isXmlFile(file) || filesSearched.has(file)) {
continue;
}
filesSearched.add(file);
for (const statement of file.parser.references.functionStatements) {
if (funcNames.has(statement.name.text)) {
if (!results.has(statement)) {
results.set(statement, { item: statement, file: file });
}
}
}
}
return [...results.values()];
}
/**
* Find all available completion items at the given position
* @param filePath can be a srcPath or a destPath
* @param position the position (line & column) where completions should be found
*/
public getCompletions(filePath: string, position: Position) {
let file = this.getFile(filePath);
if (!file) {
return [];
}
//find the scopes for this file
let scopes = this.getScopesForFile(file);
//if there are no scopes, include the global scope so we at least get the built-in functions
scopes = scopes.length > 0 ? scopes : [this.globalScope];
const event: ProvideCompletionsEvent = {
program: this,
file: file,
scopes: scopes,
position: position,
completions: []
};
this.plugins.emit('beforeProvideCompletions', event);
this.plugins.emit('provideCompletions', event);
this.plugins.emit('afterProvideCompletions', event);
return event.completions;
}
/**
* Goes through each file and builds a list of workspace symbols for the program. Used by LanguageServer's onWorkspaceSymbol functionality
*/
public getWorkspaceSymbols() {
const results = Object.keys(this.files).map(key => {
const file = this.files[key];
if (isBrsFile(file)) {
return file.getWorkspaceSymbols();
}
return [];
});
return util.flatMap(results, c => c);
}
/**
* Given a position in a file, if the position is sitting on some type of identifier,
* go to the definition of that identifier (where this thing was first defined)
*/
public getDefinition(srcPath: string, position: Position) {
let file = this.getFile(srcPath);
if (!file) {
return [];
}
if (isBrsFile(file)) {
return file.getDefinition(position);
} else {
let results = [] as Location[];
const scopes = this.getScopesForFile(file);
for (const scope of scopes) {
results = results.concat(...scope.getDefinition(file, position));
}
return results;
}
}
/**
* Get hover information for a file and position
*/
public getHover(srcPath: string, position: Position): Hover[] {
let file = this.getFile(srcPath);
let result: Hover[];
if (file) {
const event = {
program: this,
file: file,
position: position,
scopes: this.getScopesForFile(file),
hovers: []
} as ProvideHoverEvent;
this.plugins.emit('beforeProvideHover', event);
this.plugins.emit('provideHover', event);
this.plugins.emit('afterProvideHover', event);
result = event.hovers;
}
return result ?? [];
}
/**
* Compute code actions for the given file and range
*/
public getCodeActions(srcPath: string, range: Range) {
const codeActions = [] as CodeAction[];
const file = this.getFile(srcPath);
if (file) {
const diagnostics = this
//get all current diagnostics (filtered by diagnostic filters)
.getDiagnostics()
//only keep diagnostics related to this file
.filter(x => x.file === file)
//only keep diagnostics that touch this range
.filter(x => util.rangesIntersectOrTouch(x.range, range));
const scopes = this.getScopesForFile(file);
this.plugins.emit('onGetCodeActions', {
program: this,
file: file,
range: range,
diagnostics: diagnostics,
scopes: scopes,
codeActions: codeActions
});
}
return codeActions;
}
/**
* Get semantic tokens for the specified file
*/
public getSemanticTokens(srcPath: string) {
const file = this.getFile(srcPath);
if (file) {
const result = [] as SemanticToken[];
this.plugins.emit('onGetSemanticTokens', {
program: this,
file: file,