circle-ir-ai 4.37.0 → 4.40.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/CHANGELOG.md +126 -0
- package/dist/agents/mastra/workflow.d.ts +16 -0
- package/dist/agents/mastra/workflow.d.ts.map +1 -1
- package/dist/agents/mastra/workflow.js +118 -22
- package/dist/agents/mastra/workflow.js.map +1 -1
- package/dist/blast-radius/import-map.d.ts +121 -0
- package/dist/blast-radius/import-map.d.ts.map +1 -0
- package/dist/blast-radius/import-map.js +735 -0
- package/dist/blast-radius/import-map.js.map +1 -0
- package/dist/blast-radius/index.d.ts +36 -4
- package/dist/blast-radius/index.d.ts.map +1 -1
- package/dist/blast-radius/index.js +397 -45
- package/dist/blast-radius/index.js.map +1 -1
- package/dist/blast-radius/radius.d.ts +304 -6
- package/dist/blast-radius/radius.d.ts.map +1 -1
- package/dist/blast-radius/radius.js +1547 -6
- package/dist/blast-radius/radius.js.map +1 -1
- package/dist/blast-radius/types.d.ts +79 -2
- package/dist/blast-radius/types.d.ts.map +1 -1
- package/dist/blast-radius/types.js +2 -2
- package/dist/cache/tree-cache.d.ts +10 -0
- package/dist/cache/tree-cache.d.ts.map +1 -1
- package/dist/cache/tree-cache.js +3 -1
- package/dist/cache/tree-cache.js.map +1 -1
- package/dist/cache/verify-cache.d.ts +7 -0
- package/dist/cache/verify-cache.d.ts.map +1 -1
- package/dist/cache/verify-cache.js +19 -2
- package/dist/cache/verify-cache.js.map +1 -1
- package/dist/dead-code/detector.d.ts +29 -2
- package/dist/dead-code/detector.d.ts.map +1 -1
- package/dist/dead-code/detector.js +6 -2
- package/dist/dead-code/detector.js.map +1 -1
- package/dist/dead-code/engine.d.ts +35 -1
- package/dist/dead-code/engine.d.ts.map +1 -1
- package/dist/dead-code/engine.js +247 -3
- package/dist/dead-code/engine.js.map +1 -1
- package/dist/dead-code/illata-client.d.ts +160 -0
- package/dist/dead-code/illata-client.d.ts.map +1 -0
- package/dist/dead-code/illata-client.js +291 -0
- package/dist/dead-code/illata-client.js.map +1 -0
- package/dist/dead-code/index.d.ts +1 -0
- package/dist/dead-code/index.d.ts.map +1 -1
- package/dist/dead-code/index.js +1 -0
- package/dist/dead-code/index.js.map +1 -1
- package/dist/dead-code/rules/dead-code-java.dl +132 -0
- package/dist/health-score/calculator.d.ts.map +1 -1
- package/dist/health-score/calculator.js +13 -5
- package/dist/health-score/calculator.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/llm/config.d.ts +21 -0
- package/dist/llm/config.d.ts.map +1 -1
- package/dist/llm/config.js +36 -0
- package/dist/llm/config.js.map +1 -1
- package/dist/llm/cwe-rubrics.d.ts +17 -0
- package/dist/llm/cwe-rubrics.d.ts.map +1 -0
- package/dist/llm/cwe-rubrics.js +51 -0
- package/dist/llm/cwe-rubrics.js.map +1 -0
- package/dist/llm/model-route-dispatcher.d.ts +17 -0
- package/dist/llm/model-route-dispatcher.d.ts.map +1 -1
- package/dist/llm/model-route-dispatcher.js +53 -3
- package/dist/llm/model-route-dispatcher.js.map +1 -1
- package/dist/llm/model-route.d.ts.map +1 -1
- package/dist/llm/model-route.js +4 -1
- package/dist/llm/model-route.js.map +1 -1
- package/dist/llm/verification.d.ts +1 -0
- package/dist/llm/verification.d.ts.map +1 -1
- package/dist/llm/verification.js +14 -6
- package/dist/llm/verification.js.map +1 -1
- package/dist/mcp/tools/blast-radius.d.ts +6 -4
- package/dist/mcp/tools/blast-radius.d.ts.map +1 -1
- package/dist/mcp/tools/blast-radius.js +53 -12
- package/dist/mcp/tools/blast-radius.js.map +1 -1
- package/dist/quality/calculator.d.ts.map +1 -1
- package/dist/quality/calculator.js +11 -2
- package/dist/quality/calculator.js.map +1 -1
- package/dist/scope/product-paths.d.ts +117 -12
- package/dist/scope/product-paths.d.ts.map +1 -1
- package/dist/scope/product-paths.js +422 -38
- package/dist/scope/product-paths.js.map +1 -1
- package/dist/secret-scan/scanner.d.ts +5 -0
- package/dist/secret-scan/scanner.d.ts.map +1 -1
- package/dist/secret-scan/scanner.js +74 -3
- package/dist/secret-scan/scanner.js.map +1 -1
- package/dist/security-scan/finding-labels.d.ts +3 -0
- package/dist/security-scan/finding-labels.d.ts.map +1 -0
- package/dist/security-scan/finding-labels.js +18 -0
- package/dist/security-scan/finding-labels.js.map +1 -0
- package/dist/security-scan/scanner.d.ts +32 -4
- package/dist/security-scan/scanner.d.ts.map +1 -1
- package/dist/security-scan/scanner.js +81 -13
- package/dist/security-scan/scanner.js.map +1 -1
- package/dist/selectors/exclude.d.ts +5 -1
- package/dist/selectors/exclude.d.ts.map +1 -1
- package/dist/selectors/exclude.js +15 -2
- package/dist/selectors/exclude.js.map +1 -1
- package/dist/skills/bundle-loader.d.ts.map +1 -1
- package/dist/skills/bundle-loader.js +6 -3
- package/dist/skills/bundle-loader.js.map +1 -1
- package/dist/spec-gap/analyzer.d.ts +8 -0
- package/dist/spec-gap/analyzer.d.ts.map +1 -1
- package/dist/spec-gap/analyzer.js +6 -3
- package/dist/spec-gap/analyzer.js.map +1 -1
- package/dist/specifica/binary-entries.d.ts +96 -0
- package/dist/specifica/binary-entries.d.ts.map +1 -0
- package/dist/specifica/binary-entries.js +318 -0
- package/dist/specifica/binary-entries.js.map +1 -0
- package/dist/specifica/environment/index.d.ts.map +1 -1
- package/dist/specifica/environment/index.js +5 -3
- package/dist/specifica/environment/index.js.map +1 -1
- package/dist/specifica/environment/read-code.d.ts +9 -2
- package/dist/specifica/environment/read-code.d.ts.map +1 -1
- package/dist/specifica/environment/read-code.js +12 -5
- package/dist/specifica/environment/read-code.js.map +1 -1
- package/dist/specifica/evidence-extractor.d.ts.map +1 -1
- package/dist/specifica/evidence-extractor.js +12 -1
- package/dist/specifica/evidence-extractor.js.map +1 -1
- package/dist/specifica/file-routes.d.ts.map +1 -1
- package/dist/specifica/file-routes.js +2 -1
- package/dist/specifica/file-routes.js.map +1 -1
- package/dist/specifica/generator.js +1 -0
- package/dist/specifica/generator.js.map +1 -1
- package/dist/specifica/learned-diff.d.ts.map +1 -1
- package/dist/specifica/learned-diff.js +3 -2
- package/dist/specifica/learned-diff.js.map +1 -1
- package/dist/specifica/level-design.d.ts +7 -0
- package/dist/specifica/level-design.d.ts.map +1 -1
- package/dist/specifica/level-design.js +10 -7
- package/dist/specifica/level-design.js.map +1 -1
- package/dist/specifica/library-surface-python-rust.d.ts +56 -0
- package/dist/specifica/library-surface-python-rust.d.ts.map +1 -0
- package/dist/specifica/library-surface-python-rust.js +466 -0
- package/dist/specifica/library-surface-python-rust.js.map +1 -0
- package/dist/specifica/library-surface.d.ts +13 -1
- package/dist/specifica/library-surface.d.ts.map +1 -1
- package/dist/specifica/library-surface.js +41 -1
- package/dist/specifica/library-surface.js.map +1 -1
- package/dist/specifica/modules.d.ts +28 -1
- package/dist/specifica/modules.d.ts.map +1 -1
- package/dist/specifica/modules.js +141 -10
- package/dist/specifica/modules.js.map +1 -1
- package/dist/specifica/spec-tree.d.ts +34 -1
- package/dist/specifica/spec-tree.d.ts.map +1 -1
- package/dist/specifica/spec-tree.js +242 -54
- package/dist/specifica/spec-tree.js.map +1 -1
- package/dist/specifica/toml-lines.d.ts +33 -0
- package/dist/specifica/toml-lines.d.ts.map +1 -0
- package/dist/specifica/toml-lines.js +77 -0
- package/dist/specifica/toml-lines.js.map +1 -0
- package/dist/specifica/tree-types.d.ts +2 -2
- package/dist/specifica/tree-types.d.ts.map +1 -1
- package/dist/specifica/tree-writer.d.ts +1 -0
- package/dist/specifica/tree-writer.d.ts.map +1 -1
- package/dist/specifica/tree-writer.js +4 -1
- package/dist/specifica/tree-writer.js.map +1 -1
- package/dist/specifica/ts-rule-sources.d.ts +10 -1
- package/dist/specifica/ts-rule-sources.d.ts.map +1 -1
- package/dist/specifica/ts-rule-sources.js +98 -1
- package/dist/specifica/ts-rule-sources.js.map +1 -1
- package/dist/specifica/types.d.ts +13 -0
- package/dist/specifica/types.d.ts.map +1 -1
- package/dist/specifica/use-cases.d.ts +78 -3
- package/dist/specifica/use-cases.d.ts.map +1 -1
- package/dist/specifica/use-cases.js +236 -12
- package/dist/specifica/use-cases.js.map +1 -1
- package/dist/trust/compare.d.ts.map +1 -1
- package/dist/trust/compare.js +11 -1
- package/dist/trust/compare.js.map +1 -1
- package/dist/trust/passes/ai-config-detect.d.ts +4 -0
- package/dist/trust/passes/ai-config-detect.d.ts.map +1 -1
- package/dist/trust/passes/ai-config-detect.js +23 -2
- package/dist/trust/passes/ai-config-detect.js.map +1 -1
- package/dist/trust/passes/ai-generated-fingerprint.d.ts.map +1 -1
- package/dist/trust/passes/ai-generated-fingerprint.js +2 -1
- package/dist/trust/passes/ai-generated-fingerprint.js.map +1 -1
- package/dist/trust/passes/code-complexity.d.ts.map +1 -1
- package/dist/trust/passes/code-complexity.js +2 -1
- package/dist/trust/passes/code-complexity.js.map +1 -1
- package/dist/trust/passes/conformance-attestation.d.ts.map +1 -1
- package/dist/trust/passes/conformance-attestation.js +2 -1
- package/dist/trust/passes/conformance-attestation.js.map +1 -1
- package/dist/trust/passes/cross-skill-interaction.d.ts.map +1 -1
- package/dist/trust/passes/cross-skill-interaction.js +3 -2
- package/dist/trust/passes/cross-skill-interaction.js.map +1 -1
- package/dist/trust/passes/data-exfiltration.d.ts.map +1 -1
- package/dist/trust/passes/data-exfiltration.js +2 -1
- package/dist/trust/passes/data-exfiltration.js.map +1 -1
- package/dist/trust/passes/dep-manifests.d.ts.map +1 -1
- package/dist/trust/passes/dep-manifests.js +2 -1
- package/dist/trust/passes/dep-manifests.js.map +1 -1
- package/dist/trust/passes/deprecated-usage.d.ts.map +1 -1
- package/dist/trust/passes/deprecated-usage.js +2 -1
- package/dist/trust/passes/deprecated-usage.js.map +1 -1
- package/dist/trust/passes/deprecation-no-replacement.d.ts.map +1 -1
- package/dist/trust/passes/deprecation-no-replacement.js +2 -1
- package/dist/trust/passes/deprecation-no-replacement.js.map +1 -1
- package/dist/trust/passes/doc-coverage.d.ts.map +1 -1
- package/dist/trust/passes/doc-coverage.js +2 -1
- package/dist/trust/passes/doc-coverage.js.map +1 -1
- package/dist/trust/passes/eu-ai-act-flags.d.ts.map +1 -1
- package/dist/trust/passes/eu-ai-act-flags.js +3 -2
- package/dist/trust/passes/eu-ai-act-flags.js.map +1 -1
- package/dist/trust/passes/excessive-permissions.d.ts.map +1 -1
- package/dist/trust/passes/excessive-permissions.js +2 -1
- package/dist/trust/passes/excessive-permissions.js.map +1 -1
- package/dist/trust/passes/inconsistent-error-handling.d.ts.map +1 -1
- package/dist/trust/passes/inconsistent-error-handling.js +2 -1
- package/dist/trust/passes/inconsistent-error-handling.js.map +1 -1
- package/dist/trust/passes/inconsistent-naming.d.ts.map +1 -1
- package/dist/trust/passes/inconsistent-naming.js +51 -12
- package/dist/trust/passes/inconsistent-naming.js.map +1 -1
- package/dist/trust/passes/inconsistent-param-order.d.ts.map +1 -1
- package/dist/trust/passes/inconsistent-param-order.js +2 -1
- package/dist/trust/passes/inconsistent-param-order.js.map +1 -1
- package/dist/trust/passes/missing-guard-dom.d.ts.map +1 -1
- package/dist/trust/passes/missing-guard-dom.js +2 -1
- package/dist/trust/passes/missing-guard-dom.js.map +1 -1
- package/dist/trust/passes/performance-passes.d.ts.map +1 -1
- package/dist/trust/passes/performance-passes.js +2 -1
- package/dist/trust/passes/performance-passes.js.map +1 -1
- package/dist/trust/passes/prompt-injection.d.ts.map +1 -1
- package/dist/trust/passes/prompt-injection.js +36 -4
- package/dist/trust/passes/prompt-injection.js.map +1 -1
- package/dist/trust/passes/throws-mismatch.d.ts.map +1 -1
- package/dist/trust/passes/throws-mismatch.js +2 -1
- package/dist/trust/passes/throws-mismatch.js.map +1 -1
- package/dist/trust/passes/tool-poisoning.d.ts.map +1 -1
- package/dist/trust/passes/tool-poisoning.js +3 -2
- package/dist/trust/passes/tool-poisoning.js.map +1 -1
- package/dist/trust/passes/unnecessary-object-hotspot.d.ts.map +1 -1
- package/dist/trust/passes/unnecessary-object-hotspot.js +2 -1
- package/dist/trust/passes/unnecessary-object-hotspot.js.map +1 -1
- package/dist/trust/scoring.d.ts.map +1 -1
- package/dist/trust/scoring.js +6 -2
- package/dist/trust/scoring.js.map +1 -1
- package/dist/utils/dirent-order.d.ts +21 -0
- package/dist/utils/dirent-order.d.ts.map +1 -0
- package/dist/utils/dirent-order.js +21 -0
- package/dist/utils/dirent-order.js.map +1 -0
- package/dist/utils/file-skip.d.ts +11 -0
- package/dist/utils/file-skip.d.ts.map +1 -1
- package/dist/utils/file-skip.js +29 -0
- package/dist/utils/file-skip.js.map +1 -1
- package/package.json +3 -3
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* No IO and no model. Given the same code facts and items it gives the same
|
|
6
6
|
* answer, with every list sorted.
|
|
7
7
|
*/
|
|
8
|
+
import { PRODUCT_SCOPE_RULE_VERSION } from '../scope/product-paths.js';
|
|
8
9
|
// ---------------------------------------------------------------------------
|
|
9
10
|
// Thresholds
|
|
10
11
|
// ---------------------------------------------------------------------------
|
|
@@ -154,6 +155,1525 @@ function sortImportSites(sites) {
|
|
|
154
155
|
return sites.sort((a, b) => byString(a.file, b.file) || (a.line ?? 0) - (b.line ?? 0) || byString(a.package, b.package));
|
|
155
156
|
}
|
|
156
157
|
// ---------------------------------------------------------------------------
|
|
158
|
+
// Tests that reach the change (cognium-ai#1072)
|
|
159
|
+
// ---------------------------------------------------------------------------
|
|
160
|
+
/** How many calls back from the change the test walk follows by default, and at most. */
|
|
161
|
+
export const BLAST_TEST_HOPS = { default: 4, min: 1, max: 8 };
|
|
162
|
+
/** The rule that says which files are tests (the product-scope rule, reason `test`). */
|
|
163
|
+
export const BLAST_TEST_RULE = PRODUCT_SCOPE_RULE_VERSION;
|
|
164
|
+
/** Edge tiers from weakest to strongest; a tier the engine adds later counts as the weakest. */
|
|
165
|
+
const TIER_RANK = { inferred: 1, polymorphic: 2, exact: 3 };
|
|
166
|
+
const rankOf = (tier) => TIER_RANK[tier] ?? 0;
|
|
167
|
+
const weaker = (a, b) => (rankOf(a) <= rankOf(b) ? a : b);
|
|
168
|
+
const stronger = (a, b) => (rankOf(a) >= rankOf(b) ? a : b);
|
|
169
|
+
/** The tests answer before the walk has run, or when it cannot back one: not known. */
|
|
170
|
+
export function unknownTests(maxHops = BLAST_TEST_HOPS.default) {
|
|
171
|
+
return { reached: [], unreached: [], unresolved_sites: 0, status: 'unknown', max_hops: maxHops, rule: BLAST_TEST_RULE };
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Where the walk starts: each changed declaration, and the functions and
|
|
175
|
+
* methods it is nested in (a callback or local function runs inside its
|
|
176
|
+
* enclosing function's body, and the graph has no call edge into it).
|
|
177
|
+
* Each start maps to the changed declarations it carries. A type does not
|
|
178
|
+
* carry its members: reaching a class does not reach its uncalled methods.
|
|
179
|
+
*/
|
|
180
|
+
export function carriersOf(facts, changed) {
|
|
181
|
+
const declById = new Map();
|
|
182
|
+
for (const f of facts.files)
|
|
183
|
+
for (const d of f.decls)
|
|
184
|
+
declById.set(d.id, d);
|
|
185
|
+
const out = new Map();
|
|
186
|
+
const add = (start, c) => {
|
|
187
|
+
const set = out.get(start);
|
|
188
|
+
if (set)
|
|
189
|
+
set.add(c);
|
|
190
|
+
else
|
|
191
|
+
out.set(start, new Set([c]));
|
|
192
|
+
};
|
|
193
|
+
for (const c of changed) {
|
|
194
|
+
add(c, c);
|
|
195
|
+
for (let p = declById.get(c)?.parent ?? null; p !== null;) {
|
|
196
|
+
const parent = declById.get(p);
|
|
197
|
+
if (!parent || (parent.kind !== 'function' && parent.kind !== 'method'))
|
|
198
|
+
break;
|
|
199
|
+
add(p, c);
|
|
200
|
+
p = parent.parent;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* The edges the walk follows: the calls, and the references (a function or
|
|
207
|
+
* class used as a value: passed as an argument, stored in a table, rendered
|
|
208
|
+
* as `<Component/>`, returned), which "may run" and so count as `inferred`.
|
|
209
|
+
* A call or reference made from inside a changed region (the lines, or the
|
|
210
|
+
* whole file, the change rewrites) by a declaration the walk does not start
|
|
211
|
+
* from is part of the change, as in `callersOf`; edges between changed
|
|
212
|
+
* declarations are kept, so a test that calls one changed function reaches
|
|
213
|
+
* the changed functions it calls.
|
|
214
|
+
*/
|
|
215
|
+
function walkEdges(facts, starts, regions) {
|
|
216
|
+
const all = [
|
|
217
|
+
...facts.edges,
|
|
218
|
+
...(facts.references ?? []).map((r) => ({ from: r.from, to: r.to, tier: 'inferred', methodName: '', site: r.site, reference: true })),
|
|
219
|
+
];
|
|
220
|
+
if (regions.length === 0)
|
|
221
|
+
return all;
|
|
222
|
+
return all.filter((e) => starts.has(e.from) || !inRegion(regions, e.site.file, e.site.line));
|
|
223
|
+
}
|
|
224
|
+
/** Kinds of declaration a nested function runs inside: a function's or method's body, or a field's initializer. */
|
|
225
|
+
const STEP_OUT_KINDS = new Set(['function', 'method', 'field']);
|
|
226
|
+
/** Kinds whose own code holds an inline function that runs without a call: a module's top level, a class's static blocks and decorators. */
|
|
227
|
+
const HOLDER_KINDS = new Set(['module', 'type']);
|
|
228
|
+
/** A function that is not a declaration a caller can name (`<anonymous>`, or flagged `unstable:anonymous` by the engine). */
|
|
229
|
+
function isInlineFunction(decl) {
|
|
230
|
+
return decl.kind === 'function' && (decl.name === '<anonymous>' || (decl.flags ?? []).includes('unstable:anonymous'));
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* The declaration a declaration is nested in, when the walk should step out
|
|
234
|
+
* to it: a callback or local function runs inside its enclosing function's
|
|
235
|
+
* body, and the graph has no call edge into an inline arrow
|
|
236
|
+
* (`.map((c) => parseConfig(c))`). A function in a field's initializer
|
|
237
|
+
* (`export const GET = withAuth((req) => …)`, a class field's `.map`
|
|
238
|
+
* callback) steps out to the field. An inline function directly under a
|
|
239
|
+
* module or a class, that no call or reference enters
|
|
240
|
+
* (`RAW.forEach((c) => …)`, `setTimeout(…)`, `bus.on('x', …)`,
|
|
241
|
+
* `Object.defineProperty(o, 'size', { get: … })`, a callback in a
|
|
242
|
+
* `static {}` block or a decorator argument, `module.exports = function () {}`),
|
|
243
|
+
* steps out to the module or the class. `testsOf` treats both as code that
|
|
244
|
+
* runs without a call. A named declaration under a module or a class (a
|
|
245
|
+
* function, a method) does not step out: nothing runs it but its callers.
|
|
246
|
+
* Not for test files: a test's nested callbacks are reported as tests
|
|
247
|
+
* themselves.
|
|
248
|
+
*/
|
|
249
|
+
export function stepOutOf(facts, isTest) {
|
|
250
|
+
const at = new Map();
|
|
251
|
+
for (const f of facts.files)
|
|
252
|
+
for (const d of f.decls)
|
|
253
|
+
at.set(d.id, { decl: d, file: f.file });
|
|
254
|
+
const entered = enteredIds(facts);
|
|
255
|
+
return (id) => {
|
|
256
|
+
const self = at.get(id);
|
|
257
|
+
if (!self || !self.decl.parent || isTest(self.file))
|
|
258
|
+
return null;
|
|
259
|
+
const parent = at.get(self.decl.parent);
|
|
260
|
+
if (!parent)
|
|
261
|
+
return null;
|
|
262
|
+
if (STEP_OUT_KINDS.has(parent.decl.kind))
|
|
263
|
+
return parent.decl.id;
|
|
264
|
+
return HOLDER_KINDS.has(parent.decl.kind) && isInlineFunction(self.decl) && !entered.has(id) ? parent.decl.id : null;
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
/** Declarations some call or reference enters. */
|
|
268
|
+
function enteredIds(facts) {
|
|
269
|
+
return new Set([...facts.edges.map((e) => e.to), ...(facts.references ?? []).map((r) => r.to)]);
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Breadth-first, backwards over the calls and references from `starts` (the
|
|
273
|
+
* changed declarations and their carriers, `carriersOf`): who calls them (1
|
|
274
|
+
* hop), who calls those (2), up to `maxHops`. A start's tier is `exact`
|
|
275
|
+
* unless `startTier` says otherwise (a carrier only may run the code it
|
|
276
|
+
* holds). With `stepOut`, every declaration reached also reaches the
|
|
277
|
+
* functions it is nested in, at the same hop and at `inferred` (nesting is
|
|
278
|
+
* not a call). Deterministic: distances are minima and tiers are the best
|
|
279
|
+
* of the weakest, whatever the edge order.
|
|
280
|
+
*/
|
|
281
|
+
export function walkBackwards(facts, starts, maxHops, regions = [], startTier = new Map(), stepOut) {
|
|
282
|
+
const callers = new Map();
|
|
283
|
+
for (const e of walkEdges(facts, starts, regions)) {
|
|
284
|
+
const list = callers.get(e.to);
|
|
285
|
+
if (list)
|
|
286
|
+
list.push(e);
|
|
287
|
+
else
|
|
288
|
+
callers.set(e.to, [e]);
|
|
289
|
+
}
|
|
290
|
+
const dist = new Map();
|
|
291
|
+
const tier = new Map();
|
|
292
|
+
// The enclosing functions of what a layer reached join it, at `inferred`.
|
|
293
|
+
const climb = (layer) => {
|
|
294
|
+
if (!stepOut)
|
|
295
|
+
return;
|
|
296
|
+
for (const [id, t] of [...layer]) {
|
|
297
|
+
const up = weaker(t, 'inferred');
|
|
298
|
+
for (let p = stepOut(id); p !== null && !dist.has(p); p = stepOut(p)) {
|
|
299
|
+
const prev = layer.get(p);
|
|
300
|
+
if (prev !== undefined && rankOf(prev) >= rankOf(up))
|
|
301
|
+
break;
|
|
302
|
+
layer.set(p, prev === undefined ? up : stronger(prev, up));
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
const first = new Map([...starts].map((c) => [c, startTier.get(c) ?? 'exact']));
|
|
307
|
+
climb(first);
|
|
308
|
+
for (const [c, t] of first) {
|
|
309
|
+
dist.set(c, 0);
|
|
310
|
+
tier.set(c, t);
|
|
311
|
+
}
|
|
312
|
+
let layer = [...first.keys()];
|
|
313
|
+
for (let h = 1; h <= maxHops && layer.length > 0; h++) {
|
|
314
|
+
const next = new Map();
|
|
315
|
+
for (const n of layer) {
|
|
316
|
+
for (const e of callers.get(n) ?? []) {
|
|
317
|
+
if (dist.has(e.from))
|
|
318
|
+
continue;
|
|
319
|
+
const t = weaker(tier.get(n), e.tier);
|
|
320
|
+
const prev = next.get(e.from);
|
|
321
|
+
next.set(e.from, prev === undefined ? t : stronger(prev, t));
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
climb(next);
|
|
325
|
+
for (const [id, t] of next) {
|
|
326
|
+
dist.set(id, h);
|
|
327
|
+
tier.set(id, t);
|
|
328
|
+
}
|
|
329
|
+
layer = [...next.keys()];
|
|
330
|
+
}
|
|
331
|
+
return { dist, tier };
|
|
332
|
+
}
|
|
333
|
+
/** Entry kinds that are not a way in for a test: test files themselves, and a library's exported surface. */
|
|
334
|
+
const NOT_A_WAY_IN = new Set(['test', 'export']);
|
|
335
|
+
/** Calls through these name the function they run only in the source (`k.b.call(k, 1)`): the graph reports the site by `call`. */
|
|
336
|
+
const CALL_LIKE = new Set(['call', 'apply', 'bind']);
|
|
337
|
+
/** How far after the site's start (the receiver's start) the `.call(` / `.apply(` / `.bind(` may be. */
|
|
338
|
+
const CALL_LIKE_WINDOW = 400;
|
|
339
|
+
/** Receivers whose name is not the function that runs (`Reflect.apply(fn, …)`, `f.call.call(g)`). */
|
|
340
|
+
const NOT_THE_FUNCTION = new Set(['Reflect', 'call', 'apply', 'bind']);
|
|
341
|
+
const isIdStart = (c) => (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95 || c === 36;
|
|
342
|
+
const isIdPart = (c) => isIdStart(c) || (c >= 48 && c <= 57);
|
|
343
|
+
/**
|
|
344
|
+
* The name a call-like site runs. The site starts the receiver expression;
|
|
345
|
+
* it is read only when it is a plain member chain right up to its `.call(`
|
|
346
|
+
* / `.apply(` / `.bind(`: identifiers (`this` among them) joined by `.`,
|
|
347
|
+
* `?.` or `['literal']`, in wrapping parentheses or not, on one line, with
|
|
348
|
+
* spaces between its parts. Its last name is returned. Anything else gives
|
|
349
|
+
* `null`, and the caller falls back to every name on a path the file
|
|
350
|
+
* spells: a cast (`as`, `satisfies`, `!`), `||` / `&&` / `??`, a ternary,
|
|
351
|
+
* a comma, a call (`getFn().call`, two call-like sites at one start), a
|
|
352
|
+
* comment, a line break inside the receiver, a literal with an escape or
|
|
353
|
+
* `${`, a name that is not ASCII, a site in the middle of a name, and
|
|
354
|
+
* `Reflect.apply` (the function is an argument). A line break may separate
|
|
355
|
+
* the whole receiver from its `.call` (`k.g\n .bind(k)`). Reads at most
|
|
356
|
+
* `CALL_LIKE_WINDOW` characters from the site, whatever the line's length.
|
|
357
|
+
*/
|
|
358
|
+
export function callLikeReceiver(text, offset) {
|
|
359
|
+
const end = Math.min(text.length, offset + CALL_LIKE_WINDOW);
|
|
360
|
+
// In the middle of a name (or after `#`, or a character that is not ASCII), the name read would be its tail.
|
|
361
|
+
if (offset > 0) {
|
|
362
|
+
const before = text.charCodeAt(offset - 1);
|
|
363
|
+
if (isIdPart(before) || before === 35 || before > 127)
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
let i = offset;
|
|
367
|
+
const spaces = (lineBreaks = false) => {
|
|
368
|
+
for (; i < end; i++) {
|
|
369
|
+
const c = text[i];
|
|
370
|
+
if (c !== ' ' && c !== '\t' && !(lineBreaks && (c === '\n' || c === '\r')))
|
|
371
|
+
break;
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
// An ASCII name, ending inside the window.
|
|
375
|
+
const name = () => {
|
|
376
|
+
if (i >= end || !isIdStart(text.charCodeAt(i)))
|
|
377
|
+
return null;
|
|
378
|
+
const from = i;
|
|
379
|
+
while (i < end && isIdPart(text.charCodeAt(i)))
|
|
380
|
+
i++;
|
|
381
|
+
if (i >= end || text.charCodeAt(i) > 127)
|
|
382
|
+
return null;
|
|
383
|
+
return text.slice(from, i);
|
|
384
|
+
};
|
|
385
|
+
// `['name']`, `["name"]` or a backquoted name without `${`; no escapes, no line breaks.
|
|
386
|
+
const bracket = () => {
|
|
387
|
+
i++;
|
|
388
|
+
spaces();
|
|
389
|
+
const quote = text[i];
|
|
390
|
+
if (quote !== "'" && quote !== '"' && quote !== '`')
|
|
391
|
+
return null;
|
|
392
|
+
const from = ++i;
|
|
393
|
+
for (; i < end && text[i] !== quote; i++) {
|
|
394
|
+
const c = text[i];
|
|
395
|
+
if (c === '\\' || c === '\n' || c === '\r' || (quote === '`' && c === '$' && text[i + 1] === '{'))
|
|
396
|
+
return null;
|
|
397
|
+
}
|
|
398
|
+
if (i >= end || i === from)
|
|
399
|
+
return null;
|
|
400
|
+
const lit = text.slice(from, i++);
|
|
401
|
+
spaces();
|
|
402
|
+
if (text[i] !== ']')
|
|
403
|
+
return null;
|
|
404
|
+
i++;
|
|
405
|
+
return lit;
|
|
406
|
+
};
|
|
407
|
+
let open = 0;
|
|
408
|
+
for (spaces(); text[i] === '('; spaces()) {
|
|
409
|
+
open++;
|
|
410
|
+
i++;
|
|
411
|
+
}
|
|
412
|
+
let last = name();
|
|
413
|
+
if (last === null)
|
|
414
|
+
return null;
|
|
415
|
+
// Once the wrapping parentheses close, only the call-like token may follow.
|
|
416
|
+
let closed = false;
|
|
417
|
+
for (;;) {
|
|
418
|
+
spaces();
|
|
419
|
+
if (!closed && open > 0 && text[i] === ')') {
|
|
420
|
+
for (; text[i] === ')' && open > 0; spaces()) {
|
|
421
|
+
open--;
|
|
422
|
+
i++;
|
|
423
|
+
}
|
|
424
|
+
if (open > 0)
|
|
425
|
+
return null;
|
|
426
|
+
closed = true;
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
// A line break may come only between the whole receiver and its `.call`.
|
|
430
|
+
const at = i;
|
|
431
|
+
if (open === 0)
|
|
432
|
+
spaces(true);
|
|
433
|
+
const broke = text.slice(at, i).includes('\n');
|
|
434
|
+
const dot = text.startsWith('?.', i) ? 2 : text[i] === '.' ? 1 : 0;
|
|
435
|
+
if (dot > 0) {
|
|
436
|
+
i += dot;
|
|
437
|
+
spaces();
|
|
438
|
+
if (text[i] === '[') {
|
|
439
|
+
if (closed || broke)
|
|
440
|
+
return null;
|
|
441
|
+
last = bracket();
|
|
442
|
+
if (last === null)
|
|
443
|
+
return null;
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
const word = name();
|
|
447
|
+
if (word === null)
|
|
448
|
+
return null;
|
|
449
|
+
const afterWord = i;
|
|
450
|
+
spaces();
|
|
451
|
+
if (CALL_LIKE.has(word) && text[i] === '(')
|
|
452
|
+
return open === 0 && !NOT_THE_FUNCTION.has(last) ? last : null;
|
|
453
|
+
if (closed || broke)
|
|
454
|
+
return null;
|
|
455
|
+
i = afterWord;
|
|
456
|
+
last = word;
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
if (text[i] === '[' && !closed && !broke) {
|
|
460
|
+
last = bracket();
|
|
461
|
+
if (last === null)
|
|
462
|
+
return null;
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
return null;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
/** A TypeScript accessor: the engine's signature is `get (…)` / `set (…)`, after modifiers (`static get (…)`). */
|
|
469
|
+
const TS_ACCESSOR = /^(?:[a-z]+\s+)*(?:get|set)\s*\(/;
|
|
470
|
+
/** A Python property: `@property`, `@functools.cached_property`, `@size.setter` … */
|
|
471
|
+
const PY_ACCESSOR = /^\s*@\s*[\w.]*\b(?:property|cached_property|abstractproperty|setter|getter|deleter)\b/;
|
|
472
|
+
const familyOfFile = (file) => /\.(?:[cm]?[jt]sx?)$/.test(file) ? 'ts' : file.endsWith('.py') ? 'py' : file.endsWith('.java') ? 'java' : file.endsWith('.go') ? 'go' : null;
|
|
473
|
+
/**
|
|
474
|
+
* Methods the language's runtime, standard library or a UI framework calls
|
|
475
|
+
* with no call site in the repository: string conversion and printing,
|
|
476
|
+
* JSON, `await`, iteration and spreads, `with` / try-with-resources,
|
|
477
|
+
* sorting and comparison, Python's other dunders (`__init__` is not one:
|
|
478
|
+
* construction is an edge to it), Go's standard interfaces, and component
|
|
479
|
+
* lifecycles. On a path, the code they run may run.
|
|
480
|
+
*/
|
|
481
|
+
const RUNTIME_CALLED = {
|
|
482
|
+
ts: new Set([
|
|
483
|
+
'toString', 'toJSON', 'valueOf', 'toLocaleString', 'then', 'next', 'return', 'throw', 'handleEvent',
|
|
484
|
+
'[Symbol.iterator]', '[Symbol.asyncIterator]', '[Symbol.toPrimitive]', '[Symbol.hasInstance]',
|
|
485
|
+
'[Symbol.dispose]', '[Symbol.asyncDispose]', '[util.inspect.custom]',
|
|
486
|
+
'connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback',
|
|
487
|
+
'render', 'componentDidMount', 'componentDidUpdate', 'componentWillUnmount', 'shouldComponentUpdate',
|
|
488
|
+
'getSnapshotBeforeUpdate', 'componentDidCatch', 'getDerivedStateFromProps', 'getDerivedStateFromError',
|
|
489
|
+
'ngOnInit', 'ngOnChanges', 'ngDoCheck', 'ngAfterContentInit', 'ngAfterContentChecked', 'ngAfterViewInit',
|
|
490
|
+
'ngAfterViewChecked', 'ngOnDestroy',
|
|
491
|
+
// Node streams (`class W extends Writable { _write() {} }`).
|
|
492
|
+
'_write', '_writev', '_read', '_transform', '_flush', '_final', '_destroy', '_construct',
|
|
493
|
+
// NestJS lifecycle hooks.
|
|
494
|
+
'onModuleInit', 'onApplicationBootstrap', 'onModuleDestroy', 'beforeApplicationShutdown', 'onApplicationShutdown',
|
|
495
|
+
// Lit.
|
|
496
|
+
'firstUpdated', 'updated', 'willUpdate', 'shouldUpdate', 'update',
|
|
497
|
+
// Vue class components.
|
|
498
|
+
'data', 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'beforeUnmount', 'unmounted',
|
|
499
|
+
'beforeDestroy', 'destroyed', 'activated', 'deactivated', 'errorCaptured', 'serverPrefetch',
|
|
500
|
+
]),
|
|
501
|
+
java: new Set([
|
|
502
|
+
'toString', 'equals', 'hashCode', 'compareTo', 'compare', 'close', 'run', 'call', 'iterator', 'hasNext',
|
|
503
|
+
'next', 'finalize', 'readObject', 'writeObject', 'readResolve', 'writeReplace', 'readExternal',
|
|
504
|
+
'writeExternal', 'uncaughtException',
|
|
505
|
+
]),
|
|
506
|
+
go: new Set([
|
|
507
|
+
'String', 'GoString', 'Error', 'Format', 'Unwrap', 'Is', 'As', 'MarshalJSON', 'UnmarshalJSON',
|
|
508
|
+
'MarshalText', 'UnmarshalText', 'MarshalYAML', 'UnmarshalYAML', 'MarshalBinary', 'UnmarshalBinary',
|
|
509
|
+
'ServeHTTP', 'Len', 'Less', 'Swap', 'Read', 'Write', 'Close', 'Scan', 'Value',
|
|
510
|
+
]),
|
|
511
|
+
};
|
|
512
|
+
const PY_DUNDER = /^__\w+__$/;
|
|
513
|
+
/**
|
|
514
|
+
* Lit / Vue names too common to count on any class: only on one whose
|
|
515
|
+
* header (`classHeaderText`) extends `LitElement`, `ReactiveElement` or
|
|
516
|
+
* `Vue` anywhere in its heritage clause (`extends SignalWatcher(LitElement)`)
|
|
517
|
+
* or carries `@Component` / `@Options`, or in a file that makes such
|
|
518
|
+
* components (`makesComponents`).
|
|
519
|
+
*/
|
|
520
|
+
const FRAMEWORK_CLASS_ONLY = new Set(['update', 'data']);
|
|
521
|
+
const FRAMEWORK_CLASS = /\bextends\b[\s\S]*?\b(?:LitElement|ReactiveElement|Vue)\b|@\s*(?:Component|Options)\b/;
|
|
522
|
+
/** The packages that exist to write class components: anything imported from them makes one. */
|
|
523
|
+
const CLASS_COMPONENT_PACKAGES = /^(?:vue-class-component|vue-property-decorator|vue-facing-decorator|nuxt-property-decorator)(?:\/|$)/;
|
|
524
|
+
/** Lit's decorators (`@customElement`, `@property` …), which work only on a Lit element. */
|
|
525
|
+
const LIT_DECORATORS = /^(?:lit|lit-element|@lit\/reactive-element)\/decorators(?:[./]|$)/;
|
|
526
|
+
const VUE_PACKAGE = /^(?:vue|@vue\/[^/]+)(?:\/|$)/;
|
|
527
|
+
const LIT_PACKAGE = /^(?:lit|lit-element|lit-html|@lit\/[^/]+|@lit-labs\/[^/]+)(?:\/|$)/;
|
|
528
|
+
/** Bindings that make a component whatever module they come from. */
|
|
529
|
+
const COMPONENT_BINDINGS = new Set(['LitElement', 'ReactiveElement', 'Vue', 'defineComponent']);
|
|
530
|
+
/**
|
|
531
|
+
* Whether a file makes Lit or Vue components, read from what it imports as
|
|
532
|
+
* a value (`import type` and `type` specifiers are left out) and the
|
|
533
|
+
* decorators it writes:
|
|
534
|
+
*
|
|
535
|
+
* - `LitElement`, `ReactiveElement`, `Vue` or `defineComponent`, from any
|
|
536
|
+
* module (a local re-export too);
|
|
537
|
+
* - anything from a class-component package (`vue-class-component`,
|
|
538
|
+
* `vue-property-decorator`, `vue-facing-decorator`,
|
|
539
|
+
* `nuxt-property-decorator`) or from Lit's decorators
|
|
540
|
+
* (`lit/decorators.js`);
|
|
541
|
+
* - `vue`'s default export or the whole module (`import * as`,
|
|
542
|
+
* `require('vue')`, `import('vue')`);
|
|
543
|
+
* - any value import from a Lit package (`import { html } from 'lit'`,
|
|
544
|
+
* a side-effect `import 'lit'` too): a leaf element whose `LitElement`
|
|
545
|
+
* comes through a base class in another file often takes only `html` /
|
|
546
|
+
* `css`, and the graph gives no class heritage to tell it apart
|
|
547
|
+
* (cogniumhq/cognium-dev#1343);
|
|
548
|
+
* - a `@Component` or `@Options` decorator written in its code (through a
|
|
549
|
+
* local wrapper too).
|
|
550
|
+
*
|
|
551
|
+
* A file that only uses Vue's composition API (`import { ref } from 'vue'`)
|
|
552
|
+
* or imports only types makes none.
|
|
553
|
+
*/
|
|
554
|
+
function makesComponents(text) {
|
|
555
|
+
for (const m of text.matchAll(/\bimport\b\s*(type\s+)?([^'";]*?)\s*\bfrom\s*(['"])([^'"\n]+)\3/g)) {
|
|
556
|
+
if (m[1])
|
|
557
|
+
continue;
|
|
558
|
+
const clause = m[2].trim();
|
|
559
|
+
const spec = m[4];
|
|
560
|
+
if (CLASS_COMPONENT_PACKAGES.test(spec) || LIT_DECORATORS.test(spec))
|
|
561
|
+
return true;
|
|
562
|
+
const braces = /\{([^}]*)\}/.exec(clause);
|
|
563
|
+
let valueSpecifier = false;
|
|
564
|
+
for (const part of braces ? braces[1].split(',') : []) {
|
|
565
|
+
const r = /^\s*(type\s+)?([A-Za-z_$][\w$]*)(?:\s+as\s+[A-Za-z_$][\w$]*)?\s*$/.exec(part);
|
|
566
|
+
if (r && !r[1] && COMPONENT_BINDINGS.has(r[2]))
|
|
567
|
+
return true;
|
|
568
|
+
if (r && !r[1])
|
|
569
|
+
valueSpecifier = true;
|
|
570
|
+
}
|
|
571
|
+
const whole = /^\*\s*as\b/.test(clause) || /(?:^|,)\s*\*\s*as\b/.test(clause);
|
|
572
|
+
const hasDefault = /^[A-Za-z_$][\w$]*\s*(?:,|$)/.test(clause);
|
|
573
|
+
if (VUE_PACKAGE.test(spec) && (whole || hasDefault))
|
|
574
|
+
return true;
|
|
575
|
+
// Any value import from a Lit package: a leaf element whose `LitElement` comes through a base class in another
|
|
576
|
+
// file often takes only `html` / `css` here, and the graph gives no class heritage to tell it apart.
|
|
577
|
+
if (LIT_PACKAGE.test(spec) && (whole || hasDefault || valueSpecifier))
|
|
578
|
+
return true;
|
|
579
|
+
}
|
|
580
|
+
// A side-effect import of a class-component package or a Lit package, and CommonJS or dynamic imports, which bind
|
|
581
|
+
// the whole module.
|
|
582
|
+
for (const m of text.matchAll(/(?:\bimport\s*|\brequire\s*\(\s*|\bimport\s*\(\s*)(['"])([^'"\n]+)\1/g)) {
|
|
583
|
+
const spec = m[2];
|
|
584
|
+
if (CLASS_COMPONENT_PACKAGES.test(spec) || LIT_DECORATORS.test(spec) || LIT_PACKAGE.test(spec))
|
|
585
|
+
return true;
|
|
586
|
+
if (!/^\s*import\s*['"]/.test(m[0]) && VUE_PACKAGE.test(spec))
|
|
587
|
+
return true;
|
|
588
|
+
}
|
|
589
|
+
return [codeOnly(text), codeOnly(text, false)].some((code) => /(?<![\w$'"`@/.])@\s*(?:Component|Options)\b(?![\w$])/.test(code));
|
|
590
|
+
}
|
|
591
|
+
/** How many lines above a class its decorators are read, at most. */
|
|
592
|
+
const CLASS_HEADER_MAX_LINES = 500;
|
|
593
|
+
/**
|
|
594
|
+
* A class's header: the decorators written above it, however many lines
|
|
595
|
+
* their arguments take (read upward while a bracket written below is not
|
|
596
|
+
* yet opened, or a line starts with `@`), and its own text up to the `{`
|
|
597
|
+
* that opens its body (outside `(…)`, `[…]` and `<…>`), so the whole
|
|
598
|
+
* heritage clause.
|
|
599
|
+
*/
|
|
600
|
+
function classHeaderText(cls, file, lineAt) {
|
|
601
|
+
const lineText = (n) => {
|
|
602
|
+
const at = lineAt(file, n);
|
|
603
|
+
return at ? at.text.slice(at.start, at.end) : null;
|
|
604
|
+
};
|
|
605
|
+
const balance = (t) => {
|
|
606
|
+
let b = 0;
|
|
607
|
+
for (const c of t) {
|
|
608
|
+
if (c === ')' || c === ']' || c === '}')
|
|
609
|
+
b++;
|
|
610
|
+
else if (c === '(' || c === '[' || c === '{')
|
|
611
|
+
b--;
|
|
612
|
+
}
|
|
613
|
+
return b;
|
|
614
|
+
};
|
|
615
|
+
// Upward, `open` counts the brackets closed below and not yet opened: inside a decorator's arguments. Outside
|
|
616
|
+
// them, a line is kept when it starts with `@` or closes a call (`})`, `)`): a previous declaration's `}` is not.
|
|
617
|
+
const above = [];
|
|
618
|
+
let open = 0;
|
|
619
|
+
for (let n = cls.start_line - 1; n >= Math.max(1, cls.start_line - CLASS_HEADER_MAX_LINES); n--) {
|
|
620
|
+
const raw = lineText(n);
|
|
621
|
+
if (raw === null)
|
|
622
|
+
break;
|
|
623
|
+
const t = codeOnly(raw).trim();
|
|
624
|
+
if (open <= 0 && t !== '' && !t.startsWith('@') && !(balance(t) > 0 && /\)\s*[,;]?$/.test(t)))
|
|
625
|
+
break;
|
|
626
|
+
above.unshift(raw);
|
|
627
|
+
open = Math.max(0, open + balance(t));
|
|
628
|
+
}
|
|
629
|
+
// Down from the class's start, to the `{` that opens its body.
|
|
630
|
+
const own = [];
|
|
631
|
+
let depth = 0;
|
|
632
|
+
scan: for (let n = cls.start_line; n <= Math.min(cls.end_line, cls.start_line + CLASS_HEADER_MAX_LINES); n++) {
|
|
633
|
+
const raw = lineText(n);
|
|
634
|
+
if (raw === null)
|
|
635
|
+
break;
|
|
636
|
+
const code = codeOnly(raw);
|
|
637
|
+
for (let i = n === cls.start_line ? (cls.start_column ?? 0) : 0; i < code.length; i++) {
|
|
638
|
+
const c = code[i];
|
|
639
|
+
if (c === '(' || c === '[' || c === '<')
|
|
640
|
+
depth++;
|
|
641
|
+
else if ((c === ')' || c === ']' || c === '>') && code[i - 1] !== '=')
|
|
642
|
+
depth = Math.max(0, depth - 1);
|
|
643
|
+
else if (c === '{' && depth === 0) {
|
|
644
|
+
own.push(raw.slice(0, i));
|
|
645
|
+
break scan;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
own.push(raw);
|
|
649
|
+
}
|
|
650
|
+
return [...above, ...own].join('\n');
|
|
651
|
+
}
|
|
652
|
+
function runtimeCalled(decl, family) {
|
|
653
|
+
if (decl.kind !== 'method' || family === null)
|
|
654
|
+
return false;
|
|
655
|
+
if (family === 'py')
|
|
656
|
+
return PY_DUNDER.test(decl.name) && decl.name !== '__init__';
|
|
657
|
+
// `[inspect.custom]`, `[util.inspect.custom]`, `[Symbol.for('nodejs.util.inspect.custom')]`.
|
|
658
|
+
if (family === 'ts' && /inspect\.custom/.test(decl.name))
|
|
659
|
+
return true;
|
|
660
|
+
return RUNTIME_CALLED[family].has(decl.name);
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* The names a TypeScript / JavaScript text writes as a plain decorator,
|
|
664
|
+
* `@Name` or `@ns.Name` with no `(` after it: a plain decorator is no call
|
|
665
|
+
* and no reference in the graph, so the function runs with no edge into it
|
|
666
|
+
* (a factory call, `@Name()`, is an edge). The last part of a dotted name.
|
|
667
|
+
*/
|
|
668
|
+
export function plainDecoratorNames(text) {
|
|
669
|
+
const out = new Set();
|
|
670
|
+
if (!text.includes('@'))
|
|
671
|
+
return out;
|
|
672
|
+
// Not in comments (JSDoc `@param`, `@link`) or strings (`'@repo/email'`), nor a name followed by `/` or `-`.
|
|
673
|
+
// Read twice, with regular-expression literals recognised and without: a `/` read the wrong way (a division
|
|
674
|
+
// or a JSX `</b>` taken for a regex, or a regex taken for a division) can hide the names after it in one scan,
|
|
675
|
+
// so a name either scan finds counts.
|
|
676
|
+
for (const code of new Set([codeOnly(text), codeOnly(text, false)])) {
|
|
677
|
+
for (const m of code.matchAll(/(?<![\w$'"`@/.])@\s*((?:[A-Za-z_$][\w$]*\s*\.\s*)*[A-Za-z_$][\w$]*)(?![\w$])(?!\s*[(./-])/g)) {
|
|
678
|
+
const parts = m[1].split('.');
|
|
679
|
+
out.add(parts[parts.length - 1].trim());
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
return out;
|
|
683
|
+
}
|
|
684
|
+
/** Keywords after which a `/` starts a regular expression, not a division. */
|
|
685
|
+
const REGEX_AFTER_WORDS = new Set(['return', 'typeof', 'case', 'do', 'else', 'in', 'of', 'instanceof', 'new', 'delete', 'void', 'throw', 'yield', 'await']);
|
|
686
|
+
/** The longest regular-expression literal read as one; a longer one is read as code, so a scan stays linear. */
|
|
687
|
+
const REGEX_MAX_CHARS = 1_000;
|
|
688
|
+
/**
|
|
689
|
+
* Where the regular-expression literal that starts at `i` (a `/`) closes
|
|
690
|
+
* (its closing `/`; its flags read as code), or -1 when `/` is not one
|
|
691
|
+
* there: a division (after a name, a number, `)`
|
|
692
|
+
* or `]`), or no closing `/` on the line within `REGEX_MAX_CHARS`. A regex
|
|
693
|
+
* may start at the start of the text or a line, after a punctuator
|
|
694
|
+
* (`( , = : [ ! & | ? { } ;`, an operator) or after `return`, `typeof`,
|
|
695
|
+
* `case` and the like.
|
|
696
|
+
*/
|
|
697
|
+
function regexEnd(text, i) {
|
|
698
|
+
let p = i - 1;
|
|
699
|
+
while (p >= 0 && (text[p] === ' ' || text[p] === '\t'))
|
|
700
|
+
p--;
|
|
701
|
+
if (p >= 0 && text[p] !== '\n' && text[p] !== '\r') {
|
|
702
|
+
const c = text[p];
|
|
703
|
+
if (/[\w$]/.test(c)) {
|
|
704
|
+
let w = p;
|
|
705
|
+
while (w > 0 && /[\w$]/.test(text[w - 1]))
|
|
706
|
+
w--;
|
|
707
|
+
if (!REGEX_AFTER_WORDS.has(text.slice(w, p + 1)))
|
|
708
|
+
return -1;
|
|
709
|
+
}
|
|
710
|
+
else if (!'(,=:[!&|?{};+-*%<>~^'.includes(c))
|
|
711
|
+
return -1;
|
|
712
|
+
}
|
|
713
|
+
let inClass = false;
|
|
714
|
+
const bound = Math.min(text.length, i + REGEX_MAX_CHARS);
|
|
715
|
+
for (let j = i + 1; j < bound; j++) {
|
|
716
|
+
const c = text[j];
|
|
717
|
+
if (c === '\\') {
|
|
718
|
+
j++;
|
|
719
|
+
continue;
|
|
720
|
+
}
|
|
721
|
+
if (c === '\n' || c === '\r')
|
|
722
|
+
return -1;
|
|
723
|
+
if (inClass) {
|
|
724
|
+
if (c === ']')
|
|
725
|
+
inClass = false;
|
|
726
|
+
continue;
|
|
727
|
+
}
|
|
728
|
+
if (c === '[')
|
|
729
|
+
inClass = true;
|
|
730
|
+
else if (c === '/')
|
|
731
|
+
return j;
|
|
732
|
+
}
|
|
733
|
+
return -1;
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* A TypeScript / JavaScript text with its comments and the contents of its
|
|
737
|
+
* strings, template literals (not their `${…}` code) and regular-expression
|
|
738
|
+
* literals turned to spaces, line breaks kept, so offsets stay where they
|
|
739
|
+
* were. When the scan ends inside a template literal or a block comment
|
|
740
|
+
* (a `/` it read as a division, JSX text with a backquote), the text is
|
|
741
|
+
* returned as it is: reading too much is the safe side. With
|
|
742
|
+
* `regexLiterals` false, every `/` that starts no comment is read as code.
|
|
743
|
+
*/
|
|
744
|
+
export function codeOnly(text, regexLiterals = true) {
|
|
745
|
+
const out = text.split('');
|
|
746
|
+
const blank = (from, to) => {
|
|
747
|
+
for (let k = from; k < to && k < out.length; k++)
|
|
748
|
+
if (out[k] !== '\n' && out[k] !== '\r')
|
|
749
|
+
out[k] = ' ';
|
|
750
|
+
};
|
|
751
|
+
// `${` depth inside each open template literal.
|
|
752
|
+
const templates = [];
|
|
753
|
+
let braces = 0;
|
|
754
|
+
for (let i = 0; i < text.length; i++) {
|
|
755
|
+
const c = text[i];
|
|
756
|
+
if (templates.length > 0 && braces === templates[templates.length - 1]) {
|
|
757
|
+
// In a template literal's text.
|
|
758
|
+
const from = i;
|
|
759
|
+
for (; i < text.length && text[i] !== '`' && !(text[i] === '$' && text[i + 1] === '{'); i++)
|
|
760
|
+
if (text[i] === '\\')
|
|
761
|
+
i++;
|
|
762
|
+
blank(from, i);
|
|
763
|
+
if (text[i] === '`')
|
|
764
|
+
templates.pop();
|
|
765
|
+
else if (i < text.length) {
|
|
766
|
+
braces++;
|
|
767
|
+
i++;
|
|
768
|
+
}
|
|
769
|
+
continue;
|
|
770
|
+
}
|
|
771
|
+
if (c === '/' && text[i + 1] === '/') {
|
|
772
|
+
const from = i;
|
|
773
|
+
while (i < text.length && text[i] !== '\n')
|
|
774
|
+
i++;
|
|
775
|
+
blank(from, i);
|
|
776
|
+
}
|
|
777
|
+
else if (c === '/' && text[i + 1] === '*') {
|
|
778
|
+
const end = text.indexOf('*/', i + 2);
|
|
779
|
+
if (end < 0)
|
|
780
|
+
return text;
|
|
781
|
+
blank(i, end + 2);
|
|
782
|
+
i = end + 1;
|
|
783
|
+
}
|
|
784
|
+
else if (c === '/' && regexLiterals) {
|
|
785
|
+
const close = regexEnd(text, i);
|
|
786
|
+
if (close > 0) {
|
|
787
|
+
blank(i + 1, close);
|
|
788
|
+
i = close;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
else if (c === "'" || c === '"') {
|
|
792
|
+
const from = i + 1;
|
|
793
|
+
for (i++; i < text.length && text[i] !== c && text[i] !== '\n'; i++)
|
|
794
|
+
if (text[i] === '\\')
|
|
795
|
+
i++;
|
|
796
|
+
blank(from, i);
|
|
797
|
+
}
|
|
798
|
+
else if (c === '`') {
|
|
799
|
+
templates.push(braces);
|
|
800
|
+
}
|
|
801
|
+
else if (c === '{')
|
|
802
|
+
braces++;
|
|
803
|
+
else if (c === '}')
|
|
804
|
+
braces--;
|
|
805
|
+
}
|
|
806
|
+
return templates.length > 0 ? text : out.join('');
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Whether a declaration's code runs without a call the graph records, so a
|
|
810
|
+
* test may run it with no edge to follow:
|
|
811
|
+
*
|
|
812
|
+
* - a field: its initializer runs on import (module level) or when its
|
|
813
|
+
* class is built (`new` reaches the class, not the field), and reading a
|
|
814
|
+
* field is no call. This holds the functions nested in an initializer
|
|
815
|
+
* too, which `stepOutOf` steps out of (`export const GET = withAuth(…)`);
|
|
816
|
+
* - an inline function directly under a module or a class that no call or
|
|
817
|
+
* reference enters (`RAW.forEach((c) => …)`, `setTimeout(…)`,
|
|
818
|
+
* `bus.on('x', …)`, `{ get: … }` in `Object.defineProperty`, a callback
|
|
819
|
+
* in a `static {}` block or a decorator argument, `module.exports =
|
|
820
|
+
* function () {}`): the code that holds it passes it on, at import or
|
|
821
|
+
* when the class is defined;
|
|
822
|
+
* - a class that holds calls of its own (static blocks, decorator calls,
|
|
823
|
+
* Java instance initializers): they run when the class is defined or
|
|
824
|
+
* built;
|
|
825
|
+
* - an inline function written in its parent's decorators or a parameter
|
|
826
|
+
* decorator's arguments (`@Reg(() => …)` on a method, Python
|
|
827
|
+
* `@deco(lambda: …)`): it runs when the parent is defined;
|
|
828
|
+
* - a function written as a plain decorator (`@Log`, `@Reg` on a class, an
|
|
829
|
+
* accessor or a parameter), under its own name, an `import { X as Y }`
|
|
830
|
+
* name, or as a default import of its module: it runs when the class is
|
|
831
|
+
* defined;
|
|
832
|
+
* - a getter or setter (TypeScript `get` / `set`, a Python property, by its
|
|
833
|
+
* decorator lines): a property access is no call;
|
|
834
|
+
* - a method the runtime calls (`RUNTIME_CALLED`, Python dunders);
|
|
835
|
+
* - a Java static initializer (`<clinit>`).
|
|
836
|
+
*
|
|
837
|
+
* A module's top-level code, and a Python default argument, are handled by
|
|
838
|
+
* `testsOf` (they run on import).
|
|
839
|
+
*/
|
|
840
|
+
function runsWithoutCall(decl, file, ctx) {
|
|
841
|
+
if (decl.kind === 'field')
|
|
842
|
+
return true;
|
|
843
|
+
if (decl.kind === 'type')
|
|
844
|
+
return ctx.holdsCalls.has(decl.id);
|
|
845
|
+
if (decl.kind !== 'method' && decl.kind !== 'function')
|
|
846
|
+
return false;
|
|
847
|
+
if (decl.name === '<clinit>')
|
|
848
|
+
return true;
|
|
849
|
+
const family = familyOfFile(file);
|
|
850
|
+
if (isInlineFunction(decl) && !ctx.entered.has(decl.id) && HOLDER_KINDS.has(ctx.parentKind(decl) ?? ''))
|
|
851
|
+
return true;
|
|
852
|
+
if (isInlineFunction(decl) && ctx.inParentHeader(decl, file))
|
|
853
|
+
return true;
|
|
854
|
+
if (runtimeCalled(decl, family) && !(family === 'ts' && FRAMEWORK_CLASS_ONLY.has(decl.name) && !ctx.frameworkClass(decl, file)))
|
|
855
|
+
return true;
|
|
856
|
+
if (family === 'ts' && ctx.plainDecorator(decl, file))
|
|
857
|
+
return true;
|
|
858
|
+
if (TS_ACCESSOR.test(decl.signature ?? ''))
|
|
859
|
+
return true;
|
|
860
|
+
if (family !== 'py')
|
|
861
|
+
return false;
|
|
862
|
+
// The decorator lines: from the declaration's start down to its `def`, and any right above it.
|
|
863
|
+
const lineText = (n) => {
|
|
864
|
+
const at = ctx.lineAt(file, n);
|
|
865
|
+
return at ? at.text.slice(at.start, at.end) : null;
|
|
866
|
+
};
|
|
867
|
+
for (let n = decl.start_line; n <= Math.min(decl.end_line, decl.start_line + 20); n++) {
|
|
868
|
+
const t = lineText(n);
|
|
869
|
+
if (t === null || /^\s*(?:async\s+)?def\b/.test(t))
|
|
870
|
+
break;
|
|
871
|
+
if (PY_ACCESSOR.test(t))
|
|
872
|
+
return true;
|
|
873
|
+
}
|
|
874
|
+
for (let n = decl.start_line - 1; n >= Math.max(1, decl.start_line - 20); n--) {
|
|
875
|
+
const t = lineText(n);
|
|
876
|
+
if (t === null || !/^\s*@/.test(t))
|
|
877
|
+
break;
|
|
878
|
+
if (PY_ACCESSOR.test(t))
|
|
879
|
+
return true;
|
|
880
|
+
}
|
|
881
|
+
return false;
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Where a Python function's signature is, as offsets in its file's text:
|
|
885
|
+
* from the `(` after `def name` to the `:` that ends it, parameters,
|
|
886
|
+
* defaults and annotations included. Python evaluates its defaults (and,
|
|
887
|
+
* without postponed annotations, its annotations) when the `def` runs: on
|
|
888
|
+
* import for a module's function, when the class body runs for a method.
|
|
889
|
+
* `null` when it cannot be found: no `def` in the declaration's lines, or
|
|
890
|
+
* no end within 20,000 characters (the caller then fails closed).
|
|
891
|
+
*/
|
|
892
|
+
function pySignature(decl, file, lineAt) {
|
|
893
|
+
// The `def` is after the decorators, however many: search the declaration's own lines.
|
|
894
|
+
for (let n = decl.start_line; n <= decl.end_line; n++) {
|
|
895
|
+
const at = lineAt(file, n);
|
|
896
|
+
if (!at)
|
|
897
|
+
return null;
|
|
898
|
+
const m = /^\s*(?:async\s+)?def\s+[A-Za-z_]\w*\s*(?:\[[^\]\n]*\]\s*)?\(/.exec(at.text.slice(at.start, at.end));
|
|
899
|
+
if (!m)
|
|
900
|
+
continue;
|
|
901
|
+
const text = at.text;
|
|
902
|
+
const from = at.start + m[0].length - 1;
|
|
903
|
+
const bound = Math.min(text.length, from + 20_000);
|
|
904
|
+
let depth = 0;
|
|
905
|
+
let closed = false;
|
|
906
|
+
for (let i = from; i < bound; i++) {
|
|
907
|
+
const c = text[i];
|
|
908
|
+
if (c === '#') {
|
|
909
|
+
while (i < bound && text[i] !== '\n')
|
|
910
|
+
i++;
|
|
911
|
+
}
|
|
912
|
+
else if (c === '"' || c === "'") {
|
|
913
|
+
const triple = text.startsWith(c.repeat(3), i);
|
|
914
|
+
const q = triple ? c.repeat(3) : c;
|
|
915
|
+
for (i += q.length; i < bound && !text.startsWith(q, i); i++)
|
|
916
|
+
if (text[i] === '\\')
|
|
917
|
+
i++;
|
|
918
|
+
i += q.length - 1;
|
|
919
|
+
}
|
|
920
|
+
else if (c === '(' || c === '[' || c === '{')
|
|
921
|
+
depth++;
|
|
922
|
+
else if (c === ')' || c === ']' || c === '}') {
|
|
923
|
+
depth--;
|
|
924
|
+
if (depth === 0 && c === ')')
|
|
925
|
+
closed = true;
|
|
926
|
+
}
|
|
927
|
+
else if (c === ':' && depth === 0 && closed)
|
|
928
|
+
return { from, to: i };
|
|
929
|
+
}
|
|
930
|
+
return null;
|
|
931
|
+
}
|
|
932
|
+
return null;
|
|
933
|
+
}
|
|
934
|
+
function definitionHeader(decl, file, lineAt) {
|
|
935
|
+
if (decl.start_column === undefined)
|
|
936
|
+
return null;
|
|
937
|
+
const at = lineAt(file, decl.start_line);
|
|
938
|
+
if (!at)
|
|
939
|
+
return null;
|
|
940
|
+
const start = at.start + decl.start_column;
|
|
941
|
+
const family = familyOfFile(file);
|
|
942
|
+
if (family === 'py') {
|
|
943
|
+
// No signature found: fail closed, the whole declaration counts.
|
|
944
|
+
const sig = pySignature(decl, file, lineAt);
|
|
945
|
+
return { start, end: sig ? sig.to : Number.POSITIVE_INFINITY, spans: [], python: true, all: false };
|
|
946
|
+
}
|
|
947
|
+
if (family !== 'ts')
|
|
948
|
+
return null;
|
|
949
|
+
const text = at.text;
|
|
950
|
+
const bound = Math.min(text.length, start + 20_000);
|
|
951
|
+
const spans = [];
|
|
952
|
+
// Skips a string, a template literal (naively, to its closing backquote) or a comment at `i`; the index after it.
|
|
953
|
+
const skip = (i) => {
|
|
954
|
+
const c = text[i];
|
|
955
|
+
if (c === '/' && text[i + 1] === '/') {
|
|
956
|
+
const e = text.indexOf('\n', i);
|
|
957
|
+
return e < 0 ? bound : e;
|
|
958
|
+
}
|
|
959
|
+
if (c === '/' && text[i + 1] === '*') {
|
|
960
|
+
const e = text.indexOf('*/', i + 2);
|
|
961
|
+
return e < 0 ? bound : e + 2;
|
|
962
|
+
}
|
|
963
|
+
if (c === "'" || c === '"' || c === '`') {
|
|
964
|
+
let j = i + 1;
|
|
965
|
+
for (; j < bound && text[j] !== c; j++)
|
|
966
|
+
if (text[j] === '\\')
|
|
967
|
+
j++;
|
|
968
|
+
return j + 1;
|
|
969
|
+
}
|
|
970
|
+
return i;
|
|
971
|
+
};
|
|
972
|
+
let depth = 0;
|
|
973
|
+
let params = false;
|
|
974
|
+
// Whether the scan reached the body (or the end of a signature); if not, it fails closed.
|
|
975
|
+
let ended = false;
|
|
976
|
+
for (let i = start; i < bound && !ended; i++) {
|
|
977
|
+
const after = skip(i);
|
|
978
|
+
if (after !== i) {
|
|
979
|
+
i = after - 1;
|
|
980
|
+
continue;
|
|
981
|
+
}
|
|
982
|
+
const c = text[i];
|
|
983
|
+
if (c === '(' || c === '[')
|
|
984
|
+
depth++;
|
|
985
|
+
else if (c === ')' || c === ']') {
|
|
986
|
+
depth--;
|
|
987
|
+
if (depth === 0 && c === ')')
|
|
988
|
+
params = true;
|
|
989
|
+
}
|
|
990
|
+
else if (c === '{') {
|
|
991
|
+
if (depth === 0 && params)
|
|
992
|
+
ended = true;
|
|
993
|
+
else
|
|
994
|
+
depth++;
|
|
995
|
+
}
|
|
996
|
+
else if (c === '}')
|
|
997
|
+
depth--;
|
|
998
|
+
else if ((c === ';' || c === '=') && depth === 0 && params)
|
|
999
|
+
ended = true;
|
|
1000
|
+
// An arrow with a bare parameter (`x => …`) has no parameter list.
|
|
1001
|
+
else if (c === '=' && text[i + 1] === '>' && depth === 0)
|
|
1002
|
+
ended = true;
|
|
1003
|
+
else if (c === '@' && depth > 0) {
|
|
1004
|
+
let j = i + 1;
|
|
1005
|
+
while (j < bound && /[\s\w$.]/.test(text[j]))
|
|
1006
|
+
j++;
|
|
1007
|
+
if (text[j] !== '(')
|
|
1008
|
+
continue;
|
|
1009
|
+
let d = 0;
|
|
1010
|
+
let k = j;
|
|
1011
|
+
for (; k < bound; k++) {
|
|
1012
|
+
const past = skip(k);
|
|
1013
|
+
if (past !== k) {
|
|
1014
|
+
k = past - 1;
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
if (text[k] === '(')
|
|
1018
|
+
d++;
|
|
1019
|
+
else if (text[k] === ')' && --d === 0)
|
|
1020
|
+
break;
|
|
1021
|
+
}
|
|
1022
|
+
spans.push([i, k]);
|
|
1023
|
+
i = k;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
// Not reached within the bound: the header's extent is not known, so all of the declaration counts.
|
|
1027
|
+
return { start, end: start, spans, python: false, all: !ended };
|
|
1028
|
+
}
|
|
1029
|
+
const inDefinitionHeader = (h, offset) => h.all || (h.python ? offset >= h.start && offset <= h.end : offset < h.start || h.spans.some(([a, b]) => offset >= a && offset <= b));
|
|
1030
|
+
/**
|
|
1031
|
+
* How a TypeScript / JavaScript file names what it imports, for plain
|
|
1032
|
+
* decorators written under another name: `import { Log as L }` (`L` is
|
|
1033
|
+
* `Log`), and default imports (`import Logger from './log'`,
|
|
1034
|
+
* `{ default as L }`), by their specifier.
|
|
1035
|
+
*/
|
|
1036
|
+
export function importBindings(text) {
|
|
1037
|
+
const renamed = new Map();
|
|
1038
|
+
const defaults = new Map();
|
|
1039
|
+
const named = new Map();
|
|
1040
|
+
// `import Logger = require('./log')` (TypeScript's CommonJS import): the module's `export =` value.
|
|
1041
|
+
for (const m of text.matchAll(/\bimport\s+([A-Za-z_$][\w$]*)\s*=\s*require\s*\(\s*(['"])([^'"\n]+)\2\s*\)/g))
|
|
1042
|
+
defaults.set(m[1], m[3]);
|
|
1043
|
+
for (const m of text.matchAll(/\bimport\s+(?:type\s+)?([^'";]*?)\s+from\s*(['"])([^'"\n]+)\2/g)) {
|
|
1044
|
+
const clause = m[1];
|
|
1045
|
+
const spec = m[3];
|
|
1046
|
+
const def = /^([A-Za-z_$][\w$]*)\s*(?:,|$)/.exec(clause.trim());
|
|
1047
|
+
if (def)
|
|
1048
|
+
defaults.set(def[1], spec);
|
|
1049
|
+
const braces = /\{([^}]*)\}/.exec(clause);
|
|
1050
|
+
for (const part of braces ? braces[1].split(',') : []) {
|
|
1051
|
+
const r = /^\s*(?:type\s+)?([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*$/.exec(part);
|
|
1052
|
+
if (!r)
|
|
1053
|
+
continue;
|
|
1054
|
+
const local = r[2] ?? r[1];
|
|
1055
|
+
if (r[1] === 'default')
|
|
1056
|
+
defaults.set(local, spec);
|
|
1057
|
+
else {
|
|
1058
|
+
named.set(local, { imported: r[1], spec });
|
|
1059
|
+
if (r[2])
|
|
1060
|
+
renamed.set(r[2], r[1]);
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
return { renamed, defaults, named };
|
|
1065
|
+
}
|
|
1066
|
+
export function moduleExports(text) {
|
|
1067
|
+
const lists = [];
|
|
1068
|
+
for (const m of text.matchAll(/\bexport\s+(?:type\s+)?\{([^}]*)\}(?:\s*from\s*(['"])([^'"\n]+)\2)?/g)) {
|
|
1069
|
+
for (const part of m[1].split(',')) {
|
|
1070
|
+
const r = /^\s*(?:type\s+)?([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*$/.exec(part);
|
|
1071
|
+
if (r)
|
|
1072
|
+
lists.push({ exported: r[2] ?? r[1], local: r[1], spec: m[3] ?? null });
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
const stars = [...text.matchAll(/\bexport\s+(?:type\s+)?\*\s*from\s*(['"])([^'"\n]+)\1/g)].map((m) => m[2]);
|
|
1076
|
+
const defaults = [...text.matchAll(/\bexport\s*(?:default\s+|=\s*)([A-Za-z_$][\w$]*)\s*(?:;|$)/gm)].map((m) => m[1]);
|
|
1077
|
+
return { lists, stars, defaults, bindings: importBindings(text) };
|
|
1078
|
+
}
|
|
1079
|
+
/**
|
|
1080
|
+
* How many (module, name) pairs one `followImport` may visit before it
|
|
1081
|
+
* stops: `testsOf` lets each search visit the larger of `minStates` and
|
|
1082
|
+
* `perGraphFile` times the files of its graph, so a search through a star
|
|
1083
|
+
* closure of any size ends (it visits each module once per name), and an
|
|
1084
|
+
* import whose search is cut fails closed on its own (`followableNames`).
|
|
1085
|
+
*/
|
|
1086
|
+
export const BLAST_FOLLOW_BUDGET = { minStates: 10_000, perGraphFile: 4 };
|
|
1087
|
+
const FOLLOW_MAX_STATES = BLAST_FOLLOW_BUDGET.minStates;
|
|
1088
|
+
/**
|
|
1089
|
+
* The declarations an import may name, followed through re-exports to a
|
|
1090
|
+
* fixed point:
|
|
1091
|
+
*
|
|
1092
|
+
* - `export { X as Y } from '…'` (`X` may be `default`);
|
|
1093
|
+
* - `export * from '…'`, for a name no list of the module exports;
|
|
1094
|
+
* - a local `export { X as Y }`, `export default X` or `export = X` whose
|
|
1095
|
+
* `X` the module itself imports: through that import.
|
|
1096
|
+
*
|
|
1097
|
+
* Each target is a module among `files` and the name there (`default` for
|
|
1098
|
+
* its default export). A name a module neither lists nor imports may be
|
|
1099
|
+
* declared in it, so it is a target, also when the module has `export *`
|
|
1100
|
+
* lines. A specifier that does not resolve to a file in the graph ends that
|
|
1101
|
+
* path at the module and name it was read from. `cut` is true when the
|
|
1102
|
+
* search stopped at `maxStates` pairs: the declaration is then not known
|
|
1103
|
+
* (`followableNames` says what it may be).
|
|
1104
|
+
*/
|
|
1105
|
+
export function followImport(from, spec, name, files, exportsOf, maxStates = FOLLOW_MAX_STATES) {
|
|
1106
|
+
const targets = [];
|
|
1107
|
+
const seen = new Set();
|
|
1108
|
+
const queue = [];
|
|
1109
|
+
const start = resolveRelative(from, spec, files);
|
|
1110
|
+
if (start !== null)
|
|
1111
|
+
queue.push({ file: start, name });
|
|
1112
|
+
// The import a module binds `local` to, followed one step: true when `local` is one.
|
|
1113
|
+
const viaImport = (file, local, b) => {
|
|
1114
|
+
const named = b.named.get(local);
|
|
1115
|
+
const def = b.defaults.get(local);
|
|
1116
|
+
if (named === undefined && def === undefined)
|
|
1117
|
+
return false;
|
|
1118
|
+
const next = resolveRelative(file, named ? named.spec : def, files);
|
|
1119
|
+
if (next === null)
|
|
1120
|
+
targets.push({ file, name: local });
|
|
1121
|
+
else
|
|
1122
|
+
queue.push({ file: next, name: named ? named.imported : 'default' });
|
|
1123
|
+
return true;
|
|
1124
|
+
};
|
|
1125
|
+
while (queue.length > 0) {
|
|
1126
|
+
const at = queue.shift();
|
|
1127
|
+
const key = `${at.file}\u0000${at.name}`;
|
|
1128
|
+
if (seen.has(key))
|
|
1129
|
+
continue;
|
|
1130
|
+
if (seen.size >= maxStates)
|
|
1131
|
+
return { targets, cut: true };
|
|
1132
|
+
seen.add(key);
|
|
1133
|
+
const info = exportsOf(at.file);
|
|
1134
|
+
let listed = false;
|
|
1135
|
+
for (const hop of info.lists) {
|
|
1136
|
+
if (hop.exported !== at.name)
|
|
1137
|
+
continue;
|
|
1138
|
+
listed = true;
|
|
1139
|
+
if (hop.spec !== null) {
|
|
1140
|
+
const next = resolveRelative(at.file, hop.spec, files);
|
|
1141
|
+
if (next === null)
|
|
1142
|
+
targets.push({ file: at.file, name: hop.local });
|
|
1143
|
+
else
|
|
1144
|
+
queue.push({ file: next, name: hop.local });
|
|
1145
|
+
}
|
|
1146
|
+
else if (!viaImport(at.file, hop.local, info.bindings)) {
|
|
1147
|
+
targets.push({ file: at.file, name: hop.local });
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
if (at.name === 'default') {
|
|
1151
|
+
for (const local of info.defaults)
|
|
1152
|
+
viaImport(at.file, local, info.bindings);
|
|
1153
|
+
}
|
|
1154
|
+
if (listed)
|
|
1155
|
+
continue;
|
|
1156
|
+
targets.push(at);
|
|
1157
|
+
// `export *` passes on every name but `default`.
|
|
1158
|
+
if (at.name !== 'default') {
|
|
1159
|
+
for (const s of info.stars) {
|
|
1160
|
+
const next = resolveRelative(at.file, s, files);
|
|
1161
|
+
if (next !== null)
|
|
1162
|
+
queue.push({ file: next, name: at.name });
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
return { targets, cut: false };
|
|
1167
|
+
}
|
|
1168
|
+
/**
|
|
1169
|
+
* Every name a `followImport` search for `name` may give a target under,
|
|
1170
|
+
* over the modules in `files`: `name` itself (an `export *` passes it on),
|
|
1171
|
+
* every name an `export { … }` list exports from (`local`), every name a
|
|
1172
|
+
* module exports as its default (`export default X`, `export = X`), the
|
|
1173
|
+
* name each of those is imported under where the module imports it, and
|
|
1174
|
+
* `default` when a search may reach a default export. What a search cut at
|
|
1175
|
+
* its bound fails closed on: the declarations it may name are among these.
|
|
1176
|
+
*/
|
|
1177
|
+
export function followableNames(name, files, exportsOf) {
|
|
1178
|
+
const out = new Set([name]);
|
|
1179
|
+
for (const file of files) {
|
|
1180
|
+
const info = exportsOf(file);
|
|
1181
|
+
const throughImport = (local) => {
|
|
1182
|
+
out.add(local);
|
|
1183
|
+
const named = info.bindings.named.get(local);
|
|
1184
|
+
if (named)
|
|
1185
|
+
out.add(named.imported);
|
|
1186
|
+
if (info.bindings.defaults.has(local))
|
|
1187
|
+
out.add('default');
|
|
1188
|
+
};
|
|
1189
|
+
for (const hop of info.lists) {
|
|
1190
|
+
if (hop.spec === null)
|
|
1191
|
+
throughImport(hop.local);
|
|
1192
|
+
else
|
|
1193
|
+
out.add(hop.local);
|
|
1194
|
+
}
|
|
1195
|
+
for (const local of info.defaults)
|
|
1196
|
+
throughImport(local);
|
|
1197
|
+
}
|
|
1198
|
+
return out;
|
|
1199
|
+
}
|
|
1200
|
+
/** A relative import's file among `files`, the way TypeScript finds it (`.js` for `.ts`, extensions, `index`). */
|
|
1201
|
+
function resolveRelative(from, spec, files) {
|
|
1202
|
+
if (!spec.startsWith('.'))
|
|
1203
|
+
return null;
|
|
1204
|
+
const dir = from.includes('/') ? from.slice(0, from.lastIndexOf('/')) : '';
|
|
1205
|
+
const parts = [];
|
|
1206
|
+
for (const p of `${dir}/${spec}`.split('/')) {
|
|
1207
|
+
if (p === '' || p === '.')
|
|
1208
|
+
continue;
|
|
1209
|
+
if (p === '..')
|
|
1210
|
+
parts.pop();
|
|
1211
|
+
else
|
|
1212
|
+
parts.push(p);
|
|
1213
|
+
}
|
|
1214
|
+
const base = parts.join('/');
|
|
1215
|
+
const stems = [base, base.replace(/\.(?:[cm]?js|jsx)$/, '')];
|
|
1216
|
+
for (const stem of stems) {
|
|
1217
|
+
if (files.has(stem))
|
|
1218
|
+
return stem;
|
|
1219
|
+
for (const ext of ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs']) {
|
|
1220
|
+
if (files.has(stem + ext))
|
|
1221
|
+
return stem + ext;
|
|
1222
|
+
if (files.has(`${stem}/index${ext}`))
|
|
1223
|
+
return `${stem}/index${ext}`;
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
return null;
|
|
1227
|
+
}
|
|
1228
|
+
/**
|
|
1229
|
+
* The names a file exports as its default: `export default function Log`,
|
|
1230
|
+
* `export default class X`, `export default X;`, `export { X as default }`,
|
|
1231
|
+
* TypeScript's `export = X`, and CommonJS `module.exports = X` /
|
|
1232
|
+
* `exports.default = X`.
|
|
1233
|
+
*/
|
|
1234
|
+
function defaultExportNames(text) {
|
|
1235
|
+
const out = new Set(['default']);
|
|
1236
|
+
for (const m of text.matchAll(/\bexport\s+default\s+(?:async\s+)?(?:(?:function\s*\*?|class)\s+)?([A-Za-z_$][\w$]*)/g))
|
|
1237
|
+
out.add(m[1]);
|
|
1238
|
+
for (const m of text.matchAll(/\bexport\s*=\s*(?:(?:async\s+)?function\s*\*?\s*|class\s+)?([A-Za-z_$][\w$]*)/g))
|
|
1239
|
+
out.add(m[1]);
|
|
1240
|
+
for (const m of text.matchAll(/\b(?:module\s*\.\s*)?exports(?:\s*\.\s*default)?\s*=\s*(?:(?:async\s+)?function\s*\*?\s*|class\s+)?([A-Za-z_$][\w$]*)/g))
|
|
1241
|
+
out.add(m[1]);
|
|
1242
|
+
for (const m of text.matchAll(/\bexport\s*\{([^}]*)\}/g)) {
|
|
1243
|
+
for (const part of m[1].split(',')) {
|
|
1244
|
+
const r = /^\s*([A-Za-z_$][\w$]*)\s+as\s+default\s*$/.exec(part);
|
|
1245
|
+
if (r)
|
|
1246
|
+
out.add(r[1]);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
return out;
|
|
1250
|
+
}
|
|
1251
|
+
/** `export default X;`, `export = X;`, `module.exports = X;`, `exports.x = X;` up to the reference. */
|
|
1252
|
+
const EXPORT_OPERAND_BEFORE = /(?:^|[;{}])\s*(?:export\s+default|export\s*=|module\s*\.\s*exports(?:\s*\.\s*[A-Za-z_$][\w$]*)?\s*=|exports\s*\.\s*[A-Za-z_$][\w$]*\s*=)\s*$/;
|
|
1253
|
+
/** …and the reference is the whole operand: a name, then `;` or the end of the line. */
|
|
1254
|
+
const EXPORT_OPERAND_AFTER = /^[A-Za-z_$][\w$]*\s*(?:;|$)/;
|
|
1255
|
+
/**
|
|
1256
|
+
* Whether a module-level reference is the whole operand of an export
|
|
1257
|
+
* statement (`export default CountsStrip;`): it exports the value and runs
|
|
1258
|
+
* nothing (an importer's own call is an edge to the declaration). Anything
|
|
1259
|
+
* else a module's top-level code references (`app.use(handler)`,
|
|
1260
|
+
* `[a, b].forEach(run)`, `export default memo(X)`) may run on import.
|
|
1261
|
+
*/
|
|
1262
|
+
function plainExport(site, lineAt) {
|
|
1263
|
+
if (site.col === undefined)
|
|
1264
|
+
return false;
|
|
1265
|
+
const at = lineAt(site.file, site.line);
|
|
1266
|
+
if (!at || at.start + site.col > at.end)
|
|
1267
|
+
return false;
|
|
1268
|
+
const line = at.text.slice(at.start, at.end);
|
|
1269
|
+
return EXPORT_OPERAND_BEFORE.test(line.slice(0, site.col)) && EXPORT_OPERAND_AFTER.test(line.slice(site.col));
|
|
1270
|
+
}
|
|
1271
|
+
/**
|
|
1272
|
+
* The tests, in `facts`, that reach `changed` within `maxHops` calls or
|
|
1273
|
+
* references: every declaration in a test file (`isTest`) the backward walk
|
|
1274
|
+
* reaches, except those inside the change. A test's `reaches` are all the
|
|
1275
|
+
* changed declarations it reaches within `maxHops`, not only the nearest;
|
|
1276
|
+
* reaching a function reaches the changed code nested in it (`carriersOf`,
|
|
1277
|
+
* at tier `inferred`).
|
|
1278
|
+
*
|
|
1279
|
+
* A changed declaration no reached test reaches is `notKnown`, not
|
|
1280
|
+
* unreached, when another way in may reach it within the bound: an
|
|
1281
|
+
* unresolved call (any reason, in any file) by the name of a declaration on
|
|
1282
|
+
* a path to it (for `.call` / `.apply` / `.bind`, the name they are called
|
|
1283
|
+
* on, read at the site by `callLikeReceiver`, else every such name the
|
|
1284
|
+
* site's file spells), a framework entry (anything but a test file or a
|
|
1285
|
+
* library export) on such a path, a partly parsed test file naming such a
|
|
1286
|
+
* declaration, or code that runs without a call on such a path (a field's
|
|
1287
|
+
* initializer, a class's own code, a getter or setter: `runsWithoutCall`;
|
|
1288
|
+
* a module's top-level code that calls into the path or references it
|
|
1289
|
+
* other than as a plain export: `plainExport`). Unresolved calls in test
|
|
1290
|
+
* files by such a name are counted in `unresolved_sites`.
|
|
1291
|
+
*/
|
|
1292
|
+
export function testsOf(facts, changed, qualifiedName, regions, isTest, maxHops, options = {}) {
|
|
1293
|
+
const declOf = new Map();
|
|
1294
|
+
for (const f of facts.files)
|
|
1295
|
+
for (const d of f.decls)
|
|
1296
|
+
declOf.set(d.id, { decl: d, file: f.file });
|
|
1297
|
+
const inside = new Set(changed);
|
|
1298
|
+
if (regions.length > 0) {
|
|
1299
|
+
for (const f of facts.files) {
|
|
1300
|
+
for (const d of f.decls)
|
|
1301
|
+
if (inRegion(regions, f.file, d.start_line, d.end_line))
|
|
1302
|
+
inside.add(d.id);
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
const carriers = carriersOf(facts, changed);
|
|
1306
|
+
const starts = new Set(carriers.keys());
|
|
1307
|
+
// A carrier that is not itself changed only may run the code nested in it.
|
|
1308
|
+
const startTier = new Map([...starts].filter((s) => !changed.has(s)).map((s) => [s, 'inferred']));
|
|
1309
|
+
const stepOut = stepOutOf(facts, isTest);
|
|
1310
|
+
const { dist, tier } = walkBackwards(facts, starts, maxHops, regions, startTier, stepOut);
|
|
1311
|
+
// Only edges into declarations a test can still reach within the bound matter.
|
|
1312
|
+
const edges = walkEdges(facts, starts, regions).filter((e) => (dist.get(e.to) ?? maxHops) < maxHops && dist.has(e.from));
|
|
1313
|
+
// The changed declarations each declaration reaches within maxHops (layer by layer);
|
|
1314
|
+
// what a nested declaration reaches, the functions it is nested in reach too.
|
|
1315
|
+
const stepOutReach = (r) => {
|
|
1316
|
+
for (const [id, cs] of [...r]) {
|
|
1317
|
+
for (let p = stepOut(id); p !== null && dist.has(p); p = stepOut(p)) {
|
|
1318
|
+
let into = r.get(p);
|
|
1319
|
+
if (!into) {
|
|
1320
|
+
into = new Set();
|
|
1321
|
+
r.set(p, into);
|
|
1322
|
+
}
|
|
1323
|
+
for (const c of cs)
|
|
1324
|
+
into.add(c);
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
};
|
|
1328
|
+
let reach = new Map([...carriers].map(([start, cs]) => [start, new Set(cs)]));
|
|
1329
|
+
stepOutReach(reach);
|
|
1330
|
+
for (let h = 1; h <= maxHops; h++) {
|
|
1331
|
+
const next = new Map(reach);
|
|
1332
|
+
let grew = false;
|
|
1333
|
+
for (const e of edges) {
|
|
1334
|
+
const from = reach.get(e.to);
|
|
1335
|
+
if (!from)
|
|
1336
|
+
continue;
|
|
1337
|
+
let into = next.get(e.from);
|
|
1338
|
+
if (into === undefined || into === reach.get(e.from)) {
|
|
1339
|
+
into = new Set(reach.get(e.from) ?? []);
|
|
1340
|
+
next.set(e.from, into);
|
|
1341
|
+
}
|
|
1342
|
+
for (const c of from) {
|
|
1343
|
+
if (!into.has(c)) {
|
|
1344
|
+
into.add(c);
|
|
1345
|
+
grew = true;
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
stepOutReach(next);
|
|
1350
|
+
reach = next;
|
|
1351
|
+
if (!grew)
|
|
1352
|
+
break;
|
|
1353
|
+
}
|
|
1354
|
+
const name = (id) => qualifiedName.get(id) ?? declOf.get(id)?.decl.qualified_name ?? id;
|
|
1355
|
+
const reached = [];
|
|
1356
|
+
const reachedChanged = new Set();
|
|
1357
|
+
for (const [id, hops] of dist) {
|
|
1358
|
+
if (hops === 0 || inside.has(id))
|
|
1359
|
+
continue;
|
|
1360
|
+
const at = declOf.get(id);
|
|
1361
|
+
if (!at || !isTest(at.file))
|
|
1362
|
+
continue;
|
|
1363
|
+
const reaches = reach.get(id) ?? new Set();
|
|
1364
|
+
for (const c of reaches)
|
|
1365
|
+
reachedChanged.add(c);
|
|
1366
|
+
let line = at.decl.start_line;
|
|
1367
|
+
let symbol = name(id);
|
|
1368
|
+
if (at.decl.kind === 'module') {
|
|
1369
|
+
// Top-level test code: the file, at its first call on a shortest path.
|
|
1370
|
+
symbol = at.file;
|
|
1371
|
+
const lines = edges.filter((e) => e.from === id && dist.get(e.to) === hops - 1).map((e) => e.site.line);
|
|
1372
|
+
if (lines.length > 0)
|
|
1373
|
+
line = Math.min(...lines);
|
|
1374
|
+
}
|
|
1375
|
+
reached.push({ file: at.file, symbol, line, reaches: uniqSorted([...reaches].map(name)), hops, tier: tier.get(id) });
|
|
1376
|
+
}
|
|
1377
|
+
// The declarations a test could still call within the bound, by name.
|
|
1378
|
+
const onPath = new Map();
|
|
1379
|
+
for (const [id, d] of dist) {
|
|
1380
|
+
if (d >= maxHops)
|
|
1381
|
+
continue;
|
|
1382
|
+
const at = declOf.get(id);
|
|
1383
|
+
if (!at || at.decl.kind === 'module')
|
|
1384
|
+
continue;
|
|
1385
|
+
const list = onPath.get(at.decl.name);
|
|
1386
|
+
if (list)
|
|
1387
|
+
list.push(id);
|
|
1388
|
+
else
|
|
1389
|
+
onPath.set(at.decl.name, [id]);
|
|
1390
|
+
}
|
|
1391
|
+
const notKnown = { unresolved: new Set(), entries: new Set(), partial: new Set(), uncalled: new Set() };
|
|
1392
|
+
const mark = (into, ids) => {
|
|
1393
|
+
for (const id of ids)
|
|
1394
|
+
for (const c of reach.get(id) ?? [])
|
|
1395
|
+
if (!reachedChanged.has(c))
|
|
1396
|
+
into.add(c);
|
|
1397
|
+
};
|
|
1398
|
+
// Where a site is in the text its graph was built from.
|
|
1399
|
+
const lineStarts = new Map();
|
|
1400
|
+
const lineAt = (file, line) => {
|
|
1401
|
+
const text = options.sourceText?.(file);
|
|
1402
|
+
if (text === undefined)
|
|
1403
|
+
return null;
|
|
1404
|
+
let starts = lineStarts.get(file);
|
|
1405
|
+
if (starts === undefined) {
|
|
1406
|
+
starts = [0];
|
|
1407
|
+
for (let i = text.indexOf('\n'); i >= 0; i = text.indexOf('\n', i + 1))
|
|
1408
|
+
starts.push(i + 1);
|
|
1409
|
+
lineStarts.set(file, starts);
|
|
1410
|
+
}
|
|
1411
|
+
const start = starts[line - 1];
|
|
1412
|
+
if (start === undefined)
|
|
1413
|
+
return null;
|
|
1414
|
+
const next = starts[line];
|
|
1415
|
+
return { text, start, end: next === undefined ? text.length : next - 1 };
|
|
1416
|
+
};
|
|
1417
|
+
// Calls the graph could not resolve (an import from outside the tree, an unknown receiver ...) by a name on a path.
|
|
1418
|
+
// For `.call` / `.apply` / `.bind`, the name is the one they are called on, read from the source at the site;
|
|
1419
|
+
// a file where that cannot be read is treated like a partly parsed one (every name on a path it spells).
|
|
1420
|
+
// Two call-like sites at one start are a chain with a call in it (`a.b.call(x).c.call(y)`): neither is read.
|
|
1421
|
+
const startKey = (s) => `${s.file}\0${s.line}\0${s.col}`;
|
|
1422
|
+
const callLikeStarts = new Map();
|
|
1423
|
+
for (const u of facts.unresolved) {
|
|
1424
|
+
if (CALL_LIKE.has(u.methodName) && u.site)
|
|
1425
|
+
callLikeStarts.set(startKey(u.site), (callLikeStarts.get(startKey(u.site)) ?? 0) + 1);
|
|
1426
|
+
}
|
|
1427
|
+
const unreadable = new Set();
|
|
1428
|
+
let unresolved_sites = 0;
|
|
1429
|
+
for (const u of facts.unresolved) {
|
|
1430
|
+
if (inside.has(u.from))
|
|
1431
|
+
continue;
|
|
1432
|
+
const names = [u.methodName];
|
|
1433
|
+
if (CALL_LIKE.has(u.methodName)) {
|
|
1434
|
+
let receiver = null;
|
|
1435
|
+
if (u.site && u.site.col !== undefined && callLikeStarts.get(startKey(u.site)) === 1) {
|
|
1436
|
+
const at = lineAt(u.site.file, u.site.line);
|
|
1437
|
+
if (at && at.start + u.site.col <= at.end)
|
|
1438
|
+
receiver = callLikeReceiver(at.text, at.start + u.site.col);
|
|
1439
|
+
}
|
|
1440
|
+
if (receiver !== null)
|
|
1441
|
+
names.push(receiver);
|
|
1442
|
+
else
|
|
1443
|
+
unreadable.add(u.site?.file ?? declOf.get(u.from)?.file ?? '');
|
|
1444
|
+
}
|
|
1445
|
+
const ids = names.flatMap((n) => onPath.get(n) ?? []);
|
|
1446
|
+
if (ids.length === 0)
|
|
1447
|
+
continue;
|
|
1448
|
+
const at = declOf.get(u.from);
|
|
1449
|
+
if (at && isTest(at.file))
|
|
1450
|
+
unresolved_sites++;
|
|
1451
|
+
mark(notKnown.unresolved, ids);
|
|
1452
|
+
}
|
|
1453
|
+
// A framework or the runtime runs these; a test may reach them without a call (over HTTP, through a container).
|
|
1454
|
+
for (const e of facts.entries ?? []) {
|
|
1455
|
+
if (NOT_A_WAY_IN.has(e.kind) || !dist.has(e.id))
|
|
1456
|
+
continue;
|
|
1457
|
+
mark(notKnown.entries, [e.id]);
|
|
1458
|
+
}
|
|
1459
|
+
// Code that runs without a call the graph records, on a path within the bound: an import, `new`, a property
|
|
1460
|
+
// access or the runtime runs it, and none of those is an edge. Without a test file in the language, nothing
|
|
1461
|
+
// runs it from a test.
|
|
1462
|
+
if (!options.noTestFiles) {
|
|
1463
|
+
// Plain decorators over the graph's TypeScript files: the names they are declared under, and the modules
|
|
1464
|
+
// whose default export one of them is (`anyDefault`: every module's, after a cut search that may reach one).
|
|
1465
|
+
let decorators;
|
|
1466
|
+
const plainDecorators = () => {
|
|
1467
|
+
if (decorators)
|
|
1468
|
+
return decorators;
|
|
1469
|
+
decorators = { names: new Set(), defaultsOf: new Set(), anyDefault: false };
|
|
1470
|
+
const graphFiles = new Set(facts.files.map((f) => f.file));
|
|
1471
|
+
const maxStates = options.followMaxStates ?? Math.max(BLAST_FOLLOW_BUDGET.minStates, BLAST_FOLLOW_BUDGET.perGraphFile * graphFiles.size);
|
|
1472
|
+
const exportsMemo = new Map();
|
|
1473
|
+
const exportsOf = (file) => {
|
|
1474
|
+
let e = exportsMemo.get(file);
|
|
1475
|
+
if (!e) {
|
|
1476
|
+
e = moduleExports(options.sourceText?.(file) ?? '');
|
|
1477
|
+
exportsMemo.set(file, e);
|
|
1478
|
+
}
|
|
1479
|
+
return e;
|
|
1480
|
+
};
|
|
1481
|
+
for (const f of facts.files) {
|
|
1482
|
+
if (familyOfFile(f.file) !== 'ts')
|
|
1483
|
+
continue;
|
|
1484
|
+
const text = options.sourceText?.(f.file);
|
|
1485
|
+
if (text === undefined)
|
|
1486
|
+
continue;
|
|
1487
|
+
const written = options.decoratorNames?.(f.file) ?? plainDecoratorNames(text);
|
|
1488
|
+
if (written.size === 0)
|
|
1489
|
+
continue;
|
|
1490
|
+
const { defaults, named } = exportsOf(f.file).bindings;
|
|
1491
|
+
for (const n of written) {
|
|
1492
|
+
decorators.names.add(n);
|
|
1493
|
+
// An imported name: the declarations it may name, through renames and re-exports.
|
|
1494
|
+
const imp = named.get(n);
|
|
1495
|
+
const spec = defaults.get(n);
|
|
1496
|
+
if (!imp && spec === undefined)
|
|
1497
|
+
continue;
|
|
1498
|
+
const start = imp ? imp.imported : 'default';
|
|
1499
|
+
const found = followImport(f.file, imp ? imp.spec : spec, start, graphFiles, exportsOf, maxStates);
|
|
1500
|
+
if (found.cut) {
|
|
1501
|
+
// The search stopped at its bound: this import's decorator may be any declaration a search can reach.
|
|
1502
|
+
for (const n of followableNames(start, graphFiles, exportsOf)) {
|
|
1503
|
+
if (n === 'default')
|
|
1504
|
+
decorators.anyDefault = true;
|
|
1505
|
+
else
|
|
1506
|
+
decorators.names.add(n);
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
for (const target of found.targets) {
|
|
1510
|
+
if (target.name === 'default')
|
|
1511
|
+
decorators.defaultsOf.add(target.file);
|
|
1512
|
+
else
|
|
1513
|
+
decorators.names.add(target.name);
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
return decorators;
|
|
1518
|
+
};
|
|
1519
|
+
const defaultNames = new Map();
|
|
1520
|
+
const frameworkFiles = new Map();
|
|
1521
|
+
const headers = new Map();
|
|
1522
|
+
const headerOf = (id) => {
|
|
1523
|
+
if (!headers.has(id)) {
|
|
1524
|
+
const at = declOf.get(id);
|
|
1525
|
+
headers.set(id, at && (at.decl.kind === 'function' || at.decl.kind === 'method') ? definitionHeader(at.decl, at.file, lineAt) : null);
|
|
1526
|
+
}
|
|
1527
|
+
return headers.get(id);
|
|
1528
|
+
};
|
|
1529
|
+
const offsetIn = (file, line, col) => {
|
|
1530
|
+
if (col === undefined)
|
|
1531
|
+
return null;
|
|
1532
|
+
const at = lineAt(file, line);
|
|
1533
|
+
return at ? at.start + col : null;
|
|
1534
|
+
};
|
|
1535
|
+
const ctx = {
|
|
1536
|
+
holdsCalls: new Set([...facts.edges.map((e) => e.from), ...facts.unresolved.map((u) => u.from)]),
|
|
1537
|
+
entered: enteredIds(facts),
|
|
1538
|
+
parentKind: (d) => (d.parent === null ? undefined : declOf.get(d.parent)?.decl.kind),
|
|
1539
|
+
plainDecorator: (d, file) => {
|
|
1540
|
+
const p = plainDecorators();
|
|
1541
|
+
if (p.names.has(d.name))
|
|
1542
|
+
return true;
|
|
1543
|
+
if (!p.anyDefault && !p.defaultsOf.has(file))
|
|
1544
|
+
return false;
|
|
1545
|
+
let names = defaultNames.get(file);
|
|
1546
|
+
if (!names) {
|
|
1547
|
+
names = defaultExportNames(options.sourceText?.(file) ?? '');
|
|
1548
|
+
defaultNames.set(file, names);
|
|
1549
|
+
}
|
|
1550
|
+
return names.has(d.name);
|
|
1551
|
+
},
|
|
1552
|
+
frameworkClass: (d, file) => {
|
|
1553
|
+
const parent = d.parent === null ? undefined : declOf.get(d.parent)?.decl;
|
|
1554
|
+
if (!parent || parent.kind !== 'type')
|
|
1555
|
+
return false;
|
|
1556
|
+
let imports = frameworkFiles.get(file);
|
|
1557
|
+
if (imports === undefined) {
|
|
1558
|
+
imports = makesComponents(options.sourceText?.(file) ?? '');
|
|
1559
|
+
frameworkFiles.set(file, imports);
|
|
1560
|
+
}
|
|
1561
|
+
return imports || FRAMEWORK_CLASS.test(classHeaderText(parent, file, lineAt));
|
|
1562
|
+
},
|
|
1563
|
+
inParentHeader: (d, file) => {
|
|
1564
|
+
const h = d.parent === null ? null : headerOf(d.parent);
|
|
1565
|
+
const offset = offsetIn(file, d.start_line, d.start_column);
|
|
1566
|
+
return h !== null && offset !== null && inDefinitionHeader(h, offset);
|
|
1567
|
+
},
|
|
1568
|
+
lineAt,
|
|
1569
|
+
};
|
|
1570
|
+
for (const [id, d] of dist) {
|
|
1571
|
+
if (d >= maxHops)
|
|
1572
|
+
continue;
|
|
1573
|
+
const at = declOf.get(id);
|
|
1574
|
+
if (!at || isTest(at.file) || at.decl.kind === 'module')
|
|
1575
|
+
continue;
|
|
1576
|
+
if (runsWithoutCall(at.decl, at.file, ctx))
|
|
1577
|
+
mark(notKnown.uncalled, [id]);
|
|
1578
|
+
}
|
|
1579
|
+
// A module's top-level code runs on import: what it calls, and what it references other than as a plain export.
|
|
1580
|
+
// So does a function's or method's definition header (decorators, decorator calls in its parameters, and for
|
|
1581
|
+
// Python its defaults), when the module or the class defines it.
|
|
1582
|
+
for (const e of edges) {
|
|
1583
|
+
const at = declOf.get(e.from);
|
|
1584
|
+
if (!at || isTest(at.file) || dist.get(e.to) + 1 >= maxHops)
|
|
1585
|
+
continue;
|
|
1586
|
+
if (at.decl.kind === 'module') {
|
|
1587
|
+
if (e.reference && plainExport(e.site, lineAt))
|
|
1588
|
+
continue;
|
|
1589
|
+
mark(notKnown.uncalled, [e.to]);
|
|
1590
|
+
}
|
|
1591
|
+
else if (e.site.file === at.file) {
|
|
1592
|
+
const h = headerOf(e.from);
|
|
1593
|
+
const offset = h === null ? null : offsetIn(e.site.file, e.site.line, e.site.col);
|
|
1594
|
+
if (h !== null && offset !== null && inDefinitionHeader(h, offset))
|
|
1595
|
+
mark(notKnown.uncalled, [e.to]);
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
// A test file that did not parse completely may have lost the call.
|
|
1600
|
+
const spellsOnPath = (code, into) => {
|
|
1601
|
+
const re = new RegExp(`(?<![\\w$])(?:${[...onPath.keys()].sort().map(escapeRegExp).join('|')})(?![\\w$])`, 'g');
|
|
1602
|
+
for (const m of code.matchAll(re))
|
|
1603
|
+
mark(into, onPath.get(m[0]) ?? []);
|
|
1604
|
+
};
|
|
1605
|
+
if (onPath.size > 0) {
|
|
1606
|
+
for (const t of options.partialTestTexts ?? [])
|
|
1607
|
+
spellsOnPath(t.code, notKnown.partial);
|
|
1608
|
+
// A `.call` / `.apply` / `.bind` whose receiver cannot be read may run any declaration its file names
|
|
1609
|
+
// (any on a path at all, when its text cannot be had).
|
|
1610
|
+
for (const file of [...unreadable].sort()) {
|
|
1611
|
+
const text = file === '' ? undefined : options.sourceText?.(file);
|
|
1612
|
+
if (text !== undefined)
|
|
1613
|
+
spellsOnPath(text, notKnown.unresolved);
|
|
1614
|
+
else
|
|
1615
|
+
mark(notKnown.unresolved, [...onPath.values()].flat());
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
return { reached: sortTests(reached), reachedChanged, notKnown, unresolved_sites };
|
|
1619
|
+
}
|
|
1620
|
+
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
1621
|
+
export function sortTests(tests) {
|
|
1622
|
+
return tests.sort((a, b) => byString(a.file, b.file) || a.line - b.line || byString(a.symbol, b.symbol));
|
|
1623
|
+
}
|
|
1624
|
+
/**
|
|
1625
|
+
* The key a batch joins tests on: file and symbol, plus the line for a
|
|
1626
|
+
* function (two unnamed test functions in one file share a display name).
|
|
1627
|
+
* Top-level code (`symbol` is the file) is one test per file.
|
|
1628
|
+
*/
|
|
1629
|
+
function testKey(t) {
|
|
1630
|
+
return t.symbol === t.file ? `${t.file}\0${t.symbol}` : `${t.file}\0${t.symbol}\0${t.line}`;
|
|
1631
|
+
}
|
|
1632
|
+
/**
|
|
1633
|
+
* The batch's tests: the items' joined by file and symbol (each test once,
|
|
1634
|
+
* at its fewest hops, its strongest tier at those hops, the union of what
|
|
1635
|
+
* it reaches). A test that is one of the batch's changed declarations, in a
|
|
1636
|
+
* touched file, is part of the batch's change and drops out. Not known
|
|
1637
|
+
* when any item's is not, or the items' bounds differ; `unreached` (the
|
|
1638
|
+
* items', less what a joined test reaches) only when known.
|
|
1639
|
+
*/
|
|
1640
|
+
export function joinTests(parts, inBatchChange, unresolvedFromFacts) {
|
|
1641
|
+
const maxHops = parts.length === 0 ? BLAST_TEST_HOPS.default : Math.max(...parts.map((p) => p.max_hops));
|
|
1642
|
+
const byKey = new Map();
|
|
1643
|
+
for (const p of parts) {
|
|
1644
|
+
for (const t of p.reached) {
|
|
1645
|
+
const k = testKey(t);
|
|
1646
|
+
const had = byKey.get(k);
|
|
1647
|
+
if (!had) {
|
|
1648
|
+
byKey.set(k, { ...t, reaches: [...t.reaches] });
|
|
1649
|
+
continue;
|
|
1650
|
+
}
|
|
1651
|
+
const tier = t.hops < had.hops ? t.tier : t.hops > had.hops ? had.tier : stronger(had.tier, t.tier);
|
|
1652
|
+
byKey.set(k, {
|
|
1653
|
+
...had,
|
|
1654
|
+
line: Math.min(had.line, t.line),
|
|
1655
|
+
hops: Math.min(had.hops, t.hops),
|
|
1656
|
+
tier,
|
|
1657
|
+
reaches: uniqSorted([...had.reaches, ...t.reaches]),
|
|
1658
|
+
});
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
const reached = sortTests([...byKey.values()].filter((t) => !inBatchChange(t)));
|
|
1662
|
+
// Mixed bounds cannot back "no test reaches it within max_hops".
|
|
1663
|
+
const sameBounds = parts.length > 0 && parts.every((p) => p.max_hops === maxHops);
|
|
1664
|
+
const known = sameBounds && parts.every((p) => p.status === 'known');
|
|
1665
|
+
const reachedNames = new Set(reached.flatMap((t) => t.reaches));
|
|
1666
|
+
return {
|
|
1667
|
+
reached,
|
|
1668
|
+
// "Unreached" is said only when the batch's tests are known.
|
|
1669
|
+
unreached: known ? uniqSorted(parts.flatMap((p) => p.unreached)).filter((d) => !reachedNames.has(d)) : [],
|
|
1670
|
+
unresolved_sites: unresolvedFromFacts ?? parts.reduce((n, p) => n + p.unresolved_sites, 0),
|
|
1671
|
+
status: known ? 'known' : 'unknown',
|
|
1672
|
+
max_hops: maxHops,
|
|
1673
|
+
rule: parts[0]?.rule ?? BLAST_TEST_RULE,
|
|
1674
|
+
};
|
|
1675
|
+
}
|
|
1676
|
+
// ---------------------------------------------------------------------------
|
|
157
1677
|
// Assembling and joining radii
|
|
158
1678
|
// ---------------------------------------------------------------------------
|
|
159
1679
|
export function emptyBasis() {
|
|
@@ -181,9 +1701,10 @@ export function groupByLevel(files, levelOf) {
|
|
|
181
1701
|
/**
|
|
182
1702
|
* Build a radius from what an item touches and what reaches into it;
|
|
183
1703
|
* computes reach, level, label and the learned-tree levels (`levelOf`, the
|
|
184
|
-
* repository level for every file when not given).
|
|
1704
|
+
* repository level for every file when not given). `tests` is the test walk's
|
|
1705
|
+
* answer; without one the tests are not known.
|
|
185
1706
|
*/
|
|
186
|
-
export function assembleRadius(itemId, touchedFiles, callSites, importSites, basis, known = true, levelOf = repositoryLevelOnly) {
|
|
1707
|
+
export function assembleRadius(itemId, touchedFiles, callSites, importSites, basis, known = true, levelOf = repositoryLevelOnly, tests = unknownTests()) {
|
|
187
1708
|
const files = uniqSorted(touchedFiles);
|
|
188
1709
|
const reachFiles = new Set(files);
|
|
189
1710
|
for (const s of callSites)
|
|
@@ -205,6 +1726,11 @@ export function assembleRadius(itemId, touchedFiles, callSites, importSites, bas
|
|
|
205
1726
|
touched: groupByLevel(files, levelOf),
|
|
206
1727
|
reached: groupByLevel([...reachFiles].filter((f) => !touchedSet.has(f)), levelOf),
|
|
207
1728
|
},
|
|
1729
|
+
tests: {
|
|
1730
|
+
...tests,
|
|
1731
|
+
reached: sortTests(tests.reached.map((t) => ({ ...t, reaches: uniqSorted(t.reaches) }))),
|
|
1732
|
+
unreached: uniqSorted(tests.unreached),
|
|
1733
|
+
},
|
|
208
1734
|
basis: {
|
|
209
1735
|
graphs: uniqSorted(basis.graphs),
|
|
210
1736
|
declarations: uniqSorted(basis.declarations),
|
|
@@ -234,6 +1760,10 @@ export function assembleRadius(itemId, touchedFiles, callSites, importSites, bas
|
|
|
234
1760
|
* call-site and import-site files outside them, each in the level an item
|
|
235
1761
|
* placed it in (or by `levelOf`, when given). A file one item reaches and
|
|
236
1762
|
* another touches is touched in the batch.
|
|
1763
|
+
*
|
|
1764
|
+
* `tests` are joined by file and symbol (`joinTests`); a test that is one of
|
|
1765
|
+
* the batch's changed declarations drops out. Their unresolved sites come
|
|
1766
|
+
* from `fromFacts.tests_unresolved_sites` when given, else are summed.
|
|
237
1767
|
*/
|
|
238
1768
|
export function unionRadius(batchId, radii, fromFacts, levelOf) {
|
|
239
1769
|
const callSites = new Map();
|
|
@@ -267,7 +1797,12 @@ export function unionRadius(batchId, radii, fromFacts, levelOf) {
|
|
|
267
1797
|
outside = [...callSites.values()].filter((s) => !(declared.has(s.caller) && touchedSet.has(s.file)));
|
|
268
1798
|
}
|
|
269
1799
|
const known = radii.every((r) => r.level !== 'unknown');
|
|
270
|
-
|
|
1800
|
+
const touchedFiles = new Set(touched);
|
|
1801
|
+
const declaredAll = new Set(basis.declarations);
|
|
1802
|
+
// A radius from before tests were answered has none: the batch's are then not known.
|
|
1803
|
+
const parts = radii.map((r) => r.tests ?? unknownTests());
|
|
1804
|
+
const tests = joinTests(parts, (t) => declaredAll.has(t.symbol) && touchedFiles.has(t.file), fromFacts?.tests_unresolved_sites);
|
|
1805
|
+
return assembleRadius(batchId, touched, outside, [...importSites.values()], basis, known, levelOf ?? levelsOfRadii(radii), tests);
|
|
271
1806
|
}
|
|
272
1807
|
/**
|
|
273
1808
|
* The lookup the items' own answers make: each file in the level an item
|
|
@@ -308,10 +1843,10 @@ export function displayName(qualifiedName) {
|
|
|
308
1843
|
return `${named} (anonymous function)`;
|
|
309
1844
|
}
|
|
310
1845
|
/**
|
|
311
|
-
* The radius as returned: call sites name their
|
|
1846
|
+
* The radius as returned: call sites and tests name their declarations with
|
|
312
1847
|
* `displayName`, and unnamed changed declarations are counted in a note
|
|
313
|
-
* instead of listed by id. Applied last, after any
|
|
314
|
-
* the engine's own names.
|
|
1848
|
+
* instead of listed by id in `basis.declarations`. Applied last, after any
|
|
1849
|
+
* union, which compares the engine's own names.
|
|
315
1850
|
*/
|
|
316
1851
|
export function presentRadius(r) {
|
|
317
1852
|
const anonymous = r.basis.declarations.filter((d) => d.includes('<anonymous>@'));
|
|
@@ -319,9 +1854,15 @@ export function presentRadius(r) {
|
|
|
319
1854
|
if (anonymous.length > 0) {
|
|
320
1855
|
notes.push(`${anonymous.length} unnamed ${anonymous.length === 1 ? 'function is' : 'functions are'} changed too (not listed)`);
|
|
321
1856
|
}
|
|
1857
|
+
const tests = r.tests ?? unknownTests();
|
|
322
1858
|
return {
|
|
323
1859
|
...r,
|
|
324
1860
|
call_sites: sortCallSites(r.call_sites.map((s) => ({ ...s, symbol: displayName(s.symbol), caller: displayName(s.caller) }))),
|
|
1861
|
+
tests: {
|
|
1862
|
+
...tests,
|
|
1863
|
+
reached: sortTests(tests.reached.map((t) => ({ ...t, symbol: displayName(t.symbol), reaches: uniqSorted(t.reaches.map(displayName)) }))),
|
|
1864
|
+
unreached: uniqSorted(tests.unreached.map(displayName)),
|
|
1865
|
+
},
|
|
325
1866
|
basis: {
|
|
326
1867
|
...r.basis,
|
|
327
1868
|
declarations: r.basis.declarations.filter((d) => !d.includes('<anonymous>@')),
|