@cplieger/deadset-ts 7.2.0-dev.3 → 8.0.0-dev.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 (153) hide show
  1. package/dist/bin/mapper-connection.js +7 -4
  2. package/dist/src/analysis.js +116 -16
  3. package/dist/src/augmentations.js +21 -8
  4. package/dist/src/automatic-types.js +189 -0
  5. package/dist/src/base-url.js +18 -0
  6. package/dist/src/component-files.js +96 -31
  7. package/dist/src/components.js +7 -6
  8. package/dist/src/config.js +1 -0
  9. package/dist/src/configuration-files.js +54 -15
  10. package/dist/src/configured-declarations.js +24 -2
  11. package/dist/src/conformance-record.js +2 -2
  12. package/dist/src/contextual-uses.js +26 -26
  13. package/dist/src/convention-rows.js +75 -0
  14. package/dist/src/conventions.js +101 -5
  15. package/dist/src/decorator.js +21 -18
  16. package/dist/src/dependencies.js +185 -30
  17. package/dist/src/destructuring.js +77 -2
  18. package/dist/src/discover.js +188 -85
  19. package/dist/src/edges.js +1 -1
  20. package/dist/src/entry-point-gaps.js +7 -10
  21. package/dist/src/entry-points.js +112 -11
  22. package/dist/src/findings/completion.js +116 -21
  23. package/dist/src/findings/dependencies-and-module-machinery.js +71 -25
  24. package/dist/src/findings/emitters.js +1 -1
  25. package/dist/src/findings/intra-function.js +44 -13
  26. package/dist/src/findings/non-code-artifacts.js +66 -33
  27. package/dist/src/findings/unused-declarations.js +21 -1
  28. package/dist/src/findings/visibility-narrowing.js +22 -3
  29. package/dist/src/generated-file.js +11 -0
  30. package/dist/src/git-ignore.js +86 -0
  31. package/dist/src/graph.js +4 -1
  32. package/dist/src/import-bindings.js +97 -0
  33. package/dist/src/indexed-access.js +130 -28
  34. package/dist/src/interface-satisfaction.js +30 -12
  35. package/dist/src/intra-function-parts.js +313 -50
  36. package/dist/src/inventory.js +63 -8
  37. package/dist/src/json-document.js +5 -5
  38. package/dist/src/kinds.js +13 -13
  39. package/dist/src/matrix.js +18 -9
  40. package/dist/src/mdx-entries.js +197 -0
  41. package/dist/src/module-declarations.js +9 -13
  42. package/dist/src/namespace-objects.js +28 -18
  43. package/dist/src/overrides.js +45 -9
  44. package/dist/src/paths.js +9 -0
  45. package/dist/src/print.js +1 -0
  46. package/dist/src/ref.js +10 -0
  47. package/dist/src/references.js +29 -13
  48. package/dist/src/reflective-lookup.js +8 -6
  49. package/dist/src/report.js +4 -2
  50. package/dist/src/reporters/template.js +22 -13
  51. package/dist/src/resolve.js +2 -0
  52. package/dist/src/roots.js +110 -38
  53. package/dist/src/schema.js +1 -0
  54. package/dist/src/serialization-contract.js +97 -20
  55. package/dist/src/session.js +26 -1
  56. package/dist/src/source-files.js +39 -14
  57. package/dist/src/spelled-names.js +58 -0
  58. package/dist/src/suppress-file.js +12 -4
  59. package/dist/src/suppress-inline.js +21 -3
  60. package/dist/src/suppress.js +7 -5
  61. package/dist/src/sweep.js +27 -10
  62. package/dist/src/symbol-keys.js +103 -2
  63. package/dist/src/template-field.js +9 -6
  64. package/dist/src/test-support.js +121 -17
  65. package/dist/src/type-errors.js +116 -35
  66. package/dist/src/type-parameter-reads.js +172 -0
  67. package/dist/src/value-reach.js +17 -5
  68. package/dist/src/verbs/analyze.js +19 -1
  69. package/dist/src/verbs/explain.js +4 -2
  70. package/dist/src/version-range.js +10 -5
  71. package/dist/src/version.js +1 -1
  72. package/dist/src/workflow-steps.js +119 -22
  73. package/dist/src/workspace-programs.js +7 -3
  74. package/dist/src/workspace-resolution.js +72 -13
  75. package/dist/src/workspace.js +1 -1
  76. package/jsr.json +1 -1
  77. package/package.json +2 -2
  78. package/src/analysis.ts +175 -16
  79. package/src/augmentations.ts +21 -10
  80. package/src/automatic-types.ts +246 -0
  81. package/src/base-url.ts +24 -0
  82. package/src/component-files.ts +116 -31
  83. package/src/components.ts +7 -6
  84. package/src/config.ts +3 -0
  85. package/src/configuration-files.ts +80 -18
  86. package/src/configured-declarations.ts +33 -4
  87. package/src/conformance-record.ts +2 -2
  88. package/src/contextual-uses.ts +27 -27
  89. package/src/convention-rows.ts +103 -0
  90. package/src/conventions.ts +121 -7
  91. package/src/decorator.ts +28 -18
  92. package/src/dependencies.ts +249 -43
  93. package/src/destructuring.ts +93 -2
  94. package/src/discover.ts +234 -86
  95. package/src/edges.ts +1 -1
  96. package/src/entry-point-gaps.ts +8 -11
  97. package/src/entry-points.ts +133 -11
  98. package/src/finding.ts +10 -0
  99. package/src/findings/completion.ts +147 -24
  100. package/src/findings/dependencies-and-module-machinery.ts +90 -28
  101. package/src/findings/emitters.ts +1 -1
  102. package/src/findings/intra-function.ts +56 -14
  103. package/src/findings/non-code-artifacts.ts +81 -41
  104. package/src/findings/unused-declarations.ts +25 -1
  105. package/src/findings/visibility-narrowing.ts +32 -3
  106. package/src/generated-file.ts +16 -0
  107. package/src/git-ignore.ts +98 -0
  108. package/src/graph.ts +6 -0
  109. package/src/host.ts +5 -9
  110. package/src/import-bindings.ts +128 -0
  111. package/src/indexed-access.ts +152 -30
  112. package/src/interface-satisfaction.ts +33 -13
  113. package/src/intra-function-parts.ts +415 -64
  114. package/src/inventory.ts +83 -7
  115. package/src/json-document.ts +7 -7
  116. package/src/kinds.ts +13 -13
  117. package/src/matrix.ts +32 -14
  118. package/src/mdx-entries.ts +241 -0
  119. package/src/module-declarations.ts +11 -13
  120. package/src/namespace-objects.ts +34 -21
  121. package/src/overrides.ts +56 -9
  122. package/src/paths.ts +10 -0
  123. package/src/print.ts +1 -0
  124. package/src/ref.ts +12 -0
  125. package/src/references.ts +38 -17
  126. package/src/reflective-lookup.ts +9 -7
  127. package/src/report.ts +16 -3
  128. package/src/reporters/template.ts +21 -13
  129. package/src/resolve.ts +3 -0
  130. package/src/roots.ts +163 -45
  131. package/src/schema.ts +1 -0
  132. package/src/serialization-contract.ts +108 -17
  133. package/src/session.ts +29 -1
  134. package/src/source-files.ts +66 -16
  135. package/src/spelled-names.ts +102 -0
  136. package/src/suppress-file.ts +14 -3
  137. package/src/suppress-inline.ts +21 -2
  138. package/src/suppress.ts +9 -5
  139. package/src/sweep.ts +32 -11
  140. package/src/symbol-keys.ts +129 -2
  141. package/src/template-field.ts +9 -6
  142. package/src/test-support.ts +149 -16
  143. package/src/type-errors.ts +132 -41
  144. package/src/type-parameter-reads.ts +227 -0
  145. package/src/value-reach.ts +19 -6
  146. package/src/verbs/analyze.ts +28 -1
  147. package/src/verbs/explain.ts +5 -2
  148. package/src/version-range.ts +10 -5
  149. package/src/version.ts +1 -1
  150. package/src/workflow-steps.ts +127 -22
  151. package/src/workspace-programs.ts +7 -3
  152. package/src/workspace-resolution.ts +86 -14
  153. package/src/workspace.ts +1 -1
@@ -1,4 +1,4 @@
1
- import { isClassDeclaration, isComputedPropertyName, isConstructorDeclaration, isEnumDeclaration, isEnumMember, isExportAssignment, isExportDeclaration, isFunctionDeclaration, isGetAccessorDeclaration, isIdentifier, isInterfaceDeclaration, isIntersectionTypeNode, isMethodDeclaration, isMethodSignatureDeclaration, isModuleBlock, isModuleDeclaration, isNamespaceExport, isParameterDeclaration, isParenthesizedTypeNode, isPrivateIdentifier, isPropertyDeclaration, isPropertySignatureDeclaration, isSetAccessorDeclaration, isStringLiteral, isTypeAliasDeclaration, isTypeLiteralNode, isUnionTypeNode, isVariableStatement, ModifierFlags, } from "@typescript/native/ast";
1
+ import { isArrayBindingPattern, isBindingElement, isClassDeclaration, isComputedPropertyName, isConstructorDeclaration, isEnumDeclaration, isEnumMember, isExportAssignment, isExportDeclaration, isFunctionDeclaration, isGetAccessorDeclaration, isIdentifier, isInterfaceDeclaration, isIntersectionTypeNode, isMethodDeclaration, isMethodSignatureDeclaration, isModuleBlock, isModuleDeclaration, isNamespaceExport, isObjectBindingPattern, isParameterDeclaration, isParenthesizedTypeNode, isPrivateIdentifier, isPropertyDeclaration, isPropertySignatureDeclaration, isSetAccessorDeclaration, isStringLiteral, isTypeAliasDeclaration, isTypeLiteralNode, isUnionTypeNode, isVariableStatement, ModifierFlags, } from "@typescript/native/ast";
2
2
  import { dirnamePath, joinPath, relativePath } from "./paths.js";
3
3
  import { byPosition, positionKey, renderPosition, writtenLength, } from "./position.js";
4
4
  import { computedComponent, nameComponent, renderRef } from "./ref.js";
@@ -65,6 +65,18 @@ function parentOf(path) {
65
65
  function modifiersOf(node) {
66
66
  return node.modifierFlags ?? 0;
67
67
  }
68
+ /** Whether a declaration is ambient: in a declaration file, or under a `declare` modifier. */
69
+ function isAmbient(file, node) {
70
+ if (file.isDeclarationFile) {
71
+ return true;
72
+ }
73
+ for (let at = node; at !== undefined; at = at.parent) {
74
+ if ((modifiersOf(at) & ModifierFlags.Ambient) !== 0) {
75
+ return true;
76
+ }
77
+ }
78
+ return false;
79
+ }
68
80
  /** The type parameters one node declares, and none for a node that declares none. */
69
81
  function typeParametersOf(node) {
70
82
  if (isFunctionDeclaration(node) ||
@@ -200,10 +212,46 @@ function visibilityOf(node, name) {
200
212
  }
201
213
  return "public";
202
214
  }
215
+ /**
216
+ * The binding elements of a destructuring declaration that each declare a name of their
217
+ * own, at any depth, but one with a default, whose removal skips the default's
218
+ * evaluation, and one beside a rest element of its object pattern, whose removal
219
+ * changes what the rest holds.
220
+ */
221
+ function patternElements(name) {
222
+ if (!isObjectBindingPattern(name) && !isArrayBindingPattern(name)) {
223
+ return [];
224
+ }
225
+ const rest = isObjectBindingPattern(name) &&
226
+ name.elements.some((element) => element.dotDotDotToken !== undefined);
227
+ return name.elements.flatMap((element) => {
228
+ if (!isBindingElement(element) ||
229
+ element.initializer !== undefined ||
230
+ (rest && element.dotDotDotToken === undefined)) {
231
+ return [];
232
+ }
233
+ const bound = element.name;
234
+ if (bound === undefined) {
235
+ return [];
236
+ }
237
+ return isIdentifier(bound) ? [{ element, name: bound }] : patternElements(bound);
238
+ });
239
+ }
203
240
  /** The name node of one declaration, for the kinds that carry one. */
204
241
  function nameNodeOf(node) {
205
242
  return node.name;
206
243
  }
244
+ /**
245
+ * The fragment component one declaration's name spells in a reference, as the inventory
246
+ * spells it, or undefined for a name the grammar does not represent.
247
+ */
248
+ export function declaredComponent(node) {
249
+ const component = componentOf(nameNodeOf(node));
250
+ if (component === undefined) {
251
+ return undefined;
252
+ }
253
+ return component.computed ? computedComponent(component.text) : nameComponent(component.text);
254
+ }
207
255
  /**
208
256
  * One node's identity inside one program, which is how two readings of that program
209
257
  * name one declaration.
@@ -480,15 +528,19 @@ export function inventory(project, host, targetRoot) {
480
528
  if (isVariableStatement(node)) {
481
529
  for (const declaration of node.declarationList.declarations) {
482
530
  const component = componentOf(declaration.name);
483
- if (component === undefined) {
484
- // A destructuring pattern declares binding elements, which the reference
485
- // grammar does not represent; the statement stands for them.
531
+ if (component !== undefined) {
532
+ declare(declaration, owner, "variable", declaration.name, {
533
+ component,
534
+ localName: undefined,
535
+ });
486
536
  continue;
487
537
  }
488
- declare(declaration, owner, "variable", declaration.name, {
489
- component,
490
- localName: undefined,
491
- });
538
+ for (const { element, name } of patternElements(declaration.name)) {
539
+ declare(element, owner, "variable", name, {
540
+ component: { text: name.text, computed: false },
541
+ localName: undefined,
542
+ });
543
+ }
492
544
  }
493
545
  return;
494
546
  }
@@ -743,6 +795,9 @@ export function inventory(project, host, targetRoot) {
743
795
  .map((symbol) => symbol.id),
744
796
  byName: namesOf(building),
745
797
  modules: new Map(modules.map(([record, name]) => [positionKey(record.position), name])),
798
+ ambient: new Set(building
799
+ .filter((record) => isAmbient(record.file, record.node))
800
+ .map((record) => positionKey(record.position))),
746
801
  dependents,
747
802
  };
748
803
  }
@@ -4,7 +4,7 @@
4
4
  */
5
5
  /** The token walk over a document `JSON.parse` accepted, so every token is well formed. */
6
6
  class Walk {
7
- opened = [];
7
+ starts = [];
8
8
  /** The member written twice, where one is, as the offset of its name. */
9
9
  twice;
10
10
  text;
@@ -33,11 +33,11 @@ class Walk {
33
33
  }
34
34
  value(role) {
35
35
  this.skip();
36
+ if (role === "record") {
37
+ this.starts.push(this.at);
38
+ }
36
39
  const char = this.text[this.at];
37
40
  if (char === "{") {
38
- if (role === "record") {
39
- this.opened.push(this.at);
40
- }
41
41
  this.object(role);
42
42
  }
43
43
  else if (char === "[") {
@@ -100,7 +100,7 @@ class Walk {
100
100
  export function walkDocument(text, array) {
101
101
  const walk = new Walk(text, array);
102
102
  walk.run();
103
- return { opened: walk.opened, twice: walk.twice };
103
+ return { starts: walk.starts, twice: walk.twice };
104
104
  }
105
105
  /**
106
106
  * One offset of a document as a finding carries it: the line counted from one, and the
package/dist/src/kinds.js CHANGED
@@ -20,7 +20,7 @@ const ROWS = [
20
20
  code: "DS1002",
21
21
  name: "unused-unexported",
22
22
  languages: ["go", "ts"],
23
- rule: "An unexported symbol with no reference in the target. A symbol referenced only from its own declaration site counts as unreferenced.",
23
+ rule: "An unexported symbol with no reference in the target. A symbol referenced only from its own declaration site counts as unreferenced. In TypeScript a name an import declaration binds, or an `import x = require()` declaration that is not exported, is such a symbol of its file, reported at the binding when nothing in the file reads it: a use in a type position, in a local export or in a type, a link or a `@see` tag of a doc comment reads it, and so does JSX the compiler turns into calls of a factory it names. A binding of a declaration file or of a component file is not judged, nor one of a generated file while generated files are excluded. In Go a constant or a type a function body declares, a function literal's body included, that nothing in that body names outside its own specification is reported under this code, under the reference of the enclosing declaration, as `grammar/symbol-ref.md` states for a declaration inside a function body, at the local declaration's own position, with `symbol.kind` `constant` or `type` and the liveness relation `reference-counting`.",
24
24
  defaultSeverity: "deny",
25
25
  maxClass: "certain",
26
26
  fixability: "deletable",
@@ -43,7 +43,7 @@ const ROWS = [
43
43
  code: "DS1004",
44
44
  name: "test-only-use",
45
45
  languages: ["go", "ts"],
46
- rule: "A symbol with zero production references and at least one test reference: an unused-exported, unused-unexported or unused-member candidate whose test reference count is not zero, reported once under this code. A reference from a consumer's test files is a test reference unless the configuration counts consumer tests as production. A reference from test-support code, a package or file that only tests reach, is a test reference. A declaration of test-support code that test code references is reported under this code at the reachability class possible, as grammar/analysis.md states. Such a declaration that is an interface is reported under DS1201 instead.",
46
+ rule: "A symbol with zero production references and at least one test reference: an unused-exported, unused-unexported or unused-member candidate whose test reference count is not zero, reported once under this code. A reference from a consumer's test files is a test reference unless the configuration counts consumer tests as production. A reference from test-support code, a package or file that only tests reach and that carries test evidence of its own language, is a test reference. A declaration of test-support code is test code and is no subject of this code, as grammar/analysis.md states. An interface method whose only calls and selections through the interface are in test code, and that DS1203's precondition does not exempt, is reported under this code. The methods implementing it are not reported with it, because the test reaches them through it.",
47
47
  defaultSeverity: "deny",
48
48
  maxClass: "certain",
49
49
  fixability: "deletable",
@@ -54,7 +54,7 @@ const ROWS = [
54
54
  code: "DS1005",
55
55
  name: "test-of-dead-code",
56
56
  languages: ["go", "ts"],
57
- rule: "A test symbol whose set of referenced target symbols is non-empty and every member of that set is reported dead. A test that references at least one live target symbol is never reported, no notion of a test's subject and no name matching enters the rule, and the message states the rule. The test joins the dead component of the symbols it references, and it and each of them count as referencing each other, so the test is a member of their cycle and never a dead symbol outside it.",
57
+ rule: "A test symbol whose set of referenced target symbols is non-empty and every member of that set is reported dead. In TypeScript an ambient declaration, one a declaration file holds or one a `declare` modifier carries or a declaration carrying one holds, describes code the target does not implement, so it is no target symbol of that set. A test that references at least one live target symbol is never reported, no notion of a test's subject and no name matching enters the rule, and the message states the rule. The test joins the dead component of the symbols it references, and it and each of them count as referencing each other, so the test is a member of their cycle and never a dead symbol outside it.",
58
58
  defaultSeverity: "deny",
59
59
  maxClass: "certain",
60
60
  fixability: "deletable",
@@ -110,7 +110,7 @@ const ROWS = [
110
110
  name: "redundant-export-keyword",
111
111
  languages: ["ts"],
112
112
  rule: "An exported declaration used only inside its own file, reported as a candidate for removing the export keyword. The finding names the narrower visibility the references support.",
113
- precondition: "Closed world only. Reported in a file that is not an entry file and that either belongs to a project whose consumer set the configuration declares complete or is reached by no manifest export. A declared cross-language edge counts as a reference from outside the file. Where the edge's other side is unknown to the analyzer, the finding is emitted pending. A symbol the rule of DS1301 holds for is not reported under this code, whatever severity the configuration gives DS1301, because the write-only finding names the defect to fix first.",
113
+ precondition: 'Closed world only. Reported in a file that is not an entry file, a file only a configuration string or a script token names being none, because each runs the file and reads no name it exports, and a test file being one only for the exports its test runner calls, as grammar/analysis.md "Test code" states, and that either belongs to a project whose consumer set the configuration declares complete or is reached by no manifest export. A declared cross-language edge counts as a reference from outside the file. Where the edge\'s other side is unknown to the analyzer, the finding is emitted pending. A symbol the rule of DS1301 holds for is not reported under this code, whatever severity the configuration gives DS1301, because the write-only finding names the defect to fix first.',
114
114
  defaultSeverity: "warn",
115
115
  maxClass: "certain",
116
116
  fixability: "narrowable",
@@ -131,8 +131,8 @@ const ROWS = [
131
131
  code: "DS1203",
132
132
  name: "uncalled-interface-method",
133
133
  languages: ["go", "ts"],
134
- rule: "An interface method that no call site invokes or selects through the interface, whatever the number of implementations. The finding names the concrete implementations and their positions. Each method that implements it and that nothing else keeps is reported under the code its own references select. Such a method counts as referenced by the interface method alone, so it belongs to this finding's dead component, whose root member is the interface method.",
135
- precondition: "In Go, every method of an interface that declares an unexported method is exempt. That is the sum-type shape, whose method set exists to restrict the implementors, and a TypeScript interface cannot take it because it declares no member less visible than itself. In both languages, every marker method is exempt, an interface method whose every implementation carries an empty body.",
134
+ rule: "An interface method that no call site invokes or selects through the interface, whatever the number of implementations. A call or selection in test code is no call for this rule, and an interface method only test code calls is DS1004's. The finding names the concrete implementations and their positions. Each method that implements it and that nothing else keeps is reported under the code its own references select. Such a method counts as referenced by the interface method alone, so it belongs to this finding's dead component, whose root member is the interface method.",
135
+ precondition: "In Go, every method of an exported interface whose method set holds an unexported method is exempt, a method of an interface it embeds included. An unexported interface restricts no implementor outside its package, so a method only it holds is judged. That is the sum-type shape, whose method set exists to restrict the implementors, and a TypeScript interface cannot take it because it declares no member less visible than itself. In both languages, every marker method is exempt, an interface method whose every implementation carries an empty body.",
136
136
  defaultSeverity: "warn",
137
137
  maxClass: "certain",
138
138
  fixability: "manual",
@@ -143,7 +143,7 @@ const ROWS = [
143
143
  name: "unused-satisfaction-assertion",
144
144
  languages: ["go"],
145
145
  rule: "A compile-time satisfaction assertion whose interface no symbol uses as a type.",
146
- precondition: "In a library, an assertion whose interface is published API, an exported interface of a package outside programs can import, has the reachability class possible, whatever consumers the run declares and loads. The assertion checks a promise the published API makes, that the type satisfies the published interface, and that promise is made to every program that imports the package, not only to the consumers the run declares. A loaded consumer that names the interface as a type uses it, and the assertion is not reported.",
146
+ precondition: "In a library, an assertion whose interface and whose concrete type are both published API, each an exported declaration of a package outside programs can import, is not reported: it states to every importer a promise of the published API. An assertion whose interface alone is published API has the reachability class possible, whatever consumers the run declares and loads. The assertion checks a promise the published API makes, that the type satisfies the published interface, and that promise is made to every program that imports the package, not only to the consumers the run declares. A loaded consumer that names the interface as a type uses it, and the assertion is not reported.",
147
147
  defaultSeverity: "deny",
148
148
  maxClass: "certain",
149
149
  fixability: "deletable",
@@ -153,7 +153,7 @@ const ROWS = [
153
153
  code: "DS1301",
154
154
  name: "write-only-symbol",
155
155
  languages: ["go", "ts"],
156
- rule: "A package-level or module-level variable, struct field, class member, type member or collection that production code writes and never reads. In production mode a read from a test file counts as no read. A write from a loaded consumer's code counts as a read, because the deletion the finding names would break a consumer the target does not own. A write in a consumer's test file counts as a read in the run that counts test references. It counts in a production sweep only where the configuration counts consumer tests as production. A comparison of struct values reads every field of the type: in Go, a value of a struct type used as an operand of `==` or `!=`, as a map key, or as a `switch` tag or `case` expression is a read of every field of that type, transitively through the fields of every struct type it holds, recorded at the comparison, because equality reads every field and a field that decides equality carries information. In Go a type argument the program instantiates a type parameter with, where the parameter's constraint is `comparable` or embeds it, is compared as an operand of `==` of that type is, recorded at the instantiation, so the struct values `slices.Equal`, `slices.Index` or `maps.Equal` compares have every field read. `reflect.DeepEqual` is not a comparison under this rule. In Go, a conversion the compiler accepts between two struct types, or between two pointer types that are not named types and whose base types are struct types, reads every field of the two struct types where their struct type literals are distinct, recorded at the conversion, because the conversion is legal only while their fields are identical, ignoring tags, and so no field of either can be deleted alone. It reads in the same way every field of each pair of distinct struct type literals the identity of the two types compares in turn: through each field's type, and from there through the element, key, base, parameter and result types of the type literals it reaches, through the method signatures of an interface type literal, and through the type arguments of an instantiated generic type. A field reached there has no reference of its own, as grammar/symbol-ref.md states, so it is never a subject and those reads hold no finding back. It stops at a defined type, whose fields the conversion does not read, because a defined type is identical to itself whatever fields it declares. A pair whose two sides are one struct type literal, the two struct types themselves included, as where one type is declared from the other or the conversion is to the operand's own type, reads nothing, because a field deleted from that literal leaves both sides identical. Where the operand's type or the conversion's type is a type parameter, the struct type its constraint's core type is takes that side's place, and a type parameter operand reads in the same way the fields of each struct type argument an instantiation the program holds gives it, an instantiation made through another generic declaration's own type parameters included. A conversion to any other type, an interface type among them, reads no field under this rule. In TypeScript a comparison of two object references reads no member, because `===` compares identity and never a member. A TypeScript parameter property, a constructor parameter that carries a modifier, declares a member of its class that the constructor writes with its argument, so the member is judged under this rule, and under every rule that reads a class member, as a member the class body declares is. In TypeScript a property of an object literal writes the member of the same name that the literal's contextual type declares, whether or not the compiler checks the literal for excess properties. Where that contextual type is a union or an intersection, the property writes the member of that name on each constituent that declares one. So a literal that a declaration annotates, a function returns, a call passes or a `satisfies` expression checks writes the members of the type it is given. An object literal handed to a callee the target does not implement has its members read, as grammar/analysis.md states. A store through the value a field or a member holds reads that field or member rather than writing it, because the store lands in storage every other holder of the value reads. In Go that store is an assignment, an increment, a compound assignment or a `delete` whose target is reached through a struct field holding a map, a slice or a pointer. Examples are `s.f[k] = v`, `s.f.x = v` and `delete(s.f, k)`. The same store through a field holding an array or a struct is a store into the field itself. TypeScript holds every object by reference, so an element or property store through a member's value reads the member. The finding names each write position, so the deletion set is visible. Deleting the subject and its writes also deletes every declaration whose only uses they hold. Such a declaration is a type parameter of the subject's declaring type that the subject's type alone names, an import binding the writes alone use, or a declaration whose every use is in the type annotation of the subject or of another subject this rule reports, or in the writes those findings name. The finding's message names each such declaration, and no finding is reported about the declaration itself.",
156
+ rule: "A package-level or module-level variable, struct field, class member, type member or collection that production code writes and never reads. In production mode a read from a test file counts as no read. A write from a loaded consumer's code counts as a read, because the deletion the finding names would break a consumer the target does not own. A write in a consumer's test file counts as a read in the run that counts test references. It counts in a production sweep only where the configuration counts consumer tests as production. In Go a read counts only from a declaration that is live under the finding's liveness relation, which is reference counting: a read from a declaration nothing references, whose own finding has the reachability class `certain`, is no read, so a declaration that only such declarations read is reported where a declaration something references writes it. A comparison of struct values reads every field of the type: in Go, a value of a struct type used as an operand of `==` or `!=`, as a map key, or as a `switch` tag or `case` expression is a read of every field of that type, transitively through the fields of every struct type it holds, recorded at the comparison, because equality reads every field and a field that decides equality carries information. In Go a type argument the program instantiates a type parameter with, where the parameter's constraint is `comparable` or embeds it, is compared as an operand of `==` of that type is, recorded at the instantiation, so the struct values `slices.Equal`, `slices.Index` or `maps.Equal` compares have every field read. `reflect.DeepEqual` is not a comparison under this rule. In Go, a conversion the compiler accepts between two struct types, or between two pointer types that are not named types and whose base types are struct types, reads every field of the two struct types where their struct type literals are distinct, recorded at the conversion, because the conversion is legal only while their fields are identical, ignoring tags, and so no field of either can be deleted alone. It reads in the same way every field of each pair of distinct struct type literals the identity of the two types compares in turn: through each field's type, and from there through the element, key, base, parameter and result types of the type literals it reaches, through the method signatures of an interface type literal, and through the type arguments of an instantiated generic type. A field reached there has no reference of its own, as grammar/symbol-ref.md states, so it is never a subject and those reads hold no finding back. It stops at a defined type, whose fields the conversion does not read, because a defined type is identical to itself whatever fields it declares. A pair whose two sides are one struct type literal, the two struct types themselves included, as where one type is declared from the other or the conversion is to the operand's own type, reads nothing, because a field deleted from that literal leaves both sides identical. Where the operand's type or the conversion's type is a type parameter, the struct type its constraint's core type is takes that side's place, and a type parameter operand reads in the same way the fields of each struct type argument an instantiation the program holds gives it, an instantiation made through another generic declaration's own type parameters included. A conversion to any other type, an interface type among them, reads no field under this rule. In TypeScript a comparison of two object references reads no member, because `===` compares identity and never a member. A TypeScript parameter property, a constructor parameter that carries a modifier, declares a member of its class that the constructor writes with its argument, so the member is judged under this rule, and under every rule that reads a class member, as a member the class body declares is. In TypeScript a property of an object literal writes the member of the same name that the literal's contextual type declares, whether or not the compiler checks the literal for excess properties. Where that contextual type is a union or an intersection, the property writes the member of that name on each constituent that declares one. So a literal that a declaration annotates, a function returns, a call passes or a `satisfies` expression checks writes the members of the type it is given. An object literal handed to a callee the target does not implement has its members read, as grammar/analysis.md states. A store through the value a field or a member holds reads that field or member rather than writing it, because the store lands in storage every other holder of the value reads. In Go that store is an assignment, an increment, a compound assignment or a `delete` whose target is reached through a struct field holding a map, a slice or a pointer. Examples are `s.f[k] = v`, `s.f.x = v` and `delete(s.f, k)`. The same store through a field holding an array or a struct is a store into the field itself. TypeScript holds every object by reference, so an element or property store through a member's value reads the member. The finding names each write position, so the deletion set is visible. Deleting the subject and its writes also deletes every declaration whose only uses they hold. Such a declaration is a type parameter of the subject's declaring type that the subject's type alone names, an import binding the writes alone use, or a declaration whose every use is in the type annotation of the subject or of another subject this rule reports, or in the writes those findings name. The finding's message names each such declaration, and no finding is reported about the declaration itself.",
157
157
  defaultSeverity: "deny",
158
158
  maxClass: "certain",
159
159
  fixability: "deletable",
@@ -196,7 +196,7 @@ const ROWS = [
196
196
  code: "DS1502",
197
197
  name: "file-never-imported",
198
198
  languages: ["go", "ts"],
199
- rule: "A source file that no import reaches, that no root names, and in which no declared cross-language edge names a declaration. An import written in a loaded consumer reaches a file of the target as an import written in the target does. An edge's side names a declaration as a root names one, so a file holding a declaration an edge names is evaluated with the edge rather than reported: whether that declaration is dead is the edge evaluation's to say, and the merge resolves it against the paired side.",
199
+ rule: "A source file that no import from live code reaches, that no root names, and in which no declared cross-language edge names a declaration: an import counts where it is written in a file a root, a live declaration or such an import keeps, or in a live declaration, so a file only dead code imports is reported, under reachability. An import written in a loaded consumer reaches a file of the target as an import written in the target does. An edge's side names a declaration as a root names one, so a file holding a declaration an edge names is evaluated with the edge rather than reported: whether that declaration is dead is the edge evaluation's to say, and the merge resolves it against the paired side.",
200
200
  defaultSeverity: "deny",
201
201
  maxClass: "certain",
202
202
  fixability: "deletable",
@@ -206,8 +206,8 @@ const ROWS = [
206
206
  code: "DS1601",
207
207
  name: "unused-dependency",
208
208
  languages: ["go", "ts"],
209
- rule: "A directly declared dependency that no import in the target needs. On the Go side, a direct require whose module provides no package any target package or test variant imports. On the TypeScript side, a manifest dependency, development dependency or peer dependency the project's import closure does not need. A deletion finding whose fix would remove the last use of a dependency names that dependency.",
210
- precondition: "On the Go side the rule is the semantics of `go mod tidy -diff` exactly: a requirement marked indirect is never reported, because it exists to pin a transitive version and removing it changes the build list. On the TypeScript side the import closure is the files of the run's projects, and a call of `import.meta.resolve` or of `require.resolve` in them, whatever `require` names, whose first argument is a string literal or a template literal with no substitution needs each dependency an import of that specifier needs. Four more dependencies are needed: one whose command a script entry or a workflow step runs, one that a string of a configuration file names, and one that a string names under a manifest key or a package key of an applied convention row, each as grammar/analysis.md states, and one that a needed dependency names as a peer, as stated below. A command no script entry and no workflow step runs needs nothing. A declared dependency that the installed manifest of a needed declared dependency names in its peerDependencies is needed, and so on until no further dependency joins. A peer dependency is a package the needed dependency expects beside it at a version its manifest states, whether or not it imports the package, and the project's declaration is what keeps that package present at a version the project chooses, so removing the declaration can break the needed dependency where nothing the analysis reads imports the peer. A peer that peerDependenciesMeta marks optional is needed in the same way, because the needed dependency's manifest still names it as a package it works with, and a package manager may leave an optional peer out where the project does not declare it, so the project's declaration is what keeps it present for the needed dependency. A declared dependency that only dependencies nothing needs name as a peer is needed by nothing. A dependency of a manifest whose directory holds source only in configurations the run lists in configurations_not_built is reported at the reachability class possible, because the source that may import it was not analyzed. An installed manifest is the package's manifest in the nearest node_modules directory at or above the directory of the manifest that declares the dependency, and a dependency with none is decided by the import closure alone. On the TypeScript side, the dependencies judged are those of every manifest grammar/analysis.md says the analysis reads, a nested package's among them, each read against its own directory: a dependency is needed by a use written in a file at or below the directory of the manifest that declares it, by a use no one file holds, and as a peer of a needed dependency of the same manifest or of a manifest below it. A dependency a nested package's manifest declares whose installed manifest the analysis cannot find is not judged, because no run requires a nested package to be installed and its commands and peers cannot be read, while a workspace member's and the target's own are judged as above.",
209
+ rule: "A directly declared dependency that no import in the target needs. On the Go side, a direct require whose module provides no package any target package or test variant imports. On the TypeScript side, a manifest dependency, development dependency or peer dependency the project's import closure does not need. A deletion finding whose fix would remove the last use of a dependency names that dependency. On the TypeScript side, a needed dependency whose every use is written inside declarations that are members of the run's dead components, or at the top level of a file reported under DS1502, that no command runs and that no needed dependency used otherwise names as a peer, is reported as well, dead only through that code: at the reachability class possible where one of those declarations belongs to a library's published API, and found under reachability alone where one of those declarations or files is, so at probable unless ts.roots_complete is true. A use the configuration makes, a use an unanswered specifier may make and an import none of whose bindings is used are uses by live code.",
210
+ precondition: "On the Go side the rule is the semantics of `go mod tidy -diff` exactly: a requirement marked indirect is never reported, because it exists to pin a transitive version and removing it changes the build list. On the TypeScript side the import closure is the files of the run's projects, and a call of `import.meta.resolve` or of `require.resolve` in them, whatever `require` names, whose first argument is a string literal or a template literal with no substitution needs each dependency an import of that specifier needs. A `@types/<name>` package in a type root of a compiler configuration that lists no `types`, a `node_modules/@types` directory at or above the configuration's directory or a `typeRoots` entry naming one, is needed by a use, in a file of that configuration, of a global name or an ambient module that one of the package's declaration files declares, which resolves to no declaration of the program: a compiler before version 6 includes every package of the type roots where `types` is not listed, and version 6 and later include none, so the program the analysis builds holds none of those declarations. A package's declaration files are the file its `types` or `typings` names, else its `index.d.ts`, and each file a `/// <reference path>` of one of them reaches inside the package. A global is a top-level declaration of such a file that is no module, or a declaration of a `declare global` block of one that is, and an ambient module is a `declare module` with a string name of a file that is no module. A name that names a member, a property or a label is no use of a global. Four more dependencies are needed: one whose command a script entry, a workflow step or a git hook runs, one that a string of a configuration file names, and one that a string names under a manifest key or a package key of an applied convention row, each as grammar/analysis.md states, and one that a needed dependency names as a peer, as stated below. A command no script entry, workflow step or git hook runs needs nothing. A declared dependency that the installed manifest of a needed declared dependency names in its peerDependencies is needed, and so on until no further dependency joins. A peer dependency is a package the needed dependency expects beside it at a version its manifest states, whether or not it imports the package, and the project's declaration is what keeps that package present at a version the project chooses, so removing the declaration can break the needed dependency where nothing the analysis reads imports the peer. A peer that peerDependenciesMeta marks optional is needed in the same way, because the needed dependency's manifest still names it as a package it works with, and a package manager may leave an optional peer out where the project does not declare it, so the project's declaration is what keeps it present for the needed dependency. A declared dependency that only dependencies nothing needs name as a peer is needed by nothing. A dependency of a manifest whose directory holds source only in configurations the run lists in configurations_not_built is reported at the reachability class possible, because the source that may import it was not analyzed. An installed manifest is the package's manifest in the nearest node_modules directory at or above the directory of the manifest that declares the dependency, and a dependency with none is decided by the import closure alone. On the TypeScript side, the dependencies judged are those of every manifest grammar/analysis.md says the analysis reads, a nested package's among them, each read against its own directory: a dependency is needed by a use written in a file at or below the directory of the manifest that declares it where no manifest between them declares a dependency of the same name, so a use below a nested manifest that declares the same dependency needs that nested manifest's declaration only, by a use no one file holds, and as a peer of a needed dependency of the same manifest or of a manifest below it. A dependency a nested package's manifest declares whose installed manifest the analysis cannot find is not judged, because no run requires a nested package to be installed and its commands and peers cannot be read, while a workspace member's and the target's own are judged as above.",
211
211
  defaultSeverity: "deny",
212
212
  maxClass: "certain",
213
213
  fixability: "manual",
@@ -289,7 +289,7 @@ const ROWS = [
289
289
  name: "unused-parameter",
290
290
  languages: ["go", "ts"],
291
291
  rule: "A parameter with no reference inside its function body, on a function whose signature is free to change.",
292
- precondition: "The signature must be free, defined as follows: the function is not a method retained by interface satisfaction, is not a method whose name and signature are those of a method of an exported interface type declared by a package outside the target that the import closure holds, is not used as a value, is not a go:linkname or cgo target, is not a function the Go test driver runs (a test, benchmark or fuzz test of a test file, or TestMain), and is not a stub whose body is empty or only panics. A function literal or function expression that initializes a variable the program only calls, never passing, storing, returning or assigning it, is called by name and is not used as a value. A parameter its body never names is dead whatever the callers, so a published declaration of a library is reported too, with the fixability the vocabulary gives the kind: the signature change is a breaking change. In TypeScript a caller may pass a function used as a value more arguments than it declares parameters, so in such a function whose signature is free but for that use, a parameter its body never reads is reported when its body reads no parameter after it, and an unread parameter before the last read one is not. A parameter of a TypeScript function expression or arrow function that the compiler gives a contextual type is not reported when it carries a type annotation, because the inference of the call that holds the function may read the annotation, or when it is an object binding pattern, because the pattern reads each property it names from the argument and the code that hands the argument may act on that read. No name such a pattern binds is reported either. Any other TypeScript parameter that is a binding pattern is judged by the names it binds: each name the body never reads is reported wherever the pattern stands, because removing it from the pattern moves no argument, except a name beside a rest element of the same object pattern, whose removal changes what that element holds, and the pattern counts as a read parameter when the body reads any name it binds. A rest parameter is judged as the last parameter. A TypeScript `this` parameter declares the type of `this` and receives no argument, so it is never reported. A TypeScript constructor is used as a value where its class is used as a value other than as the callee of a `new` expression or the class an `extends` clause names, and its signature is not free where its class carries a decorator or a parameter of the constructor carries one, because the code that decorator or a container runs may construct the class. A parameter property is read by the write to its member the constructor makes, so it is never reported under this kind, and its member is judged under DS1301. No name exempts a parameter. A TypeScript parameter whose name starts with an underscore is judged as any other is, and a Go parameter named by the blank identifier declares no name a body could read and is never reported.",
292
+ precondition: "The signature must be free, defined as follows: the function is not a method retained by interface satisfaction, is not a method whose name and signature are those of a method of an exported interface type declared by a package outside the target that the import closure holds, is not used as a value, is not a go:linkname or cgo target, is not a go-fuzz entry point, is not a function the Go test driver runs (a test, benchmark or fuzz test of a test file, or TestMain), and is not a stub whose body is empty or only panics. A function literal or function expression that initializes a variable the program only calls, never passing, storing, returning or assigning it, is called by name and is not used as a value. In Go a function literal that is the callee of the call it is written in, the call of a `go` or a `defer` statement included, is not used as a value, wherever the literal is written. A parameter its body never names is dead whatever the callers, so a published declaration of a library is reported too, with the fixability the vocabulary gives the kind: the signature change is a breaking change. In TypeScript a caller may pass a function used as a value more arguments than it declares parameters, so in such a function whose signature is free but for that use, a parameter its body never reads is reported for deletion when its body reads no parameter after it, and an unread parameter before the last read one is reported for a rename to its name with a leading underscore, which keeps every argument in place and which the compilers' unused-parameter rules read as declared unread, unless its name already starts with one. A parameter of a TypeScript function expression or arrow function that the compiler gives a contextual type, and that carries a type annotation, is not reported for deletion where the inference of the call holding the function may read the annotation, being where the callee is generic and its parameter type at the function's place names a type parameter at the parameter's place, or where the function is written inside an object literal such a call is passed, and it is reported for deletion at `probable` where it carries an annotation no such inference reads, because nothing in the program shows that an outside reader ignores it. Such a parameter is not reported when it is an object binding pattern, because the pattern reads each property it names from the argument and the code that hands the argument may act on that read. No name such a pattern binds is reported either. Any other TypeScript parameter that is a binding pattern is judged by the names it binds: each name the body never reads is reported wherever the pattern stands, because removing it from the pattern moves no argument, except a name beside a rest element of the same object pattern, whose removal changes what that element holds, and the pattern counts as a read parameter when the body reads any name it binds. A rest parameter is judged as the last parameter. A TypeScript `this` parameter declares the type of `this` and receives no argument, so it is never reported. A TypeScript constructor is used as a value where its class is used as a value other than as the callee of a `new` expression or the class an `extends` clause names, and its signature is not free where its class carries a decorator or a parameter of the constructor carries one, because the code that decorator or a container runs may construct the class. A parameter property is read by the write to its member the constructor makes, so it is never reported under this kind, and its member is judged under DS1301. A TypeScript name a parameter binds, whole or through a binding pattern, that starts with an underscore is never reported, because a leading underscore is the spelling unused-parameter rules read as declared unread, and no other name exempts a parameter. A Go parameter named by the blank identifier declares no name a body could read and is never reported.",
293
293
  defaultSeverity: "warn",
294
294
  maxClass: "certain",
295
295
  fixability: "manual",
@@ -336,7 +336,7 @@ const ROWS = [
336
336
  name: "dead-store",
337
337
  languages: ["go", "ts"],
338
338
  rule: "A write to a local variable with no read before the next write to it or the end of its scope, computed on the same read-and-write classification the write-only-symbol kind uses. The finding names the write position.",
339
- precondition: "In TypeScript the binding of a catch clause is a local variable the clause writes when it catches, so a binding that is a name and that the clause's block never reads is a dead store, positioned at the binding: the clause written with no binding behaves the same.",
339
+ precondition: "In TypeScript the binding of a catch clause is a local variable the clause writes when it catches, so a binding that is a name and that the clause's block never reads is a dead store, positioned at the binding: the clause written with no binding behaves the same. A TypeScript local is a name a `let` or `const` declaration of a block binds, or a `var` declaration of a block of a function, a name an object or array binding pattern of one binds at any depth included, except a name with a default, whose removal skips the default's evaluation, and a name beside a rest element of its object pattern, whose removal changes what the rest holds. A `var` of a block nested in its function's body is judged in that block, its last write kept because the function scope reads on past the block's end, and is no subject where a nested function of its function names it. A local a nested function reads is no subject, because the function may read it at any time, and every write to a local nothing reads is dead, one a nested function makes included, each positioned at the name it writes. The variable a `let` or `const` declaration of a `for…of` or `for…in` statement binds is written at each iteration, so one the loop body never reads is a dead store positioned at the binding, except a name that starts with an underscore, because a loop must bind a name and that spelling declares it unread. In Go a function literal a package-level variable's initializer holds is a function body of its own, and a finding about one of its stores carries the reference of the variable the literal initializes, which for a blank variable is its package's, as `grammar/symbol-ref.md` states for a blank-identifier declaration. In Go a range statement stores its key and its value at the start of every iteration, and an empty range stores neither. In Go a function literal reads each variable it names where it is written, and a store that a literal naming its variable may precede on some path of the control-flow graph, the literal of an earlier iteration of a loop included, is not dead, because a call of the literal the graph does not order may read it. A store no such literal precedes is judged as any other. A literal that is the callee of the call it is written in, outside a `go` or `defer` statement, runs there, so it reads its variables at that call and precedes no later store.",
340
340
  defaultSeverity: "deny",
341
341
  maxClass: "certain",
342
342
  fixability: "deletable",
@@ -72,8 +72,8 @@ export function matrixOf(per) {
72
72
  symbols.sort((a, b) => byPosition(a.position, b.position));
73
73
  return {
74
74
  configurations: per.map((one) => one.configuration),
75
- graphs: per.map((one) => graphOf(one.symbols, one.references, one.roots, one.testFiles, one.supportFiles)),
76
- union: graphOf(symbols, references, per.flatMap((one) => one.roots), [...new Set(per.flatMap((one) => one.testFiles))], [...new Set(per.flatMap((one) => one.supportFiles ?? []))]),
75
+ graphs: per.map((one) => graphOf(one.symbols, one.references, one.roots, one.testFiles, one.supportFiles, one.ambient)),
76
+ union: graphOf(symbols, references, per.flatMap((one) => one.roots), [...new Set(per.flatMap((one) => one.testFiles))], [...new Set(per.flatMap((one) => one.supportFiles ?? []))], new Set(per.flatMap((one) => [...(one.ambient ?? [])]))),
77
77
  heldIn: symbols.map((symbol) => holders.get(symbol.id) ?? []),
78
78
  dependents,
79
79
  };
@@ -100,10 +100,7 @@ export function sweepMatrix(matrix, input) {
100
100
  new Map((per[index]?.candidates ?? []).map((candidate) => [candidate.id, candidate])),
101
101
  ]));
102
102
  const union = matrix.union;
103
- const dead = union.symbols.map(() => false);
104
- const testOfDeadCode = union.symbols.map(() => false);
105
103
  const heldBy = union.symbols.map(() => undefined);
106
- const unreferencedTest = union.symbols.map(() => false);
107
104
  const testReached = reachedWithTheTests(union, [
108
105
  ...input.marked,
109
106
  ...(input.exempt ?? []).map((record) => record.id),
@@ -121,6 +118,7 @@ export function sweepMatrix(matrix, input) {
121
118
  // every configuration that holds it.
122
119
  const subjectsDead = (at) => (union.out[at] ?? []).every((edge) => union.test[edge.to] === true ||
123
120
  union.support[edge.to] === true ||
121
+ union.ambient[edge.to] === true ||
124
122
  union.subject[edge.to] !== true ||
125
123
  judged[edge.to] !== undefined);
126
124
  const candidates = [];
@@ -135,10 +133,7 @@ export function sweepMatrix(matrix, input) {
135
133
  const heldByTests = heldBy[union.parent[at] ?? OUTSIDE] ??
136
134
  (union.support[at] === true && testRefs > 0 && !admitted ? symbol.id : undefined);
137
135
  const unreferenced = union.test[at] === true && !admitted && testReached[at] !== true;
138
- dead[at] = true;
139
- testOfDeadCode[at] = admitted;
140
136
  heldBy[at] = heldByTests;
141
- unreferencedTest[at] = unreferenced;
142
137
  const productionRefs = union.made[at]?.production ?? 0;
143
138
  const counted = all.every((candidate) => candidate.relation === "reference-counting");
144
139
  candidates.push({
@@ -159,9 +154,23 @@ export function sweepMatrix(matrix, input) {
159
154
  return {
160
155
  liveUnder,
161
156
  candidates,
162
- components: componentsOf(union, dead.map((one, at) => one && heldBy[at] === undefined), testOfDeadCode, unreferencedTest, positionsOf(union, matrix.dependents, liveUnder)),
157
+ components: deadComponents(matrix, { liveUnder, candidates }, new Set()),
163
158
  };
164
159
  }
160
+ /**
161
+ * The dead components of one sweep over the union, with the file declarations at `files`
162
+ * dead as well: a file that is deleted whole takes the declarations it holds and every
163
+ * dead declaration only its top level references with it.
164
+ */
165
+ export function deadComponents(matrix, result, files) {
166
+ const union = matrix.union;
167
+ const byId = new Map(result.candidates.map((candidate) => [candidate.id, candidate]));
168
+ const candidateAt = (at) => byId.get(union.symbols[at]?.id ?? "");
169
+ return componentsOf(union, union.symbols.map((_symbol, at) => {
170
+ const candidate = candidateAt(at);
171
+ return files.has(at) || (candidate !== undefined && candidate.heldByTests === undefined);
172
+ }), union.symbols.map((_symbol, at) => candidateAt(at)?.testOfDeadCode === true), union.symbols.map((_symbol, at) => candidateAt(at)?.unreferencedTest === true), positionsOf(union, matrix.dependents, result.liveUnder));
173
+ }
165
174
  /**
166
175
  * The file declarations at `paths`, below the target root, that one sweep holds live
167
176
  * under both relations, the rule a judged declaration is live by.
@@ -0,0 +1,197 @@
1
+ /**
2
+ * The files the import declarations of the target's Markdown and MDX documents load. A
3
+ * document is read as text: a line outside a fenced code block that starts with `import`
4
+ * is an import declaration, which an MDX compiler hoists into the module it builds.
5
+ */
6
+ import { resolveRelativeSpecifier } from "./configuration-files.js";
7
+ import { dirnamePath, joinPath, resolvePath } from "./paths.js";
8
+ /** The directories no document is read below. */
9
+ const SKIPPED = new Set(["node_modules", ".git"]);
10
+ /** The extensions of a document whose imports an MDX compiler reads. */
11
+ const DOCUMENT = /\.mdx?$/u;
12
+ /** A fence line, its marker run and what follows it captured. */
13
+ const FENCE = /^ {0,3}(`{3,}|~{3,})(.*)$/u;
14
+ /** A string literal in either quote, its escapes included. */
15
+ const STRING = String.raw `"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'`;
16
+ /** An import declaration at the start of a line, its clause and its specifier captured. */
17
+ const IMPORT_LINE = new RegExp(String.raw `^import\s+(?:((?:[^"'\n]|${STRING})*?)\s+from\s*)?["']([^"'\n]+)["']`, "u");
18
+ /** The braces of an import clause, what they hold captured. */
19
+ const BRACES = new RegExp(String.raw `\{((?:[^}"']|${STRING})*)\}`, "u");
20
+ /** One comma-separated part of a clause's braces. */
21
+ const PART = new RegExp(String.raw `(?:[^,"']|${STRING})+`, "gu");
22
+ /** A named import of a clause's braces: the exported name and an optional local alias. */
23
+ const NAMED_IMPORT = new RegExp(String.raw `^([\w$]+|${STRING})(?:\s+as\s+[\w$]+)?$`, "u");
24
+ /** The single-character escapes of a string literal and the character each stands for. */
25
+ const SINGLE_ESCAPES = new Map([
26
+ ["b", "\b"],
27
+ ["f", "\f"],
28
+ ["n", "\n"],
29
+ ["r", "\r"],
30
+ ["t", "\t"],
31
+ ["v", "\v"],
32
+ ["0", "\0"],
33
+ ["'", "'"],
34
+ ['"', '"'],
35
+ ["\\", "\\"],
36
+ ]);
37
+ /**
38
+ * One escape of a string literal: two hexadecimal digits, a code unit, a code point, or one
39
+ * character and the digit after it.
40
+ */
41
+ const ESCAPE = /\\(?:x([\da-fA-F]{2})|u([\da-fA-F]{4})|u\{([\da-fA-F]+)\}|(.)(\d?))/gu;
42
+ /** What one escape stands for, or undefined for one a module cannot hold. */
43
+ function unescaped([, hex, unit, point, single, digit]) {
44
+ if (single === undefined) {
45
+ const code = Number.parseInt(hex ?? unit ?? point ?? "", 16);
46
+ return code <= 0x10ffff ? String.fromCodePoint(code) : undefined;
47
+ }
48
+ return /[1-9xu]/u.test(single) || (single === "0" && digit !== "")
49
+ ? undefined
50
+ : `${SINGLE_ESCAPES.get(single) ?? single}${digit ?? ""}`;
51
+ }
52
+ /**
53
+ * The value of a quoted export name, its escapes decoded, or undefined for an escape this
54
+ * reading does not decode. A module is strict code, so no legacy octal escape is valid.
55
+ */
56
+ function quotedName(literal) {
57
+ const body = literal.slice(1, -1);
58
+ let value = "";
59
+ let from = 0;
60
+ for (const escape of body.matchAll(ESCAPE)) {
61
+ const decoded = unescaped(escape);
62
+ if (decoded === undefined) {
63
+ return undefined;
64
+ }
65
+ value += body.slice(from, escape.index) + decoded;
66
+ from = escape.index + escape[0].length;
67
+ }
68
+ return value + body.slice(from);
69
+ }
70
+ /**
71
+ * The export names one import clause reads: `default` for a default binding and each name
72
+ * its braces list, or undefined for a namespace import, which reads every export, and for
73
+ * a clause this reading does not parse, which may read any.
74
+ */
75
+ function clauseNames(clause) {
76
+ const braces = BRACES.exec(clause);
77
+ const head = (braces === null ? clause : clause.slice(0, braces.index))
78
+ .replace(/,\s*$/u, "")
79
+ .trim();
80
+ if (head.includes("*")) {
81
+ return undefined;
82
+ }
83
+ const names = head === "" ? [] : ["default"];
84
+ if (head !== "" && !/^[\w$]+$/u.test(head)) {
85
+ return undefined;
86
+ }
87
+ for (const part of (braces?.[1]?.match(PART) ?? []).map((one) => one.trim())) {
88
+ const named = NAMED_IMPORT.exec(part);
89
+ if (part === "") {
90
+ continue;
91
+ }
92
+ if (named?.[1] === undefined) {
93
+ return undefined;
94
+ }
95
+ const name = /^["']/u.test(named[1]) ? quotedName(named[1]) : named[1];
96
+ if (name === undefined) {
97
+ return undefined;
98
+ }
99
+ names.push(name);
100
+ }
101
+ return names;
102
+ }
103
+ /** Every document below `dir`, outside every skipped directory, by absolute path. */
104
+ function documents(host, dir) {
105
+ let entries;
106
+ try {
107
+ entries = host.readDirectory(dir);
108
+ }
109
+ catch {
110
+ return [];
111
+ }
112
+ const found = [];
113
+ for (const entry of entries) {
114
+ const path = joinPath(dir, entry.name);
115
+ if (entry.directory) {
116
+ if (!SKIPPED.has(entry.name)) {
117
+ found.push(...documents(host, path));
118
+ }
119
+ }
120
+ else if (DOCUMENT.test(entry.name)) {
121
+ found.push(path);
122
+ }
123
+ }
124
+ return found.sort();
125
+ }
126
+ /** The relative specifiers one document's import lines name, its fenced code blocks skipped. */
127
+ function importedBy(text) {
128
+ const found = [];
129
+ let open;
130
+ for (const line of text.split(/\r?\n/u)) {
131
+ const fence = FENCE.exec(line);
132
+ const marker = fence?.[1];
133
+ if (marker !== undefined && open === undefined) {
134
+ open = marker;
135
+ continue;
136
+ }
137
+ // https://spec.commonmark.org/0.31.2/#fenced-code-blocks: only a run of the opening
138
+ // character, at least as long and followed by nothing, closes a fence.
139
+ if (marker !== undefined &&
140
+ open !== undefined &&
141
+ marker.startsWith(open.slice(0, 1)) &&
142
+ marker.length >= open.length &&
143
+ fence?.[2]?.trim() === "") {
144
+ open = undefined;
145
+ continue;
146
+ }
147
+ const matched = open === undefined ? IMPORT_LINE.exec(line) : null;
148
+ const specifier = matched?.[2];
149
+ if (specifier?.startsWith("./") === true || specifier?.startsWith("../") === true) {
150
+ found.push({ specifier, names: clauseNames(matched?.[1] ?? "") });
151
+ }
152
+ }
153
+ return found;
154
+ }
155
+ /**
156
+ * The documents each host's target roots hold, which every project of a run reads alike,
157
+ * kept for the host's life as {@link Host} allows.
158
+ */
159
+ const documentsOf = new WeakMap();
160
+ /** Every readable document below `root` and the import lines it writes, read once per host. */
161
+ function documentImports(host, root) {
162
+ const byRoot = documentsOf.get(host) ?? new Map();
163
+ documentsOf.set(host, byRoot);
164
+ const known = byRoot.get(root);
165
+ if (known !== undefined) {
166
+ return known;
167
+ }
168
+ const found = documents(host, root).flatMap((path) => {
169
+ try {
170
+ return [{ path, imports: importedBy(host.readFile(path)) }];
171
+ }
172
+ catch {
173
+ return [];
174
+ }
175
+ });
176
+ byRoot.set(root, found);
177
+ return found;
178
+ }
179
+ /**
180
+ * Every own file one document below the target root imports by a relative specifier,
181
+ * read against the document's directory, on disk or through the emit mapping.
182
+ */
183
+ export function documentEntries(host, targetRoot, files) {
184
+ const root = resolvePath(host.workingDirectory(), targetRoot);
185
+ const found = [];
186
+ for (const { path, imports } of documentImports(host, root)) {
187
+ const dir = dirnamePath(path);
188
+ for (const { specifier, names } of imports) {
189
+ const reached = resolveRelativeSpecifier(host, dir, specifier);
190
+ const held = reached === undefined ? undefined : files.byName.get(reached);
191
+ for (const file of held === undefined ? files.named(resolvePath(dir, specifier)) : [held]) {
192
+ found.push({ file, source: specifier, names });
193
+ }
194
+ }
195
+ }
196
+ return found;
197
+ }
@@ -103,7 +103,7 @@ function namedBy(held) {
103
103
  `${scope}#${aliasFragment(one, name)}`,
104
104
  ]));
105
105
  const members = (children.get(id) ?? []).filter((child) => wanted.has(child.ref));
106
- return [{ id, members: members.map((child) => child.id) }];
106
+ return [{ id, members: members.map((child) => child.id), wildcard: name.includes("*") }];
107
107
  });
108
108
  }
109
109
  /**
@@ -149,26 +149,22 @@ export function moduleDeclarationReferences(project, held, root, testFiles) {
149
149
  imports.forEach((one, index) => {
150
150
  const resolved = moduleOf(declared.length + index);
151
151
  const position = renderPosition(one.file, root, one.specifier.getStart());
152
- const read = (to, resolution) => {
153
- found.push({
154
- from: one.from,
155
- to,
156
- position,
157
- use: "read",
158
- resolution,
159
- test: testFiles.has(position.path),
160
- });
152
+ const read = (to, resolution, test) => {
153
+ found.push({ from: one.from, to, position, use: "read", resolution, test });
161
154
  };
155
+ const test = testFiles.has(position.path);
162
156
  const same = new Set(declared
163
157
  .filter((_, at) => resolved !== undefined && resolved === moduleOf(at))
164
158
  .map((declaration) => declaration.id));
165
159
  for (const id of same) {
166
- read(id, "batch");
160
+ read(id, "batch", test);
167
161
  }
168
162
  for (const declaration of named(one.specifier.text, one.names)) {
169
- if (!same.has(declaration.id)) {
163
+ // A wildcard declaration is how the compiler types the file a matching specifier
164
+ // names, so the import uses it whoever writes it, a test included.
165
+ if (declaration.wildcard || !same.has(declaration.id)) {
170
166
  for (const to of [declaration.id, ...declaration.members]) {
171
- read(to, "syntax");
167
+ read(to, "syntax", test && !declaration.wildcard);
172
168
  }
173
169
  }
174
170
  }