-
Notifications
You must be signed in to change notification settings - Fork 47
/
util.ts
1498 lines (1358 loc) · 54.5 KB
/
util.ts
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 fs from 'fs';
import * as fsExtra from 'fs-extra';
import type { ParseError } from 'jsonc-parser';
import { parse as parseJsonc, printParseErrorCode } from 'jsonc-parser';
import * as path from 'path';
import { rokuDeploy, DefaultFiles, standardizePath as rokuDeployStandardizePath } from 'roku-deploy';
import type { Diagnostic, Position, Range, Location } from 'vscode-languageserver';
import { URI } from 'vscode-uri';
import * as xml2js from 'xml2js';
import type { BsConfig } from './BsConfig';
import { DiagnosticMessages } from './DiagnosticMessages';
import type { CallableContainer, BsDiagnostic, FileReference, CallableContainerMap, CompilerPluginFactory, CompilerPlugin, ExpressionInfo } from './interfaces';
import { BooleanType } from './types/BooleanType';
import { DoubleType } from './types/DoubleType';
import { DynamicType } from './types/DynamicType';
import { FloatType } from './types/FloatType';
import { FunctionType } from './types/FunctionType';
import { IntegerType } from './types/IntegerType';
import { InvalidType } from './types/InvalidType';
import { LongIntegerType } from './types/LongIntegerType';
import { ObjectType } from './types/ObjectType';
import { StringType } from './types/StringType';
import { VoidType } from './types/VoidType';
import { ParseMode } from './parser/Parser';
import type { DottedGetExpression, VariableExpression } from './parser/Expression';
import { Logger, LogLevel } from './Logger';
import type { Identifier, Locatable, Token } from './lexer/Token';
import { TokenKind } from './lexer/TokenKind';
import { isAssignmentStatement, isBrsFile, isCallExpression, isCallfuncExpression, isDottedGetExpression, isExpression, isFunctionParameterExpression, isIndexedGetExpression, isNamespacedVariableNameExpression, isNewExpression, isVariableExpression, isXmlAttributeGetExpression, isXmlFile } from './astUtils/reflection';
import { WalkMode } from './astUtils/visitors';
import { CustomType } from './types/CustomType';
import { SourceNode } from 'source-map';
import type { SGAttribute } from './parser/SGTypes';
import * as requireRelative from 'require-relative';
import type { BrsFile } from './files/BrsFile';
import type { XmlFile } from './files/XmlFile';
import type { Expression, Statement } from './parser/AstNode';
export class Util {
public clearConsole() {
// process.stdout.write('\x1Bc');
}
/**
* Returns the number of parent directories in the filPath
*/
public getParentDirectoryCount(filePath: string | undefined) {
if (!filePath) {
return -1;
} else {
return filePath.replace(/^pkg:/, '').split(/[\\\/]/).length - 1;
}
}
/**
* Determine if the file exists
*/
public async pathExists(filePath: string | undefined) {
if (!filePath) {
return false;
} else {
return fsExtra.pathExists(filePath);
}
}
/**
* Determine if the file exists
*/
public pathExistsSync(filePath: string | undefined) {
if (!filePath) {
return false;
} else {
return fsExtra.pathExistsSync(filePath);
}
}
/**
* Determine if this path is a directory
*/
public isDirectorySync(dirPath: string | undefined) {
return fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
}
/**
* Given a pkg path of any kind, transform it to a roku-specific pkg path (i.e. "pkg:/some/path.brs")
*/
public sanitizePkgPath(pkgPath: string) {
pkgPath = pkgPath.replace(/\\/g, '/');
//if there's no protocol, assume it's supposed to start with `pkg:/`
if (!this.startsWithProtocol(pkgPath)) {
pkgPath = 'pkg:/' + pkgPath;
}
return pkgPath;
}
/**
* Determine if the given path starts with a protocol
*/
public startsWithProtocol(path: string) {
return !!/^[-a-z]+:\//i.exec(path);
}
/**
* Given a pkg path of any kind, transform it to a roku-specific pkg path (i.e. "pkg:/some/path.brs")
*/
public getRokuPkgPath(pkgPath: string) {
pkgPath = pkgPath.replace(/\\/g, '/');
return 'pkg:/' + pkgPath;
}
/**
* Given a path to a file/directory, replace all path separators with the current system's version.
*/
public pathSepNormalize(filePath: string, separator?: string) {
if (!filePath) {
return filePath;
}
separator = separator ? separator : path.sep;
return filePath.replace(/[\\/]+/g, separator);
}
/**
* Find the path to the config file.
* If the config file path doesn't exist
* @param cwd the current working directory where the search for configs should begin
*/
public getConfigFilePath(cwd?: string) {
cwd = cwd ?? process.cwd();
let configPath = path.join(cwd, 'bsconfig.json');
//find the nearest config file path
for (let i = 0; i < 100; i++) {
if (this.pathExistsSync(configPath)) {
return configPath;
} else {
let parentDirPath = path.dirname(path.dirname(configPath));
configPath = path.join(parentDirPath, 'bsconfig.json');
}
}
}
public getRangeFromOffsetLength(text: string, offset: number, length: number) {
let lineIndex = 0;
let colIndex = 0;
for (let i = 0; i < text.length; i++) {
if (offset === i) {
break;
}
let char = text[i];
if (char === '\n' || (char === '\r' && text[i + 1] === '\n')) {
lineIndex++;
colIndex = 0;
i++;
continue;
} else {
colIndex++;
}
}
return util.createRange(lineIndex, colIndex, lineIndex, colIndex + length);
}
/**
* Load the contents of a config file.
* If the file extends another config, this will load the base config as well.
* @param configFilePath the relative or absolute path to a brighterscript config json file
* @param parentProjectPaths a list of parent config files. This is used by this method to recursively build the config list
*/
public loadConfigFile(configFilePath: string, parentProjectPaths?: string[], cwd = process.cwd()) {
if (configFilePath) {
//if the config file path starts with question mark, then it's optional. return undefined if it doesn't exist
if (configFilePath.startsWith('?')) {
//remove leading question mark
configFilePath = configFilePath.substring(1);
if (fsExtra.pathExistsSync(path.resolve(cwd, configFilePath)) === false) {
return undefined;
}
}
//keep track of the inheritance chain
parentProjectPaths = parentProjectPaths ? parentProjectPaths : [];
configFilePath = path.resolve(cwd, configFilePath);
if (parentProjectPaths?.includes(configFilePath)) {
parentProjectPaths.push(configFilePath);
parentProjectPaths.reverse();
throw new Error('Circular dependency detected: "' + parentProjectPaths.join('" => ') + '"');
}
//load the project file
let projectFileContents = fsExtra.readFileSync(configFilePath).toString();
let parseErrors = [] as ParseError[];
let projectConfig = parseJsonc(projectFileContents, parseErrors, {
allowEmptyContent: true,
allowTrailingComma: true,
disallowComments: false
}) as BsConfig ?? {};
if (parseErrors.length > 0) {
let err = parseErrors[0];
let diagnostic = {
...DiagnosticMessages.bsConfigJsonHasSyntaxErrors(printParseErrorCode(parseErrors[0].error)),
file: {
srcPath: configFilePath
},
range: this.getRangeFromOffsetLength(projectFileContents, err.offset, err.length)
} as BsDiagnostic;
throw diagnostic; //eslint-disable-line @typescript-eslint/no-throw-literal
}
let projectFileCwd = path.dirname(configFilePath);
//`plugins` paths should be relative to the current bsconfig
this.resolvePathsRelativeTo(projectConfig, 'plugins', projectFileCwd);
//`require` paths should be relative to cwd
util.resolvePathsRelativeTo(projectConfig, 'require', projectFileCwd);
let result: BsConfig;
//if the project has a base file, load it
if (projectConfig && typeof projectConfig.extends === 'string') {
let baseProjectConfig = this.loadConfigFile(projectConfig.extends, [...parentProjectPaths, configFilePath], projectFileCwd);
//extend the base config with the current project settings
result = { ...baseProjectConfig, ...projectConfig };
} else {
result = projectConfig;
let ancestors = parentProjectPaths ? parentProjectPaths : [];
ancestors.push(configFilePath);
(result as any)._ancestors = parentProjectPaths;
}
//make any paths in the config absolute (relative to the CURRENT config file)
if (result.outFile) {
result.outFile = path.resolve(projectFileCwd, result.outFile);
}
if (result.rootDir) {
result.rootDir = path.resolve(projectFileCwd, result.rootDir);
}
if (result.cwd) {
result.cwd = path.resolve(projectFileCwd, result.cwd);
}
return result;
}
}
/**
* Convert relative paths to absolute paths, relative to the given directory. Also de-dupes the paths. Modifies the array in-place
* @param collection usually a bsconfig.
* @param key a key of the config to read paths from (usually this is `'plugins'` or `'require'`)
* @param relativeDir the path to the folder where the paths should be resolved relative to. This should be an absolute path
*/
public resolvePathsRelativeTo(collection: any, key: string, relativeDir: string) {
if (!collection[key]) {
return;
}
const result = new Set<string>();
for (const p of collection[key] as string[] ?? []) {
if (p) {
result.add(
p?.startsWith('.') ? path.resolve(relativeDir, p) : p
);
}
}
collection[key] = [...result];
}
/**
* Do work within the scope of a changed current working directory
* @param targetCwd the cwd where the work should be performed
* @param callback a function to call when the cwd has been changed to `targetCwd`
*/
public cwdWork<T>(targetCwd: string | null | undefined, callback: () => T) {
let originalCwd = process.cwd();
if (targetCwd) {
process.chdir(targetCwd);
}
let result: T;
let err;
try {
result = callback();
} catch (e) {
err = e;
}
if (targetCwd) {
process.chdir(originalCwd);
}
if (err) {
throw err;
} else {
return result;
}
}
/**
* Given a BsConfig object, start with defaults,
* merge with bsconfig.json and the provided options.
* @param config a bsconfig object to use as the baseline for the resulting config
*/
public normalizeAndResolveConfig(config: BsConfig) {
let result = this.normalizeConfig({});
//if no options were provided, try to find a bsconfig.json file
if (!config || !config.project) {
result.project = this.getConfigFilePath(config?.cwd);
} else {
//use the config's project link
result.project = config.project;
}
if (result.project) {
let configFile = this.loadConfigFile(result.project, null, config?.cwd);
result = Object.assign(result, configFile);
}
//override the defaults with the specified options
result = Object.assign(result, config);
return result;
}
/**
* Set defaults for any missing items
* @param config a bsconfig object to use as the baseline for the resulting config
*/
public normalizeConfig(config: BsConfig) {
config = config || {} as BsConfig;
config.cwd = config.cwd ?? process.cwd();
config.deploy = config.deploy === true ? true : false;
//use default files array from rokuDeploy
config.files = config.files ?? [...DefaultFiles];
config.createPackage = config.createPackage === false ? false : true;
let rootFolderName = path.basename(config.cwd);
config.outFile = config.outFile ?? `./out/${rootFolderName}.zip`;
config.sourceMap = config.sourceMap === true;
config.username = config.username ?? 'rokudev';
config.watch = config.watch === true ? true : false;
config.emitFullPaths = config.emitFullPaths === true ? true : false;
config.retainStagingDir = (config.retainStagingDir ?? config.retainStagingFolder) === true ? true : false;
config.retainStagingFolder = config.retainStagingDir;
config.copyToStaging = config.copyToStaging === false ? false : true;
config.ignoreErrorCodes = config.ignoreErrorCodes ?? [];
config.diagnosticSeverityOverrides = config.diagnosticSeverityOverrides ?? {};
config.diagnosticFilters = config.diagnosticFilters ?? [];
config.plugins = config.plugins ?? [];
config.autoImportComponentScript = config.autoImportComponentScript === true ? true : false;
config.showDiagnosticsInConsole = config.showDiagnosticsInConsole === false ? false : true;
config.sourceRoot = config.sourceRoot ? standardizePath(config.sourceRoot) : undefined;
config.allowBrighterScriptInBrightScript = config.allowBrighterScriptInBrightScript === true ? true : false;
config.emitDefinitions = config.emitDefinitions === true ? true : false;
config.removeParameterTypes = config.removeParameterTypes === true ? true : false;
if (typeof config.logLevel === 'string') {
config.logLevel = LogLevel[(config.logLevel as string).toLowerCase()];
}
config.logLevel = config.logLevel ?? LogLevel.log;
return config;
}
/**
* Get the root directory from options.
* Falls back to options.cwd.
* Falls back to process.cwd
* @param options a bsconfig object
*/
public getRootDir(options: BsConfig) {
if (!options) {
throw new Error('Options is required');
}
let cwd = options.cwd;
cwd = cwd ? cwd : process.cwd();
let rootDir = options.rootDir ? options.rootDir : cwd;
rootDir = path.resolve(cwd, rootDir);
return rootDir;
}
/**
* Given a list of callables as a dictionary indexed by their full name (namespace included, transpiled to underscore-separated.
*/
public getCallableContainersByLowerName(callables: CallableContainer[]): CallableContainerMap {
//find duplicate functions
const result = new Map<string, CallableContainer[]>();
for (let callableContainer of callables) {
let lowerName = callableContainer.callable.getName(ParseMode.BrightScript).toLowerCase();
//create a new array for this name
const list = result.get(lowerName);
if (list) {
list.push(callableContainer);
} else {
result.set(lowerName, [callableContainer]);
}
}
return result;
}
/**
* Split a file by newline characters (LF or CRLF)
*/
public getLines(text: string) {
return text.split(/\r?\n/);
}
/**
* Given an absolute path to a source file, and a target path,
* compute the pkg path for the target relative to the source file's location
*/
public getPkgPathFromTarget(containingFilePathAbsolute: string, targetPath: string) {
//if the target starts with 'pkg:', it's an absolute path. Return as is
if (targetPath.startsWith('pkg:/')) {
targetPath = targetPath.substring(5);
if (targetPath === '') {
return null;
} else {
return path.normalize(targetPath);
}
}
if (targetPath === 'pkg:') {
return null;
}
//remove the filename
let containingFolder = path.normalize(path.dirname(containingFilePathAbsolute));
//start with the containing folder, split by slash
let result = containingFolder.split(path.sep);
//split on slash
let targetParts = path.normalize(targetPath).split(path.sep);
for (let part of targetParts) {
if (part === '' || part === '.') {
//do nothing, it means current directory
continue;
}
if (part === '..') {
//go up one directory
result.pop();
} else {
result.push(part);
}
}
return result.join(path.sep);
}
/**
* Compute the relative path from the source file to the target file
* @param pkgSrcPath - the absolute path to the source, where cwd is the package location
* @param pkgTargetPath - the absolute path to the target, where cwd is the package location
*/
public getRelativePath(pkgSrcPath: string, pkgTargetPath: string) {
pkgSrcPath = path.normalize(pkgSrcPath);
pkgTargetPath = path.normalize(pkgTargetPath);
//break by path separator
let sourceParts = pkgSrcPath.split(path.sep);
let targetParts = pkgTargetPath.split(path.sep);
let commonParts = [] as string[];
//find their common root
for (let i = 0; i < targetParts.length; i++) {
if (targetParts[i].toLowerCase() === sourceParts[i].toLowerCase()) {
commonParts.push(targetParts[i]);
} else {
//we found a non-matching part...so no more commonalities past this point
break;
}
}
//throw out the common parts from both sets
sourceParts.splice(0, commonParts.length);
targetParts.splice(0, commonParts.length);
//throw out the filename part of source
sourceParts.splice(sourceParts.length - 1, 1);
//start out by adding updir paths for each remaining source part
let resultParts = sourceParts.map(() => '..');
//now add every target part
resultParts = [...resultParts, ...targetParts];
return path.join(...resultParts);
}
/**
* Walks left in a DottedGetExpression and returns a VariableExpression if found, or undefined if not found
*/
public findBeginningVariableExpression(dottedGet: DottedGetExpression): VariableExpression | undefined {
let left: any = dottedGet;
while (left) {
if (isVariableExpression(left)) {
return left;
} else if (isDottedGetExpression(left)) {
left = left.obj;
} else {
break;
}
}
}
/**
* Do `a` and `b` overlap by at least one character. This returns false if they are at the edges. Here's some examples:
* ```
* | true | true | true | true | true | false | false | false | false |
* |------|------|------|------|------|-------|-------|-------|-------|
* | aa | aaa | aaa | aaa | a | aa | aa | a | a |
* | bbb | bb | bbb | b | bbb | bb | bb | b | a |
* ```
*/
public rangesIntersect(a: Range, b: Range) {
// Check if `a` is before `b`
if (a.end.line < b.start.line || (a.end.line === b.start.line && a.end.character <= b.start.character)) {
return false;
}
// Check if `b` is before `a`
if (b.end.line < a.start.line || (b.end.line === a.start.line && b.end.character <= a.start.character)) {
return false;
}
// These ranges must intersect
return true;
}
/**
* Do `a` and `b` overlap by at least one character or touch at the edges
* ```
* | true | true | true | true | true | true | true | false | false |
* |------|------|------|------|------|-------|-------|-------|-------|
* | aa | aaa | aaa | aaa | a | aa | aa | a | a |
* | bbb | bb | bbb | b | bbb | bb | bb | b | a |
* ```
*/
public rangesIntersectOrTouch(a: Range, b: Range) {
// Check if `a` is before `b`
if (a.end.line < b.start.line || (a.end.line === b.start.line && a.end.character < b.start.character)) {
return false;
}
// Check if `b` is before `a`
if (b.end.line < a.start.line || (b.end.line === a.start.line && b.end.character < a.start.character)) {
return false;
}
// These ranges must intersect
return true;
}
/**
* Test if `position` is in `range`. If the position is at the edges, will return true.
* Adapted from core vscode
*/
public rangeContains(range: Range, position: Position) {
return this.comparePositionToRange(position, range) === 0;
}
public comparePositionToRange(position: Position, range: Range) {
if (position.line < range.start.line || (position.line === range.start.line && position.character < range.start.character)) {
return -1;
}
if (position.line > range.end.line || (position.line === range.end.line && position.character > range.end.character)) {
return 1;
}
return 0;
}
/**
* Parse an xml file and get back a javascript object containing its results
*/
public parseXml(text: string) {
return new Promise<any>((resolve, reject) => {
xml2js.parseString(text, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
public propertyCount(object: Record<string, unknown>) {
let count = 0;
for (let key in object) {
if (object.hasOwnProperty(key)) {
count++;
}
}
return count;
}
public padLeft(subject: string, totalLength: number, char: string) {
totalLength = totalLength > 1000 ? 1000 : totalLength;
while (subject.length < totalLength) {
subject = char + subject;
}
return subject;
}
/**
* Given a URI, convert that to a regular fs path
*/
public uriToPath(uri: string) {
let parsedPath = URI.parse(uri).fsPath;
//Uri annoyingly coverts all drive letters to lower case...so this will bring back whatever case it came in as
let match = /\/\/\/([a-z]:)/i.exec(uri);
if (match) {
let originalDriveCasing = match[1];
parsedPath = originalDriveCasing + parsedPath.substring(2);
}
const normalizedPath = path.normalize(parsedPath);
return normalizedPath;
}
/**
* Force the drive letter to lower case
*/
public driveLetterToLower(fullPath: string) {
if (fullPath) {
let firstCharCode = fullPath.charCodeAt(0);
if (
//is upper case A-Z
firstCharCode >= 65 && firstCharCode <= 90 &&
//next char is colon
fullPath[1] === ':'
) {
fullPath = fullPath[0].toLowerCase() + fullPath.substring(1);
}
}
return fullPath;
}
/**
* Replace the first instance of `search` in `subject` with `replacement`
*/
public replaceCaseInsensitive(subject: string, search: string, replacement: string) {
let idx = subject.toLowerCase().indexOf(search.toLowerCase());
if (idx > -1) {
let result = subject.substring(0, idx) + replacement + subject.substring(idx + search.length);
return result;
} else {
return subject;
}
}
/**
* Determine if two arrays containing primitive values are equal.
* This considers order and compares by equality.
*/
public areArraysEqual(arr1: any[], arr2: any[]) {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
/**
* Given a file path, convert it to a URI string
*/
public pathToUri(filePath: string) {
return URI.file(filePath).toString();
}
/**
* Get the outDir from options, taking into account cwd and absolute outFile paths
*/
public getOutDir(options: BsConfig) {
options = this.normalizeConfig(options);
let cwd = path.normalize(options.cwd ? options.cwd : process.cwd());
if (path.isAbsolute(options.outFile)) {
return path.dirname(options.outFile);
} else {
return path.normalize(path.join(cwd, path.dirname(options.outFile)));
}
}
/**
* Get paths to all files on disc that match this project's source list
*/
public async getFilePaths(options: BsConfig) {
let rootDir = this.getRootDir(options);
let files = await rokuDeploy.getFilePaths(options.files, rootDir);
return files;
}
/**
* Given a path to a brs file, compute the path to a theoretical d.bs file.
* Only `.brs` files can have typedef path, so return undefined for everything else
*/
public getTypedefPath(brsSrcPath: string) {
const typedefPath = brsSrcPath
.replace(/\.brs$/i, '.d.bs')
.toLowerCase();
if (typedefPath.endsWith('.d.bs')) {
return typedefPath;
} else {
return undefined;
}
}
/**
* Determine whether this diagnostic should be supressed or not, based on brs comment-flags
*/
public diagnosticIsSuppressed(diagnostic: BsDiagnostic) {
const diagnosticCode = typeof diagnostic.code === 'string' ? diagnostic.code.toLowerCase() : diagnostic.code;
for (let flag of diagnostic.file?.commentFlags ?? []) {
//this diagnostic is affected by this flag
if (diagnostic.range && this.rangeContains(flag.affectedRange, diagnostic.range.start)) {
//if the flag acts upon this diagnostic's code
if (flag.codes === null || flag.codes.includes(diagnosticCode)) {
return true;
}
}
}
}
/**
* Walks up the chain to find the closest bsconfig.json file
*/
public async findClosestConfigFile(currentPath: string) {
//make the path absolute
currentPath = path.resolve(
path.normalize(
currentPath
)
);
let previousPath: string;
//using ../ on the root of the drive results in the same file path, so that's how we know we reached the top
while (previousPath !== currentPath) {
previousPath = currentPath;
let bsPath = path.join(currentPath, 'bsconfig.json');
let brsPath = path.join(currentPath, 'brsconfig.json');
if (await this.pathExists(bsPath)) {
return bsPath;
} else if (await this.pathExists(brsPath)) {
return brsPath;
} else {
//walk upwards one directory
currentPath = path.resolve(path.join(currentPath, '../'));
}
}
//got to the root path, no config file exists
}
/**
* Set a timeout for the specified milliseconds, and resolve the promise once the timeout is finished.
* @param milliseconds the minimum number of milliseconds to sleep for
*/
public sleep(milliseconds: number) {
return new Promise((resolve) => {
//if milliseconds is 0, don't actually timeout (improves unit test throughput)
if (milliseconds === 0) {
process.nextTick(resolve);
} else {
setTimeout(resolve, milliseconds);
}
});
}
/**
* Given an array, map and then flatten
* @param array the array to flatMap over
* @param callback a function that is called for every array item
*/
public flatMap<T, R>(array: T[], callback: (arg: T) => R) {
return Array.prototype.concat.apply([], array.map(callback)) as never as R;
}
/**
* Determines if the position is greater than the range. This means
* the position does not touch the range, and has a position greater than the end
* of the range. A position that touches the last line/char of a range is considered greater
* than the range, because the `range.end` is EXclusive
*/
public positionIsGreaterThanRange(position: Position, range: Range) {
//if the position is a higher line than the range
if (position.line > range.end.line) {
return true;
} else if (position.line < range.end.line) {
return false;
}
//they are on the same line
//if the position's char is greater than or equal to the range's
if (position.character >= range.end.character) {
return true;
} else {
return false;
}
}
/**
* Get a location object back by extracting location information from other objects that contain location
*/
public getRange(startObj: { range: Range }, endObj: { range: Range }): Range {
return util.createRangeFromPositions(startObj.range.start, endObj.range.end);
}
/**
* If the two items both start on the same line
*/
public sameStartLine(first: { range: Range }, second: { range: Range }) {
if (first && second && first.range.start.line === second.range.start.line) {
return true;
} else {
return false;
}
}
/**
* If the two items have lines that touch
*/
public linesTouch(first: { range: Range }, second: { range: Range }) {
if (first && second && (
first.range.start.line === second.range.start.line ||
first.range.start.line === second.range.end.line ||
first.range.end.line === second.range.start.line ||
first.range.end.line === second.range.end.line
)) {
return true;
} else {
return false;
}
}
/**
* Given text with (or without) dots separating text, get the rightmost word.
* (i.e. given "A.B.C", returns "C". or "B" returns "B because there's no dot)
*/
public getTextAfterFinalDot(name: string) {
if (name) {
let parts = name.split('.');
if (parts.length > 0) {
return parts[parts.length - 1];
}
}
}
/**
* Find a script import that the current position touches, or undefined if not found
*/
public getScriptImportAtPosition(scriptImports: FileReference[], position: Position) {
let scriptImport = scriptImports.find((x) => {
return x.filePathRange.start.line === position.line &&
//column between start and end
position.character >= x.filePathRange.start.character &&
position.character <= x.filePathRange.end.character;
});
return scriptImport;
}
/**
* Given the class name text, return a namespace-prefixed name.
* If the name already has a period in it, or the namespaceName was not provided, return the class name as is.
* If the name does not have a period, and a namespaceName was provided, return the class name prepended by the namespace name.
* If no namespace is provided, return the `className` unchanged.
*/
public getFullyQualifiedClassName(className: string, namespaceName?: string) {
if (className?.includes('.') === false && namespaceName) {
return `${namespaceName}.${className}`;
} else {
return className;
}
}
public splitIntoLines(string: string) {
return string.split(/\r?\n/g);
}
public getTextForRange(string: string | string[], range: Range) {
let lines: string[];
if (Array.isArray(string)) {
lines = string;
} else {
lines = this.splitIntoLines(string);
}
const start = range.start;
const end = range.end;
let endCharacter = end.character;
// If lines are the same we need to subtract out our new starting position to make it work correctly
if (start.line === end.line) {
endCharacter -= start.character;
}
let rangeLines = [lines[start.line].substring(start.character)];
for (let i = start.line + 1; i <= end.line; i++) {
rangeLines.push(lines[i]);
}
const lastLine = rangeLines.pop();
rangeLines.push(lastLine.substring(0, endCharacter));
return rangeLines.join('\n');
}
/**
* Helper for creating `Location` objects. Prefer using this function because vscode-languageserver's `Location.create()` is significantly slower at scale
*/
public createLocation(uri: string, range: Range): Location {
return {
uri: uri,
range: range
};
}
/**
* Helper for creating `Range` objects. Prefer using this function because vscode-languageserver's `Range.create()` is significantly slower
*/
public createRange(startLine: number, startCharacter: number, endLine: number, endCharacter: number): Range {
return {
start: {
line: startLine,
character: startCharacter
},
end: {
line: endLine,
character: endCharacter
}
};
}
/**
* Create a `Range` from two `Position`s
*/
public createRangeFromPositions(startPosition: Position, endPosition: Position): Range {
return {
start: {
line: startPosition.line,
character: startPosition.character
},
end: {
line: endPosition.line,
character: endPosition.character
}
};
}
/**
* Given a list of ranges, create a range that starts with the first non-null lefthand range, and ends with the first non-null
* righthand range. Returns undefined if none of the items have a range.
*/
public createBoundingRange(...locatables: Array<{ range?: Range }>) {
let leftmostRange: Range;
let rightmostRange: Range;
for (let i = 0; i < locatables.length; i++) {
//set the leftmost non-null-range item
const left = locatables[i];
//the range might be a getter, so access it exactly once
const leftRange = left?.range;
if (!leftmostRange && leftRange) {
leftmostRange = leftRange;
}
//set the rightmost non-null-range item
const right = locatables[locatables.length - 1 - i];
//the range might be a getter, so access it exactly once
const rightRange = right?.range;
if (!rightmostRange && rightRange) {
rightmostRange = rightRange;
}
//if we have both sides, quit
if (leftmostRange && rightmostRange) {
break;
}
}
if (leftmostRange) {
return this.createRangeFromPositions(leftmostRange.start, rightmostRange.end);
} else {
return undefined;
}
}
/**
* Create a `Position` object. Prefer this over `Position.create` for performance reasons
*/
public createPosition(line: number, character: number) {
return {
line: line,
character: character
};
}
/**
* Convert a list of tokens into a string, including their leading whitespace
*/
public tokensToString(tokens: Token[]) {
let result = '';
//skip iterating the final token
for (let token of tokens) {
result += token.leadingWhitespace + token.text;
}