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

rokucommunity / brighterscript / #13041

06 Sep 2024 01:54PM UTC coverage: 86.524%. Remained the same
#13041

push

web-flow
Merge b2bbc792d into 43cbf8b72

10841 of 13320 branches covered (81.39%)

Branch coverage included in aggregate %.

213 of 221 new or added lines in 8 files covered. (96.38%)

168 existing lines in 6 files now uncovered.

12537 of 13699 relevant lines covered (91.52%)

27492.54 hits per line

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

86.1
/src/util.ts
1
import * as fs from 'fs';
1✔
2
import * as fsExtra from 'fs-extra';
1✔
3
import type { ParseError } from 'jsonc-parser';
4
import { parse as parseJsonc, printParseErrorCode } from 'jsonc-parser';
1✔
5
import * as path from 'path';
1✔
6
import { rokuDeploy, DefaultFiles, standardizePath as rokuDeployStandardizePath } from 'roku-deploy';
1✔
7
import type { DiagnosticRelatedInformation, Diagnostic, Position } from 'vscode-languageserver';
8
import { Location } from 'vscode-languageserver';
1✔
9
import { Range } from 'vscode-languageserver';
1✔
10
import { URI } from 'vscode-uri';
1✔
11
import * as xml2js from 'xml2js';
1✔
12
import type { BsConfig, FinalizedBsConfig } from './BsConfig';
13
import { DiagnosticMessages } from './DiagnosticMessages';
1✔
14
import type { CallableContainer, BsDiagnostic, FileReference, CallableContainerMap, CompilerPluginFactory, CompilerPlugin, ExpressionInfo, TranspileResult, TypeChainEntry, TypeChainProcessResult, GetTypeOptions, ExtraSymbolData } from './interfaces';
15
import { BooleanType } from './types/BooleanType';
1✔
16
import { DoubleType } from './types/DoubleType';
1✔
17
import { DynamicType } from './types/DynamicType';
1✔
18
import { FloatType } from './types/FloatType';
1✔
19
import { IntegerType } from './types/IntegerType';
1✔
20
import { LongIntegerType } from './types/LongIntegerType';
1✔
21
import { ObjectType } from './types/ObjectType';
1✔
22
import { StringType } from './types/StringType';
1✔
23
import { VoidType } from './types/VoidType';
1✔
24
import { ParseMode } from './parser/Parser';
1✔
25
import type { CallExpression, CallfuncExpression, DottedGetExpression, FunctionParameterExpression, IndexedGetExpression, LiteralExpression, NewExpression, TypeExpression, VariableExpression, XmlAttributeGetExpression } from './parser/Expression';
26
import { LogLevel, createLogger } from './logging';
1✔
27
import { isToken, type Identifier, type Locatable, type Token } from './lexer/Token';
1✔
28
import { TokenKind } from './lexer/TokenKind';
1✔
29
import { isAnyReferenceType, isBinaryExpression, isBooleanType, isBrsFile, isCallExpression, isCallableType, isCallfuncExpression, isClassType, isDottedGetExpression, isDoubleType, isDynamicType, isEnumMemberType, isExpression, isFloatType, isIndexedGetExpression, isInvalidType, isLiteralString, isLongIntegerType, isNamespaceStatement, isNamespaceType, isNewExpression, isNumberType, isReferenceType, isStatement, isStringType, isTypeExpression, isTypedArrayExpression, isTypedFunctionType, isUnionType, isVariableExpression, isXmlAttributeGetExpression, isXmlFile } from './astUtils/reflection';
1✔
30
import { WalkMode } from './astUtils/visitors';
1✔
31
import { SourceNode } from 'source-map';
1✔
32
import * as requireRelative from 'require-relative';
1✔
33
import type { BrsFile } from './files/BrsFile';
34
import type { XmlFile } from './files/XmlFile';
35
import type { AstNode, Expression, Statement } from './parser/AstNode';
36
import { AstNodeKind } from './parser/AstNode';
1✔
37
import type { UnresolvedSymbol } from './AstValidationSegmenter';
38
import type { SymbolTable } from './SymbolTable';
39
import { SymbolTypeFlag } from './SymbolTypeFlag';
1✔
40
import { createIdentifier, createToken } from './astUtils/creators';
1✔
41
import { MAX_RELATED_INFOS_COUNT } from './diagnosticUtils';
1✔
42
import type { BscType } from './types/BscType';
43
import { unionTypeFactory } from './types/UnionType';
1✔
44
import { ArrayType } from './types/ArrayType';
1✔
45
import { BinaryOperatorReferenceType } from './types/ReferenceType';
1✔
46
import { AssociativeArrayType } from './types/AssociativeArrayType';
1✔
47
import { ComponentType } from './types/ComponentType';
1✔
48
import { FunctionType } from './types/FunctionType';
1✔
49
import type { AssignmentStatement, NamespaceStatement } from './parser/Statement';
50
import type { BscFile } from './files/BscFile';
51

52
export class Util {
1✔
53
    public clearConsole() {
54
        // process.stdout.write('\x1Bc');
55
    }
56

57
    /**
58
     * Returns the number of parent directories in the filPath
59
     */
60
    public getParentDirectoryCount(filePath: string | undefined) {
61
        if (!filePath) {
1,626!
62
            return -1;
×
63
        } else {
64
            return filePath.replace(/^pkg:/, '').split(/[\\\/]/).length - 1;
1,626✔
65
        }
66
    }
67

68
    /**
69
     * Determine if the file exists
70
     */
71
    public async pathExists(filePath: string | undefined) {
72
        if (!filePath) {
122✔
73
            return false;
1✔
74
        } else {
75
            return fsExtra.pathExists(filePath);
121✔
76
        }
77
    }
78

79
    /**
80
     * Determine if the file exists
81
     */
82
    public pathExistsSync(filePath: string | undefined) {
83
        if (!filePath) {
6,007!
84
            return false;
×
85
        } else {
86
            return fsExtra.pathExistsSync(filePath);
6,007✔
87
        }
88
    }
89

90
    /**
91
     * Determine if this path is a directory
92
     */
93
    public isDirectorySync(dirPath: string | undefined) {
94
        return dirPath !== undefined && fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
3✔
95
    }
96

97
    /**
98
     * Given a pkg path of any kind, transform it to a roku-specific pkg path (i.e. "pkg:/some/path.brs")
99
     */
100
    public sanitizePkgPath(pkgPath: string) {
101
        //convert all slashes to forwardslash
102
        pkgPath = pkgPath.replace(/[\/\\]+/g, '/');
49✔
103
        //ensure every path has the leading pkg:/
104
        return 'pkg:/' + pkgPath.replace(/^pkg:\//i, '');
49✔
105
    }
106

107
    /**
108
     * Determine if the given path starts with a protocol
109
     */
110
    public startsWithProtocol(path: string) {
111
        return !!/^[-a-z]+:\//i.exec(path);
×
112
    }
113

114
    /**
115
     * Given a pkg path of any kind, transform it to a roku-specific pkg path (i.e. "pkg:/some/path.brs")
116
     * @deprecated use `sanitizePkgPath instead. Will be removed in v1
117
     */
118
    public getRokuPkgPath(pkgPath: string) {
119
        return this.sanitizePkgPath(pkgPath);
×
120
    }
121

122
    /**
123
     * Given a path to a file/directory, replace all path separators with the current system's version.
124
     */
125
    public pathSepNormalize(filePath: string, separator?: string) {
126
        if (!filePath) {
14!
127
            return filePath;
×
128
        }
129
        separator = separator ? separator : path.sep;
14!
130
        return filePath.replace(/[\\/]+/g, separator);
14✔
131
    }
132

133
    /**
134
     * Find the path to the config file.
135
     * If the config file path doesn't exist
136
     * @param cwd the current working directory where the search for configs should begin
137
     */
138
    public getConfigFilePath(cwd?: string) {
139
        cwd = cwd ?? process.cwd();
66✔
140
        let configPath = path.join(cwd, 'bsconfig.json');
66✔
141
        //find the nearest config file path
142
        for (let i = 0; i < 100; i++) {
66✔
143
            if (this.pathExistsSync(configPath)) {
6,007✔
144
                return configPath;
6✔
145
            } else {
146
                let parentDirPath = path.dirname(path.dirname(configPath));
6,001✔
147
                configPath = path.join(parentDirPath, 'bsconfig.json');
6,001✔
148
            }
149
        }
150
    }
151

152
    public getRangeFromOffsetLength(text: string, offset: number, length: number) {
153
        let lineIndex = 0;
1✔
154
        let colIndex = 0;
1✔
155
        for (let i = 0; i < text.length; i++) {
1✔
156
            if (offset === i) {
1!
157
                break;
×
158
            }
159
            let char = text[i];
1✔
160
            if (char === '\n' || (char === '\r' && text[i + 1] === '\n')) {
1!
161
                lineIndex++;
×
162
                colIndex = 0;
×
163
                i++;
×
164
                continue;
×
165
            } else {
166
                colIndex++;
1✔
167
            }
168
        }
169
        return util.createRange(lineIndex, colIndex, lineIndex, colIndex + length);
1✔
170
    }
171

172
    /**
173
     * Load the contents of a config file.
174
     * If the file extends another config, this will load the base config as well.
175
     * @param configFilePath the relative or absolute path to a brighterscript config json file
176
     * @param parentProjectPaths a list of parent config files. This is used by this method to recursively build the config list
177
     */
178
    public loadConfigFile(configFilePath: string | undefined, parentProjectPaths?: string[], cwd = process.cwd()): BsConfig | undefined {
10✔
179
        if (configFilePath) {
27✔
180
            //if the config file path starts with question mark, then it's optional. return undefined if it doesn't exist
181
            if (configFilePath.startsWith('?')) {
26✔
182
                //remove leading question mark
183
                configFilePath = configFilePath.substring(1);
1✔
184
                if (fsExtra.pathExistsSync(path.resolve(cwd, configFilePath)) === false) {
1!
185
                    return undefined;
1✔
186
                }
187
            }
188
            //keep track of the inheritance chain
189
            parentProjectPaths = parentProjectPaths ? parentProjectPaths : [];
25✔
190
            configFilePath = path.resolve(cwd, configFilePath);
25✔
191
            if (parentProjectPaths?.includes(configFilePath)) {
25!
192
                parentProjectPaths.push(configFilePath);
1✔
193
                parentProjectPaths.reverse();
1✔
194
                throw new Error('Circular dependency detected: "' + parentProjectPaths.join('" => ') + '"');
1✔
195
            }
196
            //load the project file
197
            let projectFileContents = fsExtra.readFileSync(configFilePath).toString();
24✔
198
            let parseErrors = [] as ParseError[];
24✔
199
            let projectConfig = parseJsonc(projectFileContents, parseErrors, {
24✔
200
                allowEmptyContent: true,
201
                allowTrailingComma: true,
202
                disallowComments: false
203
            }) as BsConfig ?? {};
24✔
204
            if (parseErrors.length > 0) {
24✔
205
                let err = parseErrors[0];
1✔
206
                let diagnostic = {
1✔
207
                    ...DiagnosticMessages.bsConfigJsonHasSyntaxErrors(printParseErrorCode(parseErrors[0].error)),
208
                    location: {
209
                        uri: this.pathToUri(configFilePath),
210
                        range: this.getRangeFromOffsetLength(projectFileContents, err.offset, err.length)
211
                    }
212
                } as BsDiagnostic;
213
                throw diagnostic; //eslint-disable-line @typescript-eslint/no-throw-literal
1✔
214
            }
215

216
            let projectFileCwd = path.dirname(configFilePath);
23✔
217

218
            //`plugins` paths should be relative to the current bsconfig
219
            this.resolvePathsRelativeTo(projectConfig, 'plugins', projectFileCwd);
23✔
220

221
            //`require` paths should be relative to cwd
222
            util.resolvePathsRelativeTo(projectConfig, 'require', projectFileCwd);
23✔
223

224
            let result: BsConfig;
225
            //if the project has a base file, load it
226
            if (projectConfig && typeof projectConfig.extends === 'string') {
23✔
227
                let baseProjectConfig = this.loadConfigFile(projectConfig.extends, [...parentProjectPaths, configFilePath], projectFileCwd);
7✔
228
                //extend the base config with the current project settings
229
                result = { ...baseProjectConfig, ...projectConfig };
5✔
230
            } else {
231
                result = projectConfig;
16✔
232
                let ancestors = parentProjectPaths ? parentProjectPaths : [];
16!
233
                ancestors.push(configFilePath);
16✔
234
                (result as any)._ancestors = parentProjectPaths;
16✔
235
            }
236

237
            //make any paths in the config absolute (relative to the CURRENT config file)
238
            if (result.outFile) {
21✔
239
                result.outFile = path.resolve(projectFileCwd, result.outFile);
4✔
240
            }
241
            if (result.rootDir) {
21✔
242
                result.rootDir = path.resolve(projectFileCwd, result.rootDir);
5✔
243
            }
244
            if (result.cwd) {
21✔
245
                result.cwd = path.resolve(projectFileCwd, result.cwd);
1✔
246
            }
247
            if (result.stagingDir) {
21✔
248
                result.stagingDir = path.resolve(projectFileCwd, result.stagingDir);
2✔
249
            }
250
            return result;
21✔
251
        }
252
    }
253

254
    /**
255
     * Convert relative paths to absolute paths, relative to the given directory. Also de-dupes the paths. Modifies the array in-place
256
     * @param collection usually a bsconfig.
257
     * @param key a key of the config to read paths from (usually this is `'plugins'` or `'require'`)
258
     * @param relativeDir the path to the folder where the paths should be resolved relative to. This should be an absolute path
259
     */
260
    public resolvePathsRelativeTo(collection: any, key: string, relativeDir: string) {
261
        if (!collection[key]) {
48✔
262
            return;
45✔
263
        }
264
        const result = new Set<string>();
3✔
265
        for (const p of collection[key] as string[] ?? []) {
3!
266
            if (p) {
11✔
267
                result.add(
10✔
268
                    p?.startsWith('.') ? path.resolve(relativeDir, p) : p
40!
269
                );
270
            }
271
        }
272
        collection[key] = [...result];
3✔
273
    }
274

275
    /**
276
     * Do work within the scope of a changed current working directory
277
     * @param targetCwd the cwd where the work should be performed
278
     * @param callback a function to call when the cwd has been changed to `targetCwd`
279
     */
280
    public cwdWork<T>(targetCwd: string | null | undefined, callback: () => T): T {
281
        let originalCwd = process.cwd();
×
282
        if (targetCwd) {
×
283
            process.chdir(targetCwd);
×
284
        }
285

286
        let result: T;
287
        let err;
288

289
        try {
×
290
            result = callback();
×
291
        } catch (e) {
292
            err = e;
×
293
        }
294

295
        if (targetCwd) {
×
296
            process.chdir(originalCwd);
×
297
        }
298

299
        if (err) {
×
300
            throw err;
×
301
        } else {
302
            //justification: `result` is set as long as `err` is not set and vice versa
303
            return result!;
×
304
        }
305
    }
306

307
    /**
308
     * Given a BsConfig object, start with defaults,
309
     * merge with bsconfig.json and the provided options.
310
     * @param config a bsconfig object to use as the baseline for the resulting config
311
     */
312
    public normalizeAndResolveConfig(config: BsConfig | undefined): FinalizedBsConfig {
313
        let result = this.normalizeConfig({});
74✔
314

315
        if (config?.noProject) {
74!
316
            return result;
1✔
317
        }
318

319
        //if no options were provided, try to find a bsconfig.json file
320
        if (!config || !config.project) {
73✔
321
            result.project = this.getConfigFilePath(config?.cwd);
61!
322
        } else {
323
            //use the config's project link
324
            result.project = config.project;
12✔
325
        }
326
        if (result.project) {
73✔
327
            let configFile = this.loadConfigFile(result.project, undefined, config?.cwd);
15!
328
            result = Object.assign(result, configFile);
13✔
329
        }
330
        //override the defaults with the specified options
331
        result = Object.assign(result, config);
71✔
332
        return result;
71✔
333
    }
334

335
    /**
336
     * Set defaults for any missing items
337
     * @param config a bsconfig object to use as the baseline for the resulting config
338
     */
339
    public normalizeConfig(config: BsConfig | undefined): FinalizedBsConfig {
340
        config = config ?? {} as BsConfig;
1,749✔
341

342
        const cwd = config.cwd ?? process.cwd();
1,749✔
343
        const rootFolderName = path.basename(cwd);
1,749✔
344
        const retainStagingDir = (config.retainStagingDir ?? config.retainStagingDir) === true ? true : false;
1,749✔
345

346
        let logLevel: LogLevel = LogLevel.log;
1,749✔
347

348
        if (typeof config.logLevel === 'string') {
1,749!
349
            logLevel = LogLevel[(config.logLevel as string).toLowerCase()] ?? LogLevel.log;
×
350
        }
351

352
        let bslibDestinationDir = config.bslibDestinationDir ?? 'source';
1,749✔
353
        if (bslibDestinationDir !== 'source') {
1,749✔
354
            // strip leading and trailing slashes
355
            bslibDestinationDir = bslibDestinationDir.replace(/^(\/*)(.*?)(\/*)$/, '$2');
4✔
356
        }
357

358
        const configWithDefaults: Omit<FinalizedBsConfig, 'rootDir'> = {
1,749✔
359
            cwd: cwd,
360
            deploy: config.deploy === true ? true : false,
1,749!
361
            //use default files array from rokuDeploy
362
            files: config.files ?? [...DefaultFiles],
5,247✔
363
            createPackage: config.createPackage === false ? false : true,
1,749✔
364
            outFile: config.outFile ?? `./out/${rootFolderName}.zip`,
5,247✔
365
            sourceMap: config.sourceMap === true,
366
            username: config.username ?? 'rokudev',
5,247✔
367
            watch: config.watch === true ? true : false,
1,749!
368
            emitFullPaths: config.emitFullPaths === true ? true : false,
1,749!
369
            retainStagingDir: retainStagingDir,
370
            copyToStaging: config.copyToStaging === false ? false : true,
1,749✔
371
            ignoreErrorCodes: config.ignoreErrorCodes ?? [],
5,247✔
372
            diagnosticSeverityOverrides: config.diagnosticSeverityOverrides ?? {},
5,247✔
373
            diagnosticFilters: config.diagnosticFilters ?? [],
5,247✔
374
            plugins: config.plugins ?? [],
5,247✔
375
            pruneEmptyCodeFiles: config.pruneEmptyCodeFiles === true ? true : false,
1,749✔
376
            autoImportComponentScript: config.autoImportComponentScript === true ? true : false,
1,749✔
377
            showDiagnosticsInConsole: config.showDiagnosticsInConsole === false ? false : true,
1,749✔
378
            sourceRoot: config.sourceRoot ? standardizePath(config.sourceRoot) : undefined,
1,749✔
379
            allowBrighterScriptInBrightScript: config.allowBrighterScriptInBrightScript === true ? true : false,
1,749!
380
            emitDefinitions: config.emitDefinitions === true ? true : false,
1,749!
381
            removeParameterTypes: config.removeParameterTypes === true ? true : false,
1,749!
382
            logLevel: logLevel,
383
            bslibDestinationDir: bslibDestinationDir,
384
            legacyCallfuncHandling: config.legacyCallfuncHandling === true ? true : false
1,749!
385
        };
386

387
        //mutate `config` in case anyone is holding a reference to the incomplete one
388
        const merged: FinalizedBsConfig = Object.assign(config, configWithDefaults);
1,749✔
389

390
        return merged;
1,749✔
391
    }
392

393
    /**
394
     * Get the root directory from options.
395
     * Falls back to options.cwd.
396
     * Falls back to process.cwd
397
     * @param options a bsconfig object
398
     */
399
    public getRootDir(options: BsConfig) {
400
        if (!options) {
1,638!
401
            throw new Error('Options is required');
×
402
        }
403
        let cwd = options.cwd;
1,638✔
404
        cwd = cwd ? cwd : process.cwd();
1,638!
405
        let rootDir = options.rootDir ? options.rootDir : cwd;
1,638✔
406

407
        rootDir = path.resolve(cwd, rootDir);
1,638✔
408

409
        return rootDir;
1,638✔
410
    }
411

412
    /**
413
     * Given a list of callables as a dictionary indexed by their full name (namespace included, transpiled to underscore-separated.
414
     */
415
    public getCallableContainersByLowerName(callables: CallableContainer[]): CallableContainerMap {
416
        //find duplicate functions
417
        const result = new Map<string, CallableContainer[]>();
1,594✔
418

419
        for (let callableContainer of callables) {
1,594✔
420
            let lowerName = callableContainer.callable.getName(ParseMode.BrightScript).toLowerCase();
126,086✔
421

422
            //create a new array for this name
423
            const list = result.get(lowerName);
126,086✔
424
            if (list) {
126,086✔
425
                list.push(callableContainer);
6,410✔
426
            } else {
427
                result.set(lowerName, [callableContainer]);
119,676✔
428
            }
429
        }
430
        return result;
1,594✔
431
    }
432

433
    /**
434
     * Split a file by newline characters (LF or CRLF)
435
     */
436
    public getLines(text: string) {
437
        return text.split(/\r?\n/);
×
438
    }
439

440
    /**
441
     * Given an absolute path to a source file, and a target path,
442
     * compute the pkg path for the target relative to the source file's location
443
     */
444
    public getPkgPathFromTarget(containingFilePathAbsolute: string, targetPath: string) {
445
        // https://regex101.com/r/w7CG2N/1
446
        const regexp = /^(?:pkg|libpkg):(\/)?/i;
628✔
447
        const [fullScheme, slash] = regexp.exec(targetPath) ?? [];
628✔
448
        //if the target starts with 'pkg:' or 'libpkg:' then it's an absolute path. Return as is
449
        if (slash) {
628✔
450
            targetPath = targetPath.substring(fullScheme.length);
418✔
451
            if (targetPath === '') {
418✔
452
                return null;
2✔
453
            } else {
454
                return path.normalize(targetPath);
416✔
455
            }
456
        }
457
        //if the path is exactly `pkg:` or `libpkg:`
458
        if (targetPath === fullScheme && !slash) {
210✔
459
            return null;
2✔
460
        }
461

462
        //remove the filename
463
        let containingFolder = path.normalize(path.dirname(containingFilePathAbsolute));
208✔
464
        //start with the containing folder, split by slash
465
        let result = containingFolder.split(path.sep);
208✔
466

467
        //split on slash
468
        let targetParts = path.normalize(targetPath).split(path.sep);
208✔
469

470
        for (let part of targetParts) {
208✔
471
            if (part === '' || part === '.') {
212✔
472
                //do nothing, it means current directory
473
                continue;
4✔
474
            }
475
            if (part === '..') {
208✔
476
                //go up one directory
477
                result.pop();
2✔
478
            } else {
479
                result.push(part);
206✔
480
            }
481
        }
482
        return result.join(path.sep);
208✔
483
    }
484

485
    /**
486
     * Compute the relative path from the source file to the target file
487
     * @param pkgSrcPath  - the absolute path to the source, where cwd is the package location
488
     * @param pkgTargetPath  - the absolute path to the target, where cwd is the package location
489
     */
490
    public getRelativePath(pkgSrcPath: string, pkgTargetPath: string) {
491
        pkgSrcPath = path.normalize(pkgSrcPath);
11✔
492
        pkgTargetPath = path.normalize(pkgTargetPath);
11✔
493

494
        //break by path separator
495
        let sourceParts = pkgSrcPath.split(path.sep);
11✔
496
        let targetParts = pkgTargetPath.split(path.sep);
11✔
497

498
        let commonParts = [] as string[];
11✔
499
        //find their common root
500
        for (let i = 0; i < targetParts.length; i++) {
11✔
501
            if (targetParts[i].toLowerCase() === sourceParts[i].toLowerCase()) {
17✔
502
                commonParts.push(targetParts[i]);
6✔
503
            } else {
504
                //we found a non-matching part...so no more commonalities past this point
505
                break;
11✔
506
            }
507
        }
508

509
        //throw out the common parts from both sets
510
        sourceParts.splice(0, commonParts.length);
11✔
511
        targetParts.splice(0, commonParts.length);
11✔
512

513
        //throw out the filename part of source
514
        sourceParts.splice(sourceParts.length - 1, 1);
11✔
515
        //start out by adding updir paths for each remaining source part
516
        let resultParts = sourceParts.map(() => '..');
11✔
517

518
        //now add every target part
519
        resultParts = [...resultParts, ...targetParts];
11✔
520
        return path.join(...resultParts);
11✔
521
    }
522

523
    public getImportPackagePath(srcPath: string, pkgTargetPath: string) {
524
        const srcExt = this.getExtension(srcPath);
6✔
525
        const lowerSrcExt = srcExt.toLowerCase();
6✔
526
        const lowerTargetExt = this.getExtension(pkgTargetPath).toLowerCase();
6✔
527
        if (lowerSrcExt === '.bs' && lowerTargetExt === '.brs') {
6✔
528
            // if source is .bs, use that as the import extenstion
529
            return pkgTargetPath.substring(0, pkgTargetPath.length - lowerTargetExt.length) + srcExt;
3✔
530
        }
531
        return pkgTargetPath;
3✔
532
    }
533

534
    /**
535
     * Walks left in a DottedGetExpression and returns a VariableExpression if found, or undefined if not found
536
     */
537
    public findBeginningVariableExpression(dottedGet: DottedGetExpression): VariableExpression | undefined {
538
        let left: any = dottedGet;
37✔
539
        while (left) {
37✔
540
            if (isVariableExpression(left)) {
69✔
541
                return left;
37✔
542
            } else if (isDottedGetExpression(left)) {
32!
543
                left = left.obj;
32✔
544
            } else {
545
                break;
×
546
            }
547
        }
548
    }
549

550
    /**
551
     * Do `a` and `b` overlap by at least one character. This returns false if they are at the edges. Here's some examples:
552
     * ```
553
     * | true | true | true | true | true | false | false | false | false |
554
     * |------|------|------|------|------|-------|-------|-------|-------|
555
     * | aa   |  aaa |  aaa | aaa  |  a   |  aa   |    aa | a     |     a |
556
     * |  bbb | bb   |  bbb |  b   | bbb  |    bb |  bb   |     b | a     |
557
     * ```
558
     */
559
    public rangesIntersect(a: Range | undefined, b: Range | undefined) {
560
        //stop if the either range is misisng
561
        if (!a || !b) {
11✔
562
            return false;
2✔
563
        }
564

565
        // Check if `a` is before `b`
566
        if (a.end.line < b.start.line || (a.end.line === b.start.line && a.end.character <= b.start.character)) {
9✔
567
            return false;
1✔
568
        }
569

570
        // Check if `b` is before `a`
571
        if (b.end.line < a.start.line || (b.end.line === a.start.line && b.end.character <= a.start.character)) {
8✔
572
            return false;
1✔
573
        }
574

575
        // These ranges must intersect
576
        return true;
7✔
577
    }
578

579
    /**
580
     * Do `a` and `b` overlap by at least one character or touch at the edges
581
     * ```
582
     * | true | true | true | true | true | true  | true  | false | false |
583
     * |------|------|------|------|------|-------|-------|-------|-------|
584
     * | aa   |  aaa |  aaa | aaa  |  a   |  aa   |    aa | a     |     a |
585
     * |  bbb | bb   |  bbb |  b   | bbb  |    bb |  bb   |     b | a     |
586
     * ```
587
     */
588
    public rangesIntersectOrTouch(a: Range | undefined, b: Range | undefined) {
589
        //stop if the either range is misisng
590
        if (!a || !b) {
27✔
591
            return false;
2✔
592
        }
593
        // Check if `a` is before `b`
594
        if (a.end.line < b.start.line || (a.end.line === b.start.line && a.end.character < b.start.character)) {
25✔
595
            return false;
2✔
596
        }
597

598
        // Check if `b` is before `a`
599
        if (b.end.line < a.start.line || (b.end.line === a.start.line && b.end.character < a.start.character)) {
23✔
600
            return false;
2✔
601
        }
602

603
        // These ranges must intersect
604
        return true;
21✔
605
    }
606

607
    /**
608
     * Test if `position` is in `range`. If the position is at the edges, will return true.
609
     * Adapted from core vscode
610
     */
611
    public rangeContains(range: Range | undefined, position: Position | undefined) {
612
        return this.comparePositionToRange(position, range) === 0;
11,600✔
613
    }
614

615
    public comparePositionToRange(position: Position | undefined, range: Range | undefined) {
616
        //stop if the either range is missng
617
        if (!position || !range) {
13,579✔
618
            return 0;
10✔
619
        }
620

621
        if (this.comparePosition(position, range.start) < 0) {
13,569✔
622
            return -1;
2,114✔
623
        }
624
        if (this.comparePosition(position, range.end) > 0) {
11,455✔
625
            return 1;
8,208✔
626
        }
627
        return 0;
3,247✔
628
    }
629

630
    public comparePosition(a: Position | undefined, b: Position) {
631
        //stop if the either position is missing
632
        if (!a || !b) {
206,785!
633
            return 0;
×
634
        }
635

636
        if (a.line < b.line || (a.line === b.line && a.character < b.character)) {
206,785✔
637
            return -1;
14,600✔
638
        }
639
        if (a.line > b.line || (a.line === b.line && a.character > b.character)) {
192,185✔
640
            return 1;
191,389✔
641
        }
642
        return 0;
796✔
643
    }
644

645
    /**
646
     * Combine all the documentation for a node - uses the AstNode's leadingTrivia property
647
     * @param node the node to get the documentation for
648
     * @param options prettyPrint- if true, will format the comment text for markdown, matchingLocations: out Array of locations that match the comment lines
649
     */
650
    public getNodeDocumentation(node: AstNode, options: { prettyPrint?: boolean; matchingLocations?: Location[] } = { prettyPrint: true }) {
935✔
651
        if (!node) {
29,700✔
652
            return '';
1,231✔
653
        }
654
        options = options ?? { prettyPrint: true };
28,469!
655
        options.matchingLocations = options.matchingLocations ?? [];
28,469✔
656
        const nodeTrivia = node.leadingTrivia ?? [];
28,469!
657
        const leadingTrivia = isStatement(node)
28,469✔
658
            ? [...(node.annotations?.map(anno => anno.leadingTrivia ?? []).flat() ?? []), ...nodeTrivia]
32!
659
            : nodeTrivia;
660
        const tokens = leadingTrivia?.filter(t => t.kind === TokenKind.Newline || t.kind === TokenKind.Comment);
54,810!
661
        const comments = [] as Token[];
28,469✔
662

663
        let newLinesInRow = 0;
28,469✔
664
        for (let i = tokens.length - 1; i >= 0; i--) {
28,469✔
665
            const token = tokens[i];
25,061✔
666
            //skip whitespace and newline chars
667
            if (token.kind === TokenKind.Comment) {
25,061✔
668
                comments.push(token);
927✔
669
                newLinesInRow = 0;
927✔
670
            } else if (token.kind === TokenKind.Newline) {
24,134!
671
                //skip these tokens
672
                newLinesInRow++;
24,134✔
673

674
                if (newLinesInRow > 1) {
24,134✔
675
                    // stop processing on empty line.
676
                    break;
2,814✔
677
                }
678
                //any other token means there are no more comments
679
            } else {
UNCOV
680
                break;
×
681
            }
682
        }
683
        const jsDocCommentBlockLine = /(\/\*{2,}|\*{1,}\/)/i;
28,469✔
684
        let usesjsDocCommentBlock = false;
28,469✔
685
        if (comments.length === 0) {
28,469✔
686
            return '';
27,661✔
687
        }
688
        return comments.reverse()
808✔
689
            .map(x => ({ line: x.text.replace(/^('|rem)/i, '').trim(), location: x.location }))
927✔
690
            .filter(({ line }) => {
691
                if (jsDocCommentBlockLine.exec(line)) {
927✔
692
                    usesjsDocCommentBlock = true;
28✔
693
                    return false;
28✔
694
                }
695
                return true;
899✔
696
            }).map(({ line, location }) => {
697
                if (usesjsDocCommentBlock) {
899✔
698
                    if (line.startsWith('*')) {
18✔
699
                        //remove jsDoc leading '*'
700
                        line = line.slice(1).trim();
17✔
701
                    }
702
                }
703
                if (options.prettyPrint && line.startsWith('@')) {
899✔
704
                    // Handle jsdoc/brightscriptdoc tags specially
705
                    // make sure they are on their own markdown line, and add italics
706
                    const firstSpaceIndex = line.indexOf(' ');
3✔
707
                    if (firstSpaceIndex === -1) {
3✔
708
                        return `\n_${line}_`;
1✔
709
                    }
710
                    const firstWord = line.substring(0, firstSpaceIndex);
2✔
711
                    return `\n_${firstWord}_ ${line.substring(firstSpaceIndex + 1)}`;
2✔
712
                }
713
                if (options.matchingLocations) {
896!
714
                    options.matchingLocations.push(location);
896✔
715
                }
716
                return line;
896✔
717
            }).join('\n');
718
    }
719

720
    /**
721
     * Prefixes a component name so it can be used as type in the symbol table, without polluting available symbols
722
     *
723
     * @param sgNodeName the Name of the component
724
     * @returns the node name, prefixed with `roSGNode`
725
     */
726
    public getSgNodeTypeName(sgNodeName: string) {
727
        return 'roSGNode' + sgNodeName;
293,583✔
728
    }
729

730
    /**
731
     * Parse an xml file and get back a javascript object containing its results
732
     */
733
    public parseXml(text: string) {
UNCOV
734
        return new Promise<any>((resolve, reject) => {
×
UNCOV
735
            xml2js.parseString(text, (err, data) => {
×
UNCOV
736
                if (err) {
×
UNCOV
737
                    reject(err);
×
738
                } else {
UNCOV
739
                    resolve(data);
×
740
                }
741
            });
742
        });
743
    }
744

745
    public propertyCount(object: Record<string, unknown>) {
746
        let count = 0;
×
UNCOV
747
        for (let key in object) {
×
UNCOV
748
            if (object.hasOwnProperty(key)) {
×
UNCOV
749
                count++;
×
750
            }
751
        }
UNCOV
752
        return count;
×
753
    }
754

755
    public padLeft(subject: string, totalLength: number, char: string) {
756
        totalLength = totalLength > 1000 ? 1000 : totalLength;
1!
757
        while (subject.length < totalLength) {
1✔
758
            subject = char + subject;
1,000✔
759
        }
760
        return subject;
1✔
761
    }
762

763
    /**
764
     * Does the string appear to be a uri (i.e. does it start with `file:`)
765
     */
766
    public isUriLike(filePath: string) {
767
        return filePath?.indexOf('file:') === 0;// eslint-disable-line @typescript-eslint/prefer-string-starts-ends-with
273,414!
768
    }
769

770
    /**
771
     * Given a file path, convert it to a URI string
772
     */
773
    public pathToUri(filePath: string) {
774
        if (!filePath) {
239,419✔
775
            return filePath;
25,628✔
776
        } else if (this.isUriLike(filePath)) {
213,791✔
777
            return filePath;
193,687✔
778
        } else {
779
            return URI.file(filePath).toString();
20,104✔
780
        }
781
    }
782

783
    /**
784
     * Given a URI, convert that to a regular fs path
785
     */
786
    public uriToPath(uri: string) {
787
        //if this doesn't look like a URI, then assume it's already a path
788
        if (this.isUriLike(uri) === false) {
51,560✔
789
            return uri;
2✔
790
        }
791
        let parsedPath = URI.parse(uri).fsPath;
51,558✔
792

793
        //Uri annoyingly converts all drive letters to lower case...so this will bring back whatever case it came in as
794
        let match = /\/\/\/([a-z]:)/i.exec(uri);
51,558✔
795
        if (match) {
51,558✔
796
            let originalDriveCasing = match[1];
17✔
797
            parsedPath = originalDriveCasing + parsedPath.substring(2);
17✔
798
        }
799
        const normalizedPath = path.normalize(parsedPath);
51,558✔
800
        return normalizedPath;
51,558✔
801
    }
802

803
    /**
804
     * Force the drive letter to lower case
805
     */
806
    public driveLetterToLower(fullPath: string) {
807
        if (fullPath) {
32,585✔
808
            let firstCharCode = fullPath.charCodeAt(0);
32,581✔
809
            if (
32,581✔
810
                //is upper case A-Z
811
                firstCharCode >= 65 && firstCharCode <= 90 &&
66,464✔
812
                //next char is colon
813
                fullPath[1] === ':'
814
            ) {
815
                fullPath = fullPath[0].toLowerCase() + fullPath.substring(1);
1,322✔
816
            }
817
        }
818
        return fullPath;
32,585✔
819
    }
820

821
    /**
822
     * Replace the first instance of `search` in `subject` with `replacement`
823
     */
824
    public replaceCaseInsensitive(subject: string, search: string, replacement: string) {
825
        let idx = subject.toLowerCase().indexOf(search.toLowerCase());
6,631✔
826
        if (idx > -1) {
6,631✔
827
            let result = subject.substring(0, idx) + replacement + subject.substring(idx + search.length);
2,089✔
828
            return result;
2,089✔
829
        } else {
830
            return subject;
4,542✔
831
        }
832
    }
833

834
    /**
835
     * Determine if two arrays containing primitive values are equal.
836
     * This considers order and compares by equality.
837
     */
838
    public areArraysEqual(arr1: any[], arr2: any[]) {
839
        if (arr1.length !== arr2.length) {
8✔
840
            return false;
3✔
841
        }
842
        for (let i = 0; i < arr1.length; i++) {
5✔
843
            if (arr1[i] !== arr2[i]) {
7✔
844
                return false;
3✔
845
            }
846
        }
847
        return true;
2✔
848
    }
849

850
    /**
851
     * Get the outDir from options, taking into account cwd and absolute outFile paths
852
     */
853
    public getOutDir(options: FinalizedBsConfig) {
854
        options = this.normalizeConfig(options);
2✔
855
        let cwd = path.normalize(options.cwd ? options.cwd : process.cwd());
2!
856
        if (path.isAbsolute(options.outFile)) {
2!
UNCOV
857
            return path.dirname(options.outFile);
×
858
        } else {
859
            return path.normalize(path.join(cwd, path.dirname(options.outFile)));
2✔
860
        }
861
    }
862

863
    /**
864
     * Get paths to all files on disc that match this project's source list
865
     */
866
    public async getFilePaths(options: FinalizedBsConfig) {
867
        let rootDir = this.getRootDir(options);
48✔
868

869
        let files = await rokuDeploy.getFilePaths(options.files, rootDir);
48✔
870
        return files;
48✔
871
    }
872

873
    /**
874
     * Given a path to a brs file, compute the path to a theoretical d.bs file.
875
     * Only `.brs` files can have typedef path, so return undefined for everything else
876
     */
877
    public getTypedefPath(brsSrcPath: string) {
878
        const typedefPath = brsSrcPath
3,423✔
879
            .replace(/\.brs$/i, '.d.bs')
880
            .toLowerCase();
881

882
        if (typedefPath.endsWith('.d.bs')) {
3,423✔
883
            return typedefPath;
2,014✔
884
        } else {
885
            return undefined;
1,409✔
886
        }
887
    }
888

889

890
    /**
891
     * Walks up the chain to find the closest bsconfig.json file
892
     */
893
    public async findClosestConfigFile(currentPath: string): Promise<string | undefined> {
894
        //make the path absolute
895
        currentPath = path.resolve(
6✔
896
            path.normalize(
897
                currentPath
898
            )
899
        );
900

901
        let previousPath: string | undefined;
902
        //using ../ on the root of the drive results in the same file path, so that's how we know we reached the top
903
        while (previousPath !== currentPath) {
6✔
904
            previousPath = currentPath;
24✔
905

906
            let bsPath = path.join(currentPath, 'bsconfig.json');
24✔
907
            let brsPath = path.join(currentPath, 'brsconfig.json');
24✔
908
            if (await this.pathExists(bsPath)) {
24✔
909
                return bsPath;
2✔
910
            } else if (await this.pathExists(brsPath)) {
22✔
911
                return brsPath;
2✔
912
            } else {
913
                //walk upwards one directory
914
                currentPath = path.resolve(path.join(currentPath, '../'));
20✔
915
            }
916
        }
917
        //got to the root path, no config file exists
918
    }
919

920
    /**
921
     * Set a timeout for the specified milliseconds, and resolve the promise once the timeout is finished.
922
     * @param milliseconds the minimum number of milliseconds to sleep for
923
     */
924
    public sleep(milliseconds: number) {
925
        return new Promise((resolve) => {
103✔
926
            //if milliseconds is 0, don't actually timeout (improves unit test throughput)
927
            if (milliseconds === 0) {
103✔
928
                process.nextTick(resolve);
89✔
929
            } else {
930
                setTimeout(resolve, milliseconds);
14✔
931
            }
932
        });
933
    }
934

935
    /**
936
     * Given an array, map and then flatten
937
     * @param array the array to flatMap over
938
     * @param callback a function that is called for every array item
939
     */
940
    public flatMap<T, R>(array: T[], callback: (arg: T) => R[]): R[] {
941
        return Array.prototype.concat.apply([], array.map(callback));
16✔
942
    }
943

944
    /**
945
     * Determines if the position is greater than the range. This means
946
     * the position does not touch the range, and has a position greater than the end
947
     * of the range. A position that touches the last line/char of a range is considered greater
948
     * than the range, because the `range.end` is EXclusive
949
     */
950
    public positionIsGreaterThanRange(position: Position, range: Range) {
951

952
        //if the position is a higher line than the range
953
        if (position.line > range.end.line) {
1,166✔
954
            return true;
1,079✔
955
        } else if (position.line < range.end.line) {
87!
UNCOV
956
            return false;
×
957
        }
958
        //they are on the same line
959

960
        //if the position's char is greater than or equal to the range's
961
        if (position.character >= range.end.character) {
87!
962
            return true;
87✔
963
        } else {
UNCOV
964
            return false;
×
965
        }
966
    }
967

968
    /**
969
     * Get a range back from an object that contains (or is) a range
970
     */
971
    public extractRange(rangeIsh: RangeLike): Range | undefined {
972
        if (!rangeIsh) {
9,456✔
973
            return undefined;
29✔
974
        } else if ('location' in rangeIsh) {
9,427✔
975
            return rangeIsh.location?.range;
6,532✔
976
        } else if ('range' in rangeIsh) {
2,895!
977
            return rangeIsh.range;
2,895✔
UNCOV
978
        } else if (Range.is(rangeIsh)) {
×
UNCOV
979
            return rangeIsh;
×
980
        } else {
UNCOV
981
            return undefined;
×
982
        }
983
    }
984

985

986
    /**
987
     * Get a location object back by extracting location information from other objects that contain location
988
     */
989
    public getRange(startObj: | { range: Range }, endObj: { range: Range }): Range {
UNCOV
990
        if (!startObj?.range || !endObj?.range) {
×
UNCOV
991
            return undefined;
×
992
        }
UNCOV
993
        return util.createRangeFromPositions(startObj.range?.start, endObj.range?.end);
×
994
    }
995

996
    /**
997
     * If the two items both start on the same line
998
     */
999
    public sameStartLine(first: { range: Range }, second: { range: Range }) {
1000
        if (first && second && first.range.start.line === second.range.start.line) {
×
UNCOV
1001
            return true;
×
1002
        } else {
UNCOV
1003
            return false;
×
1004
        }
1005
    }
1006

1007
    /**
1008
     * If the two items have lines that touch
1009
     */
1010
    public linesTouch(first: RangeLike, second: RangeLike) {
1011
        const firstRange = this.extractRange(first);
1,476✔
1012
        const secondRange = this.extractRange(second);
1,476✔
1013
        if (firstRange && secondRange && (
1,476✔
1014
            firstRange.start.line === secondRange.start.line ||
1015
            firstRange.start.line === secondRange.end.line ||
1016
            firstRange.end.line === secondRange.start.line ||
1017
            firstRange.end.line === secondRange.end.line
1018
        )) {
1019
            return true;
91✔
1020
        } else {
1021
            return false;
1,385✔
1022
        }
1023
    }
1024

1025
    /**
1026
     * Given text with (or without) dots separating text, get the rightmost word.
1027
     * (i.e. given "A.B.C", returns "C". or "B" returns "B because there's no dot)
1028
     */
1029
    public getTextAfterFinalDot(name: string) {
UNCOV
1030
        if (name) {
×
UNCOV
1031
            let parts = name.split('.');
×
UNCOV
1032
            if (parts.length > 0) {
×
UNCOV
1033
                return parts[parts.length - 1];
×
1034
            }
1035
        }
1036
    }
1037

1038
    /**
1039
     * Find a script import that the current position touches, or undefined if not found
1040
     */
1041
    public getScriptImportAtPosition(scriptImports: FileReference[], position: Position): FileReference | undefined {
1042
        let scriptImport = scriptImports.find((x) => {
117✔
1043
            return x.filePathRange &&
5✔
1044
                x.filePathRange.start.line === position.line &&
1045
                //column between start and end
1046
                position.character >= x.filePathRange.start.character &&
1047
                position.character <= x.filePathRange.end.character;
1048
        });
1049
        return scriptImport;
117✔
1050
    }
1051

1052
    /**
1053
     * Given the class name text, return a namespace-prefixed name.
1054
     * If the name already has a period in it, or the namespaceName was not provided, return the class name as is.
1055
     * If the name does not have a period, and a namespaceName was provided, return the class name prepended by the namespace name.
1056
     * If no namespace is provided, return the `className` unchanged.
1057
     */
1058
    public getFullyQualifiedClassName(className: string, namespaceName?: string) {
1059
        if (className?.includes('.') === false && namespaceName) {
3,566✔
1060
            return `${namespaceName}.${className}`;
153✔
1061
        } else {
1062
            return className;
3,413✔
1063
        }
1064
    }
1065

1066
    public splitIntoLines(string: string) {
1067
        return string.split(/\r?\n/g);
169✔
1068
    }
1069

1070
    public getTextForRange(string: string | string[], range: Range): string {
1071
        let lines: string[];
1072
        if (Array.isArray(string)) {
171✔
1073
            lines = string;
170✔
1074
        } else {
1075
            lines = this.splitIntoLines(string);
1✔
1076
        }
1077

1078
        const start = range.start;
171✔
1079
        const end = range.end;
171✔
1080

1081
        let endCharacter = end.character;
171✔
1082
        // If lines are the same we need to subtract out our new starting position to make it work correctly
1083
        if (start.line === end.line) {
171✔
1084
            endCharacter -= start.character;
159✔
1085
        }
1086

1087
        let rangeLines = [lines[start.line].substring(start.character)];
171✔
1088
        for (let i = start.line + 1; i <= end.line; i++) {
171✔
1089
            rangeLines.push(lines[i]);
12✔
1090
        }
1091
        const lastLine = rangeLines.pop();
171✔
1092
        if (lastLine !== undefined) {
171!
1093
            rangeLines.push(lastLine.substring(0, endCharacter));
171✔
1094
        }
1095
        return rangeLines.join('\n');
171✔
1096
    }
1097

1098
    /**
1099
     * Helper for creating `Location` objects. Prefer using this function because vscode-languageserver's `Location.create()` is significantly slower at scale
1100
     */
1101
    public createLocationFromRange(uri: string, range: Range): Location {
1102
        return {
7,743✔
1103
            uri: util.pathToUri(uri),
1104
            range: range
1105
        };
1106
    }
1107

1108
    /**
1109
     * Helper for creating `Location` objects from a file and range
1110
     */
1111
    public createLocationFromFileRange(file: BscFile, range: Range): Location {
1112
        return this.createLocationFromRange(this.pathToUri(file?.srcPath), range);
379!
1113
    }
1114

1115
    /**
1116
     * Helper for creating `Location` objects by passing each range value in directly. Prefer using this function because vscode-languageserver's `Location.create()` is significantly slower at scale
1117
     */
1118
    public createLocation(startLine: number, startCharacter: number, endLine: number, endCharacter: number, uri?: string): Location {
1119
        return {
223,310✔
1120
            uri: util.pathToUri(uri),
1121
            range: {
1122
                start: {
1123
                    line: startLine,
1124
                    character: startCharacter
1125
                },
1126
                end: {
1127
                    line: endLine,
1128
                    character: endCharacter
1129
                }
1130
            }
1131
        };
1132
    }
1133

1134
    /**
1135
     * Helper for creating `Range` objects. Prefer using this function because vscode-languageserver's `Range.create()` is significantly slower.
1136
     */
1137
    public createRange(startLine: number, startCharacter: number, endLine: number, endCharacter: number): Range {
1138
        return {
7,780✔
1139
            start: {
1140
                line: startLine,
1141
                character: startCharacter
1142
            },
1143
            end: {
1144
                line: endLine,
1145
                character: endCharacter
1146
            }
1147
        };
1148
    }
1149

1150
    /**
1151
     * Create a `Range` from two `Position`s
1152
     */
1153
    public createRangeFromPositions(startPosition: Position, endPosition: Position): Range | undefined {
1154
        startPosition = startPosition ?? endPosition;
171✔
1155
        endPosition = endPosition ?? startPosition;
171✔
1156
        if (!startPosition && !endPosition) {
171!
UNCOV
1157
            return undefined;
×
1158
        }
1159
        return this.createRange(startPosition.line, startPosition.character, endPosition.line, endPosition.character);
171✔
1160
    }
1161

1162
    /**
1163
     *  Gets the bounding range of a bunch of ranges or objects that have ranges
1164
     *  TODO: this does a full iteration of the args. If the args were guaranteed to be in range order, we could optimize this
1165
     */
1166
    public createBoundingLocation(...locatables: Array<{ location?: Location } | Location | { range?: Range } | Range | undefined>): Location | undefined {
1167
        let uri: string | undefined;
1168
        let startPosition: Position | undefined;
1169
        let endPosition: Position | undefined;
1170

1171
        for (let locatable of locatables) {
43,899✔
1172
            let range: Range;
1173
            if (!locatable) {
177,694✔
1174
                continue;
47,927✔
1175
            } else if ('location' in locatable) {
129,767✔
1176
                range = locatable.location?.range;
124,657✔
1177
                if (!uri) {
124,657✔
1178
                    uri = locatable.location?.uri;
48,353✔
1179
                }
1180
            } else if (Location.is(locatable)) {
5,110✔
1181
                range = locatable.range;
5,102✔
1182
                if (!uri) {
5,102✔
1183
                    uri = locatable.uri;
4,515✔
1184
                }
1185
            } else if ('range' in locatable) {
8!
UNCOV
1186
                range = locatable.range;
×
1187
            } else {
1188
                range = locatable as Range;
8✔
1189
            }
1190

1191
            //skip undefined locations or locations without a range
1192
            if (!range) {
129,767✔
1193
                continue;
3,551✔
1194
            }
1195

1196
            if (!startPosition) {
126,216✔
1197
                startPosition = range.start;
42,691✔
1198
            } else if (this.comparePosition(range.start, startPosition) < 0) {
83,525✔
1199
                startPosition = range.start;
829✔
1200
            }
1201
            if (!endPosition) {
126,216✔
1202
                endPosition = range.end;
42,691✔
1203
            } else if (this.comparePosition(range.end, endPosition) > 0) {
83,525✔
1204
                endPosition = range.end;
78,735✔
1205
            }
1206
        }
1207
        if (startPosition && endPosition) {
43,899✔
1208
            return util.createLocation(startPosition.line, startPosition.character, endPosition.line, endPosition.character, uri);
42,691✔
1209
        } else {
1210
            return undefined;
1,208✔
1211
        }
1212
    }
1213

1214
    /**
1215
     *  Gets the bounding range of a bunch of ranges or objects that have ranges
1216
     *  TODO: this does a full iteration of the args. If the args were guaranteed to be in range order, we could optimize this
1217
     */
1218
    public createBoundingRange(...locatables: Array<RangeLike>): Range | undefined {
1219
        return this.createBoundingLocation(...locatables)?.range;
505✔
1220
    }
1221

1222
    /**
1223
     * Gets the bounding range of an object that contains a bunch of tokens
1224
     * @param tokens Object with tokens in it
1225
     * @returns Range containing all the tokens
1226
     */
1227
    public createBoundingLocationFromTokens(tokens: Record<string, { location?: Location }>): Location | undefined {
1228
        let uri: string;
1229
        let startPosition: Position | undefined;
1230
        let endPosition: Position | undefined;
1231
        for (let key in tokens) {
4,908✔
1232
            let token = tokens?.[key];
17,497!
1233
            let locatableRange = token?.location?.range;
17,497✔
1234
            if (!locatableRange) {
17,497✔
1235
                continue;
5,396✔
1236
            }
1237

1238
            if (!startPosition) {
12,101✔
1239
                startPosition = locatableRange.start;
4,751✔
1240
            } else if (this.comparePosition(locatableRange.start, startPosition) < 0) {
7,350✔
1241
                startPosition = locatableRange.start;
2,012✔
1242
            }
1243
            if (!endPosition) {
12,101✔
1244
                endPosition = locatableRange.end;
4,751✔
1245
            } else if (this.comparePosition(locatableRange.end, endPosition) > 0) {
7,350✔
1246
                endPosition = locatableRange.end;
5,226✔
1247
            }
1248
            if (!uri) {
12,101✔
1249
                uri = token.location.uri;
5,790✔
1250
            }
1251
        }
1252
        if (startPosition && endPosition) {
4,908✔
1253
            return this.createLocation(startPosition.line, startPosition.character, endPosition.line, endPosition.character, uri);
4,751✔
1254
        } else {
1255
            return undefined;
157✔
1256
        }
1257
    }
1258

1259
    /**
1260
     * Create a `Position` object. Prefer this over `Position.create` for performance reasons.
1261
     */
1262
    public createPosition(line: number, character: number) {
1263
        return {
367✔
1264
            line: line,
1265
            character: character
1266
        };
1267
    }
1268

1269
    /**
1270
     * Convert a list of tokens into a string, including their leading whitespace
1271
     */
1272
    public tokensToString(tokens: Token[]) {
1273
        let result = '';
1✔
1274
        //skip iterating the final token
1275
        for (let token of tokens) {
1✔
1276
            result += token.leadingWhitespace + token.text;
16✔
1277
        }
1278
        return result;
1✔
1279
    }
1280

1281
    /**
1282
     * Convert a token into a BscType
1283
     */
1284
    public tokenToBscType(token: Token) {
1285
        // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
1286
        switch (token.kind) {
1,634,390✔
1287
            case TokenKind.Boolean:
1,637,587✔
1288
                return new BooleanType(token.text);
106✔
1289
            case TokenKind.True:
1290
            case TokenKind.False:
1291
                return BooleanType.instance;
161✔
1292
            case TokenKind.Double:
1293
                return new DoubleType(token.text);
74✔
1294
            case TokenKind.DoubleLiteral:
1295
                return DoubleType.instance;
8✔
1296
            case TokenKind.Dynamic:
1297
                return new DynamicType(token.text);
96✔
1298
            case TokenKind.Float:
1299
                return new FloatType(token.text);
300✔
1300
            case TokenKind.FloatLiteral:
1301
                return FloatType.instance;
117✔
1302
            case TokenKind.Function:
1303
                return new FunctionType(token.text);
137✔
1304
            case TokenKind.Integer:
1305
                return new IntegerType(token.text);
1,035✔
1306
            case TokenKind.IntegerLiteral:
1307
                return IntegerType.instance;
1,841✔
1308
            case TokenKind.Invalid:
1309
                return DynamicType.instance; // TODO: use InvalidType better new InvalidType(token.text);
78✔
1310
            case TokenKind.LongInteger:
1311
                return new LongIntegerType(token.text);
46✔
1312
            case TokenKind.LongIntegerLiteral:
1313
                return LongIntegerType.instance;
3✔
1314
            case TokenKind.Object:
1315
                return new ObjectType(token.text);
307✔
1316
            case TokenKind.String:
1317
                return new StringType(token.text);
1,778✔
1318
            case TokenKind.StringLiteral:
1319
            case TokenKind.TemplateStringExpressionBegin:
1320
            case TokenKind.TemplateStringExpressionEnd:
1321
            case TokenKind.TemplateStringQuasi:
1322
                return StringType.instance;
1,032✔
1323
            case TokenKind.Void:
1324
                return new VoidType(token.text);
24✔
1325
            case TokenKind.Identifier:
1326
                switch (token.text.toLowerCase()) {
1,627,224✔
1327
                    case 'boolean':
874,548!
1328
                        return new BooleanType(token.text);
201,936✔
1329
                    case 'double':
1330
                        return new DoubleType(token.text);
4✔
1331
                    case 'dynamic':
1332
                        return new DynamicType(token.text);
4✔
1333
                    case 'float':
1334
                        return new FloatType(token.text);
201,938✔
1335
                    case 'function':
UNCOV
1336
                        return new FunctionType(token.text);
×
1337
                    case 'integer':
1338
                        return new IntegerType(token.text);
165,364✔
1339
                    case 'invalid':
UNCOV
1340
                        return DynamicType.instance; // TODO: use InvalidType better new InvalidType(token.text);
×
1341
                    case 'longinteger':
1342
                        return new LongIntegerType(token.text);
4✔
1343
                    case 'object':
1344
                        return new ObjectType(token.text);
4✔
1345
                    case 'string':
1346
                        return new StringType(token.text);
305,290✔
1347
                    case 'void':
1348
                        return new VoidType(token.text);
4✔
1349
                }
1350
        }
1351
    }
1352

1353
    /**
1354
     * Deciphers the correct types for fields based on docs
1355
     * https://developer.roku.com/en-ca/docs/references/scenegraph/xml-elements/interface.md
1356
     * @param typeDescriptor the type descriptor from the docs
1357
     * @returns {BscType} the known type, or dynamic
1358
     */
1359
    public getNodeFieldType(typeDescriptor: string, lookupTable?: SymbolTable): BscType {
1360
        let typeDescriptorLower = typeDescriptor.toLowerCase().trim().replace(/\*/g, '');
1,610,709✔
1361

1362
        if (typeDescriptorLower.startsWith('as ')) {
1,610,709✔
1363
            typeDescriptorLower = typeDescriptorLower.substring(3).trim();
6,360✔
1364
        }
1365
        const nodeFilter = (new RegExp(/^\[?(.* node)/, 'i')).exec(typeDescriptorLower);
1,610,709✔
1366
        if (nodeFilter?.[1]) {
1,610,709✔
1367
            typeDescriptorLower = nodeFilter[1].trim();
33,390✔
1368
        }
1369
        const parensFilter = (new RegExp(/(.*)\(.*\)/, 'gi')).exec(typeDescriptorLower);
1,610,709✔
1370
        if (parensFilter?.[1]) {
1,610,709✔
1371
            typeDescriptorLower = parensFilter[1].trim();
3,180✔
1372
        }
1373

1374
        const bscType = this.tokenToBscType(createToken(TokenKind.Identifier, typeDescriptorLower));
1,610,709✔
1375
        if (bscType) {
1,610,709✔
1376
            return bscType;
874,512✔
1377
        }
1378

1379
        function getRect2dType() {
1380
            const rect2dType = new AssociativeArrayType();
4,774✔
1381
            rect2dType.addMember('height', {}, FloatType.instance, SymbolTypeFlag.runtime);
4,774✔
1382
            rect2dType.addMember('width', {}, FloatType.instance, SymbolTypeFlag.runtime);
4,774✔
1383
            rect2dType.addMember('x', {}, FloatType.instance, SymbolTypeFlag.runtime);
4,774✔
1384
            rect2dType.addMember('y', {}, FloatType.instance, SymbolTypeFlag.runtime);
4,774✔
1385
            return rect2dType;
4,774✔
1386
        }
1387

1388
        function getColorType() {
1389
            return unionTypeFactory([IntegerType.instance, StringType.instance]);
98,584✔
1390
        }
1391

1392
        //check for uniontypes
1393
        const multipleTypes = typeDescriptorLower.split(' or ').map(s => s.trim());
739,377✔
1394
        if (multipleTypes.length > 1) {
736,197✔
1395
            const individualTypes = multipleTypes.map(t => this.getNodeFieldType(t, lookupTable));
6,360✔
1396
            return unionTypeFactory(individualTypes);
3,180✔
1397
        }
1398

1399
        const typeIsArray = typeDescriptorLower.startsWith('array of ') || typeDescriptorLower.startsWith('roarray of ');
733,017✔
1400

1401
        if (typeIsArray) {
733,017✔
1402
            const ofSearch = ' of ';
92,220✔
1403
            const arrayPrefixLength = typeDescriptorLower.indexOf(ofSearch) + ofSearch.length;
92,220✔
1404
            let arrayOfTypeName = typeDescriptorLower.substring(arrayPrefixLength); //cut off beginnin, eg. 'array of' or 'roarray of'
92,220✔
1405
            if (arrayOfTypeName.endsWith('s')) {
92,220✔
1406
                // remove "s" in "floats", etc.
1407
                arrayOfTypeName = arrayOfTypeName.substring(0, arrayOfTypeName.length - 1);
68,370✔
1408
            }
1409
            if (arrayOfTypeName.endsWith('\'')) {
92,220✔
1410
                // remove "'" in "float's", etc.
1411
                arrayOfTypeName = arrayOfTypeName.substring(0, arrayOfTypeName.length - 1);
6,360✔
1412
            }
1413
            if (arrayOfTypeName === 'rectangle') {
92,220✔
1414
                arrayOfTypeName = 'rect2d';
1,590✔
1415
            }
1416
            let arrayType = this.getNodeFieldType(arrayOfTypeName, lookupTable);
92,220✔
1417
            return new ArrayType(arrayType);
92,220✔
1418
        } else if (typeDescriptorLower.startsWith('option ')) {
640,797✔
1419
            const actualTypeName = typeDescriptorLower.substring('option '.length); //cut off beginning 'option '
31,800✔
1420
            return this.getNodeFieldType(actualTypeName, lookupTable);
31,800✔
1421
        } else if (typeDescriptorLower.startsWith('value ')) {
608,997✔
1422
            const actualTypeName = typeDescriptorLower.substring('value '.length); //cut off beginning 'value '
12,720✔
1423
            return this.getNodeFieldType(actualTypeName, lookupTable);
12,720✔
1424
        } else if (typeDescriptorLower === 'n/a') {
596,277✔
1425
            return DynamicType.instance;
3,180✔
1426
        } else if (typeDescriptorLower === 'uri') {
593,097✔
1427
            return StringType.instance;
114,485✔
1428
        } else if (typeDescriptorLower === 'color') {
478,612✔
1429
            return getColorType();
98,583✔
1430
        } else if (typeDescriptorLower === 'vector2d' || typeDescriptorLower === 'floatarray') {
380,029✔
1431
            return new ArrayType(FloatType.instance);
36,571✔
1432
        } else if (typeDescriptorLower === 'vector2darray') {
343,458!
UNCOV
1433
            return new ArrayType(new ArrayType(FloatType.instance));
×
1434
        } else if (typeDescriptorLower === 'intarray') {
343,458✔
1435
            return new ArrayType(IntegerType.instance);
1✔
1436
        } else if (typeDescriptorLower === 'colorarray') {
343,457✔
1437
            return new ArrayType(getColorType());
1✔
1438
        } else if (typeDescriptorLower === 'boolarray') {
343,456!
UNCOV
1439
            return new ArrayType(BooleanType.instance);
×
1440
        } else if (typeDescriptorLower === 'stringarray' || typeDescriptorLower === 'strarray') {
343,456✔
1441
            return new ArrayType(StringType.instance);
1✔
1442
        } else if (typeDescriptorLower === 'int') {
343,455✔
1443
            return IntegerType.instance;
6,360✔
1444
        } else if (typeDescriptorLower === 'time') {
337,095✔
1445
            return DoubleType.instance;
30,211✔
1446
        } else if (typeDescriptorLower === 'str') {
306,884!
UNCOV
1447
            return StringType.instance;
×
1448
        } else if (typeDescriptorLower === 'bool') {
306,884✔
1449
            return BooleanType.instance;
1,590✔
1450
        } else if (typeDescriptorLower === 'array' || typeDescriptorLower === 'roarray') {
305,294✔
1451
            return new ArrayType();
12,721✔
1452
        } else if (typeDescriptorLower === 'assocarray' ||
292,573✔
1453
            typeDescriptorLower === 'associative array' ||
1454
            typeDescriptorLower === 'associativearray' ||
1455
            typeDescriptorLower === 'roassociativearray' ||
1456
            typeDescriptorLower.startsWith('associative array of') ||
1457
            typeDescriptorLower.startsWith('associativearray of') ||
1458
            typeDescriptorLower.startsWith('roassociativearray of')
1459
        ) {
1460
            return new AssociativeArrayType();
55,651✔
1461
        } else if (typeDescriptorLower === 'node') {
236,922✔
1462
            return ComponentType.instance;
14,311✔
1463
        } else if (typeDescriptorLower === 'nodearray') {
222,611✔
1464
            return new ArrayType(ComponentType.instance);
1✔
1465
        } else if (typeDescriptorLower === 'rect2d') {
222,610✔
1466
            return getRect2dType();
4,772✔
1467
        } else if (typeDescriptorLower === 'rect2darray') {
217,838✔
1468
            return new ArrayType(getRect2dType());
2✔
1469
        } else if (typeDescriptorLower === 'font') {
217,836✔
1470
            return this.getNodeFieldType('roSGNodeFont', lookupTable);
34,982✔
1471
        } else if (typeDescriptorLower === 'contentnode') {
182,854✔
1472
            return this.getNodeFieldType('roSGNodeContentNode', lookupTable);
31,800✔
1473
        } else if (typeDescriptorLower.endsWith(' node')) {
151,054✔
1474
            return this.getNodeFieldType('roSgNode' + typeDescriptorLower.substring(0, typeDescriptorLower.length - 5), lookupTable);
31,800✔
1475
        } else if (lookupTable) {
119,254!
1476
            //try doing a lookup
1477
            return lookupTable.getSymbolType(typeDescriptorLower, {
119,254✔
1478
                flags: SymbolTypeFlag.typetime,
1479
                fullName: typeDescriptor,
1480
                tableProvider: () => lookupTable
2✔
1481
            });
1482
        }
1483

UNCOV
1484
        return DynamicType.instance;
×
1485
    }
1486

1487
    /**
1488
     * Return the type of the result of a binary operator
1489
     * Note: compound assignments (eg. +=) internally use a binary expression, so that's why TokenKind.PlusEqual, etc. are here too
1490
     */
1491
    public binaryOperatorResultType(leftType: BscType, operator: Token, rightType: BscType): BscType {
1492
        if ((isAnyReferenceType(leftType) && !leftType.isResolvable()) ||
511✔
1493
            (isAnyReferenceType(rightType) && !rightType.isResolvable())) {
1494
            return new BinaryOperatorReferenceType(leftType, operator, rightType, (lhs, op, rhs) => {
29✔
1495
                return this.binaryOperatorResultType(lhs, op, rhs);
2✔
1496
            });
1497
        }
1498
        if (isEnumMemberType(leftType)) {
482✔
1499
            leftType = leftType.underlyingType;
9✔
1500
        }
1501
        if (isEnumMemberType(rightType)) {
482✔
1502
            rightType = rightType.underlyingType;
8✔
1503
        }
1504
        let hasDouble = isDoubleType(leftType) || isDoubleType(rightType);
482✔
1505
        let hasFloat = isFloatType(leftType) || isFloatType(rightType);
482✔
1506
        let hasLongInteger = isLongIntegerType(leftType) || isLongIntegerType(rightType);
482✔
1507
        let hasInvalid = isInvalidType(leftType) || isInvalidType(rightType);
482✔
1508
        let hasDynamic = isDynamicType(leftType) || isDynamicType(rightType);
482✔
1509
        let bothNumbers = isNumberType(leftType) && isNumberType(rightType);
482✔
1510
        let bothStrings = isStringType(leftType) && isStringType(rightType);
482✔
1511
        let eitherBooleanOrNum = (isNumberType(leftType) || isBooleanType(leftType)) && (isNumberType(rightType) || isBooleanType(rightType));
482✔
1512

1513
        // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
1514
        switch (operator.kind) {
482✔
1515
            // Math operators
1516
            case TokenKind.Plus:
1,466✔
1517
            case TokenKind.PlusEqual:
1518
                if (bothStrings) {
213✔
1519
                    // "string" + "string" is the only binary expression allowed with strings
1520
                    return StringType.instance;
121✔
1521
                }
1522
            // eslint-disable-next-line no-fallthrough
1523
            case TokenKind.Minus:
1524
            case TokenKind.MinusEqual:
1525
            case TokenKind.Star:
1526
            case TokenKind.StarEqual:
1527
            case TokenKind.Mod:
1528
                if (bothNumbers) {
156✔
1529
                    if (hasDouble) {
127✔
1530
                        return DoubleType.instance;
5✔
1531
                    } else if (hasFloat) {
122✔
1532
                        return FloatType.instance;
23✔
1533

1534
                    } else if (hasLongInteger) {
99✔
1535
                        return LongIntegerType.instance;
4✔
1536
                    }
1537
                    return IntegerType.instance;
95✔
1538
                }
1539
                break;
29✔
1540
            case TokenKind.Forwardslash:
1541
            case TokenKind.ForwardslashEqual:
1542
                if (bothNumbers) {
10✔
1543
                    if (hasDouble) {
8✔
1544
                        return DoubleType.instance;
1✔
1545
                    } else if (hasFloat) {
7✔
1546
                        return FloatType.instance;
1✔
1547

1548
                    } else if (hasLongInteger) {
6✔
1549
                        return LongIntegerType.instance;
1✔
1550
                    }
1551
                    return FloatType.instance;
5✔
1552
                }
1553
                break;
2✔
1554
            case TokenKind.Backslash:
1555
            case TokenKind.BackslashEqual:
1556
                if (bothNumbers) {
6✔
1557
                    if (hasLongInteger) {
4!
UNCOV
1558
                        return LongIntegerType.instance;
×
1559
                    }
1560
                    return IntegerType.instance;
4✔
1561
                }
1562
                break;
2✔
1563
            case TokenKind.Caret:
1564
                if (bothNumbers) {
16✔
1565
                    if (hasDouble || hasLongInteger) {
14✔
1566
                        return DoubleType.instance;
2✔
1567
                    } else if (hasFloat) {
12✔
1568
                        return FloatType.instance;
1✔
1569
                    }
1570
                    return IntegerType.instance;
11✔
1571
                }
1572
                break;
2✔
1573
            // Bitshift operators
1574
            case TokenKind.LeftShift:
1575
            case TokenKind.LeftShiftEqual:
1576
            case TokenKind.RightShift:
1577
            case TokenKind.RightShiftEqual:
1578
                if (bothNumbers) {
18✔
1579
                    if (hasLongInteger) {
14✔
1580
                        return LongIntegerType.instance;
2✔
1581
                    }
1582
                    // Bitshifts are allowed with non-integer numerics
1583
                    // but will always truncate to ints
1584
                    return IntegerType.instance;
12✔
1585
                }
1586
                break;
4✔
1587
            // Comparison operators
1588
            // All comparison operators result in boolean
1589
            case TokenKind.Equal:
1590
            case TokenKind.LessGreater:
1591
                // = and <> can accept invalid / dynamic
1592
                if (hasDynamic || hasInvalid || bothStrings || eitherBooleanOrNum) {
80✔
1593
                    return BooleanType.instance;
77✔
1594
                }
1595
                break;
3✔
1596
            case TokenKind.Greater:
1597
            case TokenKind.Less:
1598
            case TokenKind.GreaterEqual:
1599
            case TokenKind.LessEqual:
1600
                if (bothStrings || bothNumbers) {
23✔
1601
                    return BooleanType.instance;
11✔
1602
                }
1603
                break;
12✔
1604
            // Logical or bitwise operators
1605
            case TokenKind.Or:
1606
            case TokenKind.And:
1607
                if (bothNumbers) {
52✔
1608
                    // "and"/"or" represent bitwise operators
1609
                    if (hasLongInteger && !hasDouble && !hasFloat) {
12✔
1610
                        // 2 long ints or long int and int
1611
                        return LongIntegerType.instance;
1✔
1612
                    }
1613
                    return IntegerType.instance;
11✔
1614
                } else if (eitherBooleanOrNum) {
40✔
1615
                    // "and"/"or" represent logical operators
1616
                    return BooleanType.instance;
33✔
1617
                }
1618
                break;
7✔
1619
        }
1620
        return DynamicType.instance;
61✔
1621
    }
1622

1623
    /**
1624
     * Return the type of the result of a binary operator
1625
     */
1626
    public unaryOperatorResultType(operator: Token, exprType: BscType): BscType {
1627
        // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
1628
        switch (operator.kind) {
86✔
1629
            // Math operators
1630
            case TokenKind.Minus:
82✔
1631
                if (isNumberType(exprType)) {
59✔
1632
                    // a negative number will be the same type, eg, double->double, int->int, etc.
1633
                    return exprType;
49✔
1634
                }
1635
                break;
10✔
1636
            case TokenKind.Not:
1637
                if (isBooleanType(exprType)) {
23✔
1638
                    return BooleanType.instance;
10✔
1639
                } else if (isNumberType(exprType)) {
13✔
1640
                    //numbers can be "notted"
1641
                    // by default they go to ints, except longints, which stay that way
1642
                    if (isLongIntegerType(exprType)) {
10✔
1643
                        return LongIntegerType.instance;
1✔
1644
                    }
1645
                    return IntegerType.instance;
9✔
1646
                }
1647
                break;
3✔
1648
        }
1649
        return DynamicType.instance;
17✔
1650
    }
1651

1652
    /**
1653
     * Get the extension for the given file path. Basically the part after the final dot, except for
1654
     * `d.bs` which is treated as single extension
1655
     * @returns the file extension (i.e. ".d.bs", ".bs", ".brs", ".xml", ".jpg", etc...)
1656
     */
1657
    public getExtension(filePath: string) {
1658
        filePath = filePath.toLowerCase();
2,552✔
1659
        if (filePath.endsWith('.d.bs')) {
2,552✔
1660
            return '.d.bs';
33✔
1661
        } else {
1662
            return path.extname(filePath).toLowerCase();
2,519✔
1663
        }
1664
    }
1665

1666
    /**
1667
     * Load and return the list of plugins
1668
     */
1669
    public loadPlugins(cwd: string, pathOrModules: string[], onError?: (pathOrModule: string, err: Error) => void): CompilerPlugin[] {
1670
        const logger = createLogger();
53✔
1671
        return pathOrModules.reduce<CompilerPlugin[]>((acc, pathOrModule) => {
53✔
1672
            if (typeof pathOrModule === 'string') {
6!
1673
                try {
6✔
1674
                    const loaded = requireRelative(pathOrModule, cwd);
6✔
1675
                    const theExport: CompilerPlugin | CompilerPluginFactory = loaded.default ? loaded.default : loaded;
6✔
1676

1677
                    let plugin: CompilerPlugin | undefined;
1678

1679
                    // legacy plugins returned a plugin object. If we find that, then add a warning
1680
                    if (typeof theExport === 'object') {
6✔
1681
                        logger.warn(`Plugin "${pathOrModule}" was loaded as a singleton. Please contact the plugin author to update to the factory pattern.\n`);
2✔
1682
                        plugin = theExport;
2✔
1683

1684
                        // the official plugin format is a factory function that returns a new instance of a plugin.
1685
                    } else if (typeof theExport === 'function') {
4!
1686
                        plugin = theExport();
4✔
1687
                    } else {
1688
                        //this should never happen; somehow an invalid plugin has made it into here
UNCOV
1689
                        throw new Error(`TILT: Encountered an invalid plugin: ${String(plugin)}`);
×
1690
                    }
1691

1692
                    if (!plugin.name) {
6!
UNCOV
1693
                        plugin.name = pathOrModule;
×
1694
                    }
1695
                    acc.push(plugin);
6✔
1696
                } catch (err: any) {
UNCOV
1697
                    if (onError) {
×
UNCOV
1698
                        onError(pathOrModule, err);
×
1699
                    } else {
1700
                        throw err;
×
1701
                    }
1702
                }
1703
            }
1704
            return acc;
6✔
1705
        }, []);
1706
    }
1707

1708
    /**
1709
     * Gathers expressions, variables, and unique names from an expression.
1710
     * This is mostly used for the ternary expression
1711
     */
1712
    public getExpressionInfo(expression: Expression, file: BrsFile): ExpressionInfo {
1713
        const expressions = [expression];
78✔
1714
        const variableExpressions = [] as VariableExpression[];
78✔
1715
        const uniqueVarNames = new Set<string>();
78✔
1716

1717
        function expressionWalker(expression) {
1718
            if (isExpression(expression)) {
120✔
1719
                expressions.push(expression);
116✔
1720
            }
1721
            if (isVariableExpression(expression)) {
120✔
1722
                variableExpressions.push(expression);
30✔
1723
                uniqueVarNames.add(expression.tokens.name.text);
30✔
1724
            }
1725
        }
1726

1727
        // Collect all expressions. Most of these expressions are fairly small so this should be quick!
1728
        // This should only be called during transpile time and only when we actually need it.
1729
        expression?.walk(expressionWalker, {
78✔
1730
            walkMode: WalkMode.visitExpressions
1731
        });
1732

1733
        //handle the expression itself (for situations when expression is a VariableExpression)
1734
        expressionWalker(expression);
78✔
1735

1736
        const scope = file.program.getFirstScopeForFile(file);
78✔
1737
        let filteredVarNames = [...uniqueVarNames];
78✔
1738
        if (scope) {
78!
1739
            filteredVarNames = filteredVarNames.filter((varName: string) => {
78✔
1740
                const varNameLower = varName.toLowerCase();
28✔
1741
                // TODO: include namespaces in this filter
1742
                return !scope.getEnumMap().has(varNameLower) &&
28✔
1743
                    !scope.getConstMap().has(varNameLower);
1744
            });
1745
        }
1746

1747
        return { expressions: expressions, varExpressions: variableExpressions, uniqueVarNames: filteredVarNames };
78✔
1748
    }
1749

1750

1751
    public concatAnnotationLeadingTrivia(stmt: Statement): Token[] {
1752
        return [...(stmt.annotations?.map(anno => anno.leadingTrivia ?? []).flat() ?? []), ...stmt.leadingTrivia];
168!
1753
    }
1754

1755
    /**
1756
     * Create a SourceNode that maps every line to itself. Useful for creating maps for files
1757
     * that haven't changed at all, but we still need the map
1758
     */
1759
    public simpleMap(source: string, src: string) {
1760
        //create a source map from the original source code
1761
        let chunks = [] as (SourceNode | string)[];
5✔
1762
        let lines = src.split(/\r?\n/g);
5✔
1763
        for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
5✔
1764
            let line = lines[lineIndex];
19✔
1765
            chunks.push(
19✔
1766
                lineIndex > 0 ? '\n' : '',
19✔
1767
                new SourceNode(lineIndex + 1, 0, source, line)
1768
            );
1769
        }
1770
        return new SourceNode(null, null, source, chunks);
5✔
1771
    }
1772

1773
    /**
1774
     * Converts a path into a standardized format (drive letter to lower, remove extra slashes, use single slash type, resolve relative parts, etc...)
1775
     */
1776
    public standardizePath(thePath: string) {
1777
        return util.driveLetterToLower(
11,115✔
1778
            rokuDeployStandardizePath(thePath)
1779
        );
1780
    }
1781

1782
    /**
1783
     * Given a Diagnostic or BsDiagnostic, return a deep clone of the diagnostic.
1784
     * @param diagnostic the diagnostic to clone
1785
     * @param relatedInformationFallbackLocation a default location to use for all `relatedInformation` entries that are missing a location
1786
     */
1787
    public toDiagnostic(diagnostic: Diagnostic | BsDiagnostic, relatedInformationFallbackLocation: string): Diagnostic {
1788
        let relatedInformation = diagnostic.relatedInformation ?? [];
15✔
1789
        if (relatedInformation.length > MAX_RELATED_INFOS_COUNT) {
15!
UNCOV
1790
            const relatedInfoLength = relatedInformation.length;
×
UNCOV
1791
            relatedInformation = relatedInformation.slice(0, MAX_RELATED_INFOS_COUNT);
×
UNCOV
1792
            relatedInformation.push({
×
1793
                message: `...and ${relatedInfoLength - MAX_RELATED_INFOS_COUNT} more`,
1794
                location: util.createLocationFromRange('   ', util.createRange(0, 0, 0, 0))
1795
            });
1796
        }
1797

1798
        const range = (diagnostic as BsDiagnostic).location?.range ??
15✔
1799
            (diagnostic as Diagnostic).range;
1800

1801
        let result = {
15✔
1802
            severity: diagnostic.severity,
1803
            range: range,
1804
            message: diagnostic.message,
1805
            relatedInformation: relatedInformation.map(x => {
1806

1807
                //clone related information just in case a plugin added circular ref info here
1808
                const clone = { ...x };
4✔
1809
                if (!clone.location) {
4✔
1810
                    // use the fallback location if available
1811
                    if (relatedInformationFallbackLocation) {
2✔
1812
                        clone.location = util.createLocationFromRange(relatedInformationFallbackLocation, range);
1✔
1813
                    } else {
1814
                        //remove this related information so it doesn't bring crash the language server
1815
                        return undefined;
1✔
1816
                    }
1817
                }
1818
                return clone;
3✔
1819
                //filter out null relatedInformation items
1820
            }).filter((x): x is DiagnosticRelatedInformation => Boolean(x)),
4✔
1821
            code: diagnostic.code,
1822
            source: 'brs'
1823
        } as Diagnostic;
1824
        if (diagnostic?.tags?.length > 0) {
15!
UNCOV
1825
            result.tags = diagnostic.tags;
×
1826
        }
1827
        return result;
15✔
1828
    }
1829

1830
    /**
1831
     * Get the first locatable item found at the specified position
1832
     * @param locatables an array of items that have a `range` property
1833
     * @param position the position that the locatable must contain
1834
     */
1835
    public getFirstLocatableAt(locatables: Locatable[], position: Position) {
UNCOV
1836
        for (let token of locatables) {
×
UNCOV
1837
            if (util.rangeContains(token.location?.range, position)) {
×
UNCOV
1838
                return token;
×
1839
            }
1840
        }
1841
    }
1842

1843
    /**
1844
     * Sort an array of objects that have a Range
1845
     */
1846
    public sortByRange<T extends { range: Range | undefined }>(locatables: T[]) {
1847
        //sort the tokens by range
1848
        return locatables.sort((a, b) => {
27✔
1849
            //handle undefined tokens to prevent crashes
1850
            if (!a?.range) {
252!
1851
                return 1;
1✔
1852
            }
1853
            if (!b?.range) {
251!
UNCOV
1854
                return -1;
×
1855
            }
1856

1857
            //start line
1858
            if (a.range.start.line < b.range.start.line) {
251!
UNCOV
1859
                return -1;
×
1860
            }
1861
            if (a.range.start.line > b.range.start.line) {
251✔
1862
                return 1;
152✔
1863
            }
1864
            //start char
1865
            if (a.range.start.character < b.range.start.character) {
99✔
1866
                return -1;
60✔
1867
            }
1868
            if (a.range.start.character > b.range.start.character) {
39!
1869
                return 1;
39✔
1870
            }
1871
            //end line
UNCOV
1872
            if (a.range.end.line < b.range.end.line) {
×
UNCOV
1873
                return -1;
×
1874
            }
UNCOV
1875
            if (a.range.end.line > b.range.end.line) {
×
UNCOV
1876
                return 1;
×
1877
            }
1878
            //end char
1879
            if (a.range.end.character < b.range.end.character) {
×
1880
                return -1;
×
UNCOV
1881
            } else if (a.range.end.character > b.range.end.character) {
×
1882
                return 1;
×
1883
            }
UNCOV
1884
            return 0;
×
1885
        });
1886
    }
1887

1888
    /**
1889
     * Split the given text and return ranges for each chunk.
1890
     * Only works for single-line strings
1891
     */
1892
    public splitGetRange(separator: string, text: string, range: Range) {
1893
        const chunks = text.split(separator);
3✔
1894
        const result = [] as Array<{ text: string; range: Range }>;
3✔
1895
        let offset = 0;
3✔
1896
        for (let chunk of chunks) {
3✔
1897
            //only keep nonzero chunks
1898
            if (chunk.length > 0) {
8✔
1899
                result.push({
7✔
1900
                    text: chunk,
1901
                    range: this.createRange(
1902
                        range.start.line,
1903
                        range.start.character + offset,
1904
                        range.end.line,
1905
                        range.start.character + offset + chunk.length
1906
                    )
1907
                });
1908
            }
1909
            offset += chunk.length + separator.length;
8✔
1910
        }
1911
        return result;
3✔
1912
    }
1913

1914
    /**
1915
     * Wrap the given code in a markdown code fence (with the language)
1916
     */
1917
    public mdFence(code: string, language = '') {
×
1918
        return '```' + language + '\n' + code + '\n```';
120✔
1919
    }
1920

1921
    /**
1922
     * Gets each part of the dotted get.
1923
     * @param node any ast expression
1924
     * @returns an array of the parts of the dotted get. If not fully a dotted get, then returns undefined
1925
     */
1926
    public getAllDottedGetParts(node: AstNode): Identifier[] | undefined {
1927
        //this is a hot function and has been optimized. Don't rewrite unless necessary
1928
        const parts: Identifier[] = [];
9,808✔
1929
        let nextPart = node;
9,808✔
1930
        loop: while (nextPart) {
9,808✔
1931
            switch (nextPart?.kind) {
14,528!
1932
                case AstNodeKind.AssignmentStatement:
14,528!
1933
                    return [(node as AssignmentStatement).tokens.name];
9✔
1934
                case AstNodeKind.DottedGetExpression:
1935
                    parts.push((nextPart as DottedGetExpression)?.tokens.name);
4,647!
1936
                    nextPart = (nextPart as DottedGetExpression).obj;
4,647✔
1937
                    continue;
4,647✔
1938
                case AstNodeKind.CallExpression:
1939
                    nextPart = (nextPart as CallExpression).callee;
39✔
1940
                    continue;
39✔
1941
                case AstNodeKind.TypeExpression:
UNCOV
1942
                    nextPart = (nextPart as TypeExpression).expression;
×
UNCOV
1943
                    continue;
×
1944
                case AstNodeKind.VariableExpression:
1945
                    parts.push((nextPart as VariableExpression)?.tokens.name);
9,700!
1946
                    break loop;
9,700✔
1947
                case AstNodeKind.LiteralExpression:
1948
                    parts.push((nextPart as LiteralExpression)?.tokens.value as Identifier);
4!
1949
                    break loop;
4✔
1950
                case AstNodeKind.IndexedGetExpression:
1951
                    nextPart = (nextPart as unknown as IndexedGetExpression).obj;
35✔
1952
                    continue;
35✔
1953
                case AstNodeKind.FunctionParameterExpression:
1954
                    return [(nextPart as FunctionParameterExpression).tokens.name];
6✔
1955
                case AstNodeKind.GroupingExpression:
1956
                    parts.push(createIdentifier('()', nextPart.location));
6✔
1957
                    break loop;
6✔
1958
                default:
1959
                    //we found a non-DottedGet expression, so return because this whole operation is invalid.
1960
                    return undefined;
82✔
1961
            }
1962
        }
1963
        return parts.reverse();
9,711✔
1964
    }
1965

1966
    /**
1967
     * Given an expression, return all the DottedGet name parts as a string.
1968
     * Mostly used to convert namespaced item full names to a strings
1969
     */
1970
    public getAllDottedGetPartsAsString(node: Expression | Statement, parseMode = ParseMode.BrighterScript): string {
1,932✔
1971
        //this is a hot function and has been optimized. Don't rewrite unless necessary
1972
        /* eslint-disable no-var */
1973
        var sep = parseMode === ParseMode.BrighterScript ? '.' : '_';
8,676✔
1974
        const parts = this.getAllDottedGetParts(node) ?? [];
8,676✔
1975
        var result = parts[0]?.text;
8,676✔
1976
        for (var i = 1; i < parts.length; i++) {
8,676✔
1977
            result += sep + parts[i].text;
3,908✔
1978
        }
1979
        return result;
8,676✔
1980
        /* eslint-enable no-var */
1981
    }
1982

1983
    public stringJoin(strings: string[], separator: string) {
1984
        // eslint-disable-next-line no-var
UNCOV
1985
        var result = strings[0] ?? '';
×
1986
        // eslint-disable-next-line no-var
UNCOV
1987
        for (var i = 1; i < strings.length; i++) {
×
UNCOV
1988
            result += separator + strings[i];
×
1989
        }
UNCOV
1990
        return result;
×
1991
    }
1992

1993
    /**
1994
     * Break an expression into each part.
1995
     */
1996
    public splitExpression(expression: Expression) {
1997
        const parts: Expression[] = [expression];
9,919✔
1998
        let nextPart = expression;
9,919✔
1999
        while (nextPart) {
9,919✔
2000
            if (isDottedGetExpression(nextPart) || isIndexedGetExpression(nextPart) || isXmlAttributeGetExpression(nextPart)) {
12,454✔
2001
                nextPart = nextPart.obj;
993✔
2002

2003
            } else if (isCallExpression(nextPart) || isCallfuncExpression(nextPart)) {
11,461✔
2004
                nextPart = nextPart.callee;
1,542✔
2005

2006
            } else if (isTypeExpression(nextPart)) {
9,919!
UNCOV
2007
                nextPart = nextPart.expression;
×
2008
            } else {
2009
                break;
9,919✔
2010
            }
2011
            parts.unshift(nextPart);
2,535✔
2012
        }
2013
        return parts;
9,919✔
2014
    }
2015

2016
    /**
2017
     * Break an expression into each part, and return any VariableExpression or DottedGet expresisons from left-to-right.
2018
     */
2019
    public getDottedGetPath(expression: Expression): [VariableExpression, ...DottedGetExpression[]] {
UNCOV
2020
        let parts: Expression[] = [];
×
UNCOV
2021
        let nextPart = expression;
×
UNCOV
2022
        loop: while (nextPart) {
×
UNCOV
2023
            switch (nextPart?.kind) {
×
2024
                case AstNodeKind.DottedGetExpression:
×
UNCOV
2025
                    parts.push(nextPart);
×
UNCOV
2026
                    nextPart = (nextPart as DottedGetExpression).obj;
×
2027
                    continue;
×
2028
                case AstNodeKind.IndexedGetExpression:
2029
                case AstNodeKind.XmlAttributeGetExpression:
2030
                    nextPart = (nextPart as IndexedGetExpression | XmlAttributeGetExpression).obj;
×
UNCOV
2031
                    parts = [];
×
2032
                    continue;
×
2033
                case AstNodeKind.CallExpression:
2034
                case AstNodeKind.CallfuncExpression:
UNCOV
2035
                    nextPart = (nextPart as CallExpression | CallfuncExpression).callee;
×
UNCOV
2036
                    parts = [];
×
2037
                    continue;
×
2038
                case AstNodeKind.NewExpression:
2039
                    nextPart = (nextPart as NewExpression).call.callee;
×
UNCOV
2040
                    parts = [];
×
UNCOV
2041
                    continue;
×
2042
                case AstNodeKind.TypeExpression:
2043
                    nextPart = (nextPart as TypeExpression).expression;
×
2044
                    continue;
×
2045
                case AstNodeKind.VariableExpression:
2046
                    parts.push(nextPart);
×
2047
                    break loop;
×
2048
                default:
UNCOV
2049
                    return [] as any;
×
2050
            }
2051
        }
UNCOV
2052
        return parts.reverse() as any;
×
2053
    }
2054

2055
    /**
2056
     * Returns an integer if valid, or undefined. Eliminates checking for NaN
2057
     */
2058
    public parseInt(value: any) {
2059
        const result = parseInt(value);
34✔
2060
        if (!isNaN(result)) {
34✔
2061
            return result;
29✔
2062
        } else {
2063
            return undefined;
5✔
2064
        }
2065
    }
2066

2067
    /**
2068
     * Converts a range to a string in the format 1:2-3:4
2069
     */
2070
    public rangeToString(range: Range) {
2071
        return `${range?.start?.line}:${range?.start?.character}-${range?.end?.line}:${range?.end?.character}`;
1,834✔
2072
    }
2073

2074
    public validateTooDeepFile(file: (BrsFile | XmlFile)) {
2075
        //find any files nested too deep
2076
        let destPath = file?.destPath?.toString();
1,903!
2077
        let rootFolder = destPath?.replace(/^pkg:/, '').split(/[\\\/]/)[0].toLowerCase();
1,903!
2078

2079
        if (isBrsFile(file) && rootFolder !== 'source') {
1,903✔
2080
            return;
277✔
2081
        }
2082

2083
        if (isXmlFile(file) && rootFolder !== 'components') {
1,626!
UNCOV
2084
            return;
×
2085
        }
2086

2087
        let fileDepth = this.getParentDirectoryCount(destPath);
1,626✔
2088
        if (fileDepth >= 8) {
1,626✔
2089
            file.program?.diagnostics.register({
3!
2090
                ...DiagnosticMessages.detectedTooDeepFileSource(fileDepth),
2091
                location: util.createLocationFromFileRange(file, this.createRange(0, 0, 0, Number.MAX_VALUE))
2092
            });
2093
        }
2094
    }
2095

2096
    /**
2097
     * Wraps SourceNode's constructor to be compatible with the TranspileResult type
2098
     */
2099
    public sourceNodeFromTranspileResult(
2100
        line: number | null,
2101
        column: number | null,
2102
        source: string | null,
2103
        chunks?: string | SourceNode | TranspileResult,
2104
        name?: string
2105
    ): SourceNode {
2106
        // we can use a typecast rather than actually transforming the data because SourceNode
2107
        // accepts a more permissive type than its typedef states
2108
        return new SourceNode(line, column, source, chunks as any, name);
7,674✔
2109
    }
2110

2111
    /**
2112
     * Find the index of the last item in the array that matches.
2113
     */
2114
    public findLastIndex<T>(array: T[], matcher: (T) => boolean) {
2115
        for (let i = array.length - 1; i >= 0; i--) {
27✔
2116
            if (matcher(array[i])) {
24✔
2117
                return i;
16✔
2118
            }
2119
        }
2120
    }
2121

2122
    public processTypeChain(typeChain: TypeChainEntry[]): TypeChainProcessResult {
2123
        let fullChainName = '';
1,062✔
2124
        let fullErrorName = '';
1,062✔
2125
        let itemName = '';
1,062✔
2126
        let previousTypeName = '';
1,062✔
2127
        let parentTypeName = '';
1,062✔
2128
        let itemTypeKind = '';
1,062✔
2129
        let parentTypeKind = '';
1,062✔
2130
        let astNode: AstNode;
2131
        let errorLocation: Location;
2132
        let containsDynamic = false;
1,062✔
2133
        let continueResolvingAllItems = true;
1,062✔
2134
        for (let i = 0; i < typeChain.length; i++) {
1,062✔
2135
            const chainItem = typeChain[i];
2,112✔
2136
            const dotSep = chainItem.separatorToken?.text ?? '.';
2,112!
2137
            if (i > 0) {
2,112✔
2138
                fullChainName += dotSep;
1,052✔
2139
            }
2140
            fullChainName += chainItem.name;
2,112✔
2141
            if (continueResolvingAllItems) {
2,112✔
2142
                parentTypeName = previousTypeName;
1,922✔
2143
                parentTypeKind = itemTypeKind;
1,922✔
2144
                fullErrorName = previousTypeName ? `${previousTypeName}${dotSep}${chainItem.name}` : chainItem.name;
1,922✔
2145
                itemTypeKind = (chainItem.type as any)?.kind;
1,922✔
2146

2147
                let typeString = chainItem.type?.toString();
1,922✔
2148
                let typeToFindStringFor = chainItem.type;
1,922✔
2149
                while (typeToFindStringFor) {
1,922✔
2150
                    if (isUnionType(chainItem.type)) {
1,918✔
2151
                        typeString = `(${typeToFindStringFor.toString()})`;
7✔
2152
                        break;
7✔
2153
                    } else if (isCallableType(typeToFindStringFor)) {
1,911✔
2154
                        if (isTypedFunctionType(typeToFindStringFor) && i < typeChain.length - 1) {
37✔
2155
                            typeToFindStringFor = typeToFindStringFor.returnType;
10✔
2156
                        } else {
2157
                            typeString = 'function';
27✔
2158
                            break;
27✔
2159
                        }
2160
                        parentTypeName = previousTypeName;
10✔
2161
                    } else if (isNamespaceType(typeToFindStringFor) && parentTypeName) {
1,874✔
2162
                        const chainItemTypeName = typeToFindStringFor.toString();
334✔
2163
                        typeString = parentTypeName + '.' + chainItemTypeName;
334✔
2164
                        if (chainItemTypeName.toLowerCase().startsWith(parentTypeName.toLowerCase())) {
334✔
2165
                            // the following namespace already knows...
2166
                            typeString = chainItemTypeName;
330✔
2167
                        }
2168
                        break;
334✔
2169
                    } else {
2170
                        typeString = typeToFindStringFor?.toString();
1,540!
2171
                        break;
1,540✔
2172
                    }
2173
                }
2174

2175
                previousTypeName = typeString ?? '';
1,922✔
2176
                itemName = chainItem.name;
1,922✔
2177
                astNode = chainItem.astNode;
1,922✔
2178
                containsDynamic = containsDynamic || (isDynamicType(chainItem.type) && !isAnyReferenceType(chainItem.type));
1,922✔
2179
                if (!chainItem.isResolved) {
1,922✔
2180
                    errorLocation = chainItem.location;
922✔
2181
                    continueResolvingAllItems = false;
922✔
2182
                }
2183
            }
2184
        }
2185
        return {
1,062✔
2186
            itemName: itemName,
2187
            itemTypeKind: itemTypeKind,
2188
            itemParentTypeName: parentTypeName,
2189
            itemParentTypeKind: parentTypeKind,
2190
            fullNameOfItem: fullErrorName,
2191
            fullChainName: fullChainName,
2192
            location: errorLocation,
2193
            containsDynamic: containsDynamic,
2194
            astNode: astNode
2195
        };
2196
    }
2197

2198

2199
    public isInTypeExpression(expression: AstNode): boolean {
2200
        //TODO: this is much faster than node.findAncestor(), but may need to be updated for "complicated" type expressions
2201
        if (isTypeExpression(expression) ||
15,057✔
2202
            isTypeExpression(expression.parent) ||
2203
            isTypedArrayExpression(expression) ||
2204
            isTypedArrayExpression(expression.parent)) {
2205
            return true;
4,366✔
2206
        }
2207
        if (isBinaryExpression(expression.parent)) {
10,691✔
2208
            let currentExpr: AstNode = expression.parent;
2,126✔
2209
            while (isBinaryExpression(currentExpr) && currentExpr.tokens.operator.kind === TokenKind.Or) {
2,126✔
2210
                currentExpr = currentExpr.parent;
118✔
2211
            }
2212
            return isTypeExpression(currentExpr) || isTypedArrayExpression(currentExpr);
2,126✔
2213
        }
2214
        return false;
8,565✔
2215
    }
2216

2217
    public hasAnyRequiredSymbolChanged(requiredSymbols: UnresolvedSymbol[], changedSymbols: Map<SymbolTypeFlag, Set<string>>) {
2218
        if (!requiredSymbols || !changedSymbols) {
1,796!
UNCOV
2219
            return false;
×
2220
        }
2221
        const runTimeChanges = changedSymbols.get(SymbolTypeFlag.runtime);
1,796✔
2222
        const typeTimeChanges = changedSymbols.get(SymbolTypeFlag.typetime);
1,796✔
2223

2224
        for (const symbol of requiredSymbols) {
1,796✔
2225
            if (this.setContainsUnresolvedSymbol(runTimeChanges, symbol) || this.setContainsUnresolvedSymbol(typeTimeChanges, symbol)) {
637✔
2226
                return true;
299✔
2227
            }
2228
        }
2229

2230
        return false;
1,497✔
2231
    }
2232

2233
    public setContainsUnresolvedSymbol(symbolLowerNameSet: Set<string>, symbol: UnresolvedSymbol) {
2234
        if (!symbolLowerNameSet || symbolLowerNameSet.size === 0) {
986✔
2235
            return false;
361✔
2236
        }
2237

2238
        for (const possibleNameLower of symbol.lookups) {
625✔
2239
            if (symbolLowerNameSet.has(possibleNameLower)) {
2,241✔
2240
                return true;
299✔
2241
            }
2242
        }
2243
        return false;
326✔
2244
    }
2245

2246
    public truncate<T>(options: {
2247
        leadingText: string;
2248
        items: T[];
2249
        trailingText?: string;
2250
        maxLength: number;
2251
        itemSeparator?: string;
2252
        partBuilder?: (item: T) => string;
2253
    }): string {
2254
        let leadingText = options.leadingText;
19✔
2255
        let items = options?.items ?? [];
19!
2256
        let trailingText = options?.trailingText ?? '';
19!
2257
        let maxLength = options?.maxLength ?? 160;
19!
2258
        let itemSeparator = options?.itemSeparator ?? ', ';
19!
2259
        let partBuilder = options?.partBuilder ?? ((x) => x.toString());
19!
2260

2261
        let parts = [];
19✔
2262
        let length = leadingText.length + (trailingText?.length ?? 0);
19!
2263

2264
        //calculate the max number of items we could fit in the given space
2265
        for (let i = 0; i < items.length; i++) {
19✔
2266
            let part = partBuilder(items[i]);
91✔
2267
            if (i > 0) {
91✔
2268
                part = itemSeparator + part;
72✔
2269
            }
2270
            parts.push(part);
91✔
2271
            length += part.length;
91✔
2272
            //exit the loop if we've maxed out our length
2273
            if (length >= maxLength) {
91✔
2274
                break;
6✔
2275
            }
2276
        }
2277
        let message: string;
2278
        //we have enough space to include all the parts
2279
        if (parts.length >= items.length) {
19✔
2280
            message = leadingText + parts.join('') + trailingText;
13✔
2281

2282
            //we require truncation
2283
        } else {
2284
            //account for truncation message length including max possible "more" items digits, trailing text length, and the separator between last item and trailing text
2285
            length = leadingText.length + `...and ${items.length} more`.length + itemSeparator.length + (trailingText?.length ?? 0);
6!
2286
            message = leadingText;
6✔
2287
            for (let i = 0; i < parts.length; i++) {
6✔
2288
                //always include at least 2 items. if this part would overflow the max, then skip it and finalize the message
2289
                if (i > 1 && length + parts[i].length > maxLength) {
47✔
2290
                    message += itemSeparator + `...and ${items.length - i} more` + trailingText;
6✔
2291
                    return message;
6✔
2292
                } else {
2293
                    message += parts[i];
41✔
2294
                    length += parts[i].length;
41✔
2295
                }
2296
            }
2297
        }
2298
        return message;
13✔
2299
    }
2300

2301
    public getAstNodeFriendlyName(node: AstNode) {
2302
        return node?.kind.replace(/Statement|Expression/g, '');
235!
2303
    }
2304

2305

2306
    public hasLeadingComments(input: Token | AstNode) {
2307
        const leadingTrivia = isToken(input) ? input?.leadingTrivia : input?.leadingTrivia ?? [];
6,837!
2308
        return !!leadingTrivia.find(t => t.kind === TokenKind.Comment);
13,986✔
2309
    }
2310

2311
    public getLeadingComments(input: Token | AstNode) {
2312
        const leadingTrivia = isToken(input) ? input?.leadingTrivia : input?.leadingTrivia ?? [];
10,834!
2313
        return leadingTrivia.filter(t => t.kind === TokenKind.Comment);
33,353✔
2314
    }
2315

2316
    public isLeadingCommentOnSameLine(line: RangeLike, input: Token | AstNode) {
2317
        const leadingCommentRange = this.getLeadingComments(input)?.[0];
10,039!
2318
        if (leadingCommentRange) {
10,039✔
2319
            return this.linesTouch(line, leadingCommentRange?.location);
1,476!
2320
        }
2321
        return false;
8,563✔
2322
    }
2323

2324
    public isClassUsedAsFunction(potentialClassType: BscType, expression: Expression, options: GetTypeOptions) {
2325
        // eslint-disable-next-line no-bitwise
2326
        if ((options?.flags ?? 0) & SymbolTypeFlag.runtime &&
22,431!
2327
            isClassType(potentialClassType) &&
2328
            !options.isExistenceTest &&
2329
            potentialClassType.name.toLowerCase() === this.getAllDottedGetPartsAsString(expression).toLowerCase() &&
2330
            !expression.findAncestor(isNewExpression)) {
2331
            return true;
31✔
2332
        }
2333
        return false;
22,400✔
2334
    }
2335

2336
    public getSpecialCaseCallExpressionReturnType(callExpr: CallExpression) {
2337
        if (isVariableExpression(callExpr.callee) && callExpr.callee.tokens.name.text.toLowerCase() === 'createobject') {
621✔
2338
            const componentName = isLiteralString(callExpr.args[0]) ? callExpr.args[0].tokens.value?.text?.replace(/"/g, '') : '';
112!
2339
            const nodeType = componentName.toLowerCase() === 'rosgnode' && isLiteralString(callExpr.args[1]) ? callExpr.args[1].tokens.value?.text?.replace(/"/g, '') : '';
112!
2340
            if (componentName?.toLowerCase().startsWith('ro')) {
112!
2341
                const fullName = componentName + nodeType;
98✔
2342
                const data = {};
98✔
2343
                const symbolTable = callExpr.getSymbolTable();
98✔
2344
                const foundType = symbolTable.getSymbolType(fullName, {
98✔
2345
                    flags: SymbolTypeFlag.typetime,
2346
                    data: data,
2347
                    tableProvider: () => callExpr?.getSymbolTable(),
117!
2348
                    fullName: fullName
2349
                });
2350
                if (foundType) {
98!
2351
                    return foundType;
98✔
2352
                }
2353
            }
2354
        }
2355
    }
2356

2357
    public symbolComesFromSameNode(symbolName: string, definingNode: AstNode, symbolTable: SymbolTable) {
2358
        let nsData: ExtraSymbolData = {};
552✔
2359
        symbolTable.getSymbolType(symbolName, { flags: SymbolTypeFlag.runtime, data: nsData });
552✔
2360

2361
        if (definingNode === nsData?.definingNode) {
552!
2362
            return true;
361✔
2363
        }
2364
        return false;
191✔
2365
    }
2366

2367
    public isCalleeMemberOfNamespace(symbolName: string, nodeWhereUsed: AstNode, namespace?: NamespaceStatement) {
2368
        namespace = namespace ?? nodeWhereUsed.findAncestor<NamespaceStatement>(isNamespaceStatement);
39!
2369

2370
        if (!this.isVariableMemberOfNamespace(symbolName, nodeWhereUsed, namespace)) {
39✔
2371
            return false;
18✔
2372
        }
2373
        const exprType = nodeWhereUsed.getType({ flags: SymbolTypeFlag.runtime });
21✔
2374

2375
        if (isCallableType(exprType) || isClassType(exprType)) {
21✔
2376
            return true;
8✔
2377
        }
2378
        return false;
13✔
2379
    }
2380

2381
    public isVariableMemberOfNamespace(symbolName: string, nodeWhereUsed: AstNode, namespace?: NamespaceStatement) {
2382
        namespace = namespace ?? nodeWhereUsed.findAncestor<NamespaceStatement>(isNamespaceStatement);
1,696✔
2383
        if (!isNamespaceStatement(namespace)) {
1,696✔
2384
            return false;
1,354✔
2385
        }
2386
        let varData: ExtraSymbolData = {};
342✔
2387
        nodeWhereUsed.getType({ flags: SymbolTypeFlag.runtime, data: varData });
342✔
2388
        return this.symbolComesFromSameNode(symbolName, varData?.definingNode, namespace.getSymbolTable());
342!
2389
    }
2390

2391
    public isVariableShadowingSomething(symbolName: string, nodeWhereUsed: AstNode) {
2392
        let varData: ExtraSymbolData = {};
6,041✔
2393
        let exprType = nodeWhereUsed.getType({ flags: SymbolTypeFlag.runtime, data: varData });
6,041✔
2394
        if (isReferenceType(exprType)) {
6,041✔
2395
            exprType = (exprType as any).getTarget();
5,667✔
2396
        }
2397
        const namespace = nodeWhereUsed?.findAncestor<NamespaceStatement>(isNamespaceStatement);
6,041!
2398

2399
        if (isNamespaceStatement(namespace)) {
6,041✔
2400
            let namespaceHasSymbol = namespace.getSymbolTable().hasSymbol(symbolName, SymbolTypeFlag.runtime);
54✔
2401
            // check if the namespace has a symbol with the same name, but different definiton
2402
            if (namespaceHasSymbol && !this.symbolComesFromSameNode(symbolName, varData.definingNode, namespace.getSymbolTable())) {
54✔
2403
                return true;
14✔
2404
            }
2405
        }
2406
        const bodyTable = nodeWhereUsed.getRoot().getSymbolTable();
6,027✔
2407
        const hasSymbolAtFileLevel = bodyTable.hasSymbol(symbolName, SymbolTypeFlag.runtime);
6,027✔
2408
        if (hasSymbolAtFileLevel && !this.symbolComesFromSameNode(symbolName, varData.definingNode, bodyTable)) {
6,027✔
2409
            return true;
8✔
2410
        }
2411

2412
        return false;
6,019✔
2413
    }
2414

2415
    public chooseTypeFromCodeOrDocComment(codeType: BscType, docType: BscType, options: GetTypeOptions) {
2416
        let returnType: BscType;
2417
        if (options.preferDocType && docType) {
10,180!
NEW
2418
            returnType = docType;
×
NEW
2419
            if (options.data) {
×
NEW
2420
                options.data.isFromDocComment = true;
×
2421
            }
2422
        } else {
2423
            returnType = codeType;
10,180✔
2424
            if (!returnType && docType) {
10,180✔
2425
                returnType = docType;
61✔
2426
                if (options.data) {
61✔
2427
                    options.data.isFromDocComment = true;
17✔
2428
                }
2429
            }
2430
        }
2431
        return returnType;
10,180✔
2432
    }
2433
}
2434

2435
/**
2436
 * A tagged template literal function for standardizing the path. This has to be defined as standalone function since it's a tagged template literal function,
2437
 * we can't use `object.tag` syntax.
2438
 */
2439
export function standardizePath(stringParts, ...expressions: any[]) {
1✔
2440
    let result: string[] = [];
21,468✔
2441
    for (let i = 0; i < stringParts.length; i++) {
21,468✔
2442
        result.push(stringParts[i], expressions[i]);
181,391✔
2443
    }
2444
    return util.driveLetterToLower(
21,468✔
2445
        rokuDeployStandardizePath(
2446
            result.join('')
2447
        )
2448
    );
2449
}
2450

2451
/**
2452
 * An item that can be coerced into a `Range`
2453
 */
2454
export type RangeLike = { location?: Location } | Location | { range?: Range } | Range | undefined;
2455

2456
export let util = new Util();
1✔
2457
export default util;
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc