@under18dev/veritas-code-intelligence 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +12 -2
- package/dist/analyze.d.ts +14 -0
- package/dist/analyze.d.ts.map +1 -0
- package/dist/analyze.js +974 -0
- package/dist/analyze.js.map +1 -0
- package/dist/files.d.ts +20 -0
- package/dist/files.d.ts.map +1 -0
- package/dist/files.js +79 -0
- package/dist/files.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/infer.d.ts +20 -0
- package/dist/infer.d.ts.map +1 -0
- package/dist/infer.js +304 -0
- package/dist/infer.js.map +1 -0
- package/dist/schema.d.ts +315 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +62 -0
- package/dist/schema.js.map +1 -0
- package/package.json +26 -3
package/dist/analyze.js
ADDED
|
@@ -0,0 +1,974 @@
|
|
|
1
|
+
import { realpathSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { resolveInsideRoot, sha256, symbolId, } from '@under18dev/veritas-core';
|
|
4
|
+
import ts from 'typescript';
|
|
5
|
+
import { selectFiles } from './files.js';
|
|
6
|
+
const DEFAULT_OPTIONS = {
|
|
7
|
+
target: ts.ScriptTarget.ES2024,
|
|
8
|
+
module: ts.ModuleKind.ESNext,
|
|
9
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
10
|
+
strict: true,
|
|
11
|
+
allowJs: true,
|
|
12
|
+
checkJs: false,
|
|
13
|
+
skipLibCheck: true,
|
|
14
|
+
types: [],
|
|
15
|
+
};
|
|
16
|
+
const NUMERIC_KIND_ORDER = ['integer_literal', 'float_literal', 'division', 'nan', 'bigint'];
|
|
17
|
+
const COMPARISON_OPERATORS = new Map([
|
|
18
|
+
[ts.SyntaxKind.LessThanToken, '<'],
|
|
19
|
+
[ts.SyntaxKind.LessThanEqualsToken, '<='],
|
|
20
|
+
[ts.SyntaxKind.GreaterThanToken, '>'],
|
|
21
|
+
[ts.SyntaxKind.GreaterThanEqualsToken, '>='],
|
|
22
|
+
[ts.SyntaxKind.EqualsEqualsEqualsToken, '==='],
|
|
23
|
+
[ts.SyntaxKind.ExclamationEqualsEqualsToken, '!=='],
|
|
24
|
+
[ts.SyntaxKind.EqualsEqualsToken, '=='],
|
|
25
|
+
[ts.SyntaxKind.ExclamationEqualsToken, '!='],
|
|
26
|
+
]);
|
|
27
|
+
const ARITHMETIC_OPERATORS = new Set([
|
|
28
|
+
ts.SyntaxKind.MinusToken,
|
|
29
|
+
ts.SyntaxKind.AsteriskToken,
|
|
30
|
+
ts.SyntaxKind.AsteriskAsteriskToken,
|
|
31
|
+
ts.SyntaxKind.SlashToken,
|
|
32
|
+
ts.SyntaxKind.PercentToken,
|
|
33
|
+
ts.SyntaxKind.MinusEqualsToken,
|
|
34
|
+
ts.SyntaxKind.AsteriskEqualsToken,
|
|
35
|
+
ts.SyntaxKind.AsteriskAsteriskEqualsToken,
|
|
36
|
+
ts.SyntaxKind.SlashEqualsToken,
|
|
37
|
+
ts.SyntaxKind.PercentEqualsToken,
|
|
38
|
+
]);
|
|
39
|
+
/** Globals whose use is a side effect (I/O, ambient state, scheduling, non-determinism). */
|
|
40
|
+
const IMPURE_GLOBALS = new Set([
|
|
41
|
+
'console',
|
|
42
|
+
'process',
|
|
43
|
+
'fetch',
|
|
44
|
+
'XMLHttpRequest',
|
|
45
|
+
'WebSocket',
|
|
46
|
+
'EventSource',
|
|
47
|
+
'localStorage',
|
|
48
|
+
'sessionStorage',
|
|
49
|
+
'indexedDB',
|
|
50
|
+
'document',
|
|
51
|
+
'window',
|
|
52
|
+
'navigator',
|
|
53
|
+
'location',
|
|
54
|
+
'globalThis',
|
|
55
|
+
'global',
|
|
56
|
+
'self',
|
|
57
|
+
'setTimeout',
|
|
58
|
+
'setInterval',
|
|
59
|
+
'setImmediate',
|
|
60
|
+
'clearTimeout',
|
|
61
|
+
'clearInterval',
|
|
62
|
+
'clearImmediate',
|
|
63
|
+
'queueMicrotask',
|
|
64
|
+
'requestAnimationFrame',
|
|
65
|
+
'require',
|
|
66
|
+
'alert',
|
|
67
|
+
'prompt',
|
|
68
|
+
'confirm',
|
|
69
|
+
'performance',
|
|
70
|
+
'crypto',
|
|
71
|
+
'Deno',
|
|
72
|
+
'Bun',
|
|
73
|
+
]);
|
|
74
|
+
/** Modules whose imports perform I/O or touch the host. */
|
|
75
|
+
const IO_MODULES = new Set([
|
|
76
|
+
'fs',
|
|
77
|
+
'fs/promises',
|
|
78
|
+
'child_process',
|
|
79
|
+
'http',
|
|
80
|
+
'https',
|
|
81
|
+
'http2',
|
|
82
|
+
'net',
|
|
83
|
+
'tls',
|
|
84
|
+
'dgram',
|
|
85
|
+
'dns',
|
|
86
|
+
'dns/promises',
|
|
87
|
+
'os',
|
|
88
|
+
'process',
|
|
89
|
+
'readline',
|
|
90
|
+
'worker_threads',
|
|
91
|
+
'cluster',
|
|
92
|
+
'crypto',
|
|
93
|
+
'vm',
|
|
94
|
+
'module',
|
|
95
|
+
'v8',
|
|
96
|
+
'inspector',
|
|
97
|
+
'perf_hooks',
|
|
98
|
+
'timers',
|
|
99
|
+
'timers/promises',
|
|
100
|
+
'stream',
|
|
101
|
+
'stream/promises',
|
|
102
|
+
'sqlite',
|
|
103
|
+
]);
|
|
104
|
+
const MUTATING_METHODS = new Set([
|
|
105
|
+
'push',
|
|
106
|
+
'pop',
|
|
107
|
+
'shift',
|
|
108
|
+
'unshift',
|
|
109
|
+
'splice',
|
|
110
|
+
'sort',
|
|
111
|
+
'reverse',
|
|
112
|
+
'fill',
|
|
113
|
+
'copyWithin',
|
|
114
|
+
'set',
|
|
115
|
+
'add',
|
|
116
|
+
'delete',
|
|
117
|
+
'clear',
|
|
118
|
+
]);
|
|
119
|
+
/**
|
|
120
|
+
* Statically index functions with the TypeScript Compiler API. Project code is parsed and
|
|
121
|
+
* type-checked, never executed.
|
|
122
|
+
*/
|
|
123
|
+
export function analyzeCode(options) {
|
|
124
|
+
const root = realpathSync(options.root);
|
|
125
|
+
const selection = selectFiles(root, options.config, options.files);
|
|
126
|
+
const diagnostics = [...selection.diagnostics];
|
|
127
|
+
const compilerOptions = loadCompilerOptions(root, options.config, diagnostics);
|
|
128
|
+
const program = createProgram(selection.files, compilerOptions);
|
|
129
|
+
const checker = program.getTypeChecker();
|
|
130
|
+
const ctx = new Context(root, program, checker, selection.files);
|
|
131
|
+
const indexed = [];
|
|
132
|
+
for (const file of selection.files) {
|
|
133
|
+
const sf = program.getSourceFile(file.absolute);
|
|
134
|
+
if (!sf) {
|
|
135
|
+
diagnostics.push({ file: file.path, message: 'skipped: the compiler did not load this file' });
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
for (const d of program.getSyntacticDiagnostics(sf)) {
|
|
139
|
+
const line = d.start === undefined ? null : sf.getLineAndCharacterOfPosition(d.start).line + 1;
|
|
140
|
+
const text = ts.flattenDiagnosticMessageText(d.messageText, ' ');
|
|
141
|
+
diagnostics.push({ file: file.path, message: line === null ? text : `line ${line}: ${text}` });
|
|
142
|
+
}
|
|
143
|
+
for (const target of collectFunctions(sf, diagnostics, file.path)) {
|
|
144
|
+
indexed.push(analyzeFunction(target, sf, file.path, ctx));
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
dedupeSymbols(indexed, diagnostics);
|
|
148
|
+
propagatePurity(indexed);
|
|
149
|
+
return {
|
|
150
|
+
files: selection.files.map((f) => ({ path: f.path, hash: sha256(f.content) })),
|
|
151
|
+
functions: indexed.map((i) => i.info),
|
|
152
|
+
diagnostics,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
function loadCompilerOptions(root, config, diagnostics) {
|
|
156
|
+
const tsconfig = config.project.tsconfig;
|
|
157
|
+
if (!tsconfig)
|
|
158
|
+
return DEFAULT_OPTIONS;
|
|
159
|
+
let file;
|
|
160
|
+
try {
|
|
161
|
+
// Rejects `..`, absolute paths and symlinks (or links in its parents) that leave the root.
|
|
162
|
+
file = resolveInsideRoot(root, tsconfig);
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
diagnostics.push({
|
|
166
|
+
file: tsconfig,
|
|
167
|
+
message: 'tsconfig outside the project root ignored; using defaults',
|
|
168
|
+
});
|
|
169
|
+
return DEFAULT_OPTIONS;
|
|
170
|
+
}
|
|
171
|
+
const read = ts.readConfigFile(file, ts.sys.readFile);
|
|
172
|
+
if (read.error) {
|
|
173
|
+
const text = ts.flattenDiagnosticMessageText(read.error.messageText, ' ');
|
|
174
|
+
diagnostics.push({ file: tsconfig, message: `tsconfig not usable, using defaults: ${text}` });
|
|
175
|
+
return DEFAULT_OPTIONS;
|
|
176
|
+
}
|
|
177
|
+
// `extends` chains are followed through this host, so a base config outside the root is never read.
|
|
178
|
+
const inside = (name) => {
|
|
179
|
+
try {
|
|
180
|
+
resolveInsideRoot(root, name);
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
const outside = new Set();
|
|
188
|
+
const host = {
|
|
189
|
+
useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
|
|
190
|
+
readDirectory: (dir, ...rest) => (inside(dir) ? ts.sys.readDirectory(dir, ...rest) : []),
|
|
191
|
+
fileExists: (name) => inside(name) && ts.sys.fileExists(name),
|
|
192
|
+
readFile: (name) => {
|
|
193
|
+
if (inside(name))
|
|
194
|
+
return ts.sys.readFile(name);
|
|
195
|
+
outside.add(name);
|
|
196
|
+
return undefined;
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
const parsed = ts.parseJsonConfigFileContent(read.config, host, path.dirname(file), undefined, file);
|
|
200
|
+
for (const name of outside)
|
|
201
|
+
diagnostics.push({ file: tsconfig, message: `config outside the project root not read: ${name}` });
|
|
202
|
+
for (const error of parsed.errors) {
|
|
203
|
+
if (error.code === 18003)
|
|
204
|
+
continue; // "no inputs found": we supply our own root files
|
|
205
|
+
diagnostics.push({ file: tsconfig, message: ts.flattenDiagnosticMessageText(error.messageText, ' ') });
|
|
206
|
+
}
|
|
207
|
+
return { ...parsed.options, allowJs: true, noEmit: true, types: parsed.options.types ?? [] };
|
|
208
|
+
}
|
|
209
|
+
function createProgram(files, options) {
|
|
210
|
+
const host = ts.createCompilerHost({ ...options, noEmit: true });
|
|
211
|
+
// Analyze exactly the bytes that were hashed.
|
|
212
|
+
const contents = new Map(files.map((f) => [path.normalize(f.absolute), f.content]));
|
|
213
|
+
const readFile = host.readFile.bind(host);
|
|
214
|
+
const fileExists = host.fileExists.bind(host);
|
|
215
|
+
const getSourceFile = host.getSourceFile.bind(host);
|
|
216
|
+
host.readFile = (name) => contents.get(path.normalize(name)) ?? readFile(name);
|
|
217
|
+
host.fileExists = (name) => contents.has(path.normalize(name)) || fileExists(name);
|
|
218
|
+
host.getSourceFile = (name, languageVersion, onError, shouldCreate) => {
|
|
219
|
+
const content = contents.get(path.normalize(name));
|
|
220
|
+
if (content !== undefined)
|
|
221
|
+
return ts.createSourceFile(name, content, languageVersion, true);
|
|
222
|
+
return getSourceFile(name, languageVersion, onError, shouldCreate);
|
|
223
|
+
};
|
|
224
|
+
return ts.createProgram({
|
|
225
|
+
rootNames: files.map((f) => f.absolute),
|
|
226
|
+
options: { ...options, noEmit: true },
|
|
227
|
+
host,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
class Context {
|
|
231
|
+
root;
|
|
232
|
+
program;
|
|
233
|
+
checker;
|
|
234
|
+
selected;
|
|
235
|
+
/** Declaration node -> exported name, per source file. */
|
|
236
|
+
exportNames = new Map();
|
|
237
|
+
loadedExports = new Set();
|
|
238
|
+
constructor(root, program, checker, selected) {
|
|
239
|
+
this.root = root;
|
|
240
|
+
this.program = program;
|
|
241
|
+
this.checker = checker;
|
|
242
|
+
this.selected = selected;
|
|
243
|
+
}
|
|
244
|
+
/** Project-relative POSIX path for files inside the root, null for libraries and outside files. */
|
|
245
|
+
projectPath(sf) {
|
|
246
|
+
if (sf.isDeclarationFile || this.program.isSourceFileDefaultLibrary(sf))
|
|
247
|
+
return null;
|
|
248
|
+
if (this.program.isSourceFileFromExternalLibrary(sf))
|
|
249
|
+
return null;
|
|
250
|
+
const rel = path.relative(this.root, sf.fileName);
|
|
251
|
+
if (rel.startsWith('..') || path.isAbsolute(rel))
|
|
252
|
+
return null;
|
|
253
|
+
const posix = rel.split(path.sep).join('/');
|
|
254
|
+
return posix.split('/').includes('node_modules') ? null : posix;
|
|
255
|
+
}
|
|
256
|
+
exportedNames(node) {
|
|
257
|
+
const sf = node.getSourceFile();
|
|
258
|
+
if (!this.loadedExports.has(sf)) {
|
|
259
|
+
this.loadedExports.add(sf);
|
|
260
|
+
const moduleSymbol = this.checker.getSymbolAtLocation(sf);
|
|
261
|
+
for (const exported of moduleSymbol ? this.checker.getExportsOfModule(moduleSymbol) : []) {
|
|
262
|
+
const target = exported.flags & ts.SymbolFlags.Alias ? this.checker.getAliasedSymbol(exported) : exported;
|
|
263
|
+
for (const decl of target.declarations ?? []) {
|
|
264
|
+
const names = this.exportNames.get(decl) ?? [];
|
|
265
|
+
names.push(exported.name);
|
|
266
|
+
this.exportNames.set(decl, names);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return [...(this.exportNames.get(node) ?? [])].sort();
|
|
271
|
+
}
|
|
272
|
+
/** The symbol name used in ids: the exported name when exported (preferring the local one). */
|
|
273
|
+
publicName(declaration, local) {
|
|
274
|
+
const names = this.exportedNames(declaration);
|
|
275
|
+
if (names.length === 0)
|
|
276
|
+
return { name: local, exported: false };
|
|
277
|
+
return { name: names.includes(local) ? local : names[0], exported: true };
|
|
278
|
+
}
|
|
279
|
+
resolve(node) {
|
|
280
|
+
const symbol = this.checker.getSymbolAtLocation(node);
|
|
281
|
+
if (symbol && symbol.flags & ts.SymbolFlags.Alias) {
|
|
282
|
+
try {
|
|
283
|
+
return this.checker.getAliasedSymbol(symbol);
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
return undefined;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return symbol;
|
|
290
|
+
}
|
|
291
|
+
/** True when the identifier refers to an ambient global rather than a project declaration. */
|
|
292
|
+
isGlobal(identifier) {
|
|
293
|
+
const symbol = this.checker.getSymbolAtLocation(identifier);
|
|
294
|
+
if (!symbol?.declarations?.length)
|
|
295
|
+
return true;
|
|
296
|
+
return symbol.declarations.every((d) => this.projectPath(d.getSourceFile()) === null && !isImport(d));
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
function collectFunctions(sf, diagnostics, file) {
|
|
300
|
+
const out = [];
|
|
301
|
+
for (const statement of sf.statements) {
|
|
302
|
+
if (ts.isFunctionDeclaration(statement) && statement.body) {
|
|
303
|
+
out.push({ node: statement, declaration: statement, local: statement.name?.text ?? 'default' });
|
|
304
|
+
}
|
|
305
|
+
else if (ts.isVariableStatement(statement)) {
|
|
306
|
+
for (const decl of statement.declarationList.declarations) {
|
|
307
|
+
const init = decl.initializer && skipParens(decl.initializer);
|
|
308
|
+
if (ts.isIdentifier(decl.name) &&
|
|
309
|
+
init &&
|
|
310
|
+
(ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {
|
|
311
|
+
out.push({ node: init, declaration: decl, local: decl.name.text });
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
else if (ts.isClassDeclaration(statement)) {
|
|
316
|
+
const className = statement.name?.text ?? 'default';
|
|
317
|
+
for (const member of statement.members) {
|
|
318
|
+
const isAccessor = ts.isGetAccessorDeclaration(member) || ts.isSetAccessorDeclaration(member);
|
|
319
|
+
if (!(ts.isMethodDeclaration(member) || isAccessor) || !member.body)
|
|
320
|
+
continue;
|
|
321
|
+
if (!ts.isIdentifier(member.name) && !ts.isStringLiteral(member.name)) {
|
|
322
|
+
diagnostics.push({
|
|
323
|
+
file,
|
|
324
|
+
message: `line ${lineOf(sf, member)}: skipped class member with a computed or private name in ${className}`,
|
|
325
|
+
});
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
out.push({
|
|
329
|
+
node: member,
|
|
330
|
+
declaration: member,
|
|
331
|
+
local: member.name.text,
|
|
332
|
+
memberOf: { declaration: statement, local: className },
|
|
333
|
+
...(ts.isGetAccessorDeclaration(member) ? { accessor: 'get' } : {}),
|
|
334
|
+
...(ts.isSetAccessorDeclaration(member) ? { accessor: 'set' } : {}),
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
else if (ts.isExportAssignment(statement)) {
|
|
339
|
+
const expr = skipParens(statement.expression);
|
|
340
|
+
if (ts.isArrowFunction(expr) || ts.isFunctionExpression(expr)) {
|
|
341
|
+
out.push({ node: expr, declaration: statement, local: 'default' });
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return out;
|
|
346
|
+
}
|
|
347
|
+
function symbolNameOf(ctx, target) {
|
|
348
|
+
if (target.memberOf) {
|
|
349
|
+
const owner = ctx.publicName(target.memberOf.declaration, target.memberOf.local);
|
|
350
|
+
const suffix = target.accessor === 'set' ? '=' : '';
|
|
351
|
+
return { name: `${owner.name}.${target.local}${suffix}`, exported: owner.exported };
|
|
352
|
+
}
|
|
353
|
+
if (ts.isExportAssignment(target.declaration))
|
|
354
|
+
return { name: 'default', exported: true };
|
|
355
|
+
return ctx.publicName(target.declaration, target.local);
|
|
356
|
+
}
|
|
357
|
+
/** Symbol id for a callee declaration inside the project, mirroring how functions are indexed. */
|
|
358
|
+
function calleeSymbol(ctx, decl) {
|
|
359
|
+
const file = ctx.projectPath(decl.getSourceFile());
|
|
360
|
+
if (file === null)
|
|
361
|
+
return null;
|
|
362
|
+
if (ts.isFunctionDeclaration(decl))
|
|
363
|
+
return symbolId(file, decl.name ? ctx.publicName(decl, decl.name.text).name : 'default');
|
|
364
|
+
if (ts.isExportAssignment(decl)) {
|
|
365
|
+
const expr = skipParens(decl.expression);
|
|
366
|
+
return ts.isArrowFunction(expr) || ts.isFunctionExpression(expr) ? symbolId(file, 'default') : null;
|
|
367
|
+
}
|
|
368
|
+
if (ts.isVariableDeclaration(decl) && ts.isIdentifier(decl.name)) {
|
|
369
|
+
return symbolId(file, ctx.publicName(decl, decl.name.text).name);
|
|
370
|
+
}
|
|
371
|
+
if (ts.isMethodDeclaration(decl) && (ts.isIdentifier(decl.name) || ts.isStringLiteral(decl.name))) {
|
|
372
|
+
const owner = decl.parent;
|
|
373
|
+
if (ts.isClassDeclaration(owner)) {
|
|
374
|
+
const className = owner.name?.text ?? 'default';
|
|
375
|
+
return symbolId(file, `${ctx.publicName(owner, className).name}.${decl.name.text}`);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
function analyzeFunction(target, sf, file, ctx) {
|
|
381
|
+
const { node } = target;
|
|
382
|
+
const { checker } = ctx;
|
|
383
|
+
const { name: publicName, exported } = symbolNameOf(ctx, target);
|
|
384
|
+
const fnName = target.memberOf ? `${target.memberOf.local}.${target.local}` : target.local;
|
|
385
|
+
const info = {
|
|
386
|
+
symbol: symbolId(file, publicName),
|
|
387
|
+
name: fnName,
|
|
388
|
+
file,
|
|
389
|
+
exported,
|
|
390
|
+
location: loc(sf, file, target.declaration === node ? node : outerStatement(target.declaration)),
|
|
391
|
+
params: node.parameters.map((p) => ({
|
|
392
|
+
name: p.name.getText(sf),
|
|
393
|
+
type: checker.typeToString(checker.getTypeAtLocation(p), node, ts.TypeFormatFlags.NoTruncation),
|
|
394
|
+
optional: Boolean(p.questionToken || p.initializer),
|
|
395
|
+
})),
|
|
396
|
+
returnType: returnTypeOf(checker, node),
|
|
397
|
+
jsdoc: jsdocOf(sf, target),
|
|
398
|
+
async: hasModifier(node, ts.SyntaxKind.AsyncKeyword),
|
|
399
|
+
branches: [],
|
|
400
|
+
comparisons: [],
|
|
401
|
+
returns: [],
|
|
402
|
+
throws: [],
|
|
403
|
+
calls: [],
|
|
404
|
+
sideEffects: [],
|
|
405
|
+
unsupported: [],
|
|
406
|
+
purity: 'pure',
|
|
407
|
+
numericKinds: [],
|
|
408
|
+
};
|
|
409
|
+
const result = { node, info, unknown: [], internalCalls: [] };
|
|
410
|
+
const numeric = new Set();
|
|
411
|
+
const unsupportedSeen = new Set();
|
|
412
|
+
const unsupported = (at, reason) => {
|
|
413
|
+
const location = loc(sf, file, at);
|
|
414
|
+
const key = `${location.range?.start}:${reason}`;
|
|
415
|
+
if (unsupportedSeen.has(key))
|
|
416
|
+
return;
|
|
417
|
+
unsupportedSeen.add(key);
|
|
418
|
+
info.unsupported.push({ location, reason });
|
|
419
|
+
};
|
|
420
|
+
const sideEffect = (effect) => {
|
|
421
|
+
if (!info.sideEffects.includes(effect))
|
|
422
|
+
info.sideEffects.push(effect);
|
|
423
|
+
};
|
|
424
|
+
const call = (entry) => {
|
|
425
|
+
if (!info.calls.includes(entry))
|
|
426
|
+
info.calls.push(entry);
|
|
427
|
+
};
|
|
428
|
+
const text = (n) => n.getText(sf).replace(/\s+/g, ' ');
|
|
429
|
+
/**
|
|
430
|
+
* Unsupported constructs that change control flow or evaluation semantics (async, generators,
|
|
431
|
+
* accessors, `this`, dynamic code...) make purity undecidable here, so they also mark the
|
|
432
|
+
* function `unknown`. Purely numeric notes (float literals, division, NaN, bigint, coercion,
|
|
433
|
+
* `Math.*`) stay listed in `unsupported`/`numericKinds` but do not affect purity: they are
|
|
434
|
+
* deterministic and side-effect free; they only fall outside the integer model.
|
|
435
|
+
*/
|
|
436
|
+
const undecidable = (at, reason) => {
|
|
437
|
+
unsupported(at, reason);
|
|
438
|
+
result.unknown.push(reason);
|
|
439
|
+
};
|
|
440
|
+
if (info.async)
|
|
441
|
+
undecidable(node, 'async function');
|
|
442
|
+
if ((ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node)) &&
|
|
443
|
+
node.asteriskToken) {
|
|
444
|
+
undecidable(node, 'generator function');
|
|
445
|
+
}
|
|
446
|
+
if (target.accessor)
|
|
447
|
+
undecidable(node, `${target.accessor === 'get' ? 'getter' : 'setter'} accessor`);
|
|
448
|
+
const isOwnParam = (expr) => {
|
|
449
|
+
const e = skipParens(expr);
|
|
450
|
+
if (!ts.isIdentifier(e))
|
|
451
|
+
return null;
|
|
452
|
+
const symbol = checker.getSymbolAtLocation(e);
|
|
453
|
+
const decl = symbol?.valueDeclaration;
|
|
454
|
+
return decl && ts.isParameter(decl) && decl.parent === node && ts.isIdentifier(decl.name)
|
|
455
|
+
? decl.name.text
|
|
456
|
+
: null;
|
|
457
|
+
};
|
|
458
|
+
/** A parameter, or a field of one (`order.total`, `xs.length`), as `param` / `param.field`. */
|
|
459
|
+
const paramPath = (expr) => {
|
|
460
|
+
const e = skipParens(expr);
|
|
461
|
+
if (ts.isPropertyAccessExpression(e) && !e.questionDotToken && ts.isIdentifier(e.name)) {
|
|
462
|
+
const base = isOwnParam(e.expression);
|
|
463
|
+
return base ? `${base}.${e.name.text}` : null;
|
|
464
|
+
}
|
|
465
|
+
return isOwnParam(e);
|
|
466
|
+
};
|
|
467
|
+
const isLocal = (decl) => decl.getSourceFile() === sf && decl.pos >= node.pos && decl.end <= node.end;
|
|
468
|
+
/** Record writes: outer variables and parameter properties make the function impure. */
|
|
469
|
+
const recordWrite = (targetExpr, mutatesValue = false) => {
|
|
470
|
+
const t = skipParens(targetExpr);
|
|
471
|
+
if (ts.isArrayLiteralExpression(t)) {
|
|
472
|
+
for (const el of t.elements)
|
|
473
|
+
recordWrite(ts.isSpreadElement(el) ? el.expression : el);
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
if (ts.isObjectLiteralExpression(t)) {
|
|
477
|
+
for (const prop of t.properties) {
|
|
478
|
+
if (ts.isShorthandPropertyAssignment(prop))
|
|
479
|
+
recordWrite(prop.name);
|
|
480
|
+
else if (ts.isPropertyAssignment(prop))
|
|
481
|
+
recordWrite(prop.initializer);
|
|
482
|
+
else if (ts.isSpreadAssignment(prop))
|
|
483
|
+
recordWrite(prop.expression);
|
|
484
|
+
}
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
if (ts.isBinaryExpression(t) && t.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
|
|
488
|
+
recordWrite(t.left);
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
const direct = ts.isIdentifier(t) && !mutatesValue;
|
|
492
|
+
let rootExpr = t;
|
|
493
|
+
while (ts.isPropertyAccessExpression(rootExpr) || ts.isElementAccessExpression(rootExpr)) {
|
|
494
|
+
rootExpr = skipParens(rootExpr.expression);
|
|
495
|
+
}
|
|
496
|
+
if (rootExpr.kind === ts.SyntaxKind.ThisKeyword) {
|
|
497
|
+
sideEffect('mutates this');
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
if (!ts.isIdentifier(rootExpr)) {
|
|
501
|
+
sideEffect(`mutates ${text(t)}`);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
const decl = checker.getSymbolAtLocation(rootExpr)?.valueDeclaration;
|
|
505
|
+
if (decl && isLocal(decl)) {
|
|
506
|
+
if (!direct && ts.isParameter(decl))
|
|
507
|
+
sideEffect(`mutates parameter ${rootExpr.text}`);
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
sideEffect(direct ? `assigns outer variable ${rootExpr.text}` : `mutates outer ${text(t)}`);
|
|
511
|
+
};
|
|
512
|
+
const visitCall = (expr) => {
|
|
513
|
+
const callee = skipParens(expr.expression);
|
|
514
|
+
if (ts.isIdentifier(callee) && callee.text === 'eval' && ctx.isGlobal(callee)) {
|
|
515
|
+
unsupported(expr, 'eval');
|
|
516
|
+
result.unknown.push('eval');
|
|
517
|
+
}
|
|
518
|
+
if (ts.isIdentifier(callee) && callee.text === 'Function' && ctx.isGlobal(callee)) {
|
|
519
|
+
unsupported(expr, 'Function constructor');
|
|
520
|
+
result.unknown.push('Function constructor');
|
|
521
|
+
}
|
|
522
|
+
if (callee.kind === ts.SyntaxKind.ImportKeyword) {
|
|
523
|
+
unsupported(expr, 'dynamic import');
|
|
524
|
+
sideEffect('dynamic import');
|
|
525
|
+
call('import');
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
const nameNode = ts.isPropertyAccessExpression(callee) ? callee.name : callee;
|
|
529
|
+
const symbol = ctx.resolve(nameNode);
|
|
530
|
+
const decl = symbol?.declarations?.[0];
|
|
531
|
+
if (decl && isLocal(decl)) {
|
|
532
|
+
// Local helper functions are walked as part of this body; other local callees are unknown.
|
|
533
|
+
call(text(callee).slice(0, 200));
|
|
534
|
+
const init = ts.isVariableDeclaration(decl) && decl.initializer ? skipParens(decl.initializer) : null;
|
|
535
|
+
const walked = ts.isFunctionDeclaration(decl) ||
|
|
536
|
+
(init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init)));
|
|
537
|
+
if (!walked)
|
|
538
|
+
result.unknown.push(`calls a value that is not a local function: ${text(callee)}`);
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
const internal = decl ? calleeSymbol(ctx, decl) : null;
|
|
542
|
+
if (internal) {
|
|
543
|
+
call(internal);
|
|
544
|
+
result.internalCalls.push(internal);
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
call(text(callee).slice(0, 200));
|
|
548
|
+
const fromLib = decl ? ctx.projectPath(decl.getSourceFile()) === null && isLibFile(ctx, decl) : false;
|
|
549
|
+
if (ts.isPropertyAccessExpression(callee) &&
|
|
550
|
+
MUTATING_METHODS.has(callee.name.text) &&
|
|
551
|
+
(fromLib || !decl)) {
|
|
552
|
+
recordWrite(callee.expression, true);
|
|
553
|
+
}
|
|
554
|
+
if (!fromLib)
|
|
555
|
+
result.unknown.push(`unresolved callee ${text(callee)}`);
|
|
556
|
+
};
|
|
557
|
+
const visit = (n, nestedFunction) => {
|
|
558
|
+
if (ts.isTypeNode(n) && !ts.isExpressionWithTypeArguments(n))
|
|
559
|
+
return;
|
|
560
|
+
if (n !== node && ts.isFunctionLike(n)) {
|
|
561
|
+
if (hasModifier(n, ts.SyntaxKind.AsyncKeyword))
|
|
562
|
+
undecidable(n, 'async function');
|
|
563
|
+
if ((ts.isFunctionDeclaration(n) || ts.isFunctionExpression(n)) && n.asteriskToken) {
|
|
564
|
+
undecidable(n, 'generator function');
|
|
565
|
+
}
|
|
566
|
+
ts.forEachChild(n, (c) => visit(c, true));
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
switch (n.kind) {
|
|
570
|
+
case ts.SyntaxKind.ThisKeyword:
|
|
571
|
+
unsupported(n, 'this');
|
|
572
|
+
result.unknown.push('this');
|
|
573
|
+
break;
|
|
574
|
+
case ts.SyntaxKind.WithStatement:
|
|
575
|
+
unsupported(n, 'with statement');
|
|
576
|
+
result.unknown.push('with');
|
|
577
|
+
break;
|
|
578
|
+
case ts.SyntaxKind.AwaitExpression:
|
|
579
|
+
undecidable(n, 'await');
|
|
580
|
+
break;
|
|
581
|
+
case ts.SyntaxKind.YieldExpression:
|
|
582
|
+
undecidable(n, 'yield');
|
|
583
|
+
break;
|
|
584
|
+
case ts.SyntaxKind.BigIntLiteral:
|
|
585
|
+
numeric.add('bigint');
|
|
586
|
+
unsupported(n, `bigint literal ${text(n)}`);
|
|
587
|
+
break;
|
|
588
|
+
case ts.SyntaxKind.NumericLiteral: {
|
|
589
|
+
const value = Number(n.text);
|
|
590
|
+
if (Number.isInteger(value)) {
|
|
591
|
+
numeric.add('integer_literal');
|
|
592
|
+
if (!Number.isSafeInteger(value))
|
|
593
|
+
unsupported(n, `integer literal outside the safe range: ${text(n)}`);
|
|
594
|
+
}
|
|
595
|
+
else {
|
|
596
|
+
numeric.add('float_literal');
|
|
597
|
+
unsupported(n, `floating-point literal ${text(n)}`);
|
|
598
|
+
}
|
|
599
|
+
break;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
if (ts.isIdentifier(n) && isExpressionIdentifier(n)) {
|
|
603
|
+
if ((n.text === 'NaN' || n.text === 'Infinity') && ctx.isGlobal(n)) {
|
|
604
|
+
numeric.add('nan');
|
|
605
|
+
unsupported(n, n.text);
|
|
606
|
+
}
|
|
607
|
+
else if (n.text === 'arguments' && ctx.isGlobal(n)) {
|
|
608
|
+
undecidable(n, 'arguments object');
|
|
609
|
+
}
|
|
610
|
+
else if (IMPURE_GLOBALS.has(n.text) && ctx.isGlobal(n)) {
|
|
611
|
+
sideEffect(n.text);
|
|
612
|
+
}
|
|
613
|
+
else {
|
|
614
|
+
const ioModule = importedIoModule(ctx, n);
|
|
615
|
+
if (ioModule)
|
|
616
|
+
sideEffect(`io import ${ioModule}`);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
if (ts.isPropertyAccessExpression(n) && ts.isIdentifier(n.expression) && ctx.isGlobal(n.expression)) {
|
|
620
|
+
const owner = n.expression.text;
|
|
621
|
+
const prop = n.name.text;
|
|
622
|
+
if (owner === 'Math' && prop === 'random')
|
|
623
|
+
sideEffect('Math.random');
|
|
624
|
+
else if (owner === 'Math')
|
|
625
|
+
unsupported(n, `Math.${prop} is outside the integer model`);
|
|
626
|
+
if (owner === 'Date' && prop === 'now')
|
|
627
|
+
sideEffect('Date.now');
|
|
628
|
+
if (owner === 'Number' && ['NaN', 'POSITIVE_INFINITY', 'NEGATIVE_INFINITY'].includes(prop)) {
|
|
629
|
+
numeric.add('nan');
|
|
630
|
+
unsupported(n, `Number.${prop}`);
|
|
631
|
+
}
|
|
632
|
+
if (owner === 'Proxy' && prop === 'revocable') {
|
|
633
|
+
unsupported(n, 'Proxy');
|
|
634
|
+
result.unknown.push('Proxy');
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
if (ts.isNewExpression(n) && ts.isIdentifier(n.expression) && ctx.isGlobal(n.expression)) {
|
|
638
|
+
const ctor = n.expression.text;
|
|
639
|
+
if (ctor === 'Proxy') {
|
|
640
|
+
unsupported(n, 'Proxy');
|
|
641
|
+
result.unknown.push('Proxy');
|
|
642
|
+
}
|
|
643
|
+
else if (ctor === 'Function') {
|
|
644
|
+
unsupported(n, 'Function constructor');
|
|
645
|
+
result.unknown.push('Function constructor');
|
|
646
|
+
}
|
|
647
|
+
else if (ctor === 'Date' && (n.arguments?.length ?? 0) === 0) {
|
|
648
|
+
sideEffect('new Date()');
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
if (ts.isElementAccessExpression(n)) {
|
|
652
|
+
const param = isOwnParam(n.expression);
|
|
653
|
+
const key = skipParens(n.argumentExpression);
|
|
654
|
+
if (param && !ts.isStringLiteralLike(key) && !ts.isNumericLiteral(key)) {
|
|
655
|
+
undecidable(n, `computed property access on parameter ${param}`);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
if (ts.isCallExpression(n))
|
|
659
|
+
visitCall(n);
|
|
660
|
+
if (ts.isBinaryExpression(n)) {
|
|
661
|
+
const op = n.operatorToken.kind;
|
|
662
|
+
if (op >= ts.SyntaxKind.FirstAssignment && op <= ts.SyntaxKind.LastAssignment)
|
|
663
|
+
recordWrite(n.left);
|
|
664
|
+
if (op === ts.SyntaxKind.SlashToken ||
|
|
665
|
+
op === ts.SyntaxKind.SlashEqualsToken ||
|
|
666
|
+
op === ts.SyntaxKind.PercentToken ||
|
|
667
|
+
op === ts.SyntaxKind.PercentEqualsToken) {
|
|
668
|
+
numeric.add('division');
|
|
669
|
+
unsupported(n, `${n.operatorToken.getText(sf)} operator`);
|
|
670
|
+
}
|
|
671
|
+
const comparison = COMPARISON_OPERATORS.get(op);
|
|
672
|
+
if (comparison) {
|
|
673
|
+
const literal = integerLiteral(n.right) ?? integerLiteral(n.left);
|
|
674
|
+
const record = {
|
|
675
|
+
location: loc(sf, file, n),
|
|
676
|
+
operator: comparison,
|
|
677
|
+
left: text(n.left),
|
|
678
|
+
right: text(n.right),
|
|
679
|
+
literal,
|
|
680
|
+
param: paramPath(n.left) ?? paramPath(n.right),
|
|
681
|
+
};
|
|
682
|
+
if (!nestedFunction)
|
|
683
|
+
info.comparisons.push(record);
|
|
684
|
+
}
|
|
685
|
+
checkCoercion(n, ctx, unsupported);
|
|
686
|
+
}
|
|
687
|
+
if (ts.isPrefixUnaryExpression(n) || ts.isPostfixUnaryExpression(n)) {
|
|
688
|
+
const op = n.operator;
|
|
689
|
+
if (op === ts.SyntaxKind.PlusPlusToken || op === ts.SyntaxKind.MinusMinusToken)
|
|
690
|
+
recordWrite(n.operand);
|
|
691
|
+
if (ts.isPrefixUnaryExpression(n) &&
|
|
692
|
+
(op === ts.SyntaxKind.PlusToken || op === ts.SyntaxKind.MinusToken) &&
|
|
693
|
+
!ts.isNumericLiteral(n.operand) &&
|
|
694
|
+
!isNumberLike(checker.getTypeAtLocation(n.operand))) {
|
|
695
|
+
unsupported(n, `implicit coercion: unary ${op === ts.SyntaxKind.PlusToken ? '+' : '-'} on a non-number`);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
if (ts.isDeleteExpression(n))
|
|
699
|
+
recordWrite(n.expression);
|
|
700
|
+
if (!nestedFunction) {
|
|
701
|
+
if (ts.isIfStatement(n))
|
|
702
|
+
info.branches.push({ location: loc(sf, file, n), condition: text(n.expression) });
|
|
703
|
+
if (ts.isConditionalExpression(n)) {
|
|
704
|
+
info.branches.push({ location: loc(sf, file, n), condition: text(n.condition) });
|
|
705
|
+
}
|
|
706
|
+
if (ts.isCaseClause(n)) {
|
|
707
|
+
const subject = text(n.parent.parent.expression);
|
|
708
|
+
info.branches.push({ location: loc(sf, file, n), condition: `${subject} === ${text(n.expression)}` });
|
|
709
|
+
}
|
|
710
|
+
if (ts.isDefaultClause(n))
|
|
711
|
+
info.branches.push({ location: loc(sf, file, n), condition: 'default' });
|
|
712
|
+
if (ts.isWhileStatement(n) || ts.isDoStatement(n) || (ts.isForStatement(n) && n.condition)) {
|
|
713
|
+
const cond = ts.isForStatement(n) ? n.condition : n.expression;
|
|
714
|
+
info.branches.push({ location: loc(sf, file, n), condition: text(cond) });
|
|
715
|
+
}
|
|
716
|
+
if (ts.isReturnStatement(n)) {
|
|
717
|
+
info.returns.push({
|
|
718
|
+
location: loc(sf, file, n),
|
|
719
|
+
expression: n.expression ? text(n.expression) : 'undefined',
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
if (ts.isThrowStatement(n))
|
|
723
|
+
info.throws.push({ location: loc(sf, file, n), expression: text(n.expression) });
|
|
724
|
+
}
|
|
725
|
+
ts.forEachChild(n, (c) => visit(c, nestedFunction));
|
|
726
|
+
};
|
|
727
|
+
for (const param of node.parameters)
|
|
728
|
+
ts.forEachChild(param, (c) => visit(c, false));
|
|
729
|
+
if (node.body) {
|
|
730
|
+
if (ts.isBlock(node.body)) {
|
|
731
|
+
visit(node.body, false);
|
|
732
|
+
}
|
|
733
|
+
else {
|
|
734
|
+
info.returns.push({ location: loc(sf, file, node.body), expression: text(node.body) });
|
|
735
|
+
visit(node.body, false);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
info.numericKinds = NUMERIC_KIND_ORDER.filter((k) => numeric.has(k));
|
|
739
|
+
info.unsupported.sort((a, b) => (a.location.range?.start ?? 0) - (b.location.range?.start ?? 0) || a.reason.localeCompare(b.reason));
|
|
740
|
+
return result;
|
|
741
|
+
}
|
|
742
|
+
function checkCoercion(n, ctx, unsupported) {
|
|
743
|
+
const op = n.operatorToken.kind;
|
|
744
|
+
const left = ctx.checker.getTypeAtLocation(n.left);
|
|
745
|
+
const right = ctx.checker.getTypeAtLocation(n.right);
|
|
746
|
+
const opText = ts.tokenToString(op) ?? '';
|
|
747
|
+
if (op === ts.SyntaxKind.EqualsEqualsToken || op === ts.SyntaxKind.ExclamationEqualsToken) {
|
|
748
|
+
const l = categories(left);
|
|
749
|
+
const r = categories(right);
|
|
750
|
+
if (l === null || r === null || l !== r) {
|
|
751
|
+
unsupported(n, `implicit coercion: ${opText} between different or unknown types`);
|
|
752
|
+
}
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
if (op === ts.SyntaxKind.LessThanToken ||
|
|
756
|
+
op === ts.SyntaxKind.LessThanEqualsToken ||
|
|
757
|
+
op === ts.SyntaxKind.GreaterThanToken ||
|
|
758
|
+
op === ts.SyntaxKind.GreaterThanEqualsToken) {
|
|
759
|
+
const l = categories(left);
|
|
760
|
+
const r = categories(right);
|
|
761
|
+
if (l === null || r === null || l !== r) {
|
|
762
|
+
unsupported(n, `implicit coercion: ${opText} between different or unknown types`);
|
|
763
|
+
}
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
if (op === ts.SyntaxKind.PlusToken || op === ts.SyntaxKind.PlusEqualsToken) {
|
|
767
|
+
const bothNumbers = isNumberLike(left) && isNumberLike(right);
|
|
768
|
+
const bothBigInt = isBigIntLike(left) && isBigIntLike(right);
|
|
769
|
+
const bothStrings = isStringLike(left) && isStringLike(right);
|
|
770
|
+
if (!bothNumbers && !bothBigInt && !bothStrings) {
|
|
771
|
+
unsupported(n, `implicit coercion: ${opText} on mixed or non-numeric operands`);
|
|
772
|
+
}
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
if (ARITHMETIC_OPERATORS.has(op)) {
|
|
776
|
+
const ok = (isNumberLike(left) && isNumberLike(right)) || (isBigIntLike(left) && isBigIntLike(right));
|
|
777
|
+
if (!ok)
|
|
778
|
+
unsupported(n, `implicit coercion: ${opText} on non-numeric operands`);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
/** Sorted primitive categories of a type, or null when it is any/unknown/an object. */
|
|
782
|
+
function categories(type) {
|
|
783
|
+
const parts = type.isUnion() ? type.types : [type];
|
|
784
|
+
const out = new Set();
|
|
785
|
+
for (const t of parts) {
|
|
786
|
+
const f = t.flags;
|
|
787
|
+
if (f & ts.TypeFlags.NumberLike)
|
|
788
|
+
out.add('number');
|
|
789
|
+
else if (f & ts.TypeFlags.StringLike)
|
|
790
|
+
out.add('string');
|
|
791
|
+
else if (f & ts.TypeFlags.BooleanLike)
|
|
792
|
+
out.add('boolean');
|
|
793
|
+
else if (f & ts.TypeFlags.BigIntLike)
|
|
794
|
+
out.add('bigint');
|
|
795
|
+
else if (f & ts.TypeFlags.Null)
|
|
796
|
+
out.add('null');
|
|
797
|
+
else if (f & ts.TypeFlags.Undefined)
|
|
798
|
+
out.add('undefined');
|
|
799
|
+
else
|
|
800
|
+
return null;
|
|
801
|
+
}
|
|
802
|
+
return [...out].sort().join('|');
|
|
803
|
+
}
|
|
804
|
+
const isNumberLike = (t) => categories(t) === 'number';
|
|
805
|
+
const isBigIntLike = (t) => categories(t) === 'bigint';
|
|
806
|
+
const isStringLike = (t) => categories(t) === 'string';
|
|
807
|
+
/** Decimal text of an integer literal (optionally negated), e.g. `0x10` -> `16`, `-1_000` -> `-1000`. */
|
|
808
|
+
function integerLiteral(expr) {
|
|
809
|
+
let e = skipParens(expr);
|
|
810
|
+
let sign = '';
|
|
811
|
+
if (ts.isPrefixUnaryExpression(e) && e.operator === ts.SyntaxKind.MinusToken) {
|
|
812
|
+
sign = '-';
|
|
813
|
+
e = skipParens(e.operand);
|
|
814
|
+
}
|
|
815
|
+
if (!ts.isNumericLiteral(e))
|
|
816
|
+
return null;
|
|
817
|
+
const raw = e.getText().replace(/_/g, '');
|
|
818
|
+
const value = Number(raw);
|
|
819
|
+
if (!Number.isInteger(value))
|
|
820
|
+
return null;
|
|
821
|
+
let digits;
|
|
822
|
+
if (/^0[xob]/i.test(raw) || /^\d+$/.test(raw))
|
|
823
|
+
digits = BigInt(raw).toString();
|
|
824
|
+
else if (Number.isSafeInteger(value))
|
|
825
|
+
digits = String(value);
|
|
826
|
+
else
|
|
827
|
+
return null;
|
|
828
|
+
return digits === '0' ? '0' : `${sign}${digits}`;
|
|
829
|
+
}
|
|
830
|
+
function importedIoModule(ctx, identifier) {
|
|
831
|
+
const symbol = ctx.checker.getSymbolAtLocation(identifier);
|
|
832
|
+
for (const decl of symbol?.declarations ?? []) {
|
|
833
|
+
if (!isImport(decl))
|
|
834
|
+
continue;
|
|
835
|
+
let n = decl;
|
|
836
|
+
while (!ts.isImportDeclaration(n) && !ts.isImportEqualsDeclaration(n) && n.parent)
|
|
837
|
+
n = n.parent;
|
|
838
|
+
let specifier = null;
|
|
839
|
+
if (ts.isImportDeclaration(n) && ts.isStringLiteral(n.moduleSpecifier))
|
|
840
|
+
specifier = n.moduleSpecifier.text;
|
|
841
|
+
if (ts.isImportEqualsDeclaration(n) &&
|
|
842
|
+
ts.isExternalModuleReference(n.moduleReference) &&
|
|
843
|
+
ts.isStringLiteral(n.moduleReference.expression)) {
|
|
844
|
+
specifier = n.moduleReference.expression.text;
|
|
845
|
+
}
|
|
846
|
+
if (specifier && IO_MODULES.has(specifier.replace(/^node:/, '')))
|
|
847
|
+
return specifier;
|
|
848
|
+
}
|
|
849
|
+
return null;
|
|
850
|
+
}
|
|
851
|
+
function isImport(decl) {
|
|
852
|
+
return (ts.isImportSpecifier(decl) ||
|
|
853
|
+
ts.isImportClause(decl) ||
|
|
854
|
+
ts.isNamespaceImport(decl) ||
|
|
855
|
+
ts.isImportEqualsDeclaration(decl));
|
|
856
|
+
}
|
|
857
|
+
function isLibFile(ctx, decl) {
|
|
858
|
+
return ctx.program.isSourceFileDefaultLibrary(decl.getSourceFile());
|
|
859
|
+
}
|
|
860
|
+
/** Identifiers in value positions: not property names, declaration names or labels. */
|
|
861
|
+
function isExpressionIdentifier(n) {
|
|
862
|
+
const p = n.parent;
|
|
863
|
+
if (!p)
|
|
864
|
+
return false;
|
|
865
|
+
if (ts.isPropertyAccessExpression(p) && p.name === n)
|
|
866
|
+
return false;
|
|
867
|
+
if (ts.isQualifiedName(p))
|
|
868
|
+
return false;
|
|
869
|
+
if ((ts.isPropertyAssignment(p) || ts.isPropertyDeclaration(p) || ts.isMethodDeclaration(p)) &&
|
|
870
|
+
p.name === n) {
|
|
871
|
+
return false;
|
|
872
|
+
}
|
|
873
|
+
if (ts.isBindingElement(p) && p.propertyName === n)
|
|
874
|
+
return false;
|
|
875
|
+
if ((ts.isLabeledStatement(p) || ts.isBreakOrContinueStatement(p)) && p.label === n)
|
|
876
|
+
return false;
|
|
877
|
+
if (p.name === n && !ts.isShorthandPropertyAssignment(p))
|
|
878
|
+
return false;
|
|
879
|
+
return true;
|
|
880
|
+
}
|
|
881
|
+
function returnTypeOf(checker, node) {
|
|
882
|
+
const signature = checker.getSignatureFromDeclaration(node);
|
|
883
|
+
if (!signature)
|
|
884
|
+
return 'unknown';
|
|
885
|
+
return checker.typeToString(checker.getReturnTypeOfSignature(signature), node, ts.TypeFormatFlags.NoTruncation);
|
|
886
|
+
}
|
|
887
|
+
function jsdocOf(sf, target) {
|
|
888
|
+
const host = ts.isVariableDeclaration(target.declaration)
|
|
889
|
+
? outerStatement(target.declaration)
|
|
890
|
+
: ts.isExportAssignment(target.declaration)
|
|
891
|
+
? target.declaration
|
|
892
|
+
: target.node;
|
|
893
|
+
const docs = host.jsDoc;
|
|
894
|
+
if (!docs?.length)
|
|
895
|
+
return null;
|
|
896
|
+
const text = docs
|
|
897
|
+
.map((doc) => sf.text
|
|
898
|
+
.slice(doc.pos, doc.end)
|
|
899
|
+
.replace(/^\/\*\*/, '')
|
|
900
|
+
.replace(/\*\/$/, '')
|
|
901
|
+
.split('\n')
|
|
902
|
+
.map((line) => line.replace(/^\s*\*?\s?/, '').trimEnd())
|
|
903
|
+
.join('\n')
|
|
904
|
+
.trim())
|
|
905
|
+
.filter(Boolean)
|
|
906
|
+
.join('\n');
|
|
907
|
+
return text || null;
|
|
908
|
+
}
|
|
909
|
+
function outerStatement(node) {
|
|
910
|
+
if (ts.isVariableDeclaration(node) && ts.isVariableDeclarationList(node.parent)) {
|
|
911
|
+
return ts.isVariableStatement(node.parent.parent) ? node.parent.parent : node;
|
|
912
|
+
}
|
|
913
|
+
return node;
|
|
914
|
+
}
|
|
915
|
+
function hasModifier(node, kind) {
|
|
916
|
+
return ts.canHaveModifiers(node) && (ts.getModifiers(node) ?? []).some((m) => m.kind === kind);
|
|
917
|
+
}
|
|
918
|
+
function skipParens(expr) {
|
|
919
|
+
let e = expr;
|
|
920
|
+
while (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isNonNullExpression(e))
|
|
921
|
+
e = e.expression;
|
|
922
|
+
return e;
|
|
923
|
+
}
|
|
924
|
+
function lineOf(sf, node) {
|
|
925
|
+
return sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
|
|
926
|
+
}
|
|
927
|
+
function loc(sf, file, node) {
|
|
928
|
+
return {
|
|
929
|
+
file,
|
|
930
|
+
range: { start: lineOf(sf, node), end: sf.getLineAndCharacterOfPosition(node.getEnd()).line + 1 },
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
/** Disambiguate symbol ids that collide (e.g. a duplicated declaration in a broken file). */
|
|
934
|
+
function dedupeSymbols(indexed, diagnostics) {
|
|
935
|
+
const seen = new Map();
|
|
936
|
+
for (const entry of indexed) {
|
|
937
|
+
const count = (seen.get(entry.info.symbol) ?? 0) + 1;
|
|
938
|
+
seen.set(entry.info.symbol, count);
|
|
939
|
+
if (count > 1) {
|
|
940
|
+
diagnostics.push({
|
|
941
|
+
file: entry.info.file,
|
|
942
|
+
message: `duplicate symbol ${entry.info.symbol} at line ${entry.info.location.range?.start}; indexed as ~${count}`,
|
|
943
|
+
});
|
|
944
|
+
entry.info.symbol = `${entry.info.symbol}~${count}`;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
/** Direct effects make a function impure; calls into impure or unknown project functions propagate. */
|
|
949
|
+
function propagatePurity(indexed) {
|
|
950
|
+
const bySymbol = new Map(indexed.map((i) => [i.info.symbol, i]));
|
|
951
|
+
for (const entry of indexed) {
|
|
952
|
+
entry.info.purity =
|
|
953
|
+
entry.info.sideEffects.length > 0 ? 'impure' : entry.unknown.length > 0 ? 'unknown' : 'pure';
|
|
954
|
+
}
|
|
955
|
+
for (let changed = true; changed;) {
|
|
956
|
+
changed = false;
|
|
957
|
+
for (const entry of indexed) {
|
|
958
|
+
for (const callee of entry.internalCalls) {
|
|
959
|
+
const target = bySymbol.get(callee);
|
|
960
|
+
const purity = target?.info.purity ?? 'unknown';
|
|
961
|
+
if (purity === 'impure' && entry.info.purity !== 'impure') {
|
|
962
|
+
entry.info.sideEffects.push(`calls impure ${callee}`);
|
|
963
|
+
entry.info.purity = 'impure';
|
|
964
|
+
changed = true;
|
|
965
|
+
}
|
|
966
|
+
else if (purity === 'unknown' && entry.info.purity === 'pure') {
|
|
967
|
+
entry.info.purity = 'unknown';
|
|
968
|
+
changed = true;
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
//# sourceMappingURL=analyze.js.map
|