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

rokucommunity / brighterscript / #13117

01 Oct 2024 08:24AM UTC coverage: 86.842% (-1.4%) from 88.193%
#13117

push

web-flow
Merge abd960cd5 into 3a2dc7282

11537 of 14048 branches covered (82.13%)

Branch coverage included in aggregate %.

6991 of 7582 new or added lines in 100 files covered. (92.21%)

83 existing lines in 18 files now uncovered.

12692 of 13852 relevant lines covered (91.63%)

29478.96 hits per line

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

86.23
/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,632!
62
            return -1;
×
63
        } else {
64
            return filePath.replace(/^pkg:/, '').split(/[\\\/]/).length - 1;
1,632✔
65
        }
66
    }
67

68
    /**
69
     * Determine if the file exists
70
     */
71
    public async pathExists(filePath: string | undefined) {
72
        if (!filePath) {
130✔
73
            return false;
1✔
74
        } else {
75
            return fsExtra.pathExists(filePath);
129✔
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) {
NEW
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 {
12✔
179
        if (configFilePath) {
31✔
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('?')) {
30✔
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 : [];
29✔
190
            configFilePath = path.resolve(cwd, configFilePath);
29✔
191
            if (parentProjectPaths?.includes(configFilePath)) {
29!
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();
28✔
198
            let parseErrors = [] as ParseError[];
28✔
199
            let projectConfig = parseJsonc(projectFileContents, parseErrors, {
28✔
200
                allowEmptyContent: true,
201
                allowTrailingComma: true,
202
                disallowComments: false
203
            }) as BsConfig ?? {};
28✔
204
            if (parseErrors.length > 0) {
28✔
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);
27✔
217

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

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

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

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

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

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

289
        let result: T;
290
        let err;
291

UNCOV
292
        try {
×
UNCOV
293
            result = callback();
×
294
        } catch (e) {
295
            err = e;
×
296
        }
297

UNCOV
298
        if (targetCwd) {
×
UNCOV
299
            process.chdir(originalCwd);
×
300
        }
301

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

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

318
        if (config?.noProject) {
74!
319
            return result;
1✔
320
        }
321

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

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

345
        const cwd = config.cwd ?? process.cwd();
1,897✔
346
        const rootFolderName = path.basename(cwd);
1,897✔
347
        const retainStagingDir = (config.retainStagingDir ?? config.retainStagingDir) === true ? true : false;
1,897✔
348

349
        let logLevel: LogLevel = LogLevel.log;
1,897✔
350

351
        if (typeof config.logLevel === 'string') {
1,897!
352
            logLevel = LogLevel[(config.logLevel as string).toLowerCase()] ?? LogLevel.log;
×
353
        }
354

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

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

391
        //mutate `config` in case anyone is holding a reference to the incomplete one
392
        const merged: FinalizedBsConfig = Object.assign(config, configWithDefaults);
1,897✔
393

394
        return merged;
1,897✔
395
    }
396

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

411
        rootDir = path.resolve(cwd, rootDir);
1,786✔
412

413
        return rootDir;
1,786✔
414
    }
415

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

423
        for (let callableContainer of callables) {
1,600✔
424
            let lowerName = callableContainer.callable.getName(ParseMode.BrightScript).toLowerCase();
126,560✔
425

426
            //create a new array for this name
427
            const list = result.get(lowerName);
126,560✔
428
            if (list) {
126,560✔
429
                list.push(callableContainer);
6,434✔
430
            } else {
431
                result.set(lowerName, [callableContainer]);
120,126✔
432
            }
433
        }
434
        return result;
1,600✔
435
    }
436

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

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

466
        //remove the filename
467
        let containingFolder = path.normalize(path.dirname(containingFilePathAbsolute));
208✔
468
        //start with the containing folder, split by slash
469
        let result = containingFolder.split(path.sep);
208✔
470

471
        //split on slash
472
        let targetParts = path.normalize(targetPath).split(path.sep);
208✔
473

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

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

498
        //break by path separator
499
        let sourceParts = pkgSrcPath.split(path.sep);
11✔
500
        let targetParts = pkgTargetPath.split(path.sep);
11✔
501

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

513
        //throw out the common parts from both sets
514
        sourceParts.splice(0, commonParts.length);
11✔
515
        targetParts.splice(0, commonParts.length);
11✔
516

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

522
        //now add every target part
523
        resultParts = [...resultParts, ...targetParts];
11✔
524
        return path.join(...resultParts);
11✔
525
    }
526

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

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

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

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

574
        // Check if `b` is before `a`
575
        if (b.end.line < a.start.line || (b.end.line === a.start.line && b.end.character <= a.start.character)) {
8✔
576
            return false;
1✔
577
        }
578

579
        // These ranges must intersect
580
        return true;
7✔
581
    }
582

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

602
        // Check if `b` is before `a`
603
        if (b.end.line < a.start.line || (b.end.line === a.start.line && b.end.character < a.start.character)) {
23✔
604
            return false;
2✔
605
        }
606

607
        // These ranges must intersect
608
        return true;
21✔
609
    }
610

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

619
    public comparePositionToRange(position: Position | undefined, range: Range | undefined) {
620
        //stop if the either range is missng
621
        if (!position || !range) {
13,579✔
622
            return 0;
10✔
623
        }
624

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

634
    public comparePosition(a: Position | undefined, b: Position) {
635
        //stop if the either position is missing
636
        if (!a || !b) {
207,885!
NEW
637
            return 0;
×
638
        }
639

640
        if (a.line < b.line || (a.line === b.line && a.character < b.character)) {
207,885✔
641
            return -1;
14,826✔
642
        }
643
        if (a.line > b.line || (a.line === b.line && a.character > b.character)) {
193,059✔
644
            return 1;
192,237✔
645
        }
646
        return 0;
822✔
647
    }
648

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

669
        let newLinesInRow = 0;
28,569✔
670
        for (let i = tokens.length - 1; i >= 0; i--) {
28,569✔
671
            const token = tokens[i];
25,171✔
672
            //skip whitespace and newline chars
673
            if (token.kind === TokenKind.Comment) {
25,171✔
674
                comments.push(token);
942✔
675
                newLinesInRow = 0;
942✔
676
            } else if (token.kind === TokenKind.Newline) {
24,229!
677
                //skip these tokens
678
                newLinesInRow++;
24,229✔
679

680
                if (newLinesInRow > 1) {
24,229✔
681
                    // stop processing on empty line.
682
                    break;
2,814✔
683
                }
684
                //any other token means there are no more comments
685
            } else {
NEW
686
                break;
×
687
            }
688
        }
689
        const jsDocCommentBlockLine = /(\/\*{2,}|\*{1,}\/)/i;
28,569✔
690
        let usesjsDocCommentBlock = false;
28,569✔
691
        if (comments.length === 0) {
28,569✔
692
            return '';
27,758✔
693
        }
694
        return comments.reverse()
811✔
695
            .map(x => ({ line: x.text.replace(/^('|rem)/i, '').trim(), token: x }))
942✔
696
            .filter(({ line }) => {
697
                if (jsDocCommentBlockLine.exec(line)) {
942✔
698
                    usesjsDocCommentBlock = true;
30✔
699
                    return false;
30✔
700
                }
701
                return true;
912✔
702
            }).map(({ line, token }) => {
703
                if (usesjsDocCommentBlock) {
912✔
704
                    if (line.startsWith('*')) {
23✔
705
                        //remove jsDoc leading '*'
706
                        line = line.slice(1).trim();
22✔
707
                    }
708
                }
709
                if (options.prettyPrint && line.startsWith('@')) {
912✔
710
                    // Handle jsdoc/brightscriptdoc tags specially
711
                    // make sure they are on their own markdown line, and add italics
712
                    const firstSpaceIndex = line.indexOf(' ');
3✔
713
                    if (firstSpaceIndex === -1) {
3✔
714
                        return `\n_${line}_`;
1✔
715
                    }
716
                    const firstWord = line.substring(0, firstSpaceIndex);
2✔
717
                    return `\n_${firstWord}_ ${line.substring(firstSpaceIndex + 1)}`;
2✔
718
                }
719
                if (options.commentTokens) {
909!
720
                    options.commentTokens.push(token);
909✔
721
                }
722
                return line;
909✔
723
            }).join('\n');
724
    }
725

726
    /**
727
     * Prefixes a component name so it can be used as type in the symbol table, without polluting available symbols
728
     *
729
     * @param sgNodeName the Name of the component
730
     * @returns the node name, prefixed with `roSGNode`
731
     */
732
    public getSgNodeTypeName(sgNodeName: string) {
733
        return 'roSGNode' + sgNodeName;
320,817✔
734
    }
735

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

751
    public propertyCount(object: Record<string, unknown>) {
752
        let count = 0;
×
753
        for (let key in object) {
×
754
            if (object.hasOwnProperty(key)) {
×
755
                count++;
×
756
            }
757
        }
758
        return count;
×
759
    }
760

761
    public padLeft(subject: string, totalLength: number, char: string) {
762
        totalLength = totalLength > 1000 ? 1000 : totalLength;
1!
763
        while (subject.length < totalLength) {
1✔
764
            subject = char + subject;
1,000✔
765
        }
766
        return subject;
1✔
767
    }
768

769
    /**
770
     * Does the string appear to be a uri (i.e. does it start with `file:`)
771
     */
772
    public isUriLike(filePath: string) {
773
        return filePath?.indexOf('file:') === 0;// eslint-disable-line @typescript-eslint/prefer-string-starts-ends-with
273,731!
774
    }
775

776
    /**
777
     * Given a file path, convert it to a URI string
778
     */
779
    public pathToUri(filePath: string) {
780
        if (!filePath) {
244,748✔
781
            return filePath;
31,132✔
782
        } else if (this.isUriLike(filePath)) {
213,616✔
783
            return filePath;
193,466✔
784
        } else {
785
            return URI.file(filePath).toString();
20,150✔
786
        }
787
    }
788

789
    /**
790
     * Given a URI, convert that to a regular fs path
791
     */
792
    public uriToPath(uri: string) {
793
        //if this doesn't look like a URI, then assume it's already a path
794
        if (this.isUriLike(uri) === false) {
52,017✔
795
            return uri;
2✔
796
        }
797
        let parsedPath = URI.parse(uri).fsPath;
52,015✔
798

799
        //Uri annoyingly converts all drive letters to lower case...so this will bring back whatever case it came in as
800
        let match = /\/\/\/([a-z]:)/i.exec(uri);
52,015✔
801
        if (match) {
52,015✔
802
            let originalDriveCasing = match[1];
2✔
803
            parsedPath = originalDriveCasing + parsedPath.substring(2);
2✔
804
        }
805
        const normalizedPath = path.normalize(parsedPath);
52,015✔
806
        return normalizedPath;
52,015✔
807
    }
808

809
    /**
810
     * Force the drive letter to lower case
811
     */
812
    public driveLetterToLower(fullPath: string) {
813
        if (fullPath) {
32,794✔
814
            let firstCharCode = fullPath.charCodeAt(0);
32,790✔
815
            if (
32,790✔
816
                //is upper case A-Z
817
                firstCharCode >= 65 && firstCharCode <= 90 &&
47,383✔
818
                //next char is colon
819
                fullPath[1] === ':'
820
            ) {
821
                fullPath = fullPath[0].toLowerCase() + fullPath.substring(1);
3✔
822
            }
823
        }
824
        return fullPath;
32,794✔
825
    }
826

827
    /**
828
     * Replace the first instance of `search` in `subject` with `replacement`
829
     */
830
    public replaceCaseInsensitive(subject: string, search: string, replacement: string) {
831
        let idx = subject.toLowerCase().indexOf(search.toLowerCase());
6,667✔
832
        if (idx > -1) {
6,667✔
833
            let result = subject.substring(0, idx) + replacement + subject.substring(idx + search.length);
2,095✔
834
            return result;
2,095✔
835
        } else {
836
            return subject;
4,572✔
837
        }
838
    }
839

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

856
    /**
857
     * Get the outDir from options, taking into account cwd and absolute outFile paths
858
     */
859
    public getOutDir(options: FinalizedBsConfig) {
860
        options = this.normalizeConfig(options);
2✔
861
        let cwd = path.normalize(options.cwd ? options.cwd : process.cwd());
2!
862
        if (path.isAbsolute(options.outFile)) {
2!
863
            return path.dirname(options.outFile);
×
864
        } else {
865
            return path.normalize(path.join(cwd, path.dirname(options.outFile)));
2✔
866
        }
867
    }
868

869
    /**
870
     * Get paths to all files on disc that match this project's source list
871
     */
872
    public async getFilePaths(options: FinalizedBsConfig) {
873
        let rootDir = this.getRootDir(options);
48✔
874

875
        let files = await rokuDeploy.getFilePaths(options.files, rootDir);
48✔
876
        return files;
48✔
877
    }
878

879
    /**
880
     * Given a path to a brs file, compute the path to a theoretical d.bs file.
881
     * Only `.brs` files can have typedef path, so return undefined for everything else
882
     */
883
    public getTypedefPath(brsSrcPath: string) {
884
        const typedefPath = brsSrcPath
3,449✔
885
            .replace(/\.brs$/i, '.d.bs')
886
            .toLowerCase();
887

888
        if (typedefPath.endsWith('.d.bs')) {
3,449✔
889
            return typedefPath;
2,034✔
890
        } else {
891
            return undefined;
1,415✔
892
        }
893
    }
894

895

896
    /**
897
     * Walks up the chain to find the closest bsconfig.json file
898
     */
899
    public async findClosestConfigFile(currentPath: string): Promise<string | undefined> {
900
        //make the path absolute
901
        currentPath = path.resolve(
6✔
902
            path.normalize(
903
                currentPath
904
            )
905
        );
906

907
        let previousPath: string | undefined;
908
        //using ../ on the root of the drive results in the same file path, so that's how we know we reached the top
909
        while (previousPath !== currentPath) {
6✔
910
            previousPath = currentPath;
28✔
911

912
            let bsPath = path.join(currentPath, 'bsconfig.json');
28✔
913
            let brsPath = path.join(currentPath, 'brsconfig.json');
28✔
914
            if (await this.pathExists(bsPath)) {
28✔
915
                return bsPath;
2✔
916
            } else if (await this.pathExists(brsPath)) {
26✔
917
                return brsPath;
2✔
918
            } else {
919
                //walk upwards one directory
920
                currentPath = path.resolve(path.join(currentPath, '../'));
24✔
921
            }
922
        }
923
        //got to the root path, no config file exists
924
    }
925

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

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

950
    /**
951
     * Determines if the position is greater than the range. This means
952
     * the position does not touch the range, and has a position greater than the end
953
     * of the range. A position that touches the last line/char of a range is considered greater
954
     * than the range, because the `range.end` is EXclusive
955
     */
956
    public positionIsGreaterThanRange(position: Position, range: Range) {
957

958
        //if the position is a higher line than the range
959
        if (position.line > range.end.line) {
1,166✔
960
            return true;
1,079✔
961
        } else if (position.line < range.end.line) {
87!
UNCOV
962
            return false;
×
963
        }
964
        //they are on the same line
965

966
        //if the position's char is greater than or equal to the range's
967
        if (position.character >= range.end.character) {
87!
968
            return true;
87✔
969
        } else {
UNCOV
970
            return false;
×
971
        }
972
    }
973

974
    /**
975
     * Get a range back from an object that contains (or is) a range
976
     */
977
    public extractRange(rangeIsh: RangeLike): Range | undefined {
978
        if (!rangeIsh) {
9,534✔
979
            return undefined;
29✔
980
        } else if ('location' in rangeIsh) {
9,505✔
981
            return rangeIsh.location?.range;
6,586✔
982
        } else if ('range' in rangeIsh) {
2,919!
983
            return rangeIsh.range;
2,919✔
NEW
984
        } else if (Range.is(rangeIsh)) {
×
NEW
985
            return rangeIsh;
×
986
        } else {
NEW
987
            return undefined;
×
988
        }
989
    }
990

991

992
    /**
993
     * Get a location object back by extracting location information from other objects that contain location
994
     */
995
    public getRange(startObj: | { range: Range }, endObj: { range: Range }): Range {
UNCOV
996
        if (!startObj?.range || !endObj?.range) {
×
UNCOV
997
            return undefined;
×
998
        }
UNCOV
999
        return util.createRangeFromPositions(startObj.range?.start, endObj.range?.end);
×
1000
    }
1001

1002
    /**
1003
     * If the two items both start on the same line
1004
     */
1005
    public sameStartLine(first: { range: Range }, second: { range: Range }) {
1006
        if (first && second && first.range.start.line === second.range.start.line) {
×
1007
            return true;
×
1008
        } else {
1009
            return false;
×
1010
        }
1011
    }
1012

1013
    /**
1014
     * If the two items have lines that touch
1015
     */
1016
    public linesTouch(first: RangeLike, second: RangeLike) {
1017
        const firstRange = this.extractRange(first);
1,488✔
1018
        const secondRange = this.extractRange(second);
1,488✔
1019
        if (firstRange && secondRange && (
1,488✔
1020
            firstRange.start.line === secondRange.start.line ||
1021
            firstRange.start.line === secondRange.end.line ||
1022
            firstRange.end.line === secondRange.start.line ||
1023
            firstRange.end.line === secondRange.end.line
1024
        )) {
1025
            return true;
91✔
1026
        } else {
1027
            return false;
1,397✔
1028
        }
1029
    }
1030

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

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

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

1072
    public splitIntoLines(string: string) {
1073
        return string.split(/\r?\n/g);
169✔
1074
    }
1075

1076
    public getTextForRange(string: string | string[], range: Range): string {
1077
        let lines: string[];
1078
        if (Array.isArray(string)) {
171✔
1079
            lines = string;
170✔
1080
        } else {
1081
            lines = this.splitIntoLines(string);
1✔
1082
        }
1083

1084
        const start = range.start;
171✔
1085
        const end = range.end;
171✔
1086

1087
        let endCharacter = end.character;
171✔
1088
        // If lines are the same we need to subtract out our new starting position to make it work correctly
1089
        if (start.line === end.line) {
171✔
1090
            endCharacter -= start.character;
159✔
1091
        }
1092

1093
        let rangeLines = [lines[start.line].substring(start.character)];
171✔
1094
        for (let i = start.line + 1; i <= end.line; i++) {
171✔
1095
            rangeLines.push(lines[i]);
12✔
1096
        }
1097
        const lastLine = rangeLines.pop();
171✔
1098
        if (lastLine !== undefined) {
171!
1099
            rangeLines.push(lastLine.substring(0, endCharacter));
171✔
1100
        }
1101
        return rangeLines.join('\n');
171✔
1102
    }
1103

1104
    /**
1105
     * Helper for creating `Location` objects. Prefer using this function because vscode-languageserver's `Location.create()` is significantly slower at scale
1106
     */
1107
    public createLocationFromRange(uri: string, range: Range): Location {
1108
        return {
7,753✔
1109
            uri: util.pathToUri(uri),
1110
            range: range
1111
        };
1112
    }
1113

1114
    /**
1115
     * Helper for creating `Location` objects from a file and range
1116
     */
1117
    public createLocationFromFileRange(file: BscFile, range: Range): Location {
1118
        return this.createLocationFromRange(this.pathToUri(file?.srcPath), range);
379!
1119
    }
1120

1121
    /**
1122
     * 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
1123
     */
1124
    public createLocation(startLine: number, startCharacter: number, endLine: number, endCharacter: number, uri?: string): Location {
1125
        return {
228,242✔
1126
            uri: util.pathToUri(uri),
1127
            range: {
1128
                start: {
1129
                    line: startLine,
1130
                    character: startCharacter
1131
                },
1132
                end: {
1133
                    line: endLine,
1134
                    character: endCharacter
1135
                }
1136
            }
1137
        };
1138
    }
1139

1140
    /**
1141
     * Helper for creating `Range` objects. Prefer using this function because vscode-languageserver's `Range.create()` is significantly slower.
1142
     */
1143
    public createRange(startLine: number, startCharacter: number, endLine: number, endCharacter: number): Range {
1144
        return {
7,798✔
1145
            start: {
1146
                line: startLine,
1147
                character: startCharacter
1148
            },
1149
            end: {
1150
                line: endLine,
1151
                character: endCharacter
1152
            }
1153
        };
1154
    }
1155

1156
    /**
1157
     * Create a `Range` from two `Position`s
1158
     */
1159
    public createRangeFromPositions(startPosition: Position, endPosition: Position): Range | undefined {
1160
        startPosition = startPosition ?? endPosition;
171✔
1161
        endPosition = endPosition ?? startPosition;
171✔
1162
        if (!startPosition && !endPosition) {
171!
NEW
1163
            return undefined;
×
1164
        }
1165
        return this.createRange(startPosition.line, startPosition.character, endPosition.line, endPosition.character);
171✔
1166
    }
1167

1168
    /**
1169
     * Clone a range
1170
     */
1171
    public cloneLocation(location: Location) {
1172
        if (location) {
14,428✔
1173
            return {
14,263✔
1174
                uri: location.uri,
1175
                range: {
1176
                    start: {
1177
                        line: location.range.start.line,
1178
                        character: location.range.start.character
1179
                    },
1180
                    end: {
1181
                        line: location.range.end.line,
1182
                        character: location.range.end.character
1183
                    }
1184
                }
1185
            };
1186
        } else {
1187
            return location;
165✔
1188
        }
1189
    }
1190

1191
    /**
1192
     * Clone every token
1193
     */
1194
    public cloneToken<T extends Token>(token: T): T {
1195
        if (token) {
2,679✔
1196
            const result = {
2,485✔
1197
                kind: token.kind,
1198
                location: this.cloneLocation(token.location),
1199
                text: token.text,
1200
                isReserved: token.isReserved,
1201
                leadingWhitespace: token.leadingWhitespace,
1202
                leadingTrivia: token.leadingTrivia.map(x => this.cloneToken(x))
1,279✔
1203
            } as Token;
1204
            //handle those tokens that have charCode
1205
            if ('charCode' in token) {
2,485✔
1206
                (result as any).charCode = (token as any).charCode;
3✔
1207
            }
1208
            return result as T;
2,485✔
1209
        } else {
1210
            return token;
194✔
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 createBoundingLocation(...locatables: Array<{ location?: Location } | Location | { range?: Range } | Range | undefined>): Location | undefined {
1219
        let uri: string | undefined;
1220
        let startPosition: Position | undefined;
1221
        let endPosition: Position | undefined;
1222

1223
        for (let locatable of locatables) {
44,064✔
1224
            let range: Range;
1225
            if (!locatable) {
178,033✔
1226
                continue;
47,717✔
1227
            } else if ('location' in locatable) {
130,316✔
1228
                range = locatable.location?.range;
125,084✔
1229
                if (!uri) {
125,084✔
1230
                    uri = locatable.location?.uri;
50,864✔
1231
                }
1232
            } else if (Location.is(locatable)) {
5,232✔
1233
                range = locatable.range;
5,224✔
1234
                if (!uri) {
5,224✔
1235
                    uri = locatable.uri;
4,637✔
1236
                }
1237
            } else if ('range' in locatable) {
8!
NEW
1238
                range = locatable.range;
×
1239
            } else {
1240
                range = locatable as Range;
8✔
1241
            }
1242

1243
            //skip undefined locations or locations without a range
1244
            if (!range) {
130,316✔
1245
                continue;
3,567✔
1246
            }
1247

1248
            if (!startPosition) {
126,749✔
1249
                startPosition = range.start;
42,838✔
1250
            } else if (this.comparePosition(range.start, startPosition) < 0) {
83,911✔
1251
                startPosition = range.start;
854✔
1252
            }
1253
            if (!endPosition) {
126,749✔
1254
                endPosition = range.end;
42,838✔
1255
            } else if (this.comparePosition(range.end, endPosition) > 0) {
83,911✔
1256
                endPosition = range.end;
79,030✔
1257
            }
1258
        }
1259
        if (startPosition && endPosition) {
44,064✔
1260
            return util.createLocation(startPosition.line, startPosition.character, endPosition.line, endPosition.character, uri);
42,838✔
1261
        } else {
1262
            return undefined;
1,226✔
1263
        }
1264
    }
1265

1266
    /**
1267
     *  Gets the bounding range of a bunch of ranges or objects that have ranges
1268
     *  TODO: this does a full iteration of the args. If the args were guaranteed to be in range order, we could optimize this
1269
     */
1270
    public createBoundingRange(...locatables: Array<RangeLike>): Range | undefined {
1271
        return this.createBoundingLocation(...locatables)?.range;
511✔
1272
    }
1273

1274
    /**
1275
     * Gets the bounding range of an object that contains a bunch of tokens
1276
     * @param tokens Object with tokens in it
1277
     * @returns Range containing all the tokens
1278
     */
1279
    public createBoundingLocationFromTokens(tokens: Record<string, { location?: Location }>): Location | undefined {
1280
        let uri: string;
1281
        let startPosition: Position | undefined;
1282
        let endPosition: Position | undefined;
1283
        for (let key in tokens) {
5,030✔
1284
            let token = tokens?.[key];
17,914!
1285
            let locatableRange = token?.location?.range;
17,914✔
1286
            if (!locatableRange) {
17,914✔
1287
                continue;
5,527✔
1288
            }
1289

1290
            if (!startPosition) {
12,387✔
1291
                startPosition = locatableRange.start;
4,873✔
1292
            } else if (this.comparePosition(locatableRange.start, startPosition) < 0) {
7,514✔
1293
                startPosition = locatableRange.start;
2,076✔
1294
            }
1295
            if (!endPosition) {
12,387✔
1296
                endPosition = locatableRange.end;
4,873✔
1297
            } else if (this.comparePosition(locatableRange.end, endPosition) > 0) {
7,514✔
1298
                endPosition = locatableRange.end;
5,322✔
1299
            }
1300
            if (!uri) {
12,387✔
1301
                uri = token.location.uri;
6,030✔
1302
            }
1303
        }
1304
        if (startPosition && endPosition) {
5,030✔
1305
            return this.createLocation(startPosition.line, startPosition.character, endPosition.line, endPosition.character, uri);
4,873✔
1306
        } else {
1307
            return undefined;
157✔
1308
        }
1309
    }
1310

1311
    /**
1312
     * Create a `Position` object. Prefer this over `Position.create` for performance reasons.
1313
     */
1314
    public createPosition(line: number, character: number) {
1315
        return {
367✔
1316
            line: line,
1317
            character: character
1318
        };
1319
    }
1320

1321
    /**
1322
     * Convert a list of tokens into a string, including their leading whitespace
1323
     */
1324
    public tokensToString(tokens: Token[]) {
1325
        let result = '';
1✔
1326
        //skip iterating the final token
1327
        for (let token of tokens) {
1✔
1328
            result += token.leadingWhitespace + token.text;
16✔
1329
        }
1330
        return result;
1✔
1331
    }
1332

1333
    /**
1334
     * Convert a token into a BscType
1335
     */
1336
    public tokenToBscType(token: Token) {
1337
        // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
1338
        switch (token.kind) {
1,784,537✔
1339
            case TokenKind.Boolean:
1,787,774✔
1340
                return new BooleanType(token.text);
106✔
1341
            case TokenKind.True:
1342
            case TokenKind.False:
1343
                return BooleanType.instance;
162✔
1344
            case TokenKind.Double:
1345
                return new DoubleType(token.text);
74✔
1346
            case TokenKind.DoubleLiteral:
1347
                return DoubleType.instance;
8✔
1348
            case TokenKind.Dynamic:
1349
                return new DynamicType(token.text);
96✔
1350
            case TokenKind.Float:
1351
                return new FloatType(token.text);
300✔
1352
            case TokenKind.FloatLiteral:
1353
                return FloatType.instance;
117✔
1354
            case TokenKind.Function:
1355
                return new FunctionType(token.text);
137✔
1356
            case TokenKind.Integer:
1357
                return new IntegerType(token.text);
1,050✔
1358
            case TokenKind.IntegerLiteral:
1359
                return IntegerType.instance;
1,841✔
1360
            case TokenKind.Invalid:
1361
                return DynamicType.instance; // TODO: use InvalidType better new InvalidType(token.text);
78✔
1362
            case TokenKind.LongInteger:
1363
                return new LongIntegerType(token.text);
46✔
1364
            case TokenKind.LongIntegerLiteral:
1365
                return LongIntegerType.instance;
3✔
1366
            case TokenKind.Object:
1367
                return new ObjectType(token.text);
307✔
1368
            case TokenKind.String:
1369
                return new StringType(token.text);
1,820✔
1370
            case TokenKind.StringLiteral:
1371
            case TokenKind.TemplateStringExpressionBegin:
1372
            case TokenKind.TemplateStringExpressionEnd:
1373
            case TokenKind.TemplateStringQuasi:
1374
                return StringType.instance;
1,045✔
1375
            case TokenKind.Void:
1376
                return new VoidType(token.text);
24✔
1377
            case TokenKind.Identifier:
1378
                switch (token.text.toLowerCase()) {
1,777,300✔
1379
                    case 'boolean':
955,948!
1380
                        return new BooleanType(token.text);
220,732✔
1381
                    case 'double':
1382
                        return new DoubleType(token.text);
4✔
1383
                    case 'dynamic':
1384
                        return new DynamicType(token.text);
4✔
1385
                    case 'float':
1386
                        return new FloatType(token.text);
220,734✔
1387
                    case 'function':
NEW
1388
                        return new FunctionType(token.text);
×
1389
                    case 'integer':
1390
                        return new IntegerType(token.text);
180,756✔
1391
                    case 'invalid':
NEW
1392
                        return DynamicType.instance; // TODO: use InvalidType better new InvalidType(token.text);
×
1393
                    case 'longinteger':
1394
                        return new LongIntegerType(token.text);
4✔
1395
                    case 'object':
1396
                        return new ObjectType(token.text);
4✔
1397
                    case 'string':
1398
                        return new StringType(token.text);
333,706✔
1399
                    case 'void':
1400
                        return new VoidType(token.text);
4✔
1401
                }
1402
        }
1403
    }
1404

1405
    /**
1406
     * Deciphers the correct types for fields based on docs
1407
     * https://developer.roku.com/en-ca/docs/references/scenegraph/xml-elements/interface.md
1408
     * @param typeDescriptor the type descriptor from the docs
1409
     * @returns {BscType} the known type, or dynamic
1410
     */
1411
    public getNodeFieldType(typeDescriptor: string, lookupTable?: SymbolTable): BscType {
1412
        let typeDescriptorLower = typeDescriptor.toLowerCase().trim().replace(/\*/g, '');
1,760,633✔
1413

1414
        if (typeDescriptorLower.startsWith('as ')) {
1,760,633✔
1415
            typeDescriptorLower = typeDescriptorLower.substring(3).trim();
6,952✔
1416
        }
1417
        const nodeFilter = (new RegExp(/^\[?(.* node)/, 'i')).exec(typeDescriptorLower);
1,760,633✔
1418
        if (nodeFilter?.[1]) {
1,760,633✔
1419
            typeDescriptorLower = nodeFilter[1].trim();
36,498✔
1420
        }
1421
        const parensFilter = (new RegExp(/(.*)\(.*\)/, 'gi')).exec(typeDescriptorLower);
1,760,633✔
1422
        if (parensFilter?.[1]) {
1,760,633✔
1423
            typeDescriptorLower = parensFilter[1].trim();
3,476✔
1424
        }
1425

1426
        const bscType = this.tokenToBscType(createToken(TokenKind.Identifier, typeDescriptorLower));
1,760,633✔
1427
        if (bscType) {
1,760,633✔
1428
            return bscType;
955,912✔
1429
        }
1430

1431
        function getRect2dType() {
1432
            const rect2dType = new AssociativeArrayType();
5,218✔
1433
            rect2dType.addMember('height', {}, FloatType.instance, SymbolTypeFlag.runtime);
5,218✔
1434
            rect2dType.addMember('width', {}, FloatType.instance, SymbolTypeFlag.runtime);
5,218✔
1435
            rect2dType.addMember('x', {}, FloatType.instance, SymbolTypeFlag.runtime);
5,218✔
1436
            rect2dType.addMember('y', {}, FloatType.instance, SymbolTypeFlag.runtime);
5,218✔
1437
            return rect2dType;
5,218✔
1438
        }
1439

1440
        function getColorType() {
1441
            return unionTypeFactory([IntegerType.instance, StringType.instance]);
107,760✔
1442
        }
1443

1444
        //check for uniontypes
1445
        const multipleTypes = typeDescriptorLower.split(' or ').map(s => s.trim());
808,197✔
1446
        if (multipleTypes.length > 1) {
804,721✔
1447
            const individualTypes = multipleTypes.map(t => this.getNodeFieldType(t, lookupTable));
6,952✔
1448
            return unionTypeFactory(individualTypes);
3,476✔
1449
        }
1450

1451
        const typeIsArray = typeDescriptorLower.startsWith('array of ') || typeDescriptorLower.startsWith('roarray of ');
801,245✔
1452

1453
        if (typeIsArray) {
801,245✔
1454
            const ofSearch = ' of ';
100,804✔
1455
            const arrayPrefixLength = typeDescriptorLower.indexOf(ofSearch) + ofSearch.length;
100,804✔
1456
            let arrayOfTypeName = typeDescriptorLower.substring(arrayPrefixLength); //cut off beginnin, eg. 'array of' or 'roarray of'
100,804✔
1457
            if (arrayOfTypeName.endsWith('s')) {
100,804✔
1458
                // remove "s" in "floats", etc.
1459
                arrayOfTypeName = arrayOfTypeName.substring(0, arrayOfTypeName.length - 1);
74,734✔
1460
            }
1461
            if (arrayOfTypeName.endsWith('\'')) {
100,804✔
1462
                // remove "'" in "float's", etc.
1463
                arrayOfTypeName = arrayOfTypeName.substring(0, arrayOfTypeName.length - 1);
6,952✔
1464
            }
1465
            if (arrayOfTypeName === 'rectangle') {
100,804✔
1466
                arrayOfTypeName = 'rect2d';
1,738✔
1467
            }
1468
            let arrayType = this.getNodeFieldType(arrayOfTypeName, lookupTable);
100,804✔
1469
            return new ArrayType(arrayType);
100,804✔
1470
        } else if (typeDescriptorLower.startsWith('option ')) {
700,441✔
1471
            const actualTypeName = typeDescriptorLower.substring('option '.length); //cut off beginning 'option '
34,760✔
1472
            return this.getNodeFieldType(actualTypeName, lookupTable);
34,760✔
1473
        } else if (typeDescriptorLower.startsWith('value ')) {
665,681✔
1474
            const actualTypeName = typeDescriptorLower.substring('value '.length); //cut off beginning 'value '
13,904✔
1475
            return this.getNodeFieldType(actualTypeName, lookupTable);
13,904✔
1476
        } else if (typeDescriptorLower === 'n/a') {
651,777✔
1477
            return DynamicType.instance;
3,476✔
1478
        } else if (typeDescriptorLower === 'uri') {
648,301✔
1479
            return StringType.instance;
125,141✔
1480
        } else if (typeDescriptorLower === 'color') {
523,160✔
1481
            return getColorType();
107,759✔
1482
        } else if (typeDescriptorLower === 'vector2d' || typeDescriptorLower === 'floatarray') {
415,401✔
1483
            return new ArrayType(FloatType.instance);
39,975✔
1484
        } else if (typeDescriptorLower === 'vector2darray') {
375,426!
NEW
1485
            return new ArrayType(new ArrayType(FloatType.instance));
×
1486
        } else if (typeDescriptorLower === 'intarray') {
375,426✔
1487
            return new ArrayType(IntegerType.instance);
1✔
1488
        } else if (typeDescriptorLower === 'colorarray') {
375,425✔
1489
            return new ArrayType(getColorType());
1✔
1490
        } else if (typeDescriptorLower === 'boolarray') {
375,424!
NEW
1491
            return new ArrayType(BooleanType.instance);
×
1492
        } else if (typeDescriptorLower === 'stringarray' || typeDescriptorLower === 'strarray') {
375,424✔
1493
            return new ArrayType(StringType.instance);
1✔
1494
        } else if (typeDescriptorLower === 'int') {
375,423✔
1495
            return IntegerType.instance;
6,952✔
1496
        } else if (typeDescriptorLower === 'time') {
368,471✔
1497
            return DoubleType.instance;
33,023✔
1498
        } else if (typeDescriptorLower === 'str') {
335,448!
NEW
1499
            return StringType.instance;
×
1500
        } else if (typeDescriptorLower === 'bool') {
335,448✔
1501
            return BooleanType.instance;
1,738✔
1502
        } else if (typeDescriptorLower === 'array' || typeDescriptorLower === 'roarray') {
333,710✔
1503
            return new ArrayType();
13,905✔
1504
        } else if (typeDescriptorLower === 'assocarray' ||
319,805✔
1505
            typeDescriptorLower === 'associative array' ||
1506
            typeDescriptorLower === 'associativearray' ||
1507
            typeDescriptorLower === 'roassociativearray' ||
1508
            typeDescriptorLower.startsWith('associative array of') ||
1509
            typeDescriptorLower.startsWith('associativearray of') ||
1510
            typeDescriptorLower.startsWith('roassociativearray of')
1511
        ) {
1512
            return new AssociativeArrayType();
60,831✔
1513
        } else if (typeDescriptorLower === 'node') {
258,974✔
1514
            return ComponentType.instance;
15,643✔
1515
        } else if (typeDescriptorLower === 'nodearray') {
243,331✔
1516
            return new ArrayType(ComponentType.instance);
1✔
1517
        } else if (typeDescriptorLower === 'rect2d') {
243,330✔
1518
            return getRect2dType();
5,216✔
1519
        } else if (typeDescriptorLower === 'rect2darray') {
238,114✔
1520
            return new ArrayType(getRect2dType());
2✔
1521
        } else if (typeDescriptorLower === 'font') {
238,112✔
1522
            return this.getNodeFieldType('roSGNodeFont', lookupTable);
38,238✔
1523
        } else if (typeDescriptorLower === 'contentnode') {
199,874✔
1524
            return this.getNodeFieldType('roSGNodeContentNode', lookupTable);
34,760✔
1525
        } else if (typeDescriptorLower.endsWith(' node')) {
165,114✔
1526
            return this.getNodeFieldType('roSgNode' + typeDescriptorLower.substring(0, typeDescriptorLower.length - 5), lookupTable);
34,760✔
1527
        } else if (lookupTable) {
130,354!
1528
            //try doing a lookup
1529
            return lookupTable.getSymbolType(typeDescriptorLower, {
130,354✔
1530
                flags: SymbolTypeFlag.typetime,
1531
                fullName: typeDescriptor,
1532
                tableProvider: () => lookupTable
2✔
1533
            });
1534
        }
1535

NEW
1536
        return DynamicType.instance;
×
1537
    }
1538

1539
    /**
1540
     * Return the type of the result of a binary operator
1541
     * Note: compound assignments (eg. +=) internally use a binary expression, so that's why TokenKind.PlusEqual, etc. are here too
1542
     */
1543
    public binaryOperatorResultType(leftType: BscType, operator: Token, rightType: BscType): BscType {
1544
        if ((isAnyReferenceType(leftType) && !leftType.isResolvable()) ||
511✔
1545
            (isAnyReferenceType(rightType) && !rightType.isResolvable())) {
1546
            return new BinaryOperatorReferenceType(leftType, operator, rightType, (lhs, op, rhs) => {
29✔
1547
                return this.binaryOperatorResultType(lhs, op, rhs);
2✔
1548
            });
1549
        }
1550
        if (isEnumMemberType(leftType)) {
482✔
1551
            leftType = leftType.underlyingType;
9✔
1552
        }
1553
        if (isEnumMemberType(rightType)) {
482✔
1554
            rightType = rightType.underlyingType;
8✔
1555
        }
1556
        let hasDouble = isDoubleType(leftType) || isDoubleType(rightType);
482✔
1557
        let hasFloat = isFloatType(leftType) || isFloatType(rightType);
482✔
1558
        let hasLongInteger = isLongIntegerType(leftType) || isLongIntegerType(rightType);
482✔
1559
        let hasInvalid = isInvalidType(leftType) || isInvalidType(rightType);
482✔
1560
        let hasDynamic = isDynamicType(leftType) || isDynamicType(rightType);
482✔
1561
        let bothNumbers = isNumberType(leftType) && isNumberType(rightType);
482✔
1562
        let bothStrings = isStringType(leftType) && isStringType(rightType);
482✔
1563
        let eitherBooleanOrNum = (isNumberType(leftType) || isBooleanType(leftType)) && (isNumberType(rightType) || isBooleanType(rightType));
482✔
1564

1565
        // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
1566
        switch (operator.kind) {
482✔
1567
            // Math operators
1568
            case TokenKind.Plus:
1,466✔
1569
            case TokenKind.PlusEqual:
1570
                if (bothStrings) {
213✔
1571
                    // "string" + "string" is the only binary expression allowed with strings
1572
                    return StringType.instance;
121✔
1573
                }
1574
            // eslint-disable-next-line no-fallthrough
1575
            case TokenKind.Minus:
1576
            case TokenKind.MinusEqual:
1577
            case TokenKind.Star:
1578
            case TokenKind.StarEqual:
1579
            case TokenKind.Mod:
1580
                if (bothNumbers) {
156✔
1581
                    if (hasDouble) {
127✔
1582
                        return DoubleType.instance;
5✔
1583
                    } else if (hasFloat) {
122✔
1584
                        return FloatType.instance;
23✔
1585

1586
                    } else if (hasLongInteger) {
99✔
1587
                        return LongIntegerType.instance;
4✔
1588
                    }
1589
                    return IntegerType.instance;
95✔
1590
                }
1591
                break;
29✔
1592
            case TokenKind.Forwardslash:
1593
            case TokenKind.ForwardslashEqual:
1594
                if (bothNumbers) {
10✔
1595
                    if (hasDouble) {
8✔
1596
                        return DoubleType.instance;
1✔
1597
                    } else if (hasFloat) {
7✔
1598
                        return FloatType.instance;
1✔
1599

1600
                    } else if (hasLongInteger) {
6✔
1601
                        return LongIntegerType.instance;
1✔
1602
                    }
1603
                    return FloatType.instance;
5✔
1604
                }
1605
                break;
2✔
1606
            case TokenKind.Backslash:
1607
            case TokenKind.BackslashEqual:
1608
                if (bothNumbers) {
6✔
1609
                    if (hasLongInteger) {
4!
NEW
1610
                        return LongIntegerType.instance;
×
1611
                    }
1612
                    return IntegerType.instance;
4✔
1613
                }
1614
                break;
2✔
1615
            case TokenKind.Caret:
1616
                if (bothNumbers) {
16✔
1617
                    if (hasDouble || hasLongInteger) {
14✔
1618
                        return DoubleType.instance;
2✔
1619
                    } else if (hasFloat) {
12✔
1620
                        return FloatType.instance;
1✔
1621
                    }
1622
                    return IntegerType.instance;
11✔
1623
                }
1624
                break;
2✔
1625
            // Bitshift operators
1626
            case TokenKind.LeftShift:
1627
            case TokenKind.LeftShiftEqual:
1628
            case TokenKind.RightShift:
1629
            case TokenKind.RightShiftEqual:
1630
                if (bothNumbers) {
18✔
1631
                    if (hasLongInteger) {
14✔
1632
                        return LongIntegerType.instance;
2✔
1633
                    }
1634
                    // Bitshifts are allowed with non-integer numerics
1635
                    // but will always truncate to ints
1636
                    return IntegerType.instance;
12✔
1637
                }
1638
                break;
4✔
1639
            // Comparison operators
1640
            // All comparison operators result in boolean
1641
            case TokenKind.Equal:
1642
            case TokenKind.LessGreater:
1643
                // = and <> can accept invalid / dynamic
1644
                if (hasDynamic || hasInvalid || bothStrings || eitherBooleanOrNum) {
80✔
1645
                    return BooleanType.instance;
77✔
1646
                }
1647
                break;
3✔
1648
            case TokenKind.Greater:
1649
            case TokenKind.Less:
1650
            case TokenKind.GreaterEqual:
1651
            case TokenKind.LessEqual:
1652
                if (bothStrings || bothNumbers) {
23✔
1653
                    return BooleanType.instance;
11✔
1654
                }
1655
                break;
12✔
1656
            // Logical or bitwise operators
1657
            case TokenKind.Or:
1658
            case TokenKind.And:
1659
                if (bothNumbers) {
52✔
1660
                    // "and"/"or" represent bitwise operators
1661
                    if (hasLongInteger && !hasDouble && !hasFloat) {
12✔
1662
                        // 2 long ints or long int and int
1663
                        return LongIntegerType.instance;
1✔
1664
                    }
1665
                    return IntegerType.instance;
11✔
1666
                } else if (eitherBooleanOrNum) {
40✔
1667
                    // "and"/"or" represent logical operators
1668
                    return BooleanType.instance;
33✔
1669
                }
1670
                break;
7✔
1671
        }
1672
        return DynamicType.instance;
61✔
1673
    }
1674

1675
    /**
1676
     * Return the type of the result of a binary operator
1677
     */
1678
    public unaryOperatorResultType(operator: Token, exprType: BscType): BscType {
1679
        // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
1680
        switch (operator.kind) {
86✔
1681
            // Math operators
1682
            case TokenKind.Minus:
82✔
1683
                if (isNumberType(exprType)) {
59✔
1684
                    // a negative number will be the same type, eg, double->double, int->int, etc.
1685
                    return exprType;
49✔
1686
                }
1687
                break;
10✔
1688
            case TokenKind.Not:
1689
                if (isBooleanType(exprType)) {
23✔
1690
                    return BooleanType.instance;
10✔
1691
                } else if (isNumberType(exprType)) {
13✔
1692
                    //numbers can be "notted"
1693
                    // by default they go to ints, except longints, which stay that way
1694
                    if (isLongIntegerType(exprType)) {
10✔
1695
                        return LongIntegerType.instance;
1✔
1696
                    }
1697
                    return IntegerType.instance;
9✔
1698
                }
1699
                break;
3✔
1700
        }
1701
        return DynamicType.instance;
17✔
1702
    }
1703

1704
    /**
1705
     * Get the extension for the given file path. Basically the part after the final dot, except for
1706
     * `d.bs` which is treated as single extension
1707
     * @returns the file extension (i.e. ".d.bs", ".bs", ".brs", ".xml", ".jpg", etc...)
1708
     */
1709
    public getExtension(filePath: string) {
1710
        filePath = filePath.toLowerCase();
2,570✔
1711
        if (filePath.endsWith('.d.bs')) {
2,570✔
1712
            return '.d.bs';
33✔
1713
        } else {
1714
            return path.extname(filePath).toLowerCase();
2,537✔
1715
        }
1716
    }
1717

1718
    /**
1719
     * Load and return the list of plugins
1720
     */
1721
    public loadPlugins(cwd: string, pathOrModules: string[], onError?: (pathOrModule: string, err: Error) => void): CompilerPlugin[] {
1722
        const logger = createLogger();
53✔
1723
        return pathOrModules.reduce<CompilerPlugin[]>((acc, pathOrModule) => {
53✔
1724
            if (typeof pathOrModule === 'string') {
6!
1725
                try {
6✔
1726
                    const loaded = requireRelative(pathOrModule, cwd);
6✔
1727
                    const theExport: CompilerPlugin | CompilerPluginFactory = loaded.default ? loaded.default : loaded;
6✔
1728

1729
                    let plugin: CompilerPlugin | undefined;
1730

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

1736
                        // the official plugin format is a factory function that returns a new instance of a plugin.
1737
                    } else if (typeof theExport === 'function') {
4!
1738
                        plugin = theExport();
4✔
1739
                    } else {
1740
                        //this should never happen; somehow an invalid plugin has made it into here
1741
                        throw new Error(`TILT: Encountered an invalid plugin: ${String(plugin)}`);
×
1742
                    }
1743

1744
                    if (!plugin.name) {
6!
1745
                        plugin.name = pathOrModule;
×
1746
                    }
1747
                    acc.push(plugin);
6✔
1748
                } catch (err: any) {
1749
                    if (onError) {
×
1750
                        onError(pathOrModule, err);
×
1751
                    } else {
1752
                        throw err;
×
1753
                    }
1754
                }
1755
            }
1756
            return acc;
6✔
1757
        }, []);
1758
    }
1759

1760
    /**
1761
     * Gathers expressions, variables, and unique names from an expression.
1762
     * This is mostly used for the ternary expression
1763
     */
1764
    public getExpressionInfo(expression: Expression, file: BrsFile): ExpressionInfo {
1765
        const expressions = [expression];
78✔
1766
        const variableExpressions = [] as VariableExpression[];
78✔
1767
        const uniqueVarNames = new Set<string>();
78✔
1768

1769
        function expressionWalker(expression) {
1770
            if (isExpression(expression)) {
120✔
1771
                expressions.push(expression);
116✔
1772
            }
1773
            if (isVariableExpression(expression)) {
120✔
1774
                variableExpressions.push(expression);
30✔
1775
                uniqueVarNames.add(expression.tokens.name.text);
30✔
1776
            }
1777
        }
1778

1779
        // Collect all expressions. Most of these expressions are fairly small so this should be quick!
1780
        // This should only be called during transpile time and only when we actually need it.
1781
        expression?.walk(expressionWalker, {
78✔
1782
            walkMode: WalkMode.visitExpressions
1783
        });
1784

1785
        //handle the expression itself (for situations when expression is a VariableExpression)
1786
        expressionWalker(expression);
78✔
1787

1788
        const scope = file.program.getFirstScopeForFile(file);
78✔
1789
        let filteredVarNames = [...uniqueVarNames];
78✔
1790
        if (scope) {
78!
1791
            filteredVarNames = filteredVarNames.filter((varName: string) => {
78✔
1792
                const varNameLower = varName.toLowerCase();
28✔
1793
                // TODO: include namespaces in this filter
1794
                return !scope.getEnumMap().has(varNameLower) &&
28✔
1795
                    !scope.getConstMap().has(varNameLower);
1796
            });
1797
        }
1798

1799
        return { expressions: expressions, varExpressions: variableExpressions, uniqueVarNames: filteredVarNames };
78✔
1800
    }
1801

1802

1803
    public concatAnnotationLeadingTrivia(stmt: Statement): Token[] {
1804
        return [...(stmt.annotations?.map(anno => anno.leadingTrivia ?? []).flat() ?? []), ...stmt.leadingTrivia];
168!
1805
    }
1806

1807
    /**
1808
     * Create a SourceNode that maps every line to itself. Useful for creating maps for files
1809
     * that haven't changed at all, but we still need the map
1810
     */
1811
    public simpleMap(source: string, src: string) {
1812
        //create a source map from the original source code
1813
        let chunks = [] as (SourceNode | string)[];
5✔
1814
        let lines = src.split(/\r?\n/g);
5✔
1815
        for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
5✔
1816
            let line = lines[lineIndex];
19✔
1817
            chunks.push(
19✔
1818
                lineIndex > 0 ? '\n' : '',
19✔
1819
                new SourceNode(lineIndex + 1, 0, source, line)
1820
            );
1821
        }
1822
        return new SourceNode(null, null, source, chunks);
5✔
1823
    }
1824

1825
    /**
1826
     * Converts a path into a standardized format (drive letter to lower, remove extra slashes, use single slash type, resolve relative parts, etc...)
1827
     */
1828
    public standardizePath(thePath: string) {
1829
        return util.driveLetterToLower(
11,186✔
1830
            rokuDeployStandardizePath(thePath)
1831
        );
1832
    }
1833

1834
    /**
1835
     * Given a Diagnostic or BsDiagnostic, return a deep clone of the diagnostic.
1836
     * @param diagnostic the diagnostic to clone
1837
     * @param relatedInformationFallbackLocation a default location to use for all `relatedInformation` entries that are missing a location
1838
     */
1839
    public toDiagnostic(diagnostic: Diagnostic | BsDiagnostic, relatedInformationFallbackLocation: string): Diagnostic {
1840
        let relatedInformation = diagnostic.relatedInformation ?? [];
15✔
1841
        if (relatedInformation.length > MAX_RELATED_INFOS_COUNT) {
15!
NEW
1842
            const relatedInfoLength = relatedInformation.length;
×
NEW
1843
            relatedInformation = relatedInformation.slice(0, MAX_RELATED_INFOS_COUNT);
×
NEW
1844
            relatedInformation.push({
×
1845
                message: `...and ${relatedInfoLength - MAX_RELATED_INFOS_COUNT} more`,
1846
                location: util.createLocationFromRange('   ', util.createRange(0, 0, 0, 0))
1847
            });
1848
        }
1849

1850
        const range = (diagnostic as BsDiagnostic).location?.range ??
15✔
1851
            (diagnostic as Diagnostic).range;
1852

1853
        let result = {
15✔
1854
            severity: diagnostic.severity,
1855
            range: range,
1856
            message: diagnostic.message,
1857
            relatedInformation: relatedInformation.map(x => {
1858

1859
                //clone related information just in case a plugin added circular ref info here
1860
                const clone = { ...x };
4✔
1861
                if (!clone.location) {
4✔
1862
                    // use the fallback location if available
1863
                    if (relatedInformationFallbackLocation) {
2✔
1864
                        clone.location = util.createLocationFromRange(relatedInformationFallbackLocation, range);
1✔
1865
                    } else {
1866
                        //remove this related information so it doesn't bring crash the language server
1867
                        return undefined;
1✔
1868
                    }
1869
                }
1870
                return clone;
3✔
1871
                //filter out null relatedInformation items
1872
            }).filter((x): x is DiagnosticRelatedInformation => Boolean(x)),
4✔
1873
            code: diagnostic.code,
1874
            source: 'brs'
1875
        } as Diagnostic;
1876
        if (diagnostic?.tags?.length > 0) {
15!
NEW
1877
            result.tags = diagnostic.tags;
×
1878
        }
1879
        return result;
15✔
1880
    }
1881

1882
    /**
1883
     * Get the first locatable item found at the specified position
1884
     * @param locatables an array of items that have a `range` property
1885
     * @param position the position that the locatable must contain
1886
     */
1887
    public getFirstLocatableAt(locatables: Locatable[], position: Position) {
1888
        for (let token of locatables) {
×
NEW
1889
            if (util.rangeContains(token.location?.range, position)) {
×
1890
                return token;
×
1891
            }
1892
        }
1893
    }
1894

1895
    /**
1896
     * Sort an array of objects that have a Range
1897
     */
1898
    public sortByRange<T extends { range: Range | undefined }>(locatables: T[]) {
1899
        //sort the tokens by range
1900
        return locatables.sort((a, b) => {
29✔
1901
            //handle undefined tokens to prevent crashes
1902
            if (!a?.range) {
252!
1903
                return 1;
1✔
1904
            }
1905
            if (!b?.range) {
251!
NEW
1906
                return -1;
×
1907
            }
1908

1909
            //start line
1910
            if (a.range.start.line < b.range.start.line) {
251!
UNCOV
1911
                return -1;
×
1912
            }
1913
            if (a.range.start.line > b.range.start.line) {
251✔
1914
                return 1;
159✔
1915
            }
1916
            //start char
1917
            if (a.range.start.character < b.range.start.character) {
92✔
1918
                return -1;
60✔
1919
            }
1920
            if (a.range.start.character > b.range.start.character) {
32!
1921
                return 1;
32✔
1922
            }
1923
            //end line
1924
            if (a.range.end.line < b.range.end.line) {
×
1925
                return -1;
×
1926
            }
1927
            if (a.range.end.line > b.range.end.line) {
×
1928
                return 1;
×
1929
            }
1930
            //end char
1931
            if (a.range.end.character < b.range.end.character) {
×
1932
                return -1;
×
1933
            } else if (a.range.end.character > b.range.end.character) {
×
1934
                return 1;
×
1935
            }
1936
            return 0;
×
1937
        });
1938
    }
1939

1940
    /**
1941
     * Split the given text and return ranges for each chunk.
1942
     * Only works for single-line strings
1943
     */
1944
    public splitGetRange(separator: string, text: string, range: Range) {
1945
        const chunks = text.split(separator);
3✔
1946
        const result = [] as Array<{ text: string; range: Range }>;
3✔
1947
        let offset = 0;
3✔
1948
        for (let chunk of chunks) {
3✔
1949
            //only keep nonzero chunks
1950
            if (chunk.length > 0) {
8✔
1951
                result.push({
7✔
1952
                    text: chunk,
1953
                    range: this.createRange(
1954
                        range.start.line,
1955
                        range.start.character + offset,
1956
                        range.end.line,
1957
                        range.start.character + offset + chunk.length
1958
                    )
1959
                });
1960
            }
1961
            offset += chunk.length + separator.length;
8✔
1962
        }
1963
        return result;
3✔
1964
    }
1965

1966
    /**
1967
     * Wrap the given code in a markdown code fence (with the language)
1968
     */
1969
    public mdFence(code: string, language = '') {
×
1970
        return '```' + language + '\n' + code + '\n```';
120✔
1971
    }
1972

1973
    /**
1974
     * Gets each part of the dotted get.
1975
     * @param node any ast expression
1976
     * @returns an array of the parts of the dotted get. If not fully a dotted get, then returns undefined
1977
     */
1978
    public getAllDottedGetParts(node: AstNode): Identifier[] | undefined {
1979
        //this is a hot function and has been optimized. Don't rewrite unless necessary
1980
        const parts: Identifier[] = [];
11,575✔
1981
        let nextPart = node;
11,575✔
1982
        loop: while (nextPart) {
11,575✔
1983
            switch (nextPart?.kind) {
17,179!
1984
                case AstNodeKind.AssignmentStatement:
17,179!
1985
                    return [(node as AssignmentStatement).tokens.name];
9✔
1986
                case AstNodeKind.DottedGetExpression:
1987
                    parts.push((nextPart as DottedGetExpression)?.tokens.name);
5,533!
1988
                    nextPart = (nextPart as DottedGetExpression).obj;
5,533✔
1989
                    continue;
5,533✔
1990
                case AstNodeKind.CallExpression:
1991
                    nextPart = (nextPart as CallExpression).callee;
39✔
1992
                    continue;
39✔
1993
                case AstNodeKind.TypeExpression:
NEW
1994
                    nextPart = (nextPart as TypeExpression).expression;
×
NEW
1995
                    continue;
×
1996
                case AstNodeKind.VariableExpression:
1997
                    parts.push((nextPart as VariableExpression)?.tokens.name);
11,465!
1998
                    break loop;
11,465✔
1999
                case AstNodeKind.LiteralExpression:
2000
                    parts.push((nextPart as LiteralExpression)?.tokens.value as Identifier);
4!
2001
                    break loop;
4✔
2002
                case AstNodeKind.IndexedGetExpression:
2003
                    nextPart = (nextPart as unknown as IndexedGetExpression).obj;
35✔
2004
                    continue;
35✔
2005
                case AstNodeKind.FunctionParameterExpression:
2006
                    return [(nextPart as FunctionParameterExpression).tokens.name];
6✔
2007
                case AstNodeKind.GroupingExpression:
2008
                    parts.push(createIdentifier('()', nextPart.location));
6✔
2009
                    break loop;
6✔
2010
                default:
2011
                    //we found a non-DottedGet expression, so return because this whole operation is invalid.
2012
                    return undefined;
82✔
2013
            }
2014
        }
2015
        return parts.reverse();
11,478✔
2016
    }
2017

2018
    /**
2019
     * Given an expression, return all the DottedGet name parts as a string.
2020
     * Mostly used to convert namespaced item full names to a strings
2021
     */
2022
    public getAllDottedGetPartsAsString(node: Expression | Statement, parseMode = ParseMode.BrighterScript): string {
1,935✔
2023
        //this is a hot function and has been optimized. Don't rewrite unless necessary
2024
        /* eslint-disable no-var */
2025
        var sep = parseMode === ParseMode.BrighterScript ? '.' : '_';
10,443✔
2026
        const parts = this.getAllDottedGetParts(node) ?? [];
10,443✔
2027
        var result = parts[0]?.text;
10,443✔
2028
        for (var i = 1; i < parts.length; i++) {
10,443✔
2029
            result += sep + parts[i].text;
4,794✔
2030
        }
2031
        return result;
10,443✔
2032
        /* eslint-enable no-var */
2033
    }
2034

2035
    public stringJoin(strings: string[], separator: string) {
2036
        // eslint-disable-next-line no-var
NEW
2037
        var result = strings[0] ?? '';
×
2038
        // eslint-disable-next-line no-var
NEW
2039
        for (var i = 1; i < strings.length; i++) {
×
NEW
2040
            result += separator + strings[i];
×
2041
        }
NEW
2042
        return result;
×
2043
    }
2044

2045
    /**
2046
     * Break an expression into each part.
2047
     */
2048
    public splitExpression(expression: Expression) {
2049
        const parts: Expression[] = [expression];
10,003✔
2050
        let nextPart = expression;
10,003✔
2051
        while (nextPart) {
10,003✔
2052
            if (isDottedGetExpression(nextPart) || isIndexedGetExpression(nextPart) || isXmlAttributeGetExpression(nextPart)) {
12,559✔
2053
                nextPart = nextPart.obj;
1,002✔
2054

2055
            } else if (isCallExpression(nextPart) || isCallfuncExpression(nextPart)) {
11,557✔
2056
                nextPart = nextPart.callee;
1,554✔
2057

2058
            } else if (isTypeExpression(nextPart)) {
10,003!
2059
                nextPart = nextPart.expression;
×
2060
            } else {
2061
                break;
10,003✔
2062
            }
2063
            parts.unshift(nextPart);
2,556✔
2064
        }
2065
        return parts;
10,003✔
2066
    }
2067

2068
    /**
2069
     * Break an expression into each part, and return any VariableExpression or DottedGet expresisons from left-to-right.
2070
     */
2071
    public getDottedGetPath(expression: Expression): [VariableExpression, ...DottedGetExpression[]] {
UNCOV
2072
        let parts: Expression[] = [];
×
UNCOV
2073
        let nextPart = expression;
×
NEW
2074
        loop: while (nextPart) {
×
NEW
2075
            switch (nextPart?.kind) {
×
2076
                case AstNodeKind.DottedGetExpression:
×
NEW
2077
                    parts.push(nextPart);
×
NEW
2078
                    nextPart = (nextPart as DottedGetExpression).obj;
×
NEW
2079
                    continue;
×
2080
                case AstNodeKind.IndexedGetExpression:
2081
                case AstNodeKind.XmlAttributeGetExpression:
NEW
2082
                    nextPart = (nextPart as IndexedGetExpression | XmlAttributeGetExpression).obj;
×
NEW
2083
                    parts = [];
×
NEW
2084
                    continue;
×
2085
                case AstNodeKind.CallExpression:
2086
                case AstNodeKind.CallfuncExpression:
NEW
2087
                    nextPart = (nextPart as CallExpression | CallfuncExpression).callee;
×
NEW
2088
                    parts = [];
×
NEW
2089
                    continue;
×
2090
                case AstNodeKind.NewExpression:
NEW
2091
                    nextPart = (nextPart as NewExpression).call.callee;
×
NEW
2092
                    parts = [];
×
NEW
2093
                    continue;
×
2094
                case AstNodeKind.TypeExpression:
NEW
2095
                    nextPart = (nextPart as TypeExpression).expression;
×
NEW
2096
                    continue;
×
2097
                case AstNodeKind.VariableExpression:
NEW
2098
                    parts.push(nextPart);
×
NEW
2099
                    break loop;
×
2100
                default:
NEW
2101
                    return [] as any;
×
2102
            }
2103
        }
NEW
2104
        return parts.reverse() as any;
×
2105
    }
2106

2107
    /**
2108
     * Returns an integer if valid, or undefined. Eliminates checking for NaN
2109
     */
2110
    public parseInt(value: any) {
2111
        const result = parseInt(value);
34✔
2112
        if (!isNaN(result)) {
34✔
2113
            return result;
29✔
2114
        } else {
2115
            return undefined;
5✔
2116
        }
2117
    }
2118

2119
    /**
2120
     * Converts a range to a string in the format 1:2-3:4
2121
     */
2122
    public rangeToString(range: Range) {
2123
        return `${range?.start?.line}:${range?.start?.character}-${range?.end?.line}:${range?.end?.character}`;
1,849✔
2124
    }
2125

2126
    public validateTooDeepFile(file: (BrsFile | XmlFile)) {
2127
        //find any files nested too deep
2128
        let destPath = file?.destPath?.toString();
1,909!
2129
        let rootFolder = destPath?.replace(/^pkg:/, '').split(/[\\\/]/)[0].toLowerCase();
1,909!
2130

2131
        if (isBrsFile(file) && rootFolder !== 'source') {
1,909✔
2132
            return;
277✔
2133
        }
2134

2135
        if (isXmlFile(file) && rootFolder !== 'components') {
1,632!
2136
            return;
×
2137
        }
2138

2139
        let fileDepth = this.getParentDirectoryCount(destPath);
1,632✔
2140
        if (fileDepth >= 8) {
1,632✔
2141
            file.program?.diagnostics.register({
3!
2142
                ...DiagnosticMessages.detectedTooDeepFileSource(fileDepth),
2143
                location: util.createLocationFromFileRange(file, this.createRange(0, 0, 0, Number.MAX_VALUE))
2144
            });
2145
        }
2146
    }
2147

2148
    /**
2149
     * Wraps SourceNode's constructor to be compatible with the TranspileResult type
2150
     */
2151
    public sourceNodeFromTranspileResult(
2152
        line: number | null,
2153
        column: number | null,
2154
        source: string | null,
2155
        chunks?: string | SourceNode | TranspileResult,
2156
        name?: string
2157
    ): SourceNode {
2158
        // we can use a typecast rather than actually transforming the data because SourceNode
2159
        // accepts a more permissive type than its typedef states
2160
        return new SourceNode(line, column, source, chunks as any, name);
7,734✔
2161
    }
2162

2163
    /**
2164
     * Find the index of the last item in the array that matches.
2165
     */
2166
    public findLastIndex<T>(array: T[], matcher: (T) => boolean) {
2167
        for (let i = array.length - 1; i >= 0; i--) {
27✔
2168
            if (matcher(array[i])) {
24✔
2169
                return i;
16✔
2170
            }
2171
        }
2172
    }
2173

2174
    public processTypeChain(typeChain: TypeChainEntry[]): TypeChainProcessResult {
2175
        let fullChainName = '';
1,064✔
2176
        let fullErrorName = '';
1,064✔
2177
        let itemName = '';
1,064✔
2178
        let previousTypeName = '';
1,064✔
2179
        let parentTypeName = '';
1,064✔
2180
        let itemTypeKind = '';
1,064✔
2181
        let parentTypeKind = '';
1,064✔
2182
        let astNode: AstNode;
2183
        let errorLocation: Location;
2184
        let containsDynamic = false;
1,064✔
2185
        let continueResolvingAllItems = true;
1,064✔
2186
        for (let i = 0; i < typeChain.length; i++) {
1,064✔
2187
            const chainItem = typeChain[i];
2,116✔
2188
            const dotSep = chainItem.separatorToken?.text ?? '.';
2,116!
2189
            if (i > 0) {
2,116✔
2190
                fullChainName += dotSep;
1,054✔
2191
            }
2192
            fullChainName += chainItem.name;
2,116✔
2193
            if (continueResolvingAllItems) {
2,116✔
2194
                parentTypeName = previousTypeName;
1,926✔
2195
                parentTypeKind = itemTypeKind;
1,926✔
2196
                fullErrorName = previousTypeName ? `${previousTypeName}${dotSep}${chainItem.name}` : chainItem.name;
1,926✔
2197
                itemTypeKind = (chainItem.type as any)?.kind;
1,926✔
2198

2199
                let typeString = chainItem.type?.toString();
1,926✔
2200
                let typeToFindStringFor = chainItem.type;
1,926✔
2201
                while (typeToFindStringFor) {
1,926✔
2202
                    if (isUnionType(chainItem.type)) {
1,922✔
2203
                        typeString = `(${typeToFindStringFor.toString()})`;
7✔
2204
                        break;
7✔
2205
                    } else if (isCallableType(typeToFindStringFor)) {
1,915✔
2206
                        if (isTypedFunctionType(typeToFindStringFor) && i < typeChain.length - 1) {
37✔
2207
                            typeToFindStringFor = typeToFindStringFor.returnType;
10✔
2208
                        } else {
2209
                            typeString = 'function';
27✔
2210
                            break;
27✔
2211
                        }
2212
                        parentTypeName = previousTypeName;
10✔
2213
                    } else if (isNamespaceType(typeToFindStringFor) && parentTypeName) {
1,878✔
2214
                        const chainItemTypeName = typeToFindStringFor.toString();
334✔
2215
                        typeString = parentTypeName + '.' + chainItemTypeName;
334✔
2216
                        if (chainItemTypeName.toLowerCase().startsWith(parentTypeName.toLowerCase())) {
334!
2217
                            // the following namespace already knows...
2218
                            typeString = chainItemTypeName;
334✔
2219
                        }
2220
                        break;
334✔
2221
                    } else {
2222
                        typeString = typeToFindStringFor?.toString();
1,544!
2223
                        break;
1,544✔
2224
                    }
2225
                }
2226

2227
                previousTypeName = typeString ?? '';
1,926✔
2228
                itemName = chainItem.name;
1,926✔
2229
                astNode = chainItem.astNode;
1,926✔
2230
                containsDynamic = containsDynamic || (isDynamicType(chainItem.type) && !isAnyReferenceType(chainItem.type));
1,926✔
2231
                if (!chainItem.isResolved) {
1,926✔
2232
                    errorLocation = chainItem.location;
922✔
2233
                    continueResolvingAllItems = false;
922✔
2234
                }
2235
            }
2236
        }
2237
        return {
1,064✔
2238
            itemName: itemName,
2239
            itemTypeKind: itemTypeKind,
2240
            itemParentTypeName: parentTypeName,
2241
            itemParentTypeKind: parentTypeKind,
2242
            fullNameOfItem: fullErrorName,
2243
            fullChainName: fullChainName,
2244
            location: errorLocation,
2245
            containsDynamic: containsDynamic,
2246
            astNode: astNode
2247
        };
2248
    }
2249

2250

2251
    public isInTypeExpression(expression: AstNode): boolean {
2252
        //TODO: this is much faster than node.findAncestor(), but may need to be updated for "complicated" type expressions
2253
        if (isTypeExpression(expression) ||
15,120✔
2254
            isTypeExpression(expression.parent) ||
2255
            isTypedArrayExpression(expression) ||
2256
            isTypedArrayExpression(expression.parent)) {
2257
            return true;
4,374✔
2258
        }
2259
        if (isBinaryExpression(expression.parent)) {
10,746✔
2260
            let currentExpr: AstNode = expression.parent;
2,141✔
2261
            while (isBinaryExpression(currentExpr) && currentExpr.tokens.operator.kind === TokenKind.Or) {
2,141✔
2262
                currentExpr = currentExpr.parent;
118✔
2263
            }
2264
            return isTypeExpression(currentExpr) || isTypedArrayExpression(currentExpr);
2,141✔
2265
        }
2266
        return false;
8,605✔
2267
    }
2268

2269
    public hasAnyRequiredSymbolChanged(requiredSymbols: UnresolvedSymbol[], changedSymbols: Map<SymbolTypeFlag, Set<string>>) {
2270
        if (!requiredSymbols || !changedSymbols) {
1,802!
NEW
2271
            return false;
×
2272
        }
2273
        const runTimeChanges = changedSymbols.get(SymbolTypeFlag.runtime);
1,802✔
2274
        const typeTimeChanges = changedSymbols.get(SymbolTypeFlag.typetime);
1,802✔
2275

2276
        for (const symbol of requiredSymbols) {
1,802✔
2277
            if (this.setContainsUnresolvedSymbol(runTimeChanges, symbol) || this.setContainsUnresolvedSymbol(typeTimeChanges, symbol)) {
637✔
2278
                return true;
299✔
2279
            }
2280
        }
2281

2282
        return false;
1,503✔
2283
    }
2284

2285
    public setContainsUnresolvedSymbol(symbolLowerNameSet: Set<string>, symbol: UnresolvedSymbol) {
2286
        if (!symbolLowerNameSet || symbolLowerNameSet.size === 0) {
986✔
2287
            return false;
361✔
2288
        }
2289

2290
        for (const possibleNameLower of symbol.lookups) {
625✔
2291
            if (symbolLowerNameSet.has(possibleNameLower)) {
2,241✔
2292
                return true;
299✔
2293
            }
2294
        }
2295
        return false;
326✔
2296
    }
2297

2298
    public truncate<T>(options: {
2299
        leadingText: string;
2300
        items: T[];
2301
        trailingText?: string;
2302
        maxLength: number;
2303
        itemSeparator?: string;
2304
        partBuilder?: (item: T) => string;
2305
    }): string {
2306
        let leadingText = options.leadingText;
19✔
2307
        let items = options?.items ?? [];
19!
2308
        let trailingText = options?.trailingText ?? '';
19!
2309
        let maxLength = options?.maxLength ?? 160;
19!
2310
        let itemSeparator = options?.itemSeparator ?? ', ';
19!
2311
        let partBuilder = options?.partBuilder ?? ((x) => x.toString());
19!
2312

2313
        let parts = [];
19✔
2314
        let length = leadingText.length + (trailingText?.length ?? 0);
19!
2315

2316
        //calculate the max number of items we could fit in the given space
2317
        for (let i = 0; i < items.length; i++) {
19✔
2318
            let part = partBuilder(items[i]);
91✔
2319
            if (i > 0) {
91✔
2320
                part = itemSeparator + part;
72✔
2321
            }
2322
            parts.push(part);
91✔
2323
            length += part.length;
91✔
2324
            //exit the loop if we've maxed out our length
2325
            if (length >= maxLength) {
91✔
2326
                break;
6✔
2327
            }
2328
        }
2329
        let message: string;
2330
        //we have enough space to include all the parts
2331
        if (parts.length >= items.length) {
19✔
2332
            message = leadingText + parts.join('') + trailingText;
13✔
2333

2334
            //we require truncation
2335
        } else {
2336
            //account for truncation message length including max possible "more" items digits, trailing text length, and the separator between last item and trailing text
2337
            length = leadingText.length + `...and ${items.length} more`.length + itemSeparator.length + (trailingText?.length ?? 0);
6!
2338
            message = leadingText;
6✔
2339
            for (let i = 0; i < parts.length; i++) {
6✔
2340
                //always include at least 2 items. if this part would overflow the max, then skip it and finalize the message
2341
                if (i > 1 && length + parts[i].length > maxLength) {
47✔
2342
                    message += itemSeparator + `...and ${items.length - i} more` + trailingText;
6✔
2343
                    return message;
6✔
2344
                } else {
2345
                    message += parts[i];
41✔
2346
                    length += parts[i].length;
41✔
2347
                }
2348
            }
2349
        }
2350
        return message;
13✔
2351
    }
2352

2353
    public getAstNodeFriendlyName(node: AstNode) {
2354
        return node?.kind.replace(/Statement|Expression/g, '');
235!
2355
    }
2356

2357

2358
    public hasLeadingComments(input: Token | AstNode) {
2359
        const leadingTrivia = isToken(input) ? input?.leadingTrivia : input?.leadingTrivia ?? [];
6,894!
2360
        return !!leadingTrivia.find(t => t.kind === TokenKind.Comment);
14,103✔
2361
    }
2362

2363
    public getLeadingComments(input: Token | AstNode) {
2364
        const leadingTrivia = isToken(input) ? input?.leadingTrivia : input?.leadingTrivia ?? [];
10,940!
2365
        return leadingTrivia.filter(t => t.kind === TokenKind.Comment);
33,667✔
2366
    }
2367

2368
    public isLeadingCommentOnSameLine(line: RangeLike, input: Token | AstNode) {
2369
        const leadingCommentRange = this.getLeadingComments(input)?.[0];
10,139!
2370
        if (leadingCommentRange) {
10,139✔
2371
            return this.linesTouch(line, leadingCommentRange?.location);
1,488!
2372
        }
2373
        return false;
8,651✔
2374
    }
2375

2376
    public isClassUsedAsFunction(potentialClassType: BscType, expression: Expression, options: GetTypeOptions) {
2377
        // eslint-disable-next-line no-bitwise
2378
        if ((options?.flags ?? 0) & SymbolTypeFlag.runtime &&
22,597!
2379
            isClassType(potentialClassType) &&
2380
            !options.isExistenceTest &&
2381
            potentialClassType.name?.toLowerCase() === this.getAllDottedGetPartsAsString(expression)?.toLowerCase() &&
6,210✔
2382
            !expression?.findAncestor(isNewExpression)) {
1,224✔
2383
            return true;
32✔
2384
        }
2385
        return false;
22,565✔
2386
    }
2387

2388
    public getSpecialCaseCallExpressionReturnType(callExpr: CallExpression) {
2389
        if (isVariableExpression(callExpr.callee) && callExpr.callee.tokens.name.text.toLowerCase() === 'createobject') {
625✔
2390
            const componentName = isLiteralString(callExpr.args[0]) ? callExpr.args[0].tokens.value?.text?.replace(/"/g, '') : '';
116!
2391
            const nodeType = componentName.toLowerCase() === 'rosgnode' && isLiteralString(callExpr.args[1]) ? callExpr.args[1].tokens.value?.text?.replace(/"/g, '') : '';
116!
2392
            if (componentName?.toLowerCase().startsWith('ro')) {
116!
2393
                const fullName = componentName + nodeType;
102✔
2394
                const data = {};
102✔
2395
                const symbolTable = callExpr.getSymbolTable();
102✔
2396
                const foundType = symbolTable.getSymbolType(fullName, {
102✔
2397
                    flags: SymbolTypeFlag.typetime,
2398
                    data: data,
2399
                    tableProvider: () => callExpr?.getSymbolTable(),
117!
2400
                    fullName: fullName
2401
                });
2402
                if (foundType) {
102!
2403
                    return foundType;
102✔
2404
                }
2405
            }
2406
        }
2407
    }
2408

2409
    public symbolComesFromSameNode(symbolName: string, definingNode: AstNode, symbolTable: SymbolTable) {
2410
        let nsData: ExtraSymbolData = {};
553✔
2411
        symbolTable.getSymbolType(symbolName, { flags: SymbolTypeFlag.runtime, data: nsData });
553✔
2412

2413
        if (definingNode === nsData?.definingNode) {
553!
2414
            return true;
362✔
2415
        }
2416
        return false;
191✔
2417
    }
2418

2419
    public isCalleeMemberOfNamespace(symbolName: string, nodeWhereUsed: AstNode, namespace?: NamespaceStatement) {
2420
        namespace = namespace ?? nodeWhereUsed.findAncestor<NamespaceStatement>(isNamespaceStatement);
39!
2421

2422
        if (!this.isVariableMemberOfNamespace(symbolName, nodeWhereUsed, namespace)) {
39✔
2423
            return false;
18✔
2424
        }
2425
        const exprType = nodeWhereUsed.getType({ flags: SymbolTypeFlag.runtime });
21✔
2426

2427
        if (isCallableType(exprType) || isClassType(exprType)) {
21✔
2428
            return true;
8✔
2429
        }
2430
        return false;
13✔
2431
    }
2432

2433
    public isVariableMemberOfNamespace(symbolName: string, nodeWhereUsed: AstNode, namespace?: NamespaceStatement) {
2434
        namespace = namespace ?? nodeWhereUsed.findAncestor<NamespaceStatement>(isNamespaceStatement);
1,701✔
2435
        if (!isNamespaceStatement(namespace)) {
1,701✔
2436
            return false;
1,359✔
2437
        }
2438
        let varData: ExtraSymbolData = {};
342✔
2439
        nodeWhereUsed.getType({ flags: SymbolTypeFlag.runtime, data: varData });
342✔
2440
        return this.symbolComesFromSameNode(symbolName, varData?.definingNode, namespace.getSymbolTable());
342!
2441
    }
2442

2443
    public isVariableShadowingSomething(symbolName: string, nodeWhereUsed: AstNode) {
2444
        let varData: ExtraSymbolData = {};
6,094✔
2445
        let exprType = nodeWhereUsed.getType({ flags: SymbolTypeFlag.runtime, data: varData });
6,094✔
2446
        if (isReferenceType(exprType)) {
6,094✔
2447
            exprType = (exprType as any).getTarget();
5,718✔
2448
        }
2449
        const namespace = nodeWhereUsed?.findAncestor<NamespaceStatement>(isNamespaceStatement);
6,094!
2450

2451
        if (isNamespaceStatement(namespace)) {
6,094✔
2452
            let namespaceHasSymbol = namespace.getSymbolTable().hasSymbol(symbolName, SymbolTypeFlag.runtime);
54✔
2453
            // check if the namespace has a symbol with the same name, but different definiton
2454
            if (namespaceHasSymbol && !this.symbolComesFromSameNode(symbolName, varData.definingNode, namespace.getSymbolTable())) {
54✔
2455
                return true;
14✔
2456
            }
2457
        }
2458
        const bodyTable = nodeWhereUsed.getRoot().getSymbolTable();
6,080✔
2459
        const hasSymbolAtFileLevel = bodyTable.hasSymbol(symbolName, SymbolTypeFlag.runtime);
6,080✔
2460
        if (hasSymbolAtFileLevel && !this.symbolComesFromSameNode(symbolName, varData.definingNode, bodyTable)) {
6,080✔
2461
            return true;
8✔
2462
        }
2463

2464
        return false;
6,072✔
2465
    }
2466

2467
    public chooseTypeFromCodeOrDocComment(codeType: BscType, docType: BscType, options: GetTypeOptions) {
2468
        let returnType: BscType;
2469
        if (options.preferDocType && docType) {
10,211!
NEW
2470
            returnType = docType;
×
NEW
2471
            if (options.data) {
×
NEW
2472
                options.data.isFromDocComment = true;
×
2473
            }
2474
        } else {
2475
            returnType = codeType;
10,211✔
2476
            if (!returnType && docType) {
10,211✔
2477
                returnType = docType;
65✔
2478
                if (options.data) {
65✔
2479
                    options.data.isFromDocComment = true;
19✔
2480
                }
2481
            }
2482
        }
2483
        return returnType;
10,211✔
2484
    }
2485
}
2486

2487
/**
2488
 * 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,
2489
 * we can't use `object.tag` syntax.
2490
 */
2491
export function standardizePath(stringParts, ...expressions: any[]) {
1✔
2492
    let result: string[] = [];
21,606✔
2493
    for (let i = 0; i < stringParts.length; i++) {
21,606✔
2494
        result.push(stringParts[i], expressions[i]);
212,822✔
2495
    }
2496
    return util.driveLetterToLower(
21,606✔
2497
        rokuDeployStandardizePath(
2498
            result.join('')
2499
        )
2500
    );
2501
}
2502

2503
/**
2504
 * An item that can be coerced into a `Range`
2505
 */
2506
export type RangeLike = { location?: Location } | Location | { range?: Range } | Range | undefined;
2507

2508
export let util = new Util();
1✔
2509
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