@cplieger/deadset-ts 8.0.0-dev.17 → 8.0.0-dev.18

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.
Files changed (60) hide show
  1. package/dist/src/analysis.js +26 -71
  2. package/dist/src/augmentations.js +1 -1
  3. package/dist/src/calls.js +267 -48
  4. package/dist/src/conformance-record.js +1 -1
  5. package/dist/src/contract/contract.generated.js +2 -2
  6. package/dist/src/exempt.js +0 -26
  7. package/dist/src/exposure.js +400 -0
  8. package/dist/src/findings/completion.js +4 -17
  9. package/dist/src/findings/emitters.js +22 -33
  10. package/dist/src/findings/intra-function.js +3 -3
  11. package/dist/src/findings/reads-and-writes.js +71 -15
  12. package/dist/src/findings/unused-declarations.js +2 -22
  13. package/dist/src/findings/visibility-narrowing.js +14 -20
  14. package/dist/src/inventory.js +18 -0
  15. package/dist/src/{components.js → liveness/components.js} +1 -1
  16. package/dist/src/{graph.js → liveness/graph.js} +38 -21
  17. package/dist/src/liveness/matrix.js +99 -0
  18. package/dist/src/liveness/sweep.js +558 -0
  19. package/dist/src/query.js +46 -0
  20. package/dist/src/references/sink.js +87 -1
  21. package/dist/src/references.js +1 -1
  22. package/dist/src/roots/published-reach.js +4 -4
  23. package/dist/src/verbs/explain.js +73 -152
  24. package/dist/src/verbs/print-retained.js +1 -1
  25. package/jsr.json +1 -1
  26. package/package.json +1 -1
  27. package/src/analysis.ts +41 -107
  28. package/src/augmentations.ts +1 -1
  29. package/src/calls.ts +326 -52
  30. package/src/conformance-record.ts +1 -1
  31. package/src/contract/contract.generated.ts +2 -2
  32. package/src/exempt.ts +31 -46
  33. package/src/exposure.ts +492 -0
  34. package/src/finding.ts +1 -1
  35. package/src/findings/boundary.ts +7 -0
  36. package/src/findings/completion.ts +5 -19
  37. package/src/findings/emitters.ts +23 -41
  38. package/src/findings/interfaces.ts +3 -3
  39. package/src/findings/intra-function.ts +3 -3
  40. package/src/findings/reads-and-writes.ts +99 -26
  41. package/src/findings/unused-declarations.ts +4 -28
  42. package/src/findings/visibility-narrowing.ts +25 -26
  43. package/src/interface-satisfaction.ts +1 -1
  44. package/src/inventory.ts +19 -0
  45. package/src/{components.ts → liveness/components.ts} +3 -3
  46. package/src/{graph.ts → liveness/graph.ts} +74 -26
  47. package/src/liveness/matrix.ts +162 -0
  48. package/src/liveness/sweep.ts +855 -0
  49. package/src/query.ts +81 -0
  50. package/src/references/sink.ts +101 -0
  51. package/src/references.ts +8 -1
  52. package/src/roots/published-reach.ts +9 -4
  53. package/src/stores.ts +2 -1
  54. package/src/tests/file-class.ts +19 -2
  55. package/src/verbs/explain.ts +81 -199
  56. package/src/verbs/print-retained.ts +1 -1
  57. package/dist/src/matrix.js +0 -275
  58. package/dist/src/sweep.js +0 -234
  59. package/src/matrix.ts +0 -466
  60. package/src/sweep.ts +0 -384
package/dist/src/sweep.js DELETED
@@ -1,234 +0,0 @@
1
- /**
2
- * Which declarations of one graph are dead, and under which liveness relation.
3
- * Reference counting holds a declaration live when any declaration references it,
4
- * whatever that one's own liveness, or when it is a root of a kind that names a caller;
5
- * reachability holds it live when a path of references reaches it from a root. So a
6
- * declaration only unreachable ones reference is live under the first, dead under the second.
7
- */
8
- import { namesACaller, OUTSIDE } from "./graph.js";
9
- import { edgeWithheldBy } from "./tests/file-class.js";
10
- /** The references to one declaration the mode counts: under `production` none test code made but those it classes as production. */
11
- function countedRefs(made, mode) {
12
- if (made === undefined) {
13
- return 0;
14
- }
15
- if (!mode.production) {
16
- return made.production + made.test;
17
- }
18
- return made.production + (mode.consumerTestsProduction === true ? made.consumerTest : 0);
19
- }
20
- /** The references to one declaration, split as the mode classes them, whatever it counts. */
21
- export function splitRefs(made, mode) {
22
- const moved = mode.consumerTestsProduction === true ? (made?.consumerTest ?? 0) : 0;
23
- return { production: (made?.production ?? 0) + moved, test: (made?.test ?? 0) - moved };
24
- }
25
- /**
26
- * Answers which declarations of one graph are dead under the input's mode.
27
- *
28
- * The order is the order the answers depend on: the callers and the marks are live
29
- * before either relation runs, the candidate set is every judged declaration at least
30
- * one relation does not hold live and no exemption holds back, and the tests of dead
31
- * code join it.
32
- */
33
- export function sweep(graph, input) {
34
- const marked = flagged(graph, input.marked);
35
- const exempt = flagged(graph, [
36
- ...(input.exempt ?? []).map((record) => record.id),
37
- ...(input.unanswered ?? []),
38
- ]);
39
- const held = marked.map((mark, at) => mark || exempt[at] === true);
40
- // Every root, every mark and every exemption seeds reachability. A root of a kind that
41
- // names a caller, and a mark, are live under reference counting as well; a root that
42
- // only supposes a caller is not, and neither is an exemption.
43
- const called = graph.symbols.map(() => false);
44
- for (const root of graph.rooted) {
45
- if (namesACaller(root.kind)) {
46
- called[root.at] = true;
47
- }
48
- }
49
- const counted = (at) => countedRefs(graph.made[at], input.mode);
50
- const reached = reachable(graph, held, input.mode);
51
- const liveUnder = graph.symbols.map((_symbol, at) => {
52
- const relations = [];
53
- if (marked[at] === true || called[at] === true || counted(at) > 0) {
54
- relations.push("reference-counting");
55
- }
56
- if (reached[at] === true) {
57
- relations.push("reachability");
58
- }
59
- return relations;
60
- });
61
- const dead = graph.symbols.map((_symbol, at) => graph.subject[at] === true && exempt[at] !== true && (liveUnder[at]?.length ?? 0) < 2);
62
- const testOfDeadCode = admitTestsOfDeadCode(graph, dead, held);
63
- const candidates = [];
64
- const live = new Map();
65
- graph.symbols.forEach((symbol, at) => {
66
- const relations = liveUnder[at] ?? [];
67
- if (relations.length > 0) {
68
- live.set(symbol.id, relations);
69
- }
70
- if (dead[at] !== true) {
71
- return;
72
- }
73
- const split = splitRefs(graph.made[at], input.mode);
74
- candidates.push({
75
- id: symbol.id,
76
- productionRefs: split.production,
77
- testRefs: split.test,
78
- relation: counted(at) === 0 ? "reference-counting" : "reachability",
79
- testOfDeadCode: testOfDeadCode[at] === true,
80
- });
81
- });
82
- return { liveUnder: live, candidates };
83
- }
84
- /**
85
- * The directory a test runner reads a manual mock from, whose exports it puts in place of
86
- * the module's: https://jestjs.io/docs/manual-mocks
87
- */
88
- const MANUAL_MOCKS = "__mocks__";
89
- /** Whether a test runner calls or reads one export of a test file: a function, or any export of a manual mock. */
90
- export function runnerCalls(symbol) {
91
- return symbol.kind === "function" || symbol.position.path.split("/").includes(MANUAL_MOCKS);
92
- }
93
- /**
94
- * Per declaration of the graph, whether the run that counts test references reaches it.
95
- * That run's roots are the graph's own and, of each test file, its top level and every
96
- * function it exports, which a test runner may call, and every export of a manual mock,
97
- * which the runner reads; any other export of a test file, and test-support code, which
98
- * runs where a test imports it, are judged as any file's are. `held` seeds it as a mark
99
- * seeds a sweep; with `namespaces` false a file read reaches none of the file's exports.
100
- */
101
- export function reachedWithTheTests(graph, held, namespaces = true) {
102
- const tests = graph.symbols.flatMap((symbol, at) => {
103
- const exported = symbol.exported && graph.symbols[graph.parent[at] ?? OUTSIDE]?.kind === "file";
104
- const called = exported && runnerCalls(symbol);
105
- return graph.test[at] === true &&
106
- graph.support[at] !== true &&
107
- (symbol.kind === "file" || called)
108
- ? [{ at, kind: "test-runner" }]
109
- : [];
110
- });
111
- return reachable({ ...graph, rooted: [...graph.rooted, ...tests] }, flagged(graph, held), { production: false }, namespaces);
112
- }
113
- /**
114
- * The references a loaded consumer or an unheld file makes that the mode counts. A
115
- * production mode counts no test reference, but a loaded consumer's where the mode classes
116
- * a consumer's tests as production.
117
- */
118
- function callsOf(graph, mode) {
119
- return graph.consumed.filter((edge) => !edgeWithheldBy(mode, edge));
120
- }
121
- /** Per declaration of the graph, whether one of the identifiers names it. */
122
- function flagged(graph, ids) {
123
- const flags = graph.symbols.map(() => false);
124
- for (const id of ids) {
125
- const at = graph.at(id);
126
- if (at !== OUTSIDE) {
127
- flags[at] = true;
128
- }
129
- }
130
- return flags;
131
- }
132
- /**
133
- * Per declaration, whether a seed reaches it. The two seeds reach through different
134
- * reference sets: a held declaration, marked or exempt, is live by a mechanism the
135
- * analysis cannot see, so no mode withholds a reference it makes, a test declaration's
136
- * included, while a root reaches through the references the mode counts. The held seed
137
- * runs first, so what it reaches is expanded under the wider rule.
138
- */
139
- function reachable(graph, held, mode, namespaces = true) {
140
- const reached = graph.symbols.map(() => false);
141
- const expanded = graph.symbols.map(() => false);
142
- const queue = [];
143
- // Reaching a file reaches its top level: the references written outside every
144
- // declaration it holds. A reference that reads a file reads the module's namespace,
145
- // which reaches what the module exports as well. An evaluation runs the top level
146
- // and reads no export, and a root does not expand either: a file a runtime runs
147
- // without reading its exports is a root by itself.
148
- const enter = (at, expands) => {
149
- if (!reached[at]) {
150
- reached[at] = true;
151
- queue.push(at);
152
- }
153
- if (!expands || expanded[at] === true) {
154
- return;
155
- }
156
- expanded[at] = true;
157
- for (const exported of graph.exportsOf[at] ?? []) {
158
- enter(exported, false);
159
- }
160
- };
161
- const walk = (holding) => {
162
- for (let at = queue.pop(); at !== undefined; at = queue.pop()) {
163
- for (const edge of graph.out[at] ?? []) {
164
- if (!holding && edgeWithheldBy(mode, edge)) {
165
- continue;
166
- }
167
- enter(edge.to, namespaces && !edge.evaluation);
168
- }
169
- }
170
- };
171
- held.forEach((hold, at) => {
172
- if (hold) {
173
- enter(at, false);
174
- }
175
- });
176
- walk(true);
177
- for (const root of graph.rooted) {
178
- enter(root.at, false);
179
- }
180
- // A consumer's reference reaches what it names as one of the target's own does.
181
- for (const edge of callsOf(graph, mode)) {
182
- enter(edge.to, namespaces && !edge.evaluation);
183
- }
184
- walk(false);
185
- return reached;
186
- }
187
- /**
188
- * Admits every test declaration whose set of referenced production declarations is
189
- * non-empty and wholly dead, and returns which it admitted. An ambient declaration describes
190
- * code the target does not implement, so it is no production declaration here. The set is
191
- * read from every reference the test makes, which a production sweep does not count. A
192
- * test-support declaration a test referencing a live target also references is a live
193
- * target of every test referencing it. A marked or exempt test is never admitted.
194
- */
195
- function admitTestsOfDeadCode(graph, dead, held) {
196
- const testCode = (at) => graph.test[at] === true || graph.support[at] === true;
197
- const judged = graph.symbols.map((_symbol, at) => {
198
- let targets = 0;
199
- let live = 0;
200
- if (testCode(at) && graph.subject[at] === true && held[at] !== true) {
201
- for (const edge of graph.out[at] ?? []) {
202
- if (testCode(edge.to) ||
203
- graph.subject[edge.to] !== true ||
204
- graph.ambient[edge.to] === true) {
205
- continue;
206
- }
207
- targets += 1;
208
- if (dead[edge.to] !== true) {
209
- live += 1;
210
- }
211
- }
212
- }
213
- return { targets, live };
214
- });
215
- const shared = new Set();
216
- judged.forEach(({ live }, at) => {
217
- if (live > 0) {
218
- for (const edge of graph.out[at] ?? []) {
219
- if (graph.support[edge.to] === true) {
220
- shared.add(edge.to);
221
- }
222
- }
223
- }
224
- });
225
- const admitted = graph.symbols.map(() => false);
226
- judged.forEach(({ targets, live }, at) => {
227
- const sharing = (graph.out[at] ?? []).some((edge) => shared.has(edge.to) && edge.to !== at);
228
- if (targets > 0 && live === 0 && !sharing) {
229
- dead[at] = true;
230
- admitted[at] = true;
231
- }
232
- });
233
- return admitted;
234
- }
package/src/matrix.ts DELETED
@@ -1,466 +0,0 @@
1
- /**
2
- * One run's projects as one matrix: every declaration any project holds, keyed by its
3
- * position and carrying the configurations that hold it, swept once per configuration
4
- * and intersected, with the dead components computed once over every configuration.
5
- */
6
-
7
- import { componentsOf, type Component, type Positional } from "./components.ts";
8
- import { graphOf, OUTSIDE, type Graph } from "./graph.ts";
9
- import type { InventorySymbol } from "./inventory.ts";
10
- import { byPosition } from "./position.ts";
11
- import type { Reference } from "./references.ts";
12
- import type { Root } from "./roots/root-set.ts";
13
- import { edgeWithheldBy } from "./tests/file-class.ts";
14
- import {
15
- reachedWithTheTests,
16
- splitRefs,
17
- sweep,
18
- type Candidate,
19
- type Liveness,
20
- type Relation,
21
- type SweepInput,
22
- } from "./sweep.ts";
23
-
24
- /** What the passes answered for one configuration of the run. */
25
- export interface Configured {
26
- /** The name discovery gives the configuration's project. */
27
- readonly configuration: string;
28
- readonly symbols: readonly InventorySymbol[];
29
- readonly references: readonly Reference[];
30
- readonly roots: readonly Root[];
31
- /** The paths the reference pass classified as test files. */
32
- readonly testFiles: readonly string[];
33
- /** The paths of the test-support files, which only test code imports. */
34
- readonly supportFiles?: readonly string[] | undefined;
35
- /** The paths of the files only tests reach that are no test-support file. */
36
- readonly testUsedFiles?: readonly string[] | undefined;
37
- /** The ids of the ambient declarations, which describe code the target does not implement. */
38
- readonly ambient?: ReadonlySet<string> | undefined;
39
- /**
40
- * The paths of the workspace-package files the configuration holds but does not
41
- * compile itself. Their declarations count in its graph and its verdict on them is no
42
- * finding.
43
- */
44
- readonly referenceOnly?: readonly string[] | undefined;
45
- /** Each declaration's dependents, by id, as the configuration's inventory states them. */
46
- readonly dependents?: ReadonlyMap<string, readonly string[]> | undefined;
47
- }
48
-
49
- /** The run's configurations, indexed for the sweep. */
50
- export interface Matrix {
51
- /** The configurations, in the run's order. */
52
- readonly configurations: readonly string[];
53
- /** Per configuration, in the same order, the graph of what that configuration holds. */
54
- readonly graphs: readonly Graph[];
55
- /**
56
- * The graph over every configuration at once: every declaration a configuration
57
- * holds in a file it does not hold only for its references, once per position and in
58
- * site order, and every reference any configuration makes, a reference several
59
- * configurations make at one position counted once.
60
- */
61
- readonly union: Graph;
62
- /**
63
- * Per declaration of {@link Matrix.union}, at its position there, the configurations
64
- * whose project holds it, in the run's order.
65
- */
66
- readonly heldIn: readonly (readonly string[])[];
67
- /**
68
- * Per declaration of {@link Matrix.union}, whether a file only tests reach that is no
69
- * test-support file holds it in some configuration: production code only tests use.
70
- */
71
- readonly testUsed: readonly boolean[];
72
- /** Each declaration's dependents, by id, as the first configuration holding it states them. */
73
- readonly dependents: ReadonlyMap<string, readonly string[]>;
74
- }
75
-
76
- /** One declaration dead in every configuration that holds it. */
77
- export interface MatrixCandidate extends Candidate {
78
- /** The configurations the declaration is dead in, which are every one that holds it. */
79
- readonly configurations: readonly string[];
80
- /**
81
- * The declaration of test-support code that test code references, outside the
82
- * test-of-dead-code rule, that is or contains this one, the outermost where two do.
83
- * Such a declaration is not dead while test code references it, so neither it nor a
84
- * declaration it contains is a member of a dead component.
85
- */
86
- readonly heldByTests: string | undefined;
87
- /**
88
- * Whether a test file declares it, no test of dead code, and the run that counts test
89
- * references does not reach it: it is reported as a production declaration of its
90
- * shape nothing references would be.
91
- */
92
- readonly unreferencedTest: boolean;
93
- /**
94
- * Whether it is dead only because code only tests use is: production code only tests
95
- * use holds it and the run that counts test references reaches it, or such a
96
- * declaration reaches it through dead declarations.
97
- */
98
- readonly testUsed: boolean;
99
- /**
100
- * Whether test code the run that counts test references reaches, and that is no test of
101
- * dead code, references it: a test that stays keeps it.
102
- */
103
- readonly keptByTests: boolean;
104
- }
105
-
106
- /** One run's sweep. */
107
- export interface SweepResult {
108
- /**
109
- * Per declaration, the relations that hold it live in at least one configuration,
110
- * reference counting first. A declaration no relation holds live anywhere has no entry.
111
- */
112
- readonly liveUnder: ReadonlyMap<string, readonly Relation[]>;
113
- /** The declarations dead in every configuration that holds them, in site order. */
114
- readonly candidates: readonly MatrixCandidate[];
115
- /** The dead components, each before every component it reaches, each identifier once per run. */
116
- readonly components: readonly Component[];
117
- }
118
-
119
- /**
120
- * What makes one reference one reference, whichever configuration made it. A consumer's
121
- * position is rendered against its own root, so the consumer is part of what it names.
122
- */
123
- export function referenceKey(reference: Reference): string {
124
- const { path, line, column } = reference.position;
125
- return [
126
- reference.consumer ?? "",
127
- reference.from,
128
- reference.to,
129
- path,
130
- String(line),
131
- String(column),
132
- reference.use,
133
- ].join("\u0000");
134
- }
135
-
136
- /**
137
- * Indexes what the passes answered for each configuration of one run, in the run's order.
138
- * A declaration is keyed by its rendered position, with the fields of the first
139
- * configuration that judges it; one in a file every holder holds only for its references
140
- * is judged by none and is not in the union. One reference at one position of a file
141
- * several configurations compile is one reference; two one configuration makes are two.
142
- */
143
- export function matrixOf(per: readonly Configured[]): Matrix {
144
- const symbols: InventorySymbol[] = [];
145
- const holders = new Map<string, string[]>();
146
- const references: Reference[] = [];
147
- const firstSeen = new Map<string, number>();
148
- const judged = new Set<string>();
149
- const dependents = new Map<string, readonly string[]>();
150
- per.forEach((one, index) => {
151
- for (const [id, after] of one.dependents ?? []) {
152
- if (!dependents.has(id)) {
153
- dependents.set(id, after);
154
- }
155
- }
156
- const referenceOnly = new Set(one.referenceOnly);
157
- for (const symbol of one.symbols) {
158
- const held = holders.get(symbol.id);
159
- if (held === undefined) {
160
- holders.set(symbol.id, [one.configuration]);
161
- } else if (!held.includes(one.configuration)) {
162
- held.push(one.configuration);
163
- }
164
- if (!referenceOnly.has(symbol.position.path) && !judged.has(symbol.id)) {
165
- judged.add(symbol.id);
166
- symbols.push(symbol);
167
- }
168
- }
169
- for (const reference of one.references) {
170
- const key = referenceKey(reference);
171
- const seen = firstSeen.get(key);
172
- if (seen === undefined) {
173
- firstSeen.set(key, index);
174
- } else if (seen !== index) {
175
- continue;
176
- }
177
- references.push(reference);
178
- }
179
- });
180
- symbols.sort((a, b) => byPosition(a.position, b.position));
181
- const testUsed = new Set(per.flatMap((one) => one.testUsedFiles ?? []));
182
-
183
- return {
184
- configurations: per.map((one) => one.configuration),
185
- graphs: per.map((one) =>
186
- graphOf(one.symbols, one.references, one.roots, one.testFiles, one.supportFiles, one.ambient),
187
- ),
188
- union: graphOf(
189
- symbols,
190
- references,
191
- per.flatMap((one) => one.roots),
192
- [...new Set(per.flatMap((one) => one.testFiles))],
193
- [...new Set(per.flatMap((one) => one.supportFiles ?? []))],
194
- new Set(per.flatMap((one) => [...(one.ambient ?? [])])),
195
- ),
196
- heldIn: symbols.map((symbol) => holders.get(symbol.id) ?? []),
197
- testUsed: symbols.map((symbol) => testUsed.has(symbol.position.path)),
198
- dependents,
199
- };
200
- }
201
-
202
- /**
203
- * Which declarations of the run are dead in every configuration that holds them. Each
204
- * configuration is swept on its own graph, since a file it does not compile references nothing
205
- * there and a root it does not hold seeds nothing. A declaration is a candidate when every
206
- * configuration holding it judged it one; its relation is reference counting where every one
207
- * found it so, else reachability, and its counts are the union's. Components are computed once,
208
- * over the union and the intersected dead set, so one dead component has one identifier.
209
- */
210
- export function sweepMatrix(matrix: Matrix, input: SweepInput): SweepResult {
211
- const per = matrix.graphs.map((graph) => sweep(graph, input));
212
- const byConfiguration = new Map<string, ReadonlyMap<string, Candidate>>(
213
- matrix.configurations.map((configuration, index) => [
214
- configuration,
215
- new Map((per[index]?.candidates ?? []).map((candidate) => [candidate.id, candidate])),
216
- ]),
217
- );
218
-
219
- const union = matrix.union;
220
- const heldBy: (string | undefined)[] = union.symbols.map(() => undefined);
221
- const held = [
222
- ...input.marked,
223
- ...(input.exempt ?? []).map((record) => record.id),
224
- ...(input.unanswered ?? []),
225
- ];
226
- const testReached = reachedWithTheTests(union, held);
227
- // A test uses what it names: a file a test reads through a star re-export or a
228
- // namespace keeps the exports nothing names at their own class.
229
- const testNamed = reachedWithTheTests(union, held, false);
230
- const everywhere = union.symbols.map((symbol, at): readonly Candidate[] | undefined => {
231
- const held = matrix.heldIn[at] ?? [];
232
- const found = held.map((configuration) => byConfiguration.get(configuration)?.get(symbol.id));
233
- return held.length === 0 || found.some((candidate) => candidate === undefined)
234
- ? undefined
235
- : found.filter((candidate): candidate is Candidate => candidate !== undefined);
236
- });
237
- const compiled = compiledReferences(
238
- matrix,
239
- new Set(
240
- union.symbols.flatMap((symbol, at) => (everywhere[at] === undefined ? [] : [symbol.id])),
241
- ),
242
- input.mode,
243
- );
244
- const judged = everywhere.map((found, at) =>
245
- compiled.has(union.symbols[at]?.id ?? "") ? undefined : found,
246
- );
247
- // A configuration that does not hold a test's subject's caller finds the subject dead,
248
- // so a test is of dead code only where every production subject it names is dead in
249
- // every configuration that holds it.
250
- const subjectsDead = (at: number): boolean =>
251
- (union.out[at] ?? []).every(
252
- (edge) =>
253
- union.test[edge.to] === true ||
254
- union.support[edge.to] === true ||
255
- union.ambient[edge.to] === true ||
256
- union.subject[edge.to] !== true ||
257
- judged[edge.to] !== undefined,
258
- );
259
- const admittedAt = (at: number): boolean =>
260
- judged[at]?.every((candidate) => candidate.testOfDeadCode) === true && subjectsDead(at);
261
- const kept = keptByTests(union, testReached, admittedAt);
262
- const testUsed = testUsedReach(
263
- union,
264
- union.symbols.map((_symbol, at) => matrix.testUsed[at] === true && testNamed[at] === true),
265
- judged.map((one) => one !== undefined),
266
- );
267
- const candidates: MatrixCandidate[] = [];
268
- union.symbols.forEach((symbol, at) => {
269
- const all = judged[at];
270
- if (all === undefined) {
271
- return;
272
- }
273
- const held = matrix.heldIn[at] ?? [];
274
- const admitted = admittedAt(at);
275
- const split = splitRefs(union.made[at], input.mode);
276
- const testRefs = split.test;
277
- const heldByTests =
278
- heldBy[union.parent[at] ?? OUTSIDE] ??
279
- (union.support[at] === true && testRefs > 0 && !admitted ? symbol.id : undefined);
280
- const unreferenced = union.test[at] === true && !admitted && testReached[at] !== true;
281
- heldBy[at] = heldByTests;
282
- const productionRefs = split.production;
283
- const counted = all.every((candidate) => candidate.relation === "reference-counting");
284
- candidates.push({
285
- id: symbol.id,
286
- productionRefs,
287
- testRefs,
288
- // The run that judges a test-file declaration counts its test references.
289
- relation: (unreferenced ? productionRefs + testRefs === 0 : counted)
290
- ? "reference-counting"
291
- : "reachability",
292
- testOfDeadCode: admitted,
293
- configurations: held,
294
- heldByTests,
295
- unreferencedTest: unreferenced,
296
- testUsed: testUsed[at] === true,
297
- keptByTests: kept[at] === true,
298
- });
299
- });
300
-
301
- const liveUnder = liveAnywhere(union.symbols, per);
302
- return {
303
- liveUnder,
304
- candidates,
305
- components: deadComponents(matrix, { liveUnder, candidates }, new Set()),
306
- };
307
- }
308
-
309
- /**
310
- * Every declaration of `dead`, those dead in every configuration that holds them, that a
311
- * configuration's graph references from a judged declaration outside `dead` or already
312
- * kept, until none joins: deleting one would break that configuration's compile. A
313
- * production run counts no reference a test file made.
314
- */
315
- function compiledReferences(
316
- matrix: Matrix,
317
- dead: ReadonlySet<string>,
318
- mode: SweepInput["mode"],
319
- ): ReadonlySet<string> {
320
- const kept = new Set<string>();
321
- for (let changed = true; changed;) {
322
- changed = false;
323
- for (const graph of matrix.graphs) {
324
- graph.out.forEach((edges, from) => {
325
- const id = graph.symbols[from]?.id ?? "";
326
- if (graph.subject[from] !== true || (dead.has(id) && !kept.has(id))) {
327
- return;
328
- }
329
- for (const edge of edges) {
330
- const to = graph.symbols[edge.to]?.id ?? "";
331
- if (!edgeWithheldBy(mode, edge) && dead.has(to) && !kept.has(to)) {
332
- kept.add(to);
333
- changed = true;
334
- }
335
- }
336
- });
337
- }
338
- }
339
- return kept;
340
- }
341
-
342
- /** Per declaration of the union, whether one of `seeds` is it or reaches it through `dead` declarations. */
343
- function testUsedReach(
344
- union: Graph,
345
- seeds: readonly boolean[],
346
- dead: readonly boolean[],
347
- ): readonly boolean[] {
348
- // A file is no candidate, and its top level is what reaches what it alone calls.
349
- const reached = seeds.map((seed, at) => seed && dead[at] === true);
350
- const queue = seeds.flatMap((one, at) => (one ? [at] : []));
351
- for (let at = queue.pop(); at !== undefined; at = queue.pop()) {
352
- for (const edge of union.out[at] ?? []) {
353
- if (dead[edge.to] === true && reached[edge.to] !== true) {
354
- reached[edge.to] = true;
355
- queue.push(edge.to);
356
- }
357
- }
358
- }
359
- return reached;
360
- }
361
-
362
- /** Per declaration of the union, whether test code `reached` holds and `admitted` rejects references it. */
363
- function keptByTests(
364
- union: Graph,
365
- reached: readonly boolean[],
366
- admitted: (at: number) => boolean,
367
- ): readonly boolean[] {
368
- const kept = union.symbols.map(() => false);
369
- union.out.forEach((edges, from) => {
370
- const testCode = union.test[from] === true || union.support[from] === true;
371
- if (!testCode || reached[from] !== true || admitted(from)) {
372
- return;
373
- }
374
- for (const edge of edges) {
375
- if (edge.test) {
376
- kept[edge.to] = true;
377
- }
378
- }
379
- });
380
- return kept;
381
- }
382
-
383
- /**
384
- * The dead components of one sweep over the union, with the file declarations at `files`
385
- * dead as well: a file that is deleted whole takes the declarations it holds and every
386
- * dead declaration only its top level references with it.
387
- */
388
- export function deadComponents(
389
- matrix: Matrix,
390
- result: Pick<SweepResult, "liveUnder" | "candidates">,
391
- files: ReadonlySet<number>,
392
- ): readonly Component[] {
393
- const union = matrix.union;
394
- const byId = new Map(result.candidates.map((candidate) => [candidate.id, candidate]));
395
- const candidateAt = (at: number): MatrixCandidate | undefined =>
396
- byId.get(union.symbols[at]?.id ?? "");
397
- return componentsOf(
398
- union,
399
- union.symbols.map((_symbol, at) => {
400
- const candidate = candidateAt(at);
401
- return files.has(at) || (candidate !== undefined && candidate.heldByTests === undefined);
402
- }),
403
- union.symbols.map((_symbol, at) => candidateAt(at)?.testOfDeadCode === true),
404
- union.symbols.map((_symbol, at) => candidateAt(at)?.unreferencedTest === true),
405
- positionsOf(union, matrix.dependents, result.liveUnder),
406
- );
407
- }
408
-
409
- /**
410
- * The file declarations at `paths`, below the target root, that one sweep holds live
411
- * under both relations, the rule a judged declaration is live by.
412
- */
413
- export function liveFilesAt(
414
- matrix: Matrix,
415
- result: SweepResult,
416
- paths: ReadonlySet<string>,
417
- ): readonly InventorySymbol[] {
418
- return matrix.union.symbols.filter(
419
- (symbol) =>
420
- symbol.kind === "file" &&
421
- paths.has(symbol.position.path) &&
422
- (result.liveUnder.get(symbol.id)?.length ?? 0) === RELATIONS.length,
423
- );
424
- }
425
-
426
- /**
427
- * Each declaration's dependents by its place in the union, and per place whether the
428
- * declaration is live under reachability in some configuration.
429
- */
430
- function positionsOf(
431
- union: Graph,
432
- dependents: ReadonlyMap<string, readonly string[]>,
433
- liveUnder: ReadonlyMap<string, readonly Relation[]>,
434
- ): Positional {
435
- return {
436
- dependents: union.symbols.map((symbol) =>
437
- (dependents.get(symbol.id) ?? []).map((id) => union.at(id)).filter((at) => at !== OUTSIDE),
438
- ),
439
- live: union.symbols.map(
440
- (symbol) => liveUnder.get(symbol.id)?.includes("reachability") === true,
441
- ),
442
- };
443
- }
444
-
445
- /** The relations in the order a declaration's entry lists them. */
446
- const RELATIONS: readonly Relation[] = ["reference-counting", "reachability"];
447
-
448
- /**
449
- * Per declaration, in site order, every relation that holds it live in at least one
450
- * configuration.
451
- */
452
- function liveAnywhere(
453
- symbols: readonly InventorySymbol[],
454
- per: readonly Liveness[],
455
- ): ReadonlyMap<string, readonly Relation[]> {
456
- const live = new Map<string, readonly Relation[]>();
457
- for (const symbol of symbols) {
458
- const relations = RELATIONS.filter((relation) =>
459
- per.some((liveness) => (liveness.liveUnder.get(symbol.id) ?? []).includes(relation)),
460
- );
461
- if (relations.length > 0) {
462
- live.set(symbol.id, relations);
463
- }
464
- }
465
- return live;
466
- }