fallow-type-aware 3.42.0 → 3.43.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/README.md +6 -0
- package/package.json +1 -1
- package/src/accessor-direction.mjs +113 -0
- package/src/call-evidence.mjs +1493 -0
- package/src/cli.mjs +16 -2
- package/src/declaration-facts.mjs +27 -0
- package/src/file-identity.mjs +18 -2
- package/src/generated-protocol.mjs +2 -0
- package/src/mutant-typecheck.mjs +2 -2
- package/src/optional-chain-proof.mjs +107 -82
- package/src/project-state.mjs +28 -1
- package/src/protocol.mjs +106 -0
- package/src/reference-names.mjs +97 -22
- package/src/semantic-identity.mjs +32 -3
- package/src/semantic.mjs +7 -20
|
@@ -0,0 +1,1493 @@
|
|
|
1
|
+
// Call evidence for the `constant-parameter` rule.
|
|
2
|
+
//
|
|
3
|
+
// The static rule selects the candidates. This module answers two questions
|
|
4
|
+
// for them and returns evidence only, never a finding:
|
|
5
|
+
//
|
|
6
|
+
// - Whether a call argument that the static facts do not know can be
|
|
7
|
+
// `undefined`. When no argument of a parameter with a default can be
|
|
8
|
+
// `undefined`, the default never applies.
|
|
9
|
+
// - The calls of one exact class method, with the same fact for each
|
|
10
|
+
// argument, or the reason that the calls are not all visible.
|
|
11
|
+
//
|
|
12
|
+
// The checker resolves the calls of a method with `getSignatureUsage`, which
|
|
13
|
+
// follows the class and interface hierarchy. The list can hold a call that
|
|
14
|
+
// dispatches to an override or to another implementer. That is safe for each
|
|
15
|
+
// claim of the rule: a value that each call of a larger set passes is also the
|
|
16
|
+
// value of each call of the real set. A missing call is not safe, so the
|
|
17
|
+
// module abstains when a reference of the method name does not resolve, when a
|
|
18
|
+
// file outside the program names the method, and when a computed member
|
|
19
|
+
// access can read it.
|
|
20
|
+
|
|
21
|
+
import { readFileSync } from "node:fs";
|
|
22
|
+
import path from "node:path";
|
|
23
|
+
|
|
24
|
+
import {
|
|
25
|
+
createApi as createBackendApi,
|
|
26
|
+
isInferredProject,
|
|
27
|
+
projectCompilerOptions,
|
|
28
|
+
ast,
|
|
29
|
+
NodeFlags,
|
|
30
|
+
SyntaxKind,
|
|
31
|
+
sync,
|
|
32
|
+
} from "./backend.mjs";
|
|
33
|
+
import { targetDirection } from "./accessor-direction.mjs";
|
|
34
|
+
import { hasToken, isAmbient } from "./declaration-facts.mjs";
|
|
35
|
+
import { canonicalFileIdentity } from "./file-identity.mjs";
|
|
36
|
+
import { declarationsForSymbol } from "./semantic-identity.mjs";
|
|
37
|
+
|
|
38
|
+
const { SymbolFlags, TypeFlags } = sync;
|
|
39
|
+
const {
|
|
40
|
+
isArrowFunction,
|
|
41
|
+
isAsExpression,
|
|
42
|
+
isBinaryExpression,
|
|
43
|
+
isCallExpression,
|
|
44
|
+
isClassDeclaration,
|
|
45
|
+
isConditionalExpression,
|
|
46
|
+
isDoStatement,
|
|
47
|
+
isElementAccessExpression,
|
|
48
|
+
isForStatement,
|
|
49
|
+
isFunctionDeclaration,
|
|
50
|
+
isFunctionExpression,
|
|
51
|
+
isIdentifier,
|
|
52
|
+
isIfStatement,
|
|
53
|
+
isMethodDeclaration,
|
|
54
|
+
isNonNullExpression,
|
|
55
|
+
isParenthesizedExpression,
|
|
56
|
+
isPrefixUnaryExpression,
|
|
57
|
+
isPropertyAccessExpression,
|
|
58
|
+
isSatisfiesExpression,
|
|
59
|
+
isSpreadElement,
|
|
60
|
+
isStringLiteralLikeNode,
|
|
61
|
+
isTypeAssertion,
|
|
62
|
+
isVariableDeclaration,
|
|
63
|
+
isWhileStatement,
|
|
64
|
+
} = ast;
|
|
65
|
+
|
|
66
|
+
const SCRIPT_EXTENSIONS = new Set([".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"]);
|
|
67
|
+
const IDENTIFIER_TOKENS = /[A-Za-z_$][\w$]*/gu;
|
|
68
|
+
const MAX_UNION_MEMBERS = 64;
|
|
69
|
+
const MAYBE_UNDEFINED_FLAGS =
|
|
70
|
+
TypeFlags.Undefined |
|
|
71
|
+
TypeFlags.Void |
|
|
72
|
+
TypeFlags.Any |
|
|
73
|
+
TypeFlags.Unknown |
|
|
74
|
+
TypeFlags.TypeParameter |
|
|
75
|
+
TypeFlags.Index |
|
|
76
|
+
TypeFlags.IndexedAccess |
|
|
77
|
+
TypeFlags.Conditional |
|
|
78
|
+
TypeFlags.Substitution;
|
|
79
|
+
|
|
80
|
+
const utf16Offset = (bytes, byteOffset) => bytes.subarray(0, byteOffset).toString("utf8").length;
|
|
81
|
+
|
|
82
|
+
const strictNullChecks = (project) => {
|
|
83
|
+
const options = projectCompilerOptions(project);
|
|
84
|
+
return (
|
|
85
|
+
options.strictNullChecks === true ||
|
|
86
|
+
(options.strictNullChecks === undefined && options.strict === true)
|
|
87
|
+
);
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const withoutWrappers = (node) => {
|
|
91
|
+
let current = node;
|
|
92
|
+
while (isParenthesizedExpression(current) || isSatisfiesExpression(current))
|
|
93
|
+
current = current.expression;
|
|
94
|
+
return current;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const isConstAssertion = (node) =>
|
|
98
|
+
isAsExpression(node) &&
|
|
99
|
+
node.type?.kind === SyntaxKind.TypeReference &&
|
|
100
|
+
node.type.typeName?.text === "const";
|
|
101
|
+
|
|
102
|
+
// An assertion tells the checker a type that no code proves, so a value under
|
|
103
|
+
// one has no type evidence. `as const` only narrows a literal.
|
|
104
|
+
const containsAssertion = (node) => {
|
|
105
|
+
if (
|
|
106
|
+
isNonNullExpression(node) ||
|
|
107
|
+
isTypeAssertion(node) ||
|
|
108
|
+
(isAsExpression(node) && !isConstAssertion(node))
|
|
109
|
+
) {
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
let found = false;
|
|
113
|
+
node.forEachChild((child) => {
|
|
114
|
+
found = found || containsAssertion(child);
|
|
115
|
+
return found ? true : undefined;
|
|
116
|
+
});
|
|
117
|
+
return found;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
// The checker can fail on the members of some generic types. No members means
|
|
121
|
+
// no proof.
|
|
122
|
+
const membersOf = (type) => {
|
|
123
|
+
try {
|
|
124
|
+
return type.getTypes?.() ?? [];
|
|
125
|
+
} catch {
|
|
126
|
+
return [];
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const maybeUndefined = (type, depth = 0) => {
|
|
131
|
+
if (depth > 4) return true;
|
|
132
|
+
if (type.flags & TypeFlags.Union) {
|
|
133
|
+
const members = membersOf(type);
|
|
134
|
+
if (members.length === 0 || members.length > MAX_UNION_MEMBERS) return true;
|
|
135
|
+
return members.some((member) => maybeUndefined(member, depth + 1));
|
|
136
|
+
}
|
|
137
|
+
if (type.flags & TypeFlags.Intersection) {
|
|
138
|
+
const members = membersOf(type);
|
|
139
|
+
// An intersection with no known member proves nothing.
|
|
140
|
+
if (members.length === 0) return true;
|
|
141
|
+
return members.every((member) => maybeUndefined(member, depth + 1));
|
|
142
|
+
}
|
|
143
|
+
return type.flags === 0 || (type.flags & MAYBE_UNDEFINED_FLAGS) !== 0;
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const JAVASCRIPT_EXTENSIONS = new Set([".js", ".jsx", ".mjs", ".cjs"]);
|
|
147
|
+
|
|
148
|
+
// A JavaScript file that the project does not check has inferred types that
|
|
149
|
+
// no code proves, so only the form of the argument counts there.
|
|
150
|
+
const isTypeChecked = (project, sourceFile) =>
|
|
151
|
+
!JAVASCRIPT_EXTENSIONS.has(path.extname(sourceFile.fileName).toLowerCase()) ||
|
|
152
|
+
projectCompilerOptions(project).checkJs === true;
|
|
153
|
+
|
|
154
|
+
// Expressions whose value is never `undefined`, whatever the types say.
|
|
155
|
+
const NEVER_UNDEFINED_KINDS = new Set([
|
|
156
|
+
SyntaxKind.StringLiteral,
|
|
157
|
+
SyntaxKind.NoSubstitutionTemplateLiteral,
|
|
158
|
+
SyntaxKind.TemplateExpression,
|
|
159
|
+
SyntaxKind.NumericLiteral,
|
|
160
|
+
SyntaxKind.BigIntLiteral,
|
|
161
|
+
SyntaxKind.RegularExpressionLiteral,
|
|
162
|
+
SyntaxKind.TrueKeyword,
|
|
163
|
+
SyntaxKind.FalseKeyword,
|
|
164
|
+
SyntaxKind.NullKeyword,
|
|
165
|
+
SyntaxKind.ObjectLiteralExpression,
|
|
166
|
+
SyntaxKind.ArrayLiteralExpression,
|
|
167
|
+
SyntaxKind.ArrowFunction,
|
|
168
|
+
SyntaxKind.FunctionExpression,
|
|
169
|
+
SyntaxKind.ClassExpression,
|
|
170
|
+
SyntaxKind.NewExpression,
|
|
171
|
+
]);
|
|
172
|
+
|
|
173
|
+
// The evidence for one argument that needs no type, or `null` when the type
|
|
174
|
+
// decides. The second value is the expression whose type decides.
|
|
175
|
+
const syntacticArgument = (project, argument) => {
|
|
176
|
+
const expression = withoutWrappers(argument);
|
|
177
|
+
const unknown = { maybe_undefined: true };
|
|
178
|
+
if (NEVER_UNDEFINED_KINDS.has(expression.kind)) return [{ maybe_undefined: false }, null];
|
|
179
|
+
if (!isTypeChecked(project, expression.getSourceFile())) {
|
|
180
|
+
return [{ ...unknown, reason: "unchecked-javascript" }, null];
|
|
181
|
+
}
|
|
182
|
+
if (containsAssertion(expression)) return [{ ...unknown, reason: "assertion" }, null];
|
|
183
|
+
return [null, expression];
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
const typedArgument = (project, type) => {
|
|
187
|
+
if (!type) return { maybe_undefined: true, reason: "no-type" };
|
|
188
|
+
// Without `strictNullChecks`, a type drops `undefined`, so `T | undefined`
|
|
189
|
+
// reads as `T`. Such a type proves nothing.
|
|
190
|
+
if (!strictNullChecks(project)) return { maybe_undefined: true, reason: "not-strict" };
|
|
191
|
+
return { maybe_undefined: maybeUndefined(type) };
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
const isConstDeclaration = (declaration) =>
|
|
195
|
+
isVariableDeclaration(declaration) && (declaration.parent.flags & NodeFlags.Const) !== 0;
|
|
196
|
+
|
|
197
|
+
const MUTABLE_KINDS = new Set([
|
|
198
|
+
SyntaxKind.VariableDeclaration,
|
|
199
|
+
SyntaxKind.Parameter,
|
|
200
|
+
SyntaxKind.BindingElement,
|
|
201
|
+
]);
|
|
202
|
+
|
|
203
|
+
// The ids of the symbols that code of a file writes, from one batched checker
|
|
204
|
+
// request. `unresolved` is true when a write target has no symbol.
|
|
205
|
+
const writesOf = (project, sourceFile, cache) => {
|
|
206
|
+
if (cache.has(sourceFile.fileName)) return cache.get(sourceFile.fileName);
|
|
207
|
+
const targets = [];
|
|
208
|
+
const visit = (node) => {
|
|
209
|
+
if (isIdentifier(node) && targetDirection(node) !== "read") targets.push(node);
|
|
210
|
+
node.forEachChild(visit);
|
|
211
|
+
};
|
|
212
|
+
visit(sourceFile);
|
|
213
|
+
const writes = { ids: new Set(), unresolved: false };
|
|
214
|
+
if (targets.length > 0) {
|
|
215
|
+
const symbols = project.checker.getSymbolAtLocation(targets);
|
|
216
|
+
symbols.forEach((symbol) => {
|
|
217
|
+
if (symbol) writes.ids.add(symbol.id);
|
|
218
|
+
else writes.unresolved = true;
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
cache.set(sourceFile.fileName, writes);
|
|
222
|
+
return writes;
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
// True when a binding can hold a value that the narrowed type at a read does
|
|
226
|
+
// not show. The checker keeps a narrowing across a call, also when the call
|
|
227
|
+
// writes the binding in a closure, so a `let`, `var` or parameter that any
|
|
228
|
+
// code of the module writes has only its declared type as evidence.
|
|
229
|
+
const isWrittenBinding = (project, symbol, cache) => {
|
|
230
|
+
const declarations = declarationsForSymbol(project, symbol);
|
|
231
|
+
if (declarations.length !== 1) return declarations.length > 1;
|
|
232
|
+
const [declaration] = declarations;
|
|
233
|
+
if (!MUTABLE_KINDS.has(declaration.kind) || isConstDeclaration(declaration)) return false;
|
|
234
|
+
const sourceFile = declaration.getSourceFile();
|
|
235
|
+
if (sourceFile.externalModuleIndicator === undefined && sourceFile.isDeclarationFile !== true)
|
|
236
|
+
return true;
|
|
237
|
+
const writes = writesOf(project, sourceFile, cache);
|
|
238
|
+
return writes.unresolved || writes.ids.has(symbol.id);
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
// The identifiers that an expression reads, whether it reads a member, and
|
|
242
|
+
// whether it reads an index.
|
|
243
|
+
const readsOf = (expression) => {
|
|
244
|
+
const identifiers = [];
|
|
245
|
+
let members = false;
|
|
246
|
+
let indexes = false;
|
|
247
|
+
let calls = false;
|
|
248
|
+
let optional = false;
|
|
249
|
+
const visit = (node) => {
|
|
250
|
+
if (isFunctionLike(node)) return;
|
|
251
|
+
if (isPropertyAccessExpression(node) || isElementAccessExpression(node)) members = true;
|
|
252
|
+
if (isElementAccessExpression(node)) indexes = true;
|
|
253
|
+
if (isCallExpression(node)) calls = true;
|
|
254
|
+
if (node.questionDotToken !== undefined) optional = true;
|
|
255
|
+
if (isIdentifier(node)) {
|
|
256
|
+
const parent = node.parent;
|
|
257
|
+
const isName =
|
|
258
|
+
(isPropertyAccessExpression(parent) && parent.name === node) ||
|
|
259
|
+
(parent?.kind === SyntaxKind.PropertyAssignment && parent.name === node);
|
|
260
|
+
if (!isName) identifiers.push(node);
|
|
261
|
+
}
|
|
262
|
+
node.forEachChild(visit);
|
|
263
|
+
};
|
|
264
|
+
visit(expression);
|
|
265
|
+
return { identifiers, members, indexes, calls, optional };
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
const uncheckedIndexes = (project) =>
|
|
269
|
+
projectCompilerOptions(project).noUncheckedIndexedAccess !== true;
|
|
270
|
+
|
|
271
|
+
const strictPropertyInitialization = (project) => {
|
|
272
|
+
const options = projectCompilerOptions(project);
|
|
273
|
+
return (
|
|
274
|
+
strictNullChecks(project) &&
|
|
275
|
+
(options.strictPropertyInitialization === true ||
|
|
276
|
+
(options.strictPropertyInitialization === undefined && options.strict === true))
|
|
277
|
+
);
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
const MAX_VALUE_DEPTH = 4;
|
|
281
|
+
const TS_DIRECTIVE = /@ts-(?:ignore|expect-error|nocheck)\b/u;
|
|
282
|
+
|
|
283
|
+
// A `@ts-ignore`, `@ts-expect-error` or `@ts-nocheck` comment lets a file
|
|
284
|
+
// declare a type that its code does not satisfy.
|
|
285
|
+
const hasTsDirective = (sourceFile, context) => {
|
|
286
|
+
const { fileName } = sourceFile;
|
|
287
|
+
if (!context.directives.has(fileName))
|
|
288
|
+
context.directives.set(fileName, TS_DIRECTIVE.test(sourceFile.text));
|
|
289
|
+
return context.directives.get(fileName);
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Why the value of an expression can differ from its type, or null. The
|
|
294
|
+
* check follows the bindings that the expression reads, a few levels deep:
|
|
295
|
+
* an assertion, an `any` value, a `@ts-*` comment, a definite assignment, an
|
|
296
|
+
* ambient declaration, and, without `noUncheckedIndexedAccess`, an index read
|
|
297
|
+
* or a call result, whose type can drop `undefined`.
|
|
298
|
+
*/
|
|
299
|
+
const valueRisk = (project, expression, context, depth = 0) => {
|
|
300
|
+
if (depth > MAX_VALUE_DEPTH) return "deep-value";
|
|
301
|
+
if (containsAssertion(expression)) return "assertion";
|
|
302
|
+
if (hasTsDirective(expression.getSourceFile(), context)) return "ts-directive";
|
|
303
|
+
const reads = readsOf(expression);
|
|
304
|
+
if (uncheckedIndexes(project) && reads.indexes) return "index-read";
|
|
305
|
+
if (uncheckedIndexes(project) && reads.calls) return "call-result";
|
|
306
|
+
for (const identifier of reads.identifiers) {
|
|
307
|
+
const risk = identifierRisk(project, identifier, context, depth);
|
|
308
|
+
if (risk) return risk;
|
|
309
|
+
}
|
|
310
|
+
return null;
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
const symbolOfIdentifier = (project, identifier, context) => {
|
|
314
|
+
if (!context.symbols.has(identifier)) {
|
|
315
|
+
context.symbols.set(identifier, project.checker.getSymbolAtLocation(identifier) ?? null);
|
|
316
|
+
}
|
|
317
|
+
return context.symbols.get(identifier);
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
// The symbol that an import alias names, so the check reads the declaration
|
|
321
|
+
// in the module that declares it.
|
|
322
|
+
const resolvedSymbol = (project, symbol) => {
|
|
323
|
+
if ((symbol.flags & SymbolFlags.Alias) === 0) return symbol;
|
|
324
|
+
const target = project.checker.getAliasedSymbol(symbol);
|
|
325
|
+
return project.checker.isUnknownSymbol(target) ? null : target;
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
const identifierRisk = (project, identifier, context, depth) => {
|
|
329
|
+
const found = symbolOfIdentifier(project, identifier, context);
|
|
330
|
+
const symbol = found && resolvedSymbol(project, found);
|
|
331
|
+
if (!symbol) return identifier.text === "undefined" ? "undefined" : "no-symbol";
|
|
332
|
+
if (context.visited.has(symbol.id)) return null;
|
|
333
|
+
context.visited.add(symbol.id);
|
|
334
|
+
const declarations = declarationsForSymbol(project, symbol);
|
|
335
|
+
for (const declaration of declarations) {
|
|
336
|
+
const risk = declarationRisk(project, declaration, context, depth + 1);
|
|
337
|
+
if (risk) return risk;
|
|
338
|
+
}
|
|
339
|
+
return null;
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
// Why the declared type of a declaration is not evidence of its value, or
|
|
343
|
+
// null. A destructured binding can read an index.
|
|
344
|
+
const declarationRisk = (project, declaration, context, depth) => {
|
|
345
|
+
if (isAmbient(declaration)) return "ambient";
|
|
346
|
+
if (hasTsDirective(declaration.getSourceFile(), context)) return "ts-directive";
|
|
347
|
+
if (declaration.kind === SyntaxKind.BindingElement) {
|
|
348
|
+
return uncheckedIndexes(project) ? "index-read" : null;
|
|
349
|
+
}
|
|
350
|
+
if (!isVariableDeclaration(declaration)) return null;
|
|
351
|
+
if (declaration.exclamationToken !== undefined) return "definite-assignment";
|
|
352
|
+
if (!declaration.initializer) return null;
|
|
353
|
+
const type = project.checker.getTypeAtLocation(declaration.initializer);
|
|
354
|
+
if (!type || (type.flags & (TypeFlags.Any | TypeFlags.Unknown)) !== 0) return "any-value";
|
|
355
|
+
return valueRisk(project, declaration.initializer, context, depth);
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
const SET_MEMBER_KINDS = new Set([
|
|
359
|
+
SyntaxKind.PropertySignature,
|
|
360
|
+
SyntaxKind.GetAccessor,
|
|
361
|
+
SyntaxKind.MethodDeclaration,
|
|
362
|
+
SyntaxKind.MethodSignature,
|
|
363
|
+
SyntaxKind.Parameter,
|
|
364
|
+
]);
|
|
365
|
+
|
|
366
|
+
// Why a member declaration does not hold a value of its declared type, or
|
|
367
|
+
// null. A class field without an initializer is `undefined` until code sets
|
|
368
|
+
// it, unless the checker enforces the set, and an object literal property
|
|
369
|
+
// holds the value of its initializer.
|
|
370
|
+
const memberRisk = (project, declaration, context) => {
|
|
371
|
+
if (isAmbient(declaration)) return "ambient";
|
|
372
|
+
if (hasTsDirective(declaration.getSourceFile(), context)) return "ts-directive";
|
|
373
|
+
if (SET_MEMBER_KINDS.has(declaration.kind)) return null;
|
|
374
|
+
if (declaration.kind === SyntaxKind.PropertyAssignment) {
|
|
375
|
+
return valueRisk(project, declaration.initializer, context, 1);
|
|
376
|
+
}
|
|
377
|
+
if (declaration.kind === SyntaxKind.ShorthandPropertyAssignment) {
|
|
378
|
+
return valueRisk(project, declaration.name, context, 1);
|
|
379
|
+
}
|
|
380
|
+
if (declaration.kind !== SyntaxKind.PropertyDeclaration) return "member-not-set";
|
|
381
|
+
if (hasToken(declaration, SyntaxKind.ExclamationToken)) return "member-not-set";
|
|
382
|
+
if (declaration.initializer) return valueRisk(project, declaration.initializer, context, 1);
|
|
383
|
+
return strictPropertyInitialization(project) ? null : "member-not-set";
|
|
384
|
+
};
|
|
385
|
+
|
|
386
|
+
// True for `this.x` in a constructor or a field initializer, where a field
|
|
387
|
+
// can still be unset.
|
|
388
|
+
const readsUnsetThis = (expression) => {
|
|
389
|
+
if (expression.expression?.kind !== SyntaxKind.ThisKeyword) return false;
|
|
390
|
+
for (let node = expression.parent; node; node = node.parent) {
|
|
391
|
+
if (node.kind === SyntaxKind.Constructor || node.kind === SyntaxKind.PropertyDeclaration)
|
|
392
|
+
return true;
|
|
393
|
+
if (isFunctionLike(node) || node.kind === SyntaxKind.ClassDeclaration) return false;
|
|
394
|
+
}
|
|
395
|
+
return false;
|
|
396
|
+
};
|
|
397
|
+
|
|
398
|
+
const noEvidence = (reason) => ({ maybe_undefined: true, reason });
|
|
399
|
+
|
|
400
|
+
// Why a binding gives no evidence at a call, `written` when only its declared
|
|
401
|
+
// type is evidence, or null when the type at the call is evidence.
|
|
402
|
+
const bindingReason = (project, identifier, context) => {
|
|
403
|
+
const risk = identifierRisk(project, identifier, context, 0);
|
|
404
|
+
if (risk) return risk;
|
|
405
|
+
const symbol = symbolOfIdentifier(project, identifier, context);
|
|
406
|
+
return isWrittenBinding(project, symbol, context.writes) ? "written" : null;
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
const blockingRead = (project, plan, context) => {
|
|
410
|
+
for (const identifier of plan.identifiers) {
|
|
411
|
+
context.visited = new Set();
|
|
412
|
+
const reason = bindingReason(project, identifier, context);
|
|
413
|
+
if (reason === "written")
|
|
414
|
+
return plan.expression === identifier ? "declared" : "written-binding";
|
|
415
|
+
if (reason) return reason;
|
|
416
|
+
}
|
|
417
|
+
return null;
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
const memberEvidence = (project, expression, context) => {
|
|
421
|
+
if (readsOf(expression).optional) return { reason: "optional-chain" };
|
|
422
|
+
if (readsUnsetThis(expression)) return { reason: "member-not-set" };
|
|
423
|
+
const member = project.checker.getSymbolAtLocation(expression.name);
|
|
424
|
+
if (!member) return { reason: "no-symbol" };
|
|
425
|
+
context.visited = new Set();
|
|
426
|
+
const declarations = declarationsForSymbol(project, member);
|
|
427
|
+
if (declarations.length === 0) return { reason: "member-not-set" };
|
|
428
|
+
for (const declaration of declarations) {
|
|
429
|
+
const risk = memberRisk(project, declaration, context);
|
|
430
|
+
if (risk) return { reason: risk };
|
|
431
|
+
}
|
|
432
|
+
context.visited = new Set();
|
|
433
|
+
const receiver = valueRisk(project, expression.expression, context, 1);
|
|
434
|
+
return receiver ? { reason: receiver } : { declared: member };
|
|
435
|
+
};
|
|
436
|
+
|
|
437
|
+
// Where the evidence of one argument comes from: the type at the call, the
|
|
438
|
+
// declared type of a symbol, or nowhere, with a reason.
|
|
439
|
+
const planEvidence = (project, plan, context) => {
|
|
440
|
+
const { expression } = plan;
|
|
441
|
+
if (hasTsDirective(expression.getSourceFile(), context)) return { reason: "ts-directive" };
|
|
442
|
+
if (isPropertyAccessExpression(expression)) return memberEvidence(project, expression, context);
|
|
443
|
+
if (plan.members) return { reason: "member-read" };
|
|
444
|
+
if (uncheckedIndexes(project) && plan.calls) return { reason: "call-result" };
|
|
445
|
+
const blocked = blockingRead(project, plan, context);
|
|
446
|
+
if (blocked === "declared") return { declared: symbolOfIdentifier(project, expression, context) };
|
|
447
|
+
return blocked ? { reason: blocked } : { atCall: true };
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
// A user-defined type guard (`x is T`, `asserts x is T`) is a claim that no
|
|
451
|
+
// code checks. True when a call in the function around `identifier` passes
|
|
452
|
+
// the same name to such a guard.
|
|
453
|
+
const guardedByPredicate = (project, identifier) => {
|
|
454
|
+
let scope = identifier.parent;
|
|
455
|
+
while (scope && !isFunctionLike(scope) && scope.kind !== SyntaxKind.SourceFile)
|
|
456
|
+
scope = scope.parent;
|
|
457
|
+
if (!scope) return false;
|
|
458
|
+
let guarded = false;
|
|
459
|
+
const visit = (node) => {
|
|
460
|
+
if (guarded) return;
|
|
461
|
+
if (
|
|
462
|
+
isCallExpression(node) &&
|
|
463
|
+
(node.arguments ?? []).some(
|
|
464
|
+
(argument) => isIdentifier(argument) && argument.text === identifier.text,
|
|
465
|
+
)
|
|
466
|
+
) {
|
|
467
|
+
const signature = project.checker.getResolvedSignature(node);
|
|
468
|
+
if (signature && project.checker.getTypePredicateOfSignature(signature)) guarded = true;
|
|
469
|
+
}
|
|
470
|
+
node.forEachChild(visit);
|
|
471
|
+
};
|
|
472
|
+
visit(scope);
|
|
473
|
+
return guarded;
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
// The evidence for each argument of a list. A bare identifier of a binding
|
|
477
|
+
// that the module never writes, and an expression whose reads are all such
|
|
478
|
+
// bindings, use the type at the call. A written binding uses its declared
|
|
479
|
+
// type. A bare member read uses the declared type of the member, because
|
|
480
|
+
// code can change a member through another reference. Each other expression
|
|
481
|
+
// with a member read has no evidence.
|
|
482
|
+
const typeArguments = (project, argumentNodes) => {
|
|
483
|
+
const results = Array.from({ length: argumentNodes.length });
|
|
484
|
+
const plans = [];
|
|
485
|
+
argumentNodes.forEach((argument, index) => {
|
|
486
|
+
const [result, expression] = syntacticArgument(project, argument);
|
|
487
|
+
if (result) results[index] = result;
|
|
488
|
+
else plans.push({ index, expression, ...readsOf(expression) });
|
|
489
|
+
});
|
|
490
|
+
const identifiers = plans.flatMap((plan) => plan.identifiers);
|
|
491
|
+
const symbols = identifiers.length === 0 ? [] : project.checker.getSymbolAtLocation(identifiers);
|
|
492
|
+
const context = {
|
|
493
|
+
symbols: new Map(identifiers.map((identifier, at) => [identifier, symbols[at] ?? null])),
|
|
494
|
+
writes: new Map(),
|
|
495
|
+
directives: new Map(),
|
|
496
|
+
visited: new Set(),
|
|
497
|
+
};
|
|
498
|
+
const atCall = [];
|
|
499
|
+
for (const plan of plans) {
|
|
500
|
+
const source = planEvidence(project, plan, context);
|
|
501
|
+
if (source.atCall) atCall.push(plan);
|
|
502
|
+
else if (source.declared) {
|
|
503
|
+
results[plan.index] = typedArgument(
|
|
504
|
+
project,
|
|
505
|
+
project.checker.getTypeOfSymbol(source.declared),
|
|
506
|
+
);
|
|
507
|
+
} else results[plan.index] = noEvidence(source.reason ?? "no-symbol");
|
|
508
|
+
}
|
|
509
|
+
if (atCall.length > 0) {
|
|
510
|
+
const types = project.checker.getTypeAtLocation(atCall.map((plan) => plan.expression));
|
|
511
|
+
atCall.forEach((plan, at) => {
|
|
512
|
+
const evidence = typedArgument(project, types[at]);
|
|
513
|
+
const narrowed = !evidence.maybe_undefined && isIdentifier(plan.expression);
|
|
514
|
+
results[plan.index] =
|
|
515
|
+
narrowed && guardedByPredicate(project, plan.expression)
|
|
516
|
+
? noEvidence("type-predicate")
|
|
517
|
+
: evidence;
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
return results;
|
|
521
|
+
};
|
|
522
|
+
|
|
523
|
+
// The call expression at each start. Chained calls such as `f(x).g()` share a
|
|
524
|
+
// start, so the deepest call at a start is the call of its callee.
|
|
525
|
+
const callsByStart = (sourceFile, starts) => {
|
|
526
|
+
const found = new Map();
|
|
527
|
+
const visit = (node) => {
|
|
528
|
+
if (isCallExpression(node)) {
|
|
529
|
+
const start = node.getStart(sourceFile);
|
|
530
|
+
if (starts.has(start)) found.set(start, node);
|
|
531
|
+
}
|
|
532
|
+
node.forEachChild(visit);
|
|
533
|
+
};
|
|
534
|
+
visit(sourceFile);
|
|
535
|
+
return found;
|
|
536
|
+
};
|
|
537
|
+
|
|
538
|
+
// The checker gives file names with forward slashes, and a request path has
|
|
539
|
+
// the separators of the platform. The identities make both forms comparable.
|
|
540
|
+
const programEntry = (project) => {
|
|
541
|
+
const files = new Set(project.program.getSourceFileNames());
|
|
542
|
+
return { project, files, identities: new Set([...files].map(canonicalFileIdentity)) };
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
// The programs of the request. A project object belongs to the snapshot that
|
|
546
|
+
// made it, so each snapshot stays open until the request ends.
|
|
547
|
+
class Programs {
|
|
548
|
+
constructor(root, createApi) {
|
|
549
|
+
this.api = createApi({ cwd: root });
|
|
550
|
+
this.snapshots = [];
|
|
551
|
+
this.projects = new Map();
|
|
552
|
+
this.byFile = new Map();
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
track(snapshot) {
|
|
556
|
+
this.snapshots.push(snapshot);
|
|
557
|
+
return snapshot;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
defaultConfig(absolutePath) {
|
|
561
|
+
this.probes = (this.probes ?? 0) + 1;
|
|
562
|
+
const probe = this.track(this.api.updateSnapshot({ openFiles: [absolutePath] }));
|
|
563
|
+
const project = probe.getDefaultProjectForFile(absolutePath);
|
|
564
|
+
const config = project && !isInferredProject(project) ? project.configFileName : null;
|
|
565
|
+
this.track(this.api.updateSnapshot({ closeFiles: [absolutePath] }));
|
|
566
|
+
return config;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
open(config) {
|
|
570
|
+
if (!this.projects.has(config)) {
|
|
571
|
+
const started = performance.now();
|
|
572
|
+
const snapshot = this.track(this.api.updateSnapshot({ openProjects: [config] }));
|
|
573
|
+
const project = snapshot.getProject(config) ?? null;
|
|
574
|
+
this.projects.set(config, project && programEntry(project));
|
|
575
|
+
this.openMs = (this.openMs ?? 0) + (performance.now() - started);
|
|
576
|
+
}
|
|
577
|
+
return this.projects.get(config);
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** The open program that holds a file, with its file names. */
|
|
581
|
+
entry(absolutePath) {
|
|
582
|
+
if (this.byFile.has(absolutePath)) return this.byFile.get(absolutePath);
|
|
583
|
+
let found = null;
|
|
584
|
+
// The checker parses only script files. It fails on a component file.
|
|
585
|
+
if (SCRIPT_EXTENSIONS.has(path.extname(absolutePath).toLowerCase())) {
|
|
586
|
+
for (const entry of this.projects.values()) {
|
|
587
|
+
if (entry?.identities.has(canonicalFileIdentity(absolutePath))) {
|
|
588
|
+
found = entry;
|
|
589
|
+
break;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
if (found === null) {
|
|
593
|
+
const config = this.defaultConfig(absolutePath);
|
|
594
|
+
const entry = config === null ? null : this.open(config);
|
|
595
|
+
found = entry?.identities.has(canonicalFileIdentity(absolutePath)) ? entry : null;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
this.byFile.set(absolutePath, found);
|
|
599
|
+
return found;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
project(absolutePath) {
|
|
603
|
+
return this.entry(absolutePath)?.project ?? null;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
close() {
|
|
607
|
+
for (const snapshot of this.snapshots.toReversed()) snapshot.dispose();
|
|
608
|
+
this.api.close();
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const readBytes = (absolutePath) => {
|
|
613
|
+
try {
|
|
614
|
+
return readFileSync(absolutePath);
|
|
615
|
+
} catch {
|
|
616
|
+
return null;
|
|
617
|
+
}
|
|
618
|
+
};
|
|
619
|
+
|
|
620
|
+
const unchecked = (request, reason) => ({ id: request.id, outcome: "unchecked", reason });
|
|
621
|
+
|
|
622
|
+
// The evidence of each requested argument of one file.
|
|
623
|
+
const fileArgumentEvidence = (programs, absolutePath, requests) => {
|
|
624
|
+
const project = programs.project(absolutePath);
|
|
625
|
+
if (!project) return requests.map((request) => unchecked(request, "no-project"));
|
|
626
|
+
const bytes = readBytes(absolutePath);
|
|
627
|
+
if (!bytes) return requests.map((request) => unchecked(request, "file-missing"));
|
|
628
|
+
const sourceFile = project.program.getSourceFile(absolutePath);
|
|
629
|
+
const starts = new Map(
|
|
630
|
+
requests.map((request) => [request, utf16Offset(bytes, request.call_start)]),
|
|
631
|
+
);
|
|
632
|
+
const calls = callsByStart(sourceFile, new Set(starts.values()));
|
|
633
|
+
const results = new Map();
|
|
634
|
+
const nodes = [];
|
|
635
|
+
for (const request of requests) {
|
|
636
|
+
const call = calls.get(starts.get(request));
|
|
637
|
+
const args = call?.arguments ?? [];
|
|
638
|
+
if (!call) results.set(request, unchecked(request, "call-not-found"));
|
|
639
|
+
else if (args.slice(0, request.index + 1).some(isSpreadElement))
|
|
640
|
+
results.set(request, unchecked(request, "spread"));
|
|
641
|
+
else if (!args[request.index]) results.set(request, unchecked(request, "argument-not-found"));
|
|
642
|
+
else nodes.push([request, args[request.index]]);
|
|
643
|
+
}
|
|
644
|
+
const typed = typeArguments(
|
|
645
|
+
project,
|
|
646
|
+
nodes.map(([, node]) => node),
|
|
647
|
+
);
|
|
648
|
+
nodes.forEach(([request], index) =>
|
|
649
|
+
results.set(request, { id: request.id, outcome: "typed", ...typed[index] }),
|
|
650
|
+
);
|
|
651
|
+
return requests.map((request) => results.get(request));
|
|
652
|
+
};
|
|
653
|
+
|
|
654
|
+
const typeRound = (programs, root, args) => {
|
|
655
|
+
const byFile = new Map();
|
|
656
|
+
for (const request of args) {
|
|
657
|
+
const absolutePath = path.resolve(root, request.path);
|
|
658
|
+
if (!byFile.has(absolutePath)) byFile.set(absolutePath, []);
|
|
659
|
+
byFile.get(absolutePath).push(request);
|
|
660
|
+
}
|
|
661
|
+
const results = new Map();
|
|
662
|
+
for (const [absolutePath, requests] of byFile) {
|
|
663
|
+
let evidence;
|
|
664
|
+
try {
|
|
665
|
+
evidence = fileArgumentEvidence(programs, absolutePath, requests);
|
|
666
|
+
} catch {
|
|
667
|
+
evidence = requests.map((request) => unchecked(request, "checker-error"));
|
|
668
|
+
}
|
|
669
|
+
evidence.forEach((result) => results.set(result.id, result));
|
|
670
|
+
}
|
|
671
|
+
return results;
|
|
672
|
+
};
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* The evidence of each default candidate: `defined` when no argument can be
|
|
676
|
+
* `undefined`. The first round types one argument of each candidate, the
|
|
677
|
+
* second round the rest of the candidates that the first round keeps, so a
|
|
678
|
+
* candidate that one argument rules out costs one checker request.
|
|
679
|
+
*/
|
|
680
|
+
const defaultsEvidence = (programs, root, defaults) => {
|
|
681
|
+
const state = new Map(defaults.map((candidate) => [candidate.id, { outcome: "defined" }]));
|
|
682
|
+
const args = defaults.flatMap((candidate) =>
|
|
683
|
+
candidate.arguments.map((argument, at) => ({
|
|
684
|
+
...argument,
|
|
685
|
+
id: `${candidate.id}:${at}`,
|
|
686
|
+
group: candidate.id,
|
|
687
|
+
})),
|
|
688
|
+
);
|
|
689
|
+
const first = new Set();
|
|
690
|
+
const rounds = [[], []];
|
|
691
|
+
for (const request of args) {
|
|
692
|
+
if (first.has(request.group)) rounds[1].push(request);
|
|
693
|
+
else {
|
|
694
|
+
first.add(request.group);
|
|
695
|
+
rounds[0].push(request);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
for (const round of rounds) {
|
|
699
|
+
const pending = round.filter((request) => state.get(request.group).outcome === "defined");
|
|
700
|
+
const byId = new Map(pending.map((request) => [request.id, request]));
|
|
701
|
+
for (const [id, result] of typeRound(programs, root, pending)) {
|
|
702
|
+
const group = state.get(byId.get(id).group);
|
|
703
|
+
if (group.outcome !== "defined") continue;
|
|
704
|
+
if (result.outcome !== "typed")
|
|
705
|
+
state.set(byId.get(id).group, { outcome: "unchecked", reason: result.reason });
|
|
706
|
+
else if (result.maybe_undefined)
|
|
707
|
+
state.set(byId.get(id).group, { outcome: "maybe-undefined" });
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
return defaults.map((candidate) => ({ id: candidate.id, ...state.get(candidate.id) }));
|
|
711
|
+
};
|
|
712
|
+
|
|
713
|
+
const lineCol = (sourceFile, position) => {
|
|
714
|
+
const text = sourceFile.text;
|
|
715
|
+
const lineStart = text.lastIndexOf("\n", position - 1) + 1;
|
|
716
|
+
let line = 1;
|
|
717
|
+
for (let at = text.indexOf("\n"); at !== -1 && at < position; at = text.indexOf("\n", at + 1))
|
|
718
|
+
line += 1;
|
|
719
|
+
return { line, col: Buffer.byteLength(text.slice(lineStart, position), "utf8") };
|
|
720
|
+
};
|
|
721
|
+
|
|
722
|
+
const isFunctionLike = (node) =>
|
|
723
|
+
isFunctionDeclaration(node) ||
|
|
724
|
+
isFunctionExpression(node) ||
|
|
725
|
+
isArrowFunction(node) ||
|
|
726
|
+
isMethodDeclaration(node);
|
|
727
|
+
|
|
728
|
+
const conditionTest = (node) => {
|
|
729
|
+
if (
|
|
730
|
+
isIfStatement(node) ||
|
|
731
|
+
isWhileStatement(node) ||
|
|
732
|
+
isDoStatement(node) ||
|
|
733
|
+
isConditionalExpression(node)
|
|
734
|
+
) {
|
|
735
|
+
return isConditionalExpression(node) ? node.condition : node.expression;
|
|
736
|
+
}
|
|
737
|
+
if (isForStatement(node)) return node.condition;
|
|
738
|
+
return undefined;
|
|
739
|
+
};
|
|
740
|
+
|
|
741
|
+
const testsName = (test, name) => {
|
|
742
|
+
let current = test && withoutWrappers(test);
|
|
743
|
+
while (
|
|
744
|
+
current &&
|
|
745
|
+
isPrefixUnaryExpression(current) &&
|
|
746
|
+
current.operator === SyntaxKind.ExclamationToken
|
|
747
|
+
) {
|
|
748
|
+
current = withoutWrappers(current.operand);
|
|
749
|
+
}
|
|
750
|
+
return Boolean(current && isIdentifier(current) && current.text === name);
|
|
751
|
+
};
|
|
752
|
+
|
|
753
|
+
const ASSIGNMENT_OPERATORS = new Set([
|
|
754
|
+
SyntaxKind.EqualsToken,
|
|
755
|
+
SyntaxKind.PlusEqualsToken,
|
|
756
|
+
SyntaxKind.MinusEqualsToken,
|
|
757
|
+
SyntaxKind.AsteriskEqualsToken,
|
|
758
|
+
SyntaxKind.SlashEqualsToken,
|
|
759
|
+
SyntaxKind.QuestionQuestionEqualsToken,
|
|
760
|
+
SyntaxKind.BarBarEqualsToken,
|
|
761
|
+
SyntaxKind.AmpersandAmpersandEqualsToken,
|
|
762
|
+
SyntaxKind.PercentEqualsToken,
|
|
763
|
+
]);
|
|
764
|
+
|
|
765
|
+
const isIncrement = (node) =>
|
|
766
|
+
(node.kind === SyntaxKind.PrefixUnaryExpression ||
|
|
767
|
+
node.kind === SyntaxKind.PostfixUnaryExpression) &&
|
|
768
|
+
(node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken);
|
|
769
|
+
|
|
770
|
+
// The parameter names that one node writes. A destructuring target can
|
|
771
|
+
// write each name.
|
|
772
|
+
const writtenNames = (node, names) => {
|
|
773
|
+
if (isBinaryExpression(node) && ASSIGNMENT_OPERATORS.has(node.operatorToken.kind)) {
|
|
774
|
+
const target = withoutWrappers(node.left);
|
|
775
|
+
if (isIdentifier(target)) return names.includes(target.text) ? [target.text] : [];
|
|
776
|
+
return isPropertyAccessExpression(target) || isElementAccessExpression(target) ? [] : names;
|
|
777
|
+
}
|
|
778
|
+
if (isIncrement(node)) {
|
|
779
|
+
const operand = withoutWrappers(node.operand);
|
|
780
|
+
return isIdentifier(operand) && names.includes(operand.text) ? [operand.text] : [];
|
|
781
|
+
}
|
|
782
|
+
return [];
|
|
783
|
+
};
|
|
784
|
+
|
|
785
|
+
// Syntactic facts of the body: condition reads and writes of each parameter
|
|
786
|
+
// name, and a read of `arguments`. A nested function with the same name
|
|
787
|
+
// counts too, so the facts can only be too careful.
|
|
788
|
+
const bodyFacts = (method, names) => {
|
|
789
|
+
const facts = {
|
|
790
|
+
arguments: false,
|
|
791
|
+
reads: new Map(names.map((name) => [name, 0])),
|
|
792
|
+
written: new Set(),
|
|
793
|
+
};
|
|
794
|
+
const visit = (node) => {
|
|
795
|
+
if (isIdentifier(node) && node.text === "arguments") facts.arguments = true;
|
|
796
|
+
const test = conditionTest(node);
|
|
797
|
+
for (const name of names)
|
|
798
|
+
if (testsName(test, name)) facts.reads.set(name, facts.reads.get(name) + 1);
|
|
799
|
+
for (const name of writtenNames(node, names)) facts.written.add(name);
|
|
800
|
+
node.forEachChild(visit);
|
|
801
|
+
};
|
|
802
|
+
if (method.body) visit(method.body);
|
|
803
|
+
for (const parameter of method.parameters)
|
|
804
|
+
if (parameter.initializer) visit(parameter.initializer);
|
|
805
|
+
return facts;
|
|
806
|
+
};
|
|
807
|
+
|
|
808
|
+
const hasDecorators = (node) =>
|
|
809
|
+
(node.modifiers ?? []).some((modifier) => modifier.kind === SyntaxKind.Decorator) ||
|
|
810
|
+
(node.decorators?.length ?? 0) > 0;
|
|
811
|
+
|
|
812
|
+
const methodParams = (sourceFile, method) => {
|
|
813
|
+
const params = method.parameters.filter(
|
|
814
|
+
(parameter) => !(isIdentifier(parameter.name) && parameter.name.text === "this"),
|
|
815
|
+
);
|
|
816
|
+
const names = params
|
|
817
|
+
.filter((parameter) => isIdentifier(parameter.name))
|
|
818
|
+
.map((parameter) => parameter.name.text);
|
|
819
|
+
const facts = bodyFacts(method, names);
|
|
820
|
+
return {
|
|
821
|
+
readsArguments: facts.arguments,
|
|
822
|
+
params: params.map((parameter, index) => {
|
|
823
|
+
const identifier = isIdentifier(parameter.name);
|
|
824
|
+
const name = identifier ? parameter.name.text : null;
|
|
825
|
+
return {
|
|
826
|
+
index,
|
|
827
|
+
name,
|
|
828
|
+
pattern: !identifier,
|
|
829
|
+
rest: parameter.dotDotDotToken !== undefined,
|
|
830
|
+
optional: parameter.questionToken !== undefined,
|
|
831
|
+
has_default: parameter.initializer !== undefined,
|
|
832
|
+
written: name !== null && facts.written.has(name),
|
|
833
|
+
condition_reads: name === null ? 0 : facts.reads.get(name),
|
|
834
|
+
decorated: hasDecorators(parameter),
|
|
835
|
+
...lineCol(sourceFile, parameter.name.getStart(sourceFile)),
|
|
836
|
+
};
|
|
837
|
+
}),
|
|
838
|
+
};
|
|
839
|
+
};
|
|
840
|
+
|
|
841
|
+
// The callee of a call, without parentheses, must be the reference itself.
|
|
842
|
+
const calleeIsReference = (call, name) => {
|
|
843
|
+
const callee = withoutWrappers(call.expression);
|
|
844
|
+
if (isPropertyAccessExpression(callee))
|
|
845
|
+
return callee.name === name || callee.name.pos === name.pos;
|
|
846
|
+
if (isElementAccessExpression(callee)) return callee.argumentExpression?.pos === name.pos;
|
|
847
|
+
return callee.pos === name.pos;
|
|
848
|
+
};
|
|
849
|
+
|
|
850
|
+
const isPassThrough = (project, argument, method) => {
|
|
851
|
+
const expression = withoutWrappers(argument);
|
|
852
|
+
if (!isIdentifier(expression)) return null;
|
|
853
|
+
if (expression.pos < method.pos || expression.end > method.end) return null;
|
|
854
|
+
const symbol = project.checker.getSymbolAtLocation(expression);
|
|
855
|
+
const declaration = declarationsForSymbol(project, symbol)[0];
|
|
856
|
+
if (!declaration || declaration.parent !== method) return null;
|
|
857
|
+
return method.parameters.indexOf(declaration);
|
|
858
|
+
};
|
|
859
|
+
|
|
860
|
+
// The evidence of one call. An argument that needs a type is `null`, and
|
|
861
|
+
// its node goes to `pending` for one batched checker request.
|
|
862
|
+
const callEvidence = (project, method, call, name, pending) => {
|
|
863
|
+
const sourceFile = call.getSourceFile();
|
|
864
|
+
const args = call.arguments ?? [];
|
|
865
|
+
const spread = args.findIndex(isSpreadElement);
|
|
866
|
+
const evidence = {
|
|
867
|
+
path: sourceFile.fileName,
|
|
868
|
+
...lineCol(sourceFile, name.getStart(sourceFile)),
|
|
869
|
+
arg_count: args.length,
|
|
870
|
+
spread_from: spread === -1 ? null : spread,
|
|
871
|
+
args: [],
|
|
872
|
+
};
|
|
873
|
+
evidence.args = args.map((argument, index) => {
|
|
874
|
+
if (spread !== -1 && index >= spread) return { maybe_undefined: true };
|
|
875
|
+
const through = isPassThrough(project, argument, method);
|
|
876
|
+
if (through !== null) return { maybe_undefined: true, pass_through: through };
|
|
877
|
+
pending.push(argument);
|
|
878
|
+
return null;
|
|
879
|
+
});
|
|
880
|
+
return evidence;
|
|
881
|
+
};
|
|
882
|
+
|
|
883
|
+
// The module-scope class of the name. An exported class is a statement of
|
|
884
|
+
// the module, and a local class of the same name in a function is another
|
|
885
|
+
// class.
|
|
886
|
+
const declarationOfMethod = (sourceFile, className, methodName, start) => {
|
|
887
|
+
const classes = sourceFile.statements.filter(
|
|
888
|
+
(statement) => isClassDeclaration(statement) && statement.name?.text === className,
|
|
889
|
+
);
|
|
890
|
+
if (classes.length !== 1) return { classNode: null, methods: [] };
|
|
891
|
+
const [classNode] = classes;
|
|
892
|
+
const methods = classNode.members.filter(
|
|
893
|
+
(member) =>
|
|
894
|
+
isMethodDeclaration(member) &&
|
|
895
|
+
member.name &&
|
|
896
|
+
(member.name.text ?? member.name.escapedText) === methodName,
|
|
897
|
+
);
|
|
898
|
+
return { classNode, methods, start };
|
|
899
|
+
};
|
|
900
|
+
|
|
901
|
+
// A member of a base type or an interface outside the program, such as a
|
|
902
|
+
// framework base class, is called by code that the program does not hold.
|
|
903
|
+
const inheritsExternalMember = (project, classNode, methodName) => {
|
|
904
|
+
for (const clause of classNode.heritageClauses ?? []) {
|
|
905
|
+
for (const heritage of clause.types) {
|
|
906
|
+
const type = project.checker.getTypeAtLocation(heritage);
|
|
907
|
+
const property = type && project.checker.getPropertyOfType(type, methodName);
|
|
908
|
+
if (!property) continue;
|
|
909
|
+
const external = (property.declarations ?? []).some(
|
|
910
|
+
(handle) => /\.d\.[cm]?ts$/u.test(handle.path) || handle.path.includes("/node_modules/"),
|
|
911
|
+
);
|
|
912
|
+
if (external || (property.declarations ?? []).length === 0) return true;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
return false;
|
|
916
|
+
};
|
|
917
|
+
|
|
918
|
+
/** Each identifier token of a text, for a cheap first filter by name. */
|
|
919
|
+
const tokensOf = (text) => new Set(text.match(IDENTIFIER_TOKENS) ?? []);
|
|
920
|
+
|
|
921
|
+
const COMPUTED_CALL = /\]\s*(?:\?\.\s*)?\(/u;
|
|
922
|
+
// A computed access with a key that is not a string or a number, or a
|
|
923
|
+
// reflective read. Each can read a method that no reference names.
|
|
924
|
+
const COMPUTED_ACCESS = /[\w$)\]!]\s*(?:\?\.\s*)?\[\s*[A-Za-z_$(]|\bReflect\./u;
|
|
925
|
+
const REFLECT_CALL = /\bReflect\.(?:get|apply|construct)\s*\(/u;
|
|
926
|
+
const MEMBER_NAME = /(?:\?\.|\.)\s*([A-Za-z_$][\w$]*)/gu;
|
|
927
|
+
const STRING_KEY = /\[\s*(['"`])([A-Za-z_$][\w$]*)\1\s*\]/gu;
|
|
928
|
+
const STRING_NAME = /(['"`])([A-Za-z_$][\w$]*)\1/gu;
|
|
929
|
+
const OPEN_BRACKET = /([A-Za-z_$][\w$]*|[)\]!])\s*(?:\?\.\s*)?\[/gu;
|
|
930
|
+
const NOT_A_RECEIVER = new Set([
|
|
931
|
+
"return",
|
|
932
|
+
"case",
|
|
933
|
+
"in",
|
|
934
|
+
"of",
|
|
935
|
+
"typeof",
|
|
936
|
+
"void",
|
|
937
|
+
"yield",
|
|
938
|
+
"await",
|
|
939
|
+
"new",
|
|
940
|
+
"delete",
|
|
941
|
+
"throw",
|
|
942
|
+
"else",
|
|
943
|
+
"do",
|
|
944
|
+
"instanceof",
|
|
945
|
+
"extends",
|
|
946
|
+
"export",
|
|
947
|
+
"default",
|
|
948
|
+
"const",
|
|
949
|
+
"let",
|
|
950
|
+
"var",
|
|
951
|
+
]);
|
|
952
|
+
const CALL_AFTER = /^\s*(?:\?\.\s*)?(?:\(|\.\s*(?:call|apply|bind)\b)/u;
|
|
953
|
+
|
|
954
|
+
// The index after the `]` that closes the `[` at `open`, or -1.
|
|
955
|
+
const closingBracket = (text, open) => {
|
|
956
|
+
let depth = 0;
|
|
957
|
+
for (let at = open; at < text.length; at += 1) {
|
|
958
|
+
const char = text[at];
|
|
959
|
+
if (char === "[") depth += 1;
|
|
960
|
+
else if (char === "]") {
|
|
961
|
+
depth -= 1;
|
|
962
|
+
if (depth === 0) return at + 1;
|
|
963
|
+
} else if (char === "\n" && at - open > 400) return -1;
|
|
964
|
+
}
|
|
965
|
+
return -1;
|
|
966
|
+
};
|
|
967
|
+
|
|
968
|
+
/**
|
|
969
|
+
* The computed member accesses of a text, found without a parse: `x[key]`
|
|
970
|
+
* where `key` is not a string or a number. A match in a comment or a string
|
|
971
|
+
* only makes the scan more careful.
|
|
972
|
+
*/
|
|
973
|
+
const computedAccesses = (text) => {
|
|
974
|
+
const accesses = [];
|
|
975
|
+
for (const match of text.matchAll(OPEN_BRACKET)) {
|
|
976
|
+
const receiver = match[1];
|
|
977
|
+
if (NOT_A_RECEIVER.has(receiver)) continue;
|
|
978
|
+
const open = match.index + match[0].length - 1;
|
|
979
|
+
const next = text.slice(open + 1).match(/^\s*(.)/su)?.[1];
|
|
980
|
+
if (next === undefined || next === "]" || /['"`\d]/u.test(next)) continue;
|
|
981
|
+
const close = closingBracket(text, open);
|
|
982
|
+
const called = close !== -1 && CALL_AFTER.test(text.slice(close, close + 40));
|
|
983
|
+
accesses.push({ position: /[)\]!]/u.test(receiver) ? null : match.index, called });
|
|
984
|
+
}
|
|
985
|
+
return accesses;
|
|
986
|
+
};
|
|
987
|
+
|
|
988
|
+
const memberPositions = (text, wanted) => {
|
|
989
|
+
const positions = [];
|
|
990
|
+
for (const match of text.matchAll(MEMBER_NAME)) {
|
|
991
|
+
if (wanted.has(match[1]))
|
|
992
|
+
positions.push([match[1], match.index + match[0].length - match[1].length]);
|
|
993
|
+
}
|
|
994
|
+
for (const match of text.matchAll(STRING_KEY)) {
|
|
995
|
+
if (wanted.has(match[2])) positions.push([match[2], match.index + match[0].indexOf(match[1])]);
|
|
996
|
+
}
|
|
997
|
+
return positions;
|
|
998
|
+
};
|
|
999
|
+
|
|
1000
|
+
const isUntypedType = (type) =>
|
|
1001
|
+
!type || type.flags === 0 || (type.flags & (TypeFlags.Any | TypeFlags.Unknown)) !== 0;
|
|
1002
|
+
|
|
1003
|
+
/** The scan state of one program. */
|
|
1004
|
+
const programRisks = () => ({
|
|
1005
|
+
hard: new Map(),
|
|
1006
|
+
externalMembers: new Map(),
|
|
1007
|
+
prototypes: new Set(),
|
|
1008
|
+
strings: new Set(),
|
|
1009
|
+
untypedComputedCalls: 0,
|
|
1010
|
+
properties: new Map(),
|
|
1011
|
+
references: new Map(),
|
|
1012
|
+
});
|
|
1013
|
+
|
|
1014
|
+
const addRisk = (risks, name, reason) => {
|
|
1015
|
+
if (!risks.hard.has(name)) risks.hard.set(name, reason);
|
|
1016
|
+
};
|
|
1017
|
+
|
|
1018
|
+
// The checks of one file inside the program of the declarations.
|
|
1019
|
+
const scanProgramFile = (entry, risks, absolutePath, text, named, names) => {
|
|
1020
|
+
const { checker } = entry.project;
|
|
1021
|
+
const positions = memberPositions(text, new Set(named));
|
|
1022
|
+
if (positions.length > 0) {
|
|
1023
|
+
const symbols = checker.getSymbolAtPosition(
|
|
1024
|
+
absolutePath,
|
|
1025
|
+
positions.map(([, position]) => position),
|
|
1026
|
+
);
|
|
1027
|
+
positions.forEach(([name, position], index) => {
|
|
1028
|
+
const symbol = symbols[index];
|
|
1029
|
+
if (!symbol) {
|
|
1030
|
+
addRisk(risks, name, "unresolved-reference");
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
if (!risks.references.has(name)) risks.references.set(name, []);
|
|
1034
|
+
risks.references.get(name).push({ file: absolutePath, position, symbol });
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
const accesses = computedAccesses(text);
|
|
1038
|
+
const typed = accesses.filter((access) => access.position !== null);
|
|
1039
|
+
const types =
|
|
1040
|
+
typed.length === 0
|
|
1041
|
+
? []
|
|
1042
|
+
: checker.getTypeAtPosition(
|
|
1043
|
+
absolutePath,
|
|
1044
|
+
typed.map((access) => access.position),
|
|
1045
|
+
);
|
|
1046
|
+
typed.forEach((access, index) =>
|
|
1047
|
+
recordComputedAccess(checker, risks, names, types[index], access.called),
|
|
1048
|
+
);
|
|
1049
|
+
if (accesses.some((access) => access.position === null)) {
|
|
1050
|
+
recordComplexReceivers(entry.project, risks, names, absolutePath);
|
|
1051
|
+
}
|
|
1052
|
+
if (REFLECT_CALL.test(text)) risks.untypedComputedCalls += 1;
|
|
1053
|
+
};
|
|
1054
|
+
|
|
1055
|
+
// A computed access on a receiver that is not an identifier, such as
|
|
1056
|
+
// `get()[key]` or `(x as T)[key]`, needs the parse to find the receiver.
|
|
1057
|
+
const recordComplexReceivers = (project, risks, names, absolutePath) => {
|
|
1058
|
+
const sourceFile = project.program.getSourceFile(absolutePath);
|
|
1059
|
+
if (!sourceFile) return;
|
|
1060
|
+
const accesses = [];
|
|
1061
|
+
const visit = (node) => {
|
|
1062
|
+
if (
|
|
1063
|
+
isElementAccessExpression(node) &&
|
|
1064
|
+
node.argumentExpression &&
|
|
1065
|
+
!isStringLiteralLikeNode(node.argumentExpression) &&
|
|
1066
|
+
node.argumentExpression.kind !== SyntaxKind.NumericLiteral &&
|
|
1067
|
+
!isIdentifier(node.expression)
|
|
1068
|
+
) {
|
|
1069
|
+
accesses.push(node);
|
|
1070
|
+
}
|
|
1071
|
+
node.forEachChild(visit);
|
|
1072
|
+
};
|
|
1073
|
+
visit(sourceFile);
|
|
1074
|
+
if (accesses.length === 0) return;
|
|
1075
|
+
const types = project.checker.getTypeAtLocation(accesses.map((access) => access.expression));
|
|
1076
|
+
accesses.forEach((access, index) => {
|
|
1077
|
+
const called = isCalledAccess(access);
|
|
1078
|
+
recordComputedAccess(project.checker, risks, names, types[index], called);
|
|
1079
|
+
});
|
|
1080
|
+
};
|
|
1081
|
+
|
|
1082
|
+
const isCalledAccess = (access) => {
|
|
1083
|
+
let current = access;
|
|
1084
|
+
while (isParenthesizedExpression(current.parent)) current = current.parent;
|
|
1085
|
+
const { parent } = current;
|
|
1086
|
+
if (isCallExpression(parent) && parent.expression === current) return true;
|
|
1087
|
+
return (
|
|
1088
|
+
isPropertyAccessExpression(parent) &&
|
|
1089
|
+
["call", "apply", "bind"].includes(parent.name.text) &&
|
|
1090
|
+
parent.expression === current
|
|
1091
|
+
);
|
|
1092
|
+
};
|
|
1093
|
+
|
|
1094
|
+
// A computed access on a typed receiver blocks each method of the type that
|
|
1095
|
+
// the access can read. A called access on an untyped receiver counts for the
|
|
1096
|
+
// string policy.
|
|
1097
|
+
const recordComputedAccess = (checker, risks, names, type, called) => {
|
|
1098
|
+
if (isUntypedType(type)) {
|
|
1099
|
+
if (called) risks.untypedComputedCalls += 1;
|
|
1100
|
+
return;
|
|
1101
|
+
}
|
|
1102
|
+
if (!risks.properties.has(type.id)) {
|
|
1103
|
+
let properties = [];
|
|
1104
|
+
try {
|
|
1105
|
+
properties = checker.getPropertiesOfType(type).map((property) => property.name);
|
|
1106
|
+
} catch {
|
|
1107
|
+
properties = null;
|
|
1108
|
+
}
|
|
1109
|
+
risks.properties.set(type.id, properties);
|
|
1110
|
+
}
|
|
1111
|
+
const properties = risks.properties.get(type.id);
|
|
1112
|
+
if (properties === null || properties.length === 0) {
|
|
1113
|
+
if (called) risks.untypedComputedCalls += 1;
|
|
1114
|
+
return;
|
|
1115
|
+
}
|
|
1116
|
+
for (const property of properties) {
|
|
1117
|
+
if (names.has(property)) addRisk(risks, property, "dynamic-member-access");
|
|
1118
|
+
}
|
|
1119
|
+
};
|
|
1120
|
+
|
|
1121
|
+
/**
|
|
1122
|
+
* The names that each program cannot attribute, keyed by program. A name is
|
|
1123
|
+
* blocked when a file outside the program names it, when a reference by name
|
|
1124
|
+
* does not resolve, or when a computed access on a typed receiver can read it.
|
|
1125
|
+
* `strings` holds each name that a string literal spells, and
|
|
1126
|
+
* `untypedComputedCalls` counts the computed calls on a receiver with no
|
|
1127
|
+
* known members. Such a call can reach each method whose name a string holds.
|
|
1128
|
+
*/
|
|
1129
|
+
const namesByProgram = (programs, root, classes) => {
|
|
1130
|
+
const namesByEntry = new Map();
|
|
1131
|
+
const classNames = new Set();
|
|
1132
|
+
for (const request of classes) {
|
|
1133
|
+
const entry = programs.entry(path.resolve(root, request.path));
|
|
1134
|
+
if (!entry) continue;
|
|
1135
|
+
if (!namesByEntry.has(entry)) namesByEntry.set(entry, new Set());
|
|
1136
|
+
request.methods.forEach((method) => namesByEntry.get(entry).add(method.name));
|
|
1137
|
+
classNames.add(request.class);
|
|
1138
|
+
}
|
|
1139
|
+
return { namesByEntry, classNames };
|
|
1140
|
+
};
|
|
1141
|
+
|
|
1142
|
+
const PROTOTYPE_READ = /\b([A-Za-z_$][\w$]*)\s*\.\s*prototype\b/gu;
|
|
1143
|
+
|
|
1144
|
+
// A read of `Class.prototype` can reach each method by reflection.
|
|
1145
|
+
const recordPrototypes = (risks, classNames, text) => {
|
|
1146
|
+
for (const match of text.matchAll(PROTOTYPE_READ)) {
|
|
1147
|
+
if (!classNames.has(match[1])) continue;
|
|
1148
|
+
for (const state of risks.values()) state.prototypes.add(match[1]);
|
|
1149
|
+
}
|
|
1150
|
+
};
|
|
1151
|
+
|
|
1152
|
+
// The checks of one file for the program of one class candidate.
|
|
1153
|
+
const scanEntryFile = (entry, state, names, absolutePath, text, tokens) => {
|
|
1154
|
+
const named = [...names].filter((name) => tokens.has(name));
|
|
1155
|
+
if (!entry.identities.has(canonicalFileIdentity(absolutePath))) {
|
|
1156
|
+
named.forEach((name) => addRisk(state, name, "outside-program"));
|
|
1157
|
+
if (COMPUTED_CALL.test(text) || REFLECT_CALL.test(text)) state.untypedComputedCalls += 1;
|
|
1158
|
+
return;
|
|
1159
|
+
}
|
|
1160
|
+
try {
|
|
1161
|
+
scanProgramFile(entry, state, absolutePath, text, named, names);
|
|
1162
|
+
} catch {
|
|
1163
|
+
named.forEach((name) => addRisk(state, name, "checker-error"));
|
|
1164
|
+
}
|
|
1165
|
+
};
|
|
1166
|
+
|
|
1167
|
+
const recordStrings = (risks, allNames, text) => {
|
|
1168
|
+
for (const match of text.matchAll(STRING_NAME)) {
|
|
1169
|
+
if (!allNames.has(match[2])) continue;
|
|
1170
|
+
for (const state of risks.values()) state.strings.add(match[2]);
|
|
1171
|
+
}
|
|
1172
|
+
};
|
|
1173
|
+
|
|
1174
|
+
// The checks of one project file for each program of a class candidate.
|
|
1175
|
+
const scanRiskFile = (scan, risks, allNames, absolutePath, text) => {
|
|
1176
|
+
const { namesByEntry, classNames } = scan;
|
|
1177
|
+
const tokens = tokensOf(text);
|
|
1178
|
+
if (![...allNames].some((name) => tokens.has(name)) && !COMPUTED_ACCESS.test(text)) return;
|
|
1179
|
+
recordStrings(risks, allNames, text);
|
|
1180
|
+
recordPrototypes(risks, classNames, text);
|
|
1181
|
+
for (const [entry, names] of namesByEntry) {
|
|
1182
|
+
scanEntryFile(entry, risks.get(entry), names, absolutePath, text, tokens);
|
|
1183
|
+
}
|
|
1184
|
+
};
|
|
1185
|
+
|
|
1186
|
+
const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
|
1187
|
+
|
|
1188
|
+
const DECLARATION_FILE = /\.d\.[cm]?ts$/u;
|
|
1189
|
+
const MAX_EXTERNAL_MEMBERS = 200;
|
|
1190
|
+
|
|
1191
|
+
// The member declarations of each method name in the declaration files of
|
|
1192
|
+
// a program, outside the TypeScript lib. Code of a dependency can call such a
|
|
1193
|
+
// member on a value of a class that matches the owner type.
|
|
1194
|
+
const recordExternalMembers = (entry, state, names) => {
|
|
1195
|
+
const pattern = new RegExp(
|
|
1196
|
+
`(?:^|[\\s;{,(])(${[...names].map(escapeRegExp).join("|")})\\s*\\??\\s*[(<:]`,
|
|
1197
|
+
"gu",
|
|
1198
|
+
);
|
|
1199
|
+
for (const fileName of entry.files) {
|
|
1200
|
+
// The TypeScript lib files hold the platform types, whose callers the
|
|
1201
|
+
// protocol names cover.
|
|
1202
|
+
if (!DECLARATION_FILE.test(fileName) || /^lib\.[\w.]*\.d\.ts$/u.test(path.basename(fileName)))
|
|
1203
|
+
continue;
|
|
1204
|
+
const bytes = readBytes(fileName);
|
|
1205
|
+
if (!bytes) continue;
|
|
1206
|
+
const text = bytes.toString("utf8");
|
|
1207
|
+
const positions = [...text.matchAll(pattern)].map((match) => [
|
|
1208
|
+
match[1],
|
|
1209
|
+
match.index + match[0].lastIndexOf(match[1]),
|
|
1210
|
+
]);
|
|
1211
|
+
if (positions.length === 0) continue;
|
|
1212
|
+
let symbols;
|
|
1213
|
+
try {
|
|
1214
|
+
symbols = entry.project.checker.getSymbolAtPosition(
|
|
1215
|
+
fileName,
|
|
1216
|
+
positions.map(([, position]) => position),
|
|
1217
|
+
);
|
|
1218
|
+
} catch {
|
|
1219
|
+
positions.forEach(([name]) => addRisk(state, name, "external-structural"));
|
|
1220
|
+
continue;
|
|
1221
|
+
}
|
|
1222
|
+
positions.forEach(([name], index) => {
|
|
1223
|
+
if (!state.externalMembers.has(name)) state.externalMembers.set(name, new Map());
|
|
1224
|
+
const members = state.externalMembers.get(name);
|
|
1225
|
+
const symbol = symbols[index];
|
|
1226
|
+
if (symbol) members.set(symbol.id, symbol);
|
|
1227
|
+
if (members.size > MAX_EXTERNAL_MEMBERS) addRisk(state, name, "external-structural");
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
};
|
|
1231
|
+
|
|
1232
|
+
const nameRisks = (programs, root, files, classes) => {
|
|
1233
|
+
const scan = namesByProgram(programs, root, classes);
|
|
1234
|
+
const { namesByEntry } = scan;
|
|
1235
|
+
const risks = new Map([...namesByEntry.keys()].map((entry) => [entry, programRisks()]));
|
|
1236
|
+
if (risks.size === 0) return risks;
|
|
1237
|
+
for (const [entry, names] of namesByEntry) recordExternalMembers(entry, risks.get(entry), names);
|
|
1238
|
+
const allNames = new Set([...namesByEntry.values()].flatMap((names) => [...names]));
|
|
1239
|
+
for (const file of files) {
|
|
1240
|
+
const absolutePath = path.resolve(root, file);
|
|
1241
|
+
if (/\.d\.[cm]?ts$/u.test(absolutePath)) continue;
|
|
1242
|
+
const bytes = readBytes(absolutePath);
|
|
1243
|
+
if (bytes) scanRiskFile(scan, risks, allNames, absolutePath, bytes.toString("utf8"));
|
|
1244
|
+
}
|
|
1245
|
+
return risks;
|
|
1246
|
+
};
|
|
1247
|
+
|
|
1248
|
+
const OWNER_KINDS = new Set([
|
|
1249
|
+
SyntaxKind.ClassDeclaration,
|
|
1250
|
+
SyntaxKind.ClassExpression,
|
|
1251
|
+
SyntaxKind.InterfaceDeclaration,
|
|
1252
|
+
SyntaxKind.TypeLiteral,
|
|
1253
|
+
SyntaxKind.ObjectLiteralExpression,
|
|
1254
|
+
]);
|
|
1255
|
+
|
|
1256
|
+
const ownerType = (project, member) => {
|
|
1257
|
+
const owner = member?.parent;
|
|
1258
|
+
if (!owner || !OWNER_KINDS.has(owner.kind)) return null;
|
|
1259
|
+
if (owner.name && owner.kind !== SyntaxKind.ObjectLiteralExpression) {
|
|
1260
|
+
const symbol = project.checker.getSymbolAtLocation(owner.name);
|
|
1261
|
+
return symbol ? project.checker.getDeclaredTypeOfSymbol(symbol) : null;
|
|
1262
|
+
}
|
|
1263
|
+
return project.checker.getTypeAtLocation(owner) ?? null;
|
|
1264
|
+
};
|
|
1265
|
+
|
|
1266
|
+
const usagePositions = (project, usages) => {
|
|
1267
|
+
const known = new Set();
|
|
1268
|
+
for (const usage of usages) {
|
|
1269
|
+
const name = usage.name.resolve(project);
|
|
1270
|
+
if (name) {
|
|
1271
|
+
known.add(`${canonicalFileIdentity(name.getSourceFile().fileName)}\u0000${name.getStart()}`);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
return known;
|
|
1275
|
+
};
|
|
1276
|
+
|
|
1277
|
+
const classTypeOf = (project, classNode, declaration) => {
|
|
1278
|
+
const classSymbol = project.checker.getSymbolAtLocation(classNode.name);
|
|
1279
|
+
if (!classSymbol) return null;
|
|
1280
|
+
const isStatic = (declaration.modifiers ?? []).some(
|
|
1281
|
+
(modifier) => modifier.kind === SyntaxKind.StaticKeyword,
|
|
1282
|
+
);
|
|
1283
|
+
return isStatic
|
|
1284
|
+
? project.checker.getTypeOfSymbol(classSymbol)
|
|
1285
|
+
: project.checker.getDeclaredTypeOfSymbol(classSymbol);
|
|
1286
|
+
};
|
|
1287
|
+
|
|
1288
|
+
// The reason for one member symbol of the same name, or null when a value of
|
|
1289
|
+
// the class cannot stand behind it.
|
|
1290
|
+
const memberAlias = (project, symbol, declaration, classType) => {
|
|
1291
|
+
const members = declarationsForSymbol(project, symbol);
|
|
1292
|
+
if (members.length === 0) return "unresolved-member";
|
|
1293
|
+
for (const member of members) {
|
|
1294
|
+
if (member === declaration) continue;
|
|
1295
|
+
const type = ownerType(project, member);
|
|
1296
|
+
if (!type || project.checker.isTypeAssignableTo(classType, type)) return "structural-alias";
|
|
1297
|
+
}
|
|
1298
|
+
return null;
|
|
1299
|
+
};
|
|
1300
|
+
|
|
1301
|
+
// A member of the same name in a dependency type that the class matches. A
|
|
1302
|
+
// dependency can receive an instance and call the method through that type.
|
|
1303
|
+
const externalStructural = (project, classNode, declaration, members) => {
|
|
1304
|
+
if (!members || members.size === 0) return null;
|
|
1305
|
+
const classType = classTypeOf(project, classNode, declaration);
|
|
1306
|
+
if (!classType) return "unresolved-class";
|
|
1307
|
+
for (const symbol of members.values()) {
|
|
1308
|
+
if (memberAlias(project, symbol, declaration, classType)) return "external-structural";
|
|
1309
|
+
}
|
|
1310
|
+
return null;
|
|
1311
|
+
};
|
|
1312
|
+
|
|
1313
|
+
/**
|
|
1314
|
+
* A reason when a reference by the method name names another member that a
|
|
1315
|
+
* value of the class can stand behind. TypeScript types are structural, so
|
|
1316
|
+
* code can pass an instance as a type that the class never `implements`, and
|
|
1317
|
+
* call the method through that type. The checker does not link such a call to
|
|
1318
|
+
* the method.
|
|
1319
|
+
*/
|
|
1320
|
+
const structuralAlias = (project, classNode, declaration, references, usages) => {
|
|
1321
|
+
const known = usagePositions(project, usages);
|
|
1322
|
+
const classType = classTypeOf(project, classNode, declaration);
|
|
1323
|
+
if (!classType) return "unresolved-class";
|
|
1324
|
+
const checked = new Map();
|
|
1325
|
+
for (const reference of references) {
|
|
1326
|
+
if (known.has(`${canonicalFileIdentity(reference.file)}\u0000${reference.position}`)) continue;
|
|
1327
|
+
const { id } = reference.symbol;
|
|
1328
|
+
if (!checked.has(id))
|
|
1329
|
+
checked.set(id, memberAlias(project, reference.symbol, declaration, classType));
|
|
1330
|
+
if (checked.get(id)) return checked.get(id);
|
|
1331
|
+
}
|
|
1332
|
+
return null;
|
|
1333
|
+
};
|
|
1334
|
+
|
|
1335
|
+
const abstained = (reason) => ({ outcome: "abstained", reason });
|
|
1336
|
+
|
|
1337
|
+
// The declaration of a method, or the reason that the method has no
|
|
1338
|
+
// closed set of calls by its form.
|
|
1339
|
+
// Methods that the language or the platform calls by name: a promise
|
|
1340
|
+
// `then`, a string or JSON conversion, an iterator step, an event listener.
|
|
1341
|
+
const PROTOCOL_METHODS = new Set([
|
|
1342
|
+
"then",
|
|
1343
|
+
"catch",
|
|
1344
|
+
"finally",
|
|
1345
|
+
"toString",
|
|
1346
|
+
"toLocaleString",
|
|
1347
|
+
"valueOf",
|
|
1348
|
+
"toJSON",
|
|
1349
|
+
"handleEvent",
|
|
1350
|
+
"next",
|
|
1351
|
+
"return",
|
|
1352
|
+
"throw",
|
|
1353
|
+
"constructor",
|
|
1354
|
+
]);
|
|
1355
|
+
|
|
1356
|
+
const methodDeclaration = (project, sourceFile, classRequest, name) => {
|
|
1357
|
+
if (PROTOCOL_METHODS.has(name)) return { reason: "protocol-method" };
|
|
1358
|
+
const { classNode, methods } = declarationOfMethod(sourceFile, classRequest.class, name);
|
|
1359
|
+
if (!classNode) return { reason: "class-not-found" };
|
|
1360
|
+
if (hasDecorators(classNode)) return { reason: "decorator" };
|
|
1361
|
+
if (methods.length !== 1 || !methods[0].body)
|
|
1362
|
+
return { reason: methods.length > 1 ? "overload" : "no-body" };
|
|
1363
|
+
const [declaration] = methods;
|
|
1364
|
+
if (hasDecorators(declaration)) return { reason: "decorator" };
|
|
1365
|
+
if (declaration.name.kind !== SyntaxKind.Identifier) return { reason: "computed-name" };
|
|
1366
|
+
if (declaration.asteriskToken) return { reason: "generator" };
|
|
1367
|
+
if (inheritsExternalMember(project, classNode, name)) return { reason: "external-contract" };
|
|
1368
|
+
return { classNode, declaration };
|
|
1369
|
+
};
|
|
1370
|
+
|
|
1371
|
+
const isMemberDeclarationName = (name) =>
|
|
1372
|
+
isMethodDeclaration(name.parent) || name.parent?.kind === SyntaxKind.MethodSignature;
|
|
1373
|
+
|
|
1374
|
+
// The calls of a method, or the reason that a reference is not a call.
|
|
1375
|
+
const methodCalls = (project, sourceFile, declaration, usages) => {
|
|
1376
|
+
const calls = [];
|
|
1377
|
+
const pending = [];
|
|
1378
|
+
for (const usage of usages) {
|
|
1379
|
+
const name = usage.name.resolve(project);
|
|
1380
|
+
if (!name) return { reason: "unresolved-usage" };
|
|
1381
|
+
if (name.pos === declaration.name.pos && name.getSourceFile() === sourceFile) continue;
|
|
1382
|
+
const call = usage.call?.resolve(project);
|
|
1383
|
+
const isCall = call && isCallExpression(call) && calleeIsReference(call, name);
|
|
1384
|
+
if (isCall) calls.push(callEvidence(project, declaration, call, name, pending));
|
|
1385
|
+
else if (!isMemberDeclarationName(name)) return { reason: "value-reference" };
|
|
1386
|
+
}
|
|
1387
|
+
// `pending` holds the arguments in the order of their placeholders.
|
|
1388
|
+
const typed = typeArguments(project, pending);
|
|
1389
|
+
let next = 0;
|
|
1390
|
+
for (const evidence of calls) {
|
|
1391
|
+
evidence.args = evidence.args.map((value) =>
|
|
1392
|
+
value === null ? { maybe_undefined: typed[next++].maybe_undefined } : value,
|
|
1393
|
+
);
|
|
1394
|
+
}
|
|
1395
|
+
return { calls };
|
|
1396
|
+
};
|
|
1397
|
+
|
|
1398
|
+
const nameRisk = (state, name) => {
|
|
1399
|
+
const risk = state.hard.get(name);
|
|
1400
|
+
if (risk) return risk;
|
|
1401
|
+
return state.untypedComputedCalls > 0 && state.strings.has(name) ? "name-in-string" : null;
|
|
1402
|
+
};
|
|
1403
|
+
|
|
1404
|
+
const methodEvidence = (programs, root, classRequest, method, risks) => {
|
|
1405
|
+
const absolutePath = path.resolve(root, classRequest.path);
|
|
1406
|
+
const entry = programs.entry(absolutePath);
|
|
1407
|
+
if (!entry) return abstained("no-project");
|
|
1408
|
+
const state = risks.get(entry);
|
|
1409
|
+
const risk = nameRisk(state, method.name);
|
|
1410
|
+
if (risk) return abstained(risk);
|
|
1411
|
+
if (state.prototypes.has(classRequest.class)) return abstained("prototype-access");
|
|
1412
|
+
const { project } = entry;
|
|
1413
|
+
const sourceFile = project.program.getSourceFile(absolutePath);
|
|
1414
|
+
const found = methodDeclaration(project, sourceFile, classRequest, method.name);
|
|
1415
|
+
if (found.reason) return abstained(found.reason);
|
|
1416
|
+
const { classNode, declaration } = found;
|
|
1417
|
+
const { readsArguments, params } = methodParams(sourceFile, declaration);
|
|
1418
|
+
if (readsArguments) return abstained("arguments-read");
|
|
1419
|
+
// The experimental tsrs backend does not serve signature usage, so it gives
|
|
1420
|
+
// no method evidence.
|
|
1421
|
+
if (typeof project.checker.getSignatureUsage !== "function")
|
|
1422
|
+
return abstained("backend-unsupported");
|
|
1423
|
+
const usages = project.checker.getSignatureUsage(declaration);
|
|
1424
|
+
const alias = structuralAlias(
|
|
1425
|
+
project,
|
|
1426
|
+
classNode,
|
|
1427
|
+
declaration,
|
|
1428
|
+
state.references.get(method.name) ?? [],
|
|
1429
|
+
usages,
|
|
1430
|
+
);
|
|
1431
|
+
if (alias) return abstained(alias);
|
|
1432
|
+
const external = externalStructural(
|
|
1433
|
+
project,
|
|
1434
|
+
classNode,
|
|
1435
|
+
declaration,
|
|
1436
|
+
state.externalMembers.get(method.name),
|
|
1437
|
+
);
|
|
1438
|
+
if (external) return abstained(external);
|
|
1439
|
+
const collected = methodCalls(project, sourceFile, declaration, usages);
|
|
1440
|
+
if (collected.reason) return abstained(collected.reason);
|
|
1441
|
+
return {
|
|
1442
|
+
outcome: "complete",
|
|
1443
|
+
...lineCol(sourceFile, declaration.name.getStart(sourceFile)),
|
|
1444
|
+
params,
|
|
1445
|
+
calls: collected.calls,
|
|
1446
|
+
};
|
|
1447
|
+
};
|
|
1448
|
+
|
|
1449
|
+
const relativePath = (root, fileName) => path.relative(root, fileName).split(path.sep).join("/");
|
|
1450
|
+
|
|
1451
|
+
/**
|
|
1452
|
+
* Collects the call evidence of a parsed `call-evidence` request: whether
|
|
1453
|
+
* the arguments of each default candidate can be `undefined`, and the calls
|
|
1454
|
+
* of each method of each class candidate.
|
|
1455
|
+
*/
|
|
1456
|
+
export const collectCallEvidence = (
|
|
1457
|
+
{ root, defaults = [], classes = [], files = [] },
|
|
1458
|
+
{ createApi = createBackendApi } = {},
|
|
1459
|
+
) => {
|
|
1460
|
+
if (defaults.length === 0 && classes.length === 0) return { defaults: [], methods: [] };
|
|
1461
|
+
const programs = new Programs(root, createApi);
|
|
1462
|
+
try {
|
|
1463
|
+
const defaultResults = defaultsEvidence(programs, root, defaults);
|
|
1464
|
+
const named = classes.map((request) => ({
|
|
1465
|
+
...request,
|
|
1466
|
+
methods: request.methods.map((name) => ({ id: request.id, name })),
|
|
1467
|
+
}));
|
|
1468
|
+
const risks = nameRisks(programs, root, files, named);
|
|
1469
|
+
const methods = named.flatMap((request) =>
|
|
1470
|
+
request.methods.map((method) => {
|
|
1471
|
+
let evidence;
|
|
1472
|
+
try {
|
|
1473
|
+
evidence = methodEvidence(programs, root, request, method, risks);
|
|
1474
|
+
} catch {
|
|
1475
|
+
evidence = { outcome: "abstained", reason: "checker-error" };
|
|
1476
|
+
}
|
|
1477
|
+
const calls = evidence.calls?.map((call) => ({
|
|
1478
|
+
...call,
|
|
1479
|
+
path: relativePath(root, call.path),
|
|
1480
|
+
}));
|
|
1481
|
+
return {
|
|
1482
|
+
class_id: request.id,
|
|
1483
|
+
method: method.name,
|
|
1484
|
+
...evidence,
|
|
1485
|
+
...(calls ? { calls } : {}),
|
|
1486
|
+
};
|
|
1487
|
+
}),
|
|
1488
|
+
);
|
|
1489
|
+
return { defaults: defaultResults, methods };
|
|
1490
|
+
} finally {
|
|
1491
|
+
programs.close();
|
|
1492
|
+
}
|
|
1493
|
+
};
|