@cplieger/deadset-ts 3.13.0 → 4.0.1

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 (92) hide show
  1. package/README.md +67 -49
  2. package/dist/bin/node-host.js +10 -7
  3. package/dist/src/alias-chain.js +59 -7
  4. package/dist/src/analysis.js +120 -24
  5. package/dist/src/calls.js +23 -22
  6. package/dist/src/class-members.js +10 -11
  7. package/dist/src/configured-declarations.js +22 -9
  8. package/dist/src/dependencies.js +34 -17
  9. package/dist/src/deprecation.js +35 -24
  10. package/dist/src/destructuring.js +37 -29
  11. package/dist/src/discover.js +106 -29
  12. package/dist/src/entry-point-gaps.js +2 -2
  13. package/dist/src/entry-points.js +7 -0
  14. package/dist/src/enum-group.js +46 -40
  15. package/dist/src/exempt.js +42 -1
  16. package/dist/src/findings/emitters.js +15 -1
  17. package/dist/src/findings/interfaces.js +7 -1
  18. package/dist/src/framework-lifecycle.js +8 -6
  19. package/dist/src/implementations.js +45 -23
  20. package/dist/src/interface-satisfaction.js +30 -27
  21. package/dist/src/intra-function-parts.js +37 -20
  22. package/dist/src/inventory.js +85 -4
  23. package/dist/src/json-chunks.js +76 -0
  24. package/dist/src/partial.js +23 -0
  25. package/dist/src/query.js +207 -0
  26. package/dist/src/references.js +92 -20
  27. package/dist/src/reflective-lookup.js +18 -9
  28. package/dist/src/report.js +3 -1
  29. package/dist/src/reporters/annotations.js +9 -5
  30. package/dist/src/reporters/json.js +3 -2
  31. package/dist/src/reporters/sarif.js +2 -1
  32. package/dist/src/reporters/template.js +51 -10
  33. package/dist/src/reporters/text.js +8 -6
  34. package/dist/src/roots.js +27 -11
  35. package/dist/src/schema.js +2 -2
  36. package/dist/src/serialization-contract.js +12 -10
  37. package/dist/src/session.js +79 -39
  38. package/dist/src/suppress-file.js +2 -1
  39. package/dist/src/sweep.js +4 -1
  40. package/dist/src/value-reach.js +14 -19
  41. package/dist/src/verbs/analyze.js +20 -3
  42. package/dist/src/verbs/explain.js +22 -9
  43. package/dist/src/verbs/print-projects.js +41 -8
  44. package/dist/src/verbs/print-retained.js +6 -2
  45. package/dist/src/verbs/print-roots.js +5 -1
  46. package/jsr.json +1 -1
  47. package/package.json +3 -3
  48. package/src/alias-chain.ts +75 -11
  49. package/src/analysis.ts +224 -62
  50. package/src/calls.ts +10 -9
  51. package/src/class-members.ts +10 -11
  52. package/src/configured-declarations.ts +29 -13
  53. package/src/dependencies.ts +42 -20
  54. package/src/deprecation.ts +53 -27
  55. package/src/destructuring.ts +50 -39
  56. package/src/discover.ts +178 -34
  57. package/src/entry-point-gaps.ts +2 -2
  58. package/src/entry-points.ts +7 -0
  59. package/src/enum-group.ts +56 -42
  60. package/src/exempt.ts +50 -2
  61. package/src/findings/emitters.ts +18 -1
  62. package/src/findings/interfaces.ts +7 -1
  63. package/src/framework-lifecycle.ts +10 -6
  64. package/src/host.ts +5 -3
  65. package/src/implementations.ts +59 -23
  66. package/src/interface-satisfaction.ts +30 -27
  67. package/src/intra-function-parts.ts +43 -25
  68. package/src/inventory.ts +97 -4
  69. package/src/json-chunks.ts +87 -0
  70. package/src/partial.ts +40 -0
  71. package/src/query.ts +522 -0
  72. package/src/references.ts +119 -38
  73. package/src/reflective-lookup.ts +21 -11
  74. package/src/report.ts +14 -2
  75. package/src/reporters/annotations.ts +23 -21
  76. package/src/reporters/json.ts +3 -2
  77. package/src/reporters/reporter.ts +2 -2
  78. package/src/reporters/sarif.ts +3 -2
  79. package/src/reporters/template.ts +53 -11
  80. package/src/reporters/text.ts +12 -12
  81. package/src/roots.ts +34 -12
  82. package/src/schema.ts +2 -2
  83. package/src/serialization-contract.ts +12 -10
  84. package/src/session.ts +146 -58
  85. package/src/suppress-file.ts +6 -2
  86. package/src/sweep.ts +9 -4
  87. package/src/value-reach.ts +20 -23
  88. package/src/verbs/analyze.ts +25 -3
  89. package/src/verbs/explain.ts +20 -9
  90. package/src/verbs/print-projects.ts +54 -8
  91. package/src/verbs/print-retained.ts +6 -2
  92. package/src/verbs/print-roots.ts +5 -1
package/README.md CHANGED
@@ -2,13 +2,22 @@
2
2
 
3
3
  [![npm](https://img.shields.io/npm/v/@cplieger/deadset-ts)](https://www.npmjs.com/package/@cplieger/deadset-ts) [![JSR](https://jsr.io/badges/@cplieger/deadset-ts)](https://jsr.io/@cplieger/deadset-ts)
4
4
 
5
- > Deterministic dead-code analysis for TypeScript, class and type members included.
5
+ deadset-ts finds dead code in TypeScript projects, down to class members, type members and dead stores inside functions, and writes a report your CI can fail on.
6
6
 
7
- deadset-ts is a command-line analyzer for TypeScript and JavaScript projects. It builds the program from your `tsconfig.json` files through the TypeScript 7 compiler API, resolves every reference in one pass, and reports the declarations nothing reaches: unused exports, type-only exports without a consumer, unused class members (private, protected, static and accessors), unused interface, type-alias, enum and namespace members, exports that can be narrowed to a smaller visibility, whole groups of declarations that only keep each other alive, and inside a function the unused parameters, results nobody reads, unreachable statements, dead stores and unreachable cases. Every finding carries an issue code, a confidence and a stable symbol reference from the [deadset Contract](https://github.com/cplieger/deadset-spec), so the same report shape works for a Go analyzer and for a merged multi-language report. The analysis is deterministic: the same tree gives the same report, with no cache and no text search.
7
+ It reads your `tsconfig.json` projects, `allowJs` JavaScript included, with the type information of TypeScript 7.1.0-dev.20261003.1, its one dependency. Your project keeps its own TypeScript version and must also compile under that version. deadset-ts reports and never edits your code. It is pre-release, tested only on Linux, needs Node.js 24 or later and is licensed under GPL-3.0-or-later.
8
8
 
9
- deadset-ts is report-only. It never edits source, and it refuses any `--fix` flag.
9
+ ## Why use it
10
10
 
11
- **Status: pre-release.** This version implements contract 4.0.0 and ships the analyzer's foundation: one compiler session per run over the projects `analysis.configurations` declares, in the order it lists them, each a compiler configuration file below the target, or, where it declares none, every `tsconfig` project discovered under the target (the explicit scope, every `tsconfig*.json`, each project's `references`), a fail-closed read of every project's diagnostics, configuration decoding against the contract's closed key list with `print-config` and its provenance, `print-projects`, the report-only guard, the symbol inventory of every declaration a project's own files hold down to its class and type members, the one-pass reference resolution over that inventory, which resolves each file's identifiers in batches ([batch-cap calibration](docs/batch-cap-calibration.md) is the measurement behind the batch size), and the root set `print-roots` prints. A root is a declaration the analysis keeps live without a reference: what a file exports when the manifest names it through `main`, `module`, `types`, `bin` or `exports`, or when `ts.entry_files` matches it; a library target's published API; the configuration, setup and test files of Vitest, Stryker and Playwright, the flat configuration of ESLint, and a worker or service worker a call addresses by a string literal; and every declaration a `roots.patterns` entry names. An entry that names nothing is reported as `DS1704` and fails the run. The entry-point conventions of other tools are not read, and `DECLINED_CONVENTIONS` lists each one with the reason. Seven exemption classes hold a declaration back from the sweep, and `print-retained` lists what each one held back: `interface-satisfaction`, a member an interface requires of a class whose value reaches that interface; `decorator`, a decorated member and every member of a decorated class; `injection-container`, a decorated property of a class a dependency-injection container constructs, being a class passed to a call `ts.injection_registrations` names or one a parameter of whose constructor carries a decorator; `framework-lifecycle`, a member a `ts.lifecycle_contracts` entry lists, on a class that is the entry's component by a decorator or a call the entry names or by extending a class it names; `serialization-contract`, the properties of a class whose values reach `JSON.stringify` or a declaration `ts.serializers` names, and those and its `toJSON` and `toString` where a value is passed to an `unknown` or `any` parameter of a function outside the analysis; and, at the lowest confidence, `template-field`, a member an action of a template under `analysis.template_dirs` names, and `reflective-lookup`, a member a literal key of an element access or of `Reflect.get`, `Reflect.set` or `Reflect.has` names. None of them holds back a `#private` member. `analyze` writes the report the Contract's report schema declares, with text, JSON, GitHub annotation, SARIF 2.1.0 and template renderings beside it on request. A scope document passed with `--scope` names the consumers loaded beside the target, each a directory whose compiler configurations open in the same session; a reference from a consumer keeps a target declaration live, the report names every consumer it loaded, and a consumer that is absent or does not load ends the run with exit code 3. A library target's published API is `certain` once every declared consumer loads and `possible` with no consumer information, and in that second case `DS1001` defaults to `allow` and the narrowing kinds report only in files no manifest export reaches. `explain` answers why one declaration is reported, retained, live or dead, from the same analysis the report is built from. `describe` prints the analyzer's description with its conformance record over the published corpus and the declared gaps `conformance.json` lists. The analysis is reached through the command, and through `run()` for a caller that runs the command in-process. The one runtime dependency is the `typescript` package at exactly 7.0.2, installed under the `@typescript/native` name until TypeScript 7.1 ships a compiler API the tooling can share.
11
+ deadset-ts is built for a CI gate on dead code. Each finding names code to delete, an `export` to drop or a setting to fix.
12
+
13
+ - It reports unused exports, files and dependencies, and unused members of classes, interfaces, type aliases, enums and namespaces, private and static included.
14
+ - Inside a function, it reports unused parameters and results, unreachable statements and cases, and dead stores.
15
+ - It reports an `export` only its own file uses, and declarations that only reference each other.
16
+ - It keeps what decorators, reflective lookups, `JSON.stringify` and the frameworks, containers, serializers and templates you name in `deadset.json` use.
17
+ - The same tree gives the same report, and a baseline keyed on code and symbol survives moved lines.
18
+ - It writes text, JSON, GitHub annotations, SARIF 2.1.0 or a custom template.
19
+
20
+ Consider [Knip](https://knip.dev) if you want issues fixed with `--fix`, plugins for over 100 tools, or Astro, MDX, Svelte and Vue files checked.
12
21
 
13
22
  ## Install
14
23
 
@@ -20,70 +29,79 @@ npx jsr add -D @cplieger/deadset-ts
20
29
  npx @cplieger/deadset-ts version
21
30
  ```
22
31
 
23
- The npm package carries the command and the library as JavaScript that the compiler emits at publish, so `npx deadset-ts` and `import("@cplieger/deadset-ts")` both run on plain Node.js 24 or later, with no loader and no flag. It carries the TypeScript source as well, which is what a TypeScript consumer's own compiler resolves. That consumer sets `allowImportingTsExtensions`, because the source names each import with its `.ts` extension. The JSR package ships source only, and Deno compiles it: a Deno program imports and type-checks the library, but the compiler's synchronous session does not open under Deno, so running an analysis needs Node.
24
-
25
32
  ## Usage
26
33
 
34
+ Create a `deadset.json` at the project root that says whether the project is an `application` or a `library`, then run `analyze`. A run reads every `tsconfig` project under that folder, project references included, and reports a declaration only when it is dead in all of them.
35
+
27
36
  ```sh
28
- npx deadset-ts version
37
+ echo '{ "target": { "kind": "application" } }' > deadset.json
38
+ npx @cplieger/deadset-ts analyze --report=deadset-report.json
29
39
  ```
30
40
 
31
- `version` prints the analyzer version and the Contract version it implements, and exits 0. `print-config`, `print-projects`, `print-roots` and `print-retained` print what their row of the table says and exit 0, or 1 when `print-roots` reports a `DS1704`, and `print-retained` exits 2 when an `exemptions.disabled` entry is not an exemption class or an `analysis.template_dirs` entry is not a directory below the target root. `analyze --report=PATH` writes the JSON report to `PATH` through a temporary file renamed into place, each `--format` rendering at `PATH` with its suffix appended (`text` as `.txt`, `json` as `.json`, `github` as `.annotations` in GitHub workflow-command form, `sarif` as `.sarif`, and `template` as `.tmpl`, rendering the file `--template=FILE` names, written in a subset of Go's `text/template` action grammar over the report's JSON member names), and with `--baseline-write=FILE` a baseline of every finding; it writes nothing to standard output and exits with the Contract's exit-code table: 0 clean, 1 for a finding at or above `reporters.fail_on` or a stale suppression, 2 for a usage error, including a template that cannot be read or does not parse, 3 for a failed load or a rendering that cannot be written, and 4 for a pending finding, which outranks 1. `--exit-code=off` exits 0 whatever the verdict and names the verdict on standard error. The report names the target relative to the directory the run is invoked from, so a target outside that directory fails with 3. `describe` writes its JSON document to standard output and exits 0. `explain --why=SYM`, or the same request spelled `--why-live=SYM` or `--why-not=SYM`, prints why that one declaration is reported, retained, live or dead, with the shortest reference path from a root or a loaded consumer for a live one, and exits 0; a request that names no one declaration exits 2 and lists up to 20 declarations it partially matches. Any other invocation and no arguments print the usage line and exit 2.
32
-
33
- | Verb | Job |
34
- | ---------------- | ---------------------------------------------------------------------------------- |
35
- | `analyze` | Analyze a project and write the report, its renderings and a baseline |
36
- | `explain` | Explain one declaration: the relation, the roots and the references that decide it |
37
- | `print-config` | Print the resolved configuration and where each setting came from |
38
- | `print-projects` | Print the identifier of every project a run analyzes |
39
- | `print-roots` | Print every declaration the analysis keeps live without a reference, and why |
40
- | `print-retained` | Print every declaration an exemption held back: each class, its site and detail |
41
- | `describe` | Describe the analyzer: versions, accepted report schemas, languages, conformance |
42
- | `version` | Print the analyzer and Contract versions |
43
-
44
- ## Requirements
45
-
46
- - Node.js 24 or later. The npm command is JavaScript the compiler emits at publish, so it runs with no loader and no flag; a clone of this repository runs the same command from its TypeScript sources through Node's own type stripping, which is what needs the version.
47
- - TypeScript 7. The analyzer is written against the `typescript` package at exactly version 7.0.2 and its `unstable/*` API. It does not run on TypeScript 6, whose compiler API TypeScript 7 removed, and it does not fall back to it.
48
- - Linux. Other platforms are untested.
41
+ `analyze` writes the JSON report to `deadset-report.json` and a text rendering beside it as `deadset-report.json.txt`. Take this `src/greet.ts`, where the rest of the project calls only `greet` and `Counter.increment`:
42
+
43
+ ```ts
44
+ export function greet(name: string): string {
45
+ return `hello ${name}`;
46
+ }
47
+ export function farewell(name: string): string {
48
+ return `bye ${name}`;
49
+ }
50
+ export class Counter {
51
+ private count = 0;
52
+ increment(): void {
53
+ this.count += 1;
54
+ }
55
+ reset(): void {
56
+ this.count = 0;
57
+ }
58
+ }
59
+ ```
49
60
 
50
- ## API
61
+ The text rendering lists three findings:
51
62
 
52
- The package exports the command line, for callers that run it in-process, and the vocabularies and helpers its output is spelled with. The command line reads the platform through a `Host`: the filesystem, the directory relative paths resolve against, and the version of the package the analyzer was installed from. `bin/node-host.ts` is the Node one the command line binds; a caller embedding the analyzer, or running it on another platform, supplies its own and supplies its own version with it.
63
+ ```text
64
+ src/greet.ts:4:17: function farewell: exported function has no reference in the target and none from any loaded consumer [certain] (DS1001)
65
+ src/greet.ts:8:11: class-member Counter.count: member Counter.count is written at 2 positions and never read [certain] (DS1301)
66
+ src/greet.ts:12:3: method Counter.reset: method has no reference in the target [certain] (DS1003)
67
+ summary: 3 findings (0 allow, 0 warn, 3 deny), 6 deletable lines, 0 suppressions in effect, 0 reasons recorded, 0 stale suppressions, 0 pending, 0 omitted
68
+ ```
53
69
 
54
- The command line:
70
+ The run exits 1 because the report holds a finding at `deny` severity, and 0 when it holds none. Three common next steps:
55
71
 
56
- - `run(args, out, err, host, openClient?)`: runs the command line over `args` (the arguments after the program name), writing to the two `Writer` streams, and returns the exit code. It never exits the process.
57
- - `SETTING_OPTIONS`: the configuration setting each command-line option supplies, by option name.
58
- - `Writer`: `{ write(text: string): void }`. `process.stdout` and `process.stderr` satisfy it.
72
+ - Add `--format=sarif` or `--format=github` for a SARIF file or GitHub workflow annotations. Naming any format turns off the default text rendering, so add `--format=text` as well to keep it.
73
+ - Run `npx @cplieger/deadset-ts explain --why=farewell` to see why one declaration is reported, retained, held by an unanswered question, live or dead.
74
+ - Add `--baseline-write=deadset-baseline.json` to record today's findings. Later runs fail on a new finding and on a baseline row whose finding has gone. To keep one declaration, put `// deadset:ignore DS1001 -- <reason>` on the line above it.
59
75
 
60
- The platform:
76
+ [Commands and exit codes](docs/commands.md) covers every verb and option, and [Configuration](docs/configuration.md) covers every setting.
61
77
 
62
- - `Host`: the filesystem a run reads, the directory it reads relative paths against, and the analyzer's own version.
63
- - `DirectoryEntry`, `PathKind`: one entry of a directory read, and what one path names.
78
+ ## API
64
79
 
65
- Positions:
80
+ The package exports the command line as a function, and the helpers that spell the positions and symbol references in a report.
66
81
 
67
- - `renderPosition(file, root, offset)`: one compiler offset as a path, a line and a column, the column counting UTF-16 code units.
68
- - `positionKey(position)`, `byPosition(a, b)`: the string one position is keyed by, and the order positions are reported in.
69
- - `PositionError`: the refusal for a position that cannot be rendered against the target root.
70
- - `Position`: one rendered position.
82
+ - `run` runs the command line and returns its exit code, without exiting the process. `Writer` is its output stream, and `SETTING_OPTIONS` maps each option to the setting it sets.
83
+ - `Host`, `DirectoryEntry` and `PathKind` describe the filesystem, working directory and version a run reads.
84
+ - `renderPosition`, `positionKey`, `byPosition`, `PositionError` and `Position` render and order positions.
85
+ - `renderRef`, `nameComponent`, `computedComponent`, `isRef`, `REF_EXPRESSIONS`, `Module`, `Component`, `Fragment` and `DependencySection` spell stable symbol references.
86
+ - `DECLINED_CONVENTIONS` and `DeclinedConvention` list the entry-point conventions of other tools the analysis does not read.
87
+ - `CONTRACT_VERSION` is the version of the [deadset Contract](https://github.com/cplieger/deadset-spec) this analyzer implements.
71
88
 
72
- Stable symbol references:
89
+ A TypeScript caller that imports the source sets `allowImportingTsExtensions`, because each import in it ends in `.ts`. [Using deadset-ts as a library](docs/library.md) covers the packages and in-process runs, and [JSR](https://jsr.io/@cplieger/deadset-ts/doc) has the full reference.
73
90
 
74
- - `renderRef(module, fragment)`: one symbol's stable reference, in the canonical spelling the contract's grammar fixes.
75
- - `nameComponent(name)`, `computedComponent(text)`: the canonical spelling of one component of that reference, from a declared name or from a computed key.
76
- - `isRef(value)`: whether one string is a reference of this language's grammar.
77
- - `REF_EXPRESSIONS`: one regular expression per form the grammar defines.
78
- - `Module`, `Component`, `Fragment`, `DependencySection`: the module half of a reference, one component of its fragment, what the fragment names, and the manifest section a dependency was declared in.
91
+ ## Related projects
79
92
 
80
- Entry points:
93
+ deadset-ts implements the [deadset Contract](https://github.com/cplieger/deadset-spec), which fixes the issue codes, the report schema and the exit codes. It passes the Contract's conformance corpus except one reflective-lookup fixture, the gap [`conformance.json`](conformance.json) declares.
81
94
 
82
- - `DECLINED_CONVENTIONS`, `DeclinedConvention`: the entry-point conventions of other tools the analysis does not read, one row per tool or convention with the reason.
95
+ - [deadset-go](https://github.com/cplieger/deadset-go) is the same analysis for Go modules.
96
+ - [deadset](https://github.com/cplieger/deadset) runs both analyzers as one command and merges their reports, resolving the edges between Go and TypeScript code.
83
97
 
84
- Versions:
98
+ ## Documentation
85
99
 
86
- - `CONTRACT_VERSION`: the contract version this analyzer implements.
100
+ - [Commands and exit codes](docs/commands.md) lists every verb, option, rendering and exit code.
101
+ - [Configuration](docs/configuration.md) lists every setting, the suppression files and the scope document.
102
+ - [How deadset-ts works](docs/how-it-works.md) explains the projects it loads, the roots it starts from and what it holds back.
103
+ - [Using deadset-ts as a library](docs/library.md) covers the npm and JSR packages and running the analyzer in-process.
104
+ - [Batch-cap calibration](docs/batch-cap-calibration.md) is the measurement behind the batch size of the reference pass.
87
105
 
88
106
  ## Contributing
89
107
 
@@ -47,18 +47,21 @@ function readVersion() {
47
47
  /** The mode every document the command writes carries. */
48
48
  const DOCUMENT_MODE = 0o644;
49
49
  /**
50
- * Writes one document through a temporary file in the same directory, flushed and then
51
- * renamed into place, so a run that dies partway leaves no truncated document at the path.
50
+ * Writes one document through a temporary file in the same directory, piece by piece,
51
+ * flushed and then renamed into place, so a run that dies partway leaves no truncated
52
+ * document at the path.
52
53
  */
53
- function writeAtomically(path, text) {
54
+ function writeAtomically(path, pieces) {
54
55
  const temporary = join(dirname(path), `.${basename(path)}.${randomBytes(6).toString("hex")}`);
55
56
  const fd = openSync(temporary, "wx", DOCUMENT_MODE);
56
57
  try {
57
58
  try {
58
59
  fchmodSync(fd, DOCUMENT_MODE);
59
- const bytes = Buffer.from(text, "utf8");
60
- for (let written = 0; written < bytes.length;) {
61
- written += writeSync(fd, bytes, written);
60
+ for (const piece of pieces) {
61
+ const bytes = Buffer.from(piece, "utf8");
62
+ for (let written = 0; written < bytes.length;) {
63
+ written += writeSync(fd, bytes, written);
64
+ }
62
65
  }
63
66
  fsyncSync(fd);
64
67
  }
@@ -99,6 +102,6 @@ export function nodeHost() {
99
102
  found ??= readVersion();
100
103
  return found;
101
104
  },
102
- writeFile: writeAtomically,
105
+ writeDocument: writeAtomically,
103
106
  };
104
107
  }
@@ -3,8 +3,10 @@
3
3
  * declaration of the target it is, and along the chain of aliases it heads to each
4
4
  * declaration every link of that chain is.
5
5
  */
6
+ import { isExportAssignment, isExportSpecifier, isIdentifier, isImportClause, isImportSpecifier, isNamespaceExport, isNamespaceImport, } from "@typescript/native/unstable/ast";
6
7
  import { SymbolFlags } from "@typescript/native/unstable/sync";
7
- import { nodeKey } from "./inventory.js";
8
+ import { declarationsByName, nodeKey } from "./inventory.js";
9
+ import { UNANSWERED } from "./query.js";
8
10
  /**
9
11
  * The chain walks over one project, against the declarations of `held`, the same
10
12
  * project's inventory.
@@ -14,7 +16,7 @@ import { nodeKey } from "./inventory.js";
14
16
  * library file is never fetched to find out that the inventory does not hold it.
15
17
  */
16
18
  export function aliasChains(project, held) {
17
- const ownFiles = new Set(project.ownSourceFiles().map((file) => file.fileName));
19
+ const ownFiles = project.ownPaths();
18
20
  const steps = new Map();
19
21
  const chains = new Map();
20
22
  let asked = 0;
@@ -50,23 +52,68 @@ export function aliasChains(project, held) {
50
52
  steps.set(symbol.id, next);
51
53
  return next;
52
54
  };
55
+ const files = held.symbols.filter((one) => one.kind === "file").map((one) => one.id);
56
+ /**
57
+ * The declarations an alias whose step went unanswered may stand for: every one the
58
+ * inventory holds under its own name or the name it carries forward, and every file
59
+ * where it carries a module, so a use through it still counts for what it reaches.
60
+ */
61
+ const sameNamed = (alias) => {
62
+ const names = new Set([alias.name]);
63
+ let module = false;
64
+ for (const handle of alias.declarations) {
65
+ const node = ownFiles.has(handle.path) ? project.declarationAt(handle)?.node : undefined;
66
+ if (node === undefined) {
67
+ continue;
68
+ }
69
+ if ((isImportSpecifier(node) || isExportSpecifier(node)) && node.propertyName !== undefined) {
70
+ names.add(node.propertyName.text);
71
+ }
72
+ else if (isImportClause(node)) {
73
+ names.add("default");
74
+ }
75
+ else if (isNamespaceImport(node) || isNamespaceExport(node)) {
76
+ module = true;
77
+ }
78
+ else if (isExportAssignment(node) && isIdentifier(node.expression)) {
79
+ names.add(node.expression.text);
80
+ }
81
+ }
82
+ const byName = declarationsByName(held);
83
+ const ids = [...names].flatMap((name) => byName.get(name) ?? []);
84
+ return [...new Set([...ids, ...(module ? files : [])])].map((id) => ({
85
+ id,
86
+ stepped: true,
87
+ guessed: true,
88
+ }));
89
+ };
53
90
  const chainOf = (symbol) => {
54
91
  const cached = chains.get(symbol.id);
55
92
  if (cached !== undefined) {
56
93
  return cached;
57
94
  }
58
95
  const targets = [];
96
+ const add = (id, stepped, guessed = false) => {
97
+ if (!targets.some((target) => target.id === id)) {
98
+ targets.push({ id, stepped, guessed });
99
+ }
100
+ };
59
101
  const walked = new Set();
60
102
  let at = symbol;
61
103
  let stepped = false;
62
104
  while (at !== undefined && !walked.has(at.id)) {
63
105
  walked.add(at.id);
64
106
  for (const id of declarationsOf(at)) {
65
- if (!targets.some((target) => target.id === id)) {
66
- targets.push({ id, stepped });
107
+ add(id, stepped);
108
+ }
109
+ const next = stepOf(at);
110
+ if (next === UNANSWERED) {
111
+ for (const target of sameNamed(at)) {
112
+ add(target.id, true, true);
67
113
  }
114
+ break;
68
115
  }
69
- at = stepOf(at);
116
+ at = next;
70
117
  stepped = true;
71
118
  }
72
119
  chains.set(symbol.id, targets);
@@ -74,13 +121,18 @@ export function aliasChains(project, held) {
74
121
  };
75
122
  const nextDeclared = (symbol) => {
76
123
  const walked = new Set([symbol.id]);
124
+ let from = symbol;
77
125
  let at = stepOf(symbol);
78
- while (at !== undefined && !walked.has(at.id)) {
126
+ while (at !== undefined && (at === UNANSWERED || !walked.has(at.id))) {
127
+ if (at === UNANSWERED) {
128
+ return sameNamed(from);
129
+ }
79
130
  walked.add(at.id);
80
131
  const ids = declarationsOf(at);
81
132
  if (ids.length > 0) {
82
- return ids;
133
+ return ids.map((id) => ({ id, stepped: true, guessed: false }));
83
134
  }
135
+ from = at;
84
136
  at = stepOf(at);
85
137
  }
86
138
  return [];
@@ -12,10 +12,10 @@ import { configuredDeclarations, configuredRef, declarationsNamed, } from "./con
12
12
  import { decorator } from "./decorator.js";
13
13
  import { dependenciesOf, projectNeeds } from "./dependencies.js";
14
14
  import { deprecatedDeclarations } from "./deprecation.js";
15
- import { diagnosticErrors, discoverProjects, DiscoveryError } from "./discover.js";
15
+ import { discoverProjects, DiscoveryError, isGuess, projectErrors, renderDiagnostic, targetRelative, } from "./discover.js";
16
16
  import { readEdgeSides } from "./edges.js";
17
17
  import { enumGroup } from "./enum-group.js";
18
- import { computeExemptions, disabledClasses, exemptionsOf, retainedIn, } from "./exempt.js";
18
+ import { computeExemptions, disabledClasses, exemptionsOf, isUnansweredRecord, retainedIn, } from "./exempt.js";
19
19
  import { heldByInclusion, sourceTree } from "./file-facts.js";
20
20
  import { findingsPass, recordedFindings, rowKey } from "./findings-pass.js";
21
21
  import { NO_SELF_CHECK, unmatchedRootFindings, } from "./findings/self-check.js";
@@ -63,12 +63,12 @@ function compare(a, b) {
63
63
  return a < b ? -1 : 1;
64
64
  }
65
65
  /**
66
- * Reads every project the scope discovers, and every project of every consumer it
67
- * declares, in one snapshot. Each is checked for errors first. A target project is then
68
- * enumerated and rooted, and `stage` reads the rest of what it needs from the project
69
- * while its view is open; a consumer project is read for its references to the target's
70
- * declarations. A project carrying an error fails the run with no answer, as every verb
71
- * that reads declarations does, and so does a declared consumer that cannot be loaded.
66
+ * Reads every project the scope discovers, and every project of each consumer it
67
+ * declares, in one snapshot, each checked for errors first. A target project is
68
+ * enumerated, rooted and handed to `stage`; a consumer project is read for its references
69
+ * to the target. A guess that does not load is dropped into `notBuilt` (see
70
+ * {@link isGuess}); any other project that does not load or carries an error fails the
71
+ * run, as does a run whose every guess was dropped.
72
72
  */
73
73
  function readProjects(engine, host, scope, config, stage) {
74
74
  const targetRoot = scope.target.path;
@@ -83,15 +83,31 @@ function readProjects(engine, host, scope, config, stage) {
83
83
  testFiles: config.ts.testFiles,
84
84
  publishedAPI: config.targetKind === "library",
85
85
  };
86
+ const absoluteRoot = resolvePath(host.workingDirectory(), targetRoot);
87
+ const notBuilt = [...discovered.notBuilt];
88
+ const dropped = (configFile, error) => {
89
+ notBuilt.push({
90
+ id: ids.get(configFile) ?? configFile,
91
+ configFile,
92
+ error: targetRelative(error, absoluteRoot),
93
+ });
94
+ };
86
95
  const failures = [];
87
96
  const consumed = new Map();
88
- const { projects } = runSession(engine, [...discovered.configFiles, ...consumerOf.keys()], (project) => {
89
- const errors = diagnosticErrors(diagnosticsOf(project));
90
- if (errors.length > 0) {
91
- failures.push(...errors);
97
+ const session = runSession(engine, [...discovered.configFiles, ...consumerOf.keys()], (project) => {
98
+ const errors = projectErrors(diagnosticsOf(project));
99
+ const consumer = consumerOf.get(project.configFile);
100
+ const [unloaded] = errors.load;
101
+ if (unloaded !== undefined &&
102
+ consumer === undefined &&
103
+ isGuess(discovered, project.configFile)) {
104
+ dropped(project.configFile, renderDiagnostic(unloaded, (path) => relativePath(absoluteRoot, path) ?? path));
105
+ return undefined;
106
+ }
107
+ if (errors.load.length > 0 || errors.check.length > 0) {
108
+ failures.push(...errors.load, ...errors.check);
92
109
  return undefined;
93
110
  }
94
- const consumer = consumerOf.get(project.configFile);
95
111
  if (consumer !== undefined) {
96
112
  for (const reference of consumerReferences(project, host, targetRoot, {
97
113
  id: consumer.id,
@@ -105,16 +121,29 @@ function readProjects(engine, host, scope, config, stage) {
105
121
  const rooted = roots(project, held, targetRoot, options);
106
122
  const configuration = ids.get(project.configFile) ?? project.configFile;
107
123
  return stage(project, { configuration, configFile: project.configFile, held, rooted });
108
- });
124
+ }, discovered.derived ? "record" : "refuse");
125
+ for (const configFile of session.unopened) {
126
+ if (consumerOf.has(configFile) || !isGuess(discovered, configFile)) {
127
+ throw new DiscoveryError(`${configFile} opened no project`, []);
128
+ }
129
+ dropped(configFile, "the compiler opened no project for the configuration");
130
+ }
109
131
  if (failures.length > 0) {
110
- throw new DiscoveryError(`${String(failures.length)} error(s); no answer was produced`, failures);
132
+ throw new DiscoveryError(`${String(failures.length)} error(s), so no answer was produced`, failures);
133
+ }
134
+ const answers = session.projects.filter((answer) => answer !== undefined);
135
+ const [first] = notBuilt;
136
+ if (answers.length === 0 && first !== undefined) {
137
+ throw new DiscoveryError(`no configuration discovery derived could be built; ${first.id}: ${first.error}`, []);
111
138
  }
112
139
  return {
113
- answers: projects.filter((answer) => answer !== undefined),
140
+ answers,
114
141
  consumers: {
115
142
  loaded: loads.map((load) => load.consumer),
116
143
  references: [...consumed.values()],
117
144
  },
145
+ notBuilt,
146
+ unanswered: session.unanswered,
118
147
  };
119
148
  }
120
149
  /**
@@ -125,7 +154,8 @@ function readProjects(engine, host, scope, config, stage) {
125
154
  */
126
155
  export function runRoots(engine, host, scope, config, provenance) {
127
156
  const targetRoot = scope.target.path;
128
- const projects = readProjects(engine, host, scope, config, (_project, read) => read).answers;
157
+ const read = readProjects(engine, host, scope, config, (_project, projectRead) => projectRead);
158
+ const projects = read.answers;
129
159
  const configurations = [];
130
160
  const merged = new Map();
131
161
  for (const answer of projects) {
@@ -159,6 +189,8 @@ export function runRoots(engine, host, scope, config, provenance) {
159
189
  configurations,
160
190
  roots: ordered,
161
191
  findings: unmatchedRootFindings(unmatched, documentOf(host, provenance, ROOTS_SETTING, targetRoot)),
192
+ notBuilt: read.notBuilt,
193
+ unanswered: read.unanswered,
162
194
  };
163
195
  }
164
196
  /** The exemption classes this analyzer detects, each by its detector; any other retains nothing. */
@@ -201,10 +233,19 @@ function readRun(engine, host, scope, config, mode, detectors, extra) {
201
233
  mode,
202
234
  testFiles: new Set(resolved.testFilePaths),
203
235
  });
236
+ const unanswered = [
237
+ ...projectRead.held.unanswered,
238
+ ...projectRead.rooted.unanswered,
239
+ ...resolved.references
240
+ .filter((reference) => reference.resolution === "by-name")
241
+ .map((reference) => reference.to),
242
+ ...exempt.filter(isUnansweredRecord).map((record) => record.id),
243
+ ];
204
244
  return {
205
245
  configFile: projectRead.configFile,
206
246
  configured,
207
247
  exempt,
248
+ unanswered,
208
249
  extra: extra(project, projectRead, resolved.references),
209
250
  };
210
251
  });
@@ -221,17 +262,64 @@ function readRun(engine, host, scope, config, mode, detectors, extra) {
221
262
  return {
222
263
  matrix: matrixOf(projects.map((one) => one.configured)),
223
264
  exempt: exemptionsOf(projects.flatMap((one) => one.exempt)),
265
+ unansweredHeld: [
266
+ ...new Set([
267
+ ...read.answers.flatMap((one) => one.unanswered),
268
+ ...consumed.filter((one) => one.resolution === "by-name").map((one) => one.to),
269
+ ]),
270
+ ],
224
271
  projects,
225
272
  consumers: read.consumers.loaded,
273
+ notBuilt: read.notBuilt,
274
+ unanswered: read.unanswered,
226
275
  };
227
276
  }
228
- /** The sweep of a run read once, under one set of marks. */
277
+ /**
278
+ * The sweep of a run read once, under one set of marks. Where a question went unanswered,
279
+ * the run is swept once more without what that question could have kept live and without
280
+ * the references that stood in for its answer, and every declaration that sweep judges
281
+ * dead and this one judges live, or dead by another rule, is held by the gap too, as is
282
+ * every declaration that makes such a reference.
283
+ */
229
284
  function sweptOf(read, input) {
230
- const swept = { ...input, exempt: read.exempt };
285
+ const swept = { ...input, exempt: read.exempt, unanswered: read.unansweredHeld };
286
+ const result = sweepMatrix(read.matrix, swept);
287
+ const held = new Set(read.unansweredHeld);
288
+ if (held.size > 0) {
289
+ // What a declaration reads where the checker did not answer is unknown, so a rule
290
+ // over what it reads, the test of dead code among them, cannot judge it.
291
+ for (const { configured } of read.projects) {
292
+ for (const reference of configured.references) {
293
+ if (reference.resolution === "by-name") {
294
+ held.add(reference.from);
295
+ }
296
+ }
297
+ }
298
+ const dead = new Map(result.candidates.map((candidate) => [candidate.id, candidate]));
299
+ const answered = matrixOf(read.projects.map(({ configured }) => ({
300
+ ...configured,
301
+ references: configured.references.filter((one) => one.resolution !== "by-name"),
302
+ })));
303
+ const bare = {
304
+ ...swept,
305
+ exempt: read.exempt.filter((record) => !isUnansweredRecord(record)),
306
+ unanswered: [],
307
+ };
308
+ for (const candidate of sweepMatrix(answered, bare).candidates) {
309
+ const kept = dead.get(candidate.id);
310
+ if (kept?.testOfDeadCode !== candidate.testOfDeadCode ||
311
+ kept.relation !== candidate.relation) {
312
+ held.add(candidate.id);
313
+ }
314
+ }
315
+ }
231
316
  return {
232
317
  matrix: read.matrix,
233
- sweep: sweepMatrix(read.matrix, swept),
318
+ sweep: result,
234
319
  retained: retainedIn(read.matrix, swept),
320
+ notBuilt: read.notBuilt,
321
+ unanswered: read.unanswered,
322
+ heldByUnanswered: [...held],
235
323
  };
236
324
  }
237
325
  /**
@@ -250,8 +338,8 @@ export function runSweep(engine, host, scope, config, input, detectors = DETECTO
250
338
  /** Reads a run's projects with every per-project fact an emitter reads. */
251
339
  function readEmitterRun(engine, host, scope, config, mode, detectors) {
252
340
  const targetRoot = scope.target.path;
253
- return readRun(engine, host, scope, config, mode, detectors, (project, read, references) => ({
254
- deprecated: deprecatedDeclarations(project, read.held),
341
+ const run = readRun(engine, host, scope, config, mode, detectors, (project, read, references) => ({
342
+ deprecation: deprecatedDeclarations(project, read.held),
255
343
  accessors: accessorsOf(project, read.held),
256
344
  needs: projectNeeds(project, read.held, host),
257
345
  implementations: implementations(project, read.held),
@@ -261,6 +349,12 @@ function readEmitterRun(engine, host, scope, config, mode, detectors) {
261
349
  declarationsNamed: declarationsNamed(project, read.held, configuredDeclarations(config)),
262
350
  parts: projectParts(project, read.held, references, targetRoot),
263
351
  }));
352
+ // Whether a declaration carries the marker decides its code, so one whose marker went
353
+ // unread is reported by nothing.
354
+ const unread = run.projects.flatMap((one) => one.extra.deprecation.unanswered);
355
+ return unread.length === 0
356
+ ? run
357
+ : { ...run, unansweredHeld: [...new Set([...run.unansweredHeld, ...unread])] };
264
358
  }
265
359
  /**
266
360
  * The input every emitter reads over one sweep of a read run: the facts beside the sweep
@@ -273,7 +367,7 @@ function emitterInputOver(host, scope, config, read, input, selfCheck) {
273
367
  return {
274
368
  config,
275
369
  swept,
276
- deprecated: new Set(projects.flatMap((one) => one.extra.deprecated)),
370
+ deprecated: new Set(projects.flatMap((one) => one.extra.deprecation.deprecated)),
277
371
  stores: storesOf(projects.map((one) => ({
278
372
  references: one.configured.references,
279
373
  accessors: one.extra.accessors,
@@ -293,7 +387,7 @@ function emitterInputOver(host, scope, config, read, input, selfCheck) {
293
387
  edges: readEdgeSides(host, targetRoot),
294
388
  },
295
389
  selfCheck,
296
- intraFunction: intraFunctionFacts(projects.map((one) => one.extra.parts), projects.flatMap((one) => one.configured.references), new Set(read.exempt.map((one) => one.id))),
390
+ intraFunction: intraFunctionFacts(projects.map((one) => one.extra.parts), projects.flatMap((one) => one.configured.references), new Set([...read.exempt.map((one) => one.id), ...swept.heldByUnanswered])),
297
391
  };
298
392
  }
299
393
  /**
@@ -332,6 +426,8 @@ function readAnalysis(engine, host, scope, config, provenance, mode, detectors)
332
426
  })),
333
427
  testFileRules: testFileRulesOf(config.ts.testFiles, read.projects.flatMap((one) => one.configured.testFiles)),
334
428
  consumers: read.consumers,
429
+ notBuilt: read.notBuilt,
430
+ unanswered: read.unanswered,
335
431
  },
336
432
  configured: read.projects.map((one) => one.configured),
337
433
  symbols,