@stateward/core 1.2.2 → 1.3.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 (75) hide show
  1. package/dist/analyses.d.ts +37 -0
  2. package/dist/analyses.js +57 -0
  3. package/dist/backend/fingerprints.d.ts +3 -1
  4. package/dist/backend/fingerprints.js +198 -9
  5. package/dist/backend/program-record.d.ts +7 -0
  6. package/dist/backend/program-size.d.ts +32 -0
  7. package/dist/backend/program-size.js +166 -0
  8. package/dist/backend/typescript6.d.ts +62 -32
  9. package/dist/backend/typescript6.js +1615 -164
  10. package/dist/baseline.d.ts +1 -1
  11. package/dist/baseline.js +14 -10
  12. package/dist/cache.d.ts +92 -4
  13. package/dist/cache.js +257 -68
  14. package/dist/checker.d.ts +28 -3
  15. package/dist/checker.js +42 -8
  16. package/dist/class-id.d.ts +34 -0
  17. package/dist/class-id.js +93 -0
  18. package/dist/code-text.d.ts +8 -0
  19. package/dist/code-text.js +66 -0
  20. package/dist/config-file.js +7 -5
  21. package/dist/config.d.ts +10 -2
  22. package/dist/config.js +490 -48
  23. package/dist/define.d.ts +8 -2
  24. package/dist/disk-cache.d.ts +34 -2
  25. package/dist/disk-cache.js +82 -15
  26. package/dist/engine.d.ts +64 -3
  27. package/dist/engine.js +474 -59
  28. package/dist/fact-lines.d.ts +31 -0
  29. package/dist/fact-lines.js +197 -0
  30. package/dist/facts-versions.d.ts +27 -0
  31. package/dist/facts-versions.js +99 -0
  32. package/dist/fixes.js +4 -1
  33. package/dist/ignores.d.ts +11 -0
  34. package/dist/ignores.js +74 -27
  35. package/dist/implementation.d.ts +0 -6
  36. package/dist/implementation.js +0 -17
  37. package/dist/index.d.ts +9 -9
  38. package/dist/index.js +12 -7
  39. package/dist/internal.d.ts +13 -6
  40. package/dist/internal.js +7 -3
  41. package/dist/journal.d.ts +40 -0
  42. package/dist/journal.js +197 -0
  43. package/dist/lazy.d.ts +8 -1
  44. package/dist/lazy.js +27 -2
  45. package/dist/ledger.d.ts +2 -2
  46. package/dist/ledger.js +2 -2
  47. package/dist/memory-plan.d.ts +121 -0
  48. package/dist/memory-plan.js +174 -0
  49. package/dist/off-by-default.d.ts +13 -0
  50. package/dist/off-by-default.js +15 -0
  51. package/dist/options.d.ts +21 -5
  52. package/dist/options.js +22 -7
  53. package/dist/package-facts.d.ts +211 -17
  54. package/dist/package-facts.js +520 -38
  55. package/dist/plan.d.ts +1 -1
  56. package/dist/plan.js +7 -2
  57. package/dist/release.d.ts +12 -21
  58. package/dist/release.js +26 -38
  59. package/dist/renamed.d.ts +22 -3
  60. package/dist/renamed.js +50 -16
  61. package/dist/rollout.js +7 -4
  62. package/dist/severity.d.ts +1 -1
  63. package/dist/severity.js +17 -3
  64. package/dist/test-runner.d.ts +18 -0
  65. package/dist/test-runner.js +483 -0
  66. package/dist/testing.d.ts +3 -3
  67. package/dist/testing.js +5 -5
  68. package/dist/timing.d.ts +17 -7
  69. package/dist/timing.js +60 -38
  70. package/dist/types.d.ts +704 -20
  71. package/dist/unread.d.ts +90 -0
  72. package/dist/unread.js +405 -0
  73. package/dist/vocabulary.d.ts +1 -1
  74. package/dist/vocabulary.js +1 -1
  75. package/package.json +4 -2
package/dist/engine.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import path from "node:path";
2
2
  import { readRollout } from "./rollout.js";
3
- import { ruleKey, sha1, summaryOf, summaryText, summaryValue } from "./cache.js";
3
+ import { missingAnalysis, readTarget } from "./analyses.js";
4
+ import { analysisKey, deepFreeze, ruleKey, sha1, summaryOf, summaryText, summaryValue, useKey, } from "./cache.js";
4
5
  import { fileLedger, ledgerKey, ledgerTraits, provesOf, tagRulesOf, withRule } from "./ledger.js";
5
6
  import { defaultOptions } from "./options.js";
6
7
  import { declarationId, fileStated } from "./stated.js";
@@ -8,7 +9,10 @@ import { codeOf, loadRule } from "./lazy.js";
8
9
  import { IGNORE_EXPLAIN, IGNORE_RULE_ID, applyIgnores, fileDirectives } from "./ignores.js";
9
10
  import { addonsWith, appliedOverrides, ruleIsOn, ruleSetting, ruleSettingWith, } from "./severity.js";
10
11
  import { matchingOverrides } from "./overrides.js";
11
- import { defaults } from "./config.js";
12
+ import { unmatchedFacts } from "./package-facts.js";
13
+ import { factsGate } from "./facts-versions.js";
14
+ import { defaults, packExcludes } from "./config.js";
15
+ import { removedOf, renamesOf } from "./renamed.js";
12
16
  import picomatch from "picomatch";
13
17
  import { isGlob } from "./tsconfigs.js";
14
18
  const RULE_SETTINGS = ["error", "warning", "info", "off"];
@@ -96,30 +100,73 @@ export const LOOSE_NULLS_FIX = `\`strictNullChecks\` is off in this project, so
96
100
  export function missingTypesReason(library) {
97
101
  return `${library}'s types are not installed (install the app's dependencies)`;
98
102
  }
103
+ function unitNotes(unit, rules, facts) {
104
+ const missing = [];
105
+ if (unit.files.length > 0) {
106
+ for (const entry of rules) {
107
+ const needs = entry.rule.meta.needsTypes;
108
+ if (needs === undefined || needs.modules.some((module) => unit.typesResolve(module)))
109
+ continue;
110
+ // A project that uses none of the library's modules has nothing for the rule to check:
111
+ // installing the types would not change that, so there is nothing to say.
112
+ if (!needs.modules.some((module) => unit.importsModule(module)))
113
+ continue;
114
+ missing.push({ library: needs.library, id: entry.id });
115
+ }
116
+ }
117
+ return {
118
+ tsconfig: unit.tsconfig,
119
+ files: unit.files,
120
+ strictNullChecks: unit.strictNullChecks,
121
+ unreadTestConfigs: unit.unreadTestConfigs,
122
+ missing,
123
+ // A line one project's types resolve is matched (0041: keys resolve through the type checker).
124
+ factKeys: Object.keys(facts).length === 0 || unit.files.length === 0 ? undefined : unit.factKeys(facts),
125
+ };
126
+ }
99
127
  /**
100
- * What the run cannot check as a whole (`CheckResult.notes`): the rules among `rules` whose
101
- * library's types do not resolve in some project with files, and the projects without
102
- * `strictNullChecks`. Undefined when there is nothing to say.
128
+ * What the run cannot check as a whole (`CheckResult.notes`), from each project's `unitNotes`:
129
+ * the rules whose library's types do not resolve in some project with files that import it, the
130
+ * projects without `strictNullChecks`, and the test-runner configs whose test files could not be
131
+ * read. Undefined when there is nothing to say.
103
132
  */
104
- function notesOf(units, rules) {
133
+ function notesOf(units, facts, gate) {
105
134
  const missing = new Map();
106
135
  const looseNulls = [];
136
+ const unreadTestConfigs = new Set();
107
137
  for (const unit of units) {
108
138
  if (unit.files.length === 0)
109
139
  continue;
110
140
  if (!unit.strictNullChecks)
111
141
  looseNulls.push(unit.tsconfig);
112
- for (const entry of rules) {
113
- const needs = entry.rule.meta.needsTypes;
114
- if (needs === undefined || needs.modules.some((module) => unit.typesResolve(module)))
115
- continue;
116
- const ids = missing.get(needs.library) ?? new Set();
117
- ids.add(entry.id);
118
- missing.set(needs.library, ids);
142
+ for (const file of unit.unreadTestConfigs)
143
+ unreadTestConfigs.add(file);
144
+ for (const { library, id } of unit.missing) {
145
+ const ids = missing.get(library) ?? new Set();
146
+ ids.add(id);
147
+ missing.set(library, ids);
148
+ }
149
+ }
150
+ const matched = unmatchedFacts(units.flatMap((unit) => (unit.factKeys === undefined ? [] : [unit.factKeys])), facts);
151
+ // The config's facts a project's version leaves out, once each: by the first file of each project.
152
+ const outOfRange = new Set();
153
+ for (const unit of units) {
154
+ const [first] = unit.files;
155
+ if (first === undefined)
156
+ continue;
157
+ for (const left of gate.at(first).withheldFacts) {
158
+ if (left.source === "config")
159
+ outOfRange.add(`${left.reason}; they are not applied`);
119
160
  }
120
161
  }
121
- if (missing.size === 0 && looseNulls.length === 0)
162
+ if (missing.size === 0 &&
163
+ looseNulls.length === 0 &&
164
+ unreadTestConfigs.size === 0 &&
165
+ matched.unmatched.length === 0 &&
166
+ matched.notChecked.length === 0 &&
167
+ outOfRange.size === 0) {
122
168
  return undefined;
169
+ }
123
170
  const missingTypes = [...missing]
124
171
  .sort(([a], [b]) => compareText(a, b))
125
172
  .map(([library, ids]) => ({
@@ -127,7 +174,14 @@ function notesOf(units, rules) {
127
174
  reason: missingTypesReason(library),
128
175
  rules: [...ids].sort(compareText),
129
176
  }));
130
- return { missingTypes, looseNulls };
177
+ return {
178
+ missingTypes,
179
+ looseNulls,
180
+ unreadTestConfigs: [...unreadTestConfigs].sort(compareText),
181
+ unmatchedFacts: matched.unmatched,
182
+ factsNotChecked: matched.notChecked,
183
+ factsOutOfRange: [...outOfRange].sort(compareText),
184
+ };
131
185
  }
132
186
  /** The own files of the projects without `strictNullChecks`. */
133
187
  function looseNullFiles(units) {
@@ -158,9 +212,28 @@ function ignoreScope(config, ran) {
158
212
  known,
159
213
  ran: new Set([SYNTAX_RULE_ID, IMPORTS_RULE_ID, ...ran.map((entry) => entry.id)]),
160
214
  options: config.ignores,
215
+ renames: renamesOf(config.plugins),
216
+ removed: removedOf(config.plugins),
217
+ offOptions: offOptionsOf(ran),
161
218
  };
162
219
  }
220
+ /** `IgnoreScope.offOptions`: each rule's convention options that are off in the options it ran with. */
221
+ function offOptionsOf(ran) {
222
+ const found = new Map();
223
+ for (const entry of ran) {
224
+ const off = Object.entries(entry.rule.meta.options ?? {})
225
+ .filter(([name, spec]) => spec.kind === "boolean" && spec.convention === true && entry.options[name] === false)
226
+ .map(([name]) => name);
227
+ if (off.length > 0)
228
+ found.set(entry.id, off);
229
+ }
230
+ return found;
231
+ }
163
232
  const FAILURE_HINT = "report this to the rule's authors; the rest of the check ran normally";
233
+ /** The default `exclude` of a config: core's test patterns, then those its packs add. */
234
+ function defaultExcludes(config) {
235
+ return [...new Set([...defaults.exclude, ...packExcludes(config.plugins)])];
236
+ }
164
237
  /**
165
238
  * The facts every loaded plugin ships, joined in plugin order: per package, per function; a later
166
239
  * plugin's line for the same function wins.
@@ -174,12 +247,61 @@ function shippedFactsOf(plugins) {
174
247
  }
175
248
  return joined;
176
249
  }
250
+ /**
251
+ * The gate of a check's facts: the config's by their `"@versions"`, the packs' by the versions
252
+ * they were verified on (`Plugin.factsVerified`; a later plugin's range for a package wins).
253
+ */
254
+ function gateOf(config) {
255
+ const verified = {};
256
+ for (const plugin of config.plugins)
257
+ Object.assign(verified, plugin.factsVerified ?? {});
258
+ return factsGate({
259
+ facts: config.facts,
260
+ versions: config.factVersions,
261
+ shipped: shippedFactsOf(config.plugins),
262
+ verified,
263
+ configDir: config.configDir,
264
+ });
265
+ }
266
+ /** What the cache key of a rule or analysis holds of the facts. */
267
+ function factsKey(config, gate, shipped) {
268
+ return { config: config.facts, shipped, platform: config.platform, versions: gate.key };
269
+ }
177
270
  function nodeLocation(node) {
178
271
  return { file: node.getSourceFile().fileName, start: node.getStart(), end: node.getEnd() };
179
272
  }
180
273
  function isStrings(value) {
181
274
  return Array.isArray(value) && value.every((item) => typeof item === "string");
182
275
  }
276
+ /** The analyses the rules read that the config's plugins publish, by id. */
277
+ function analysisRuns(config, rules, gate) {
278
+ const readers = new Map();
279
+ for (const entry of rules) {
280
+ if (entry.rule.kind !== "project")
281
+ continue;
282
+ for (const id of entry.rule.reads ?? []) {
283
+ const list = readers.get(id) ?? [];
284
+ list.push(entry.id);
285
+ readers.set(id, list);
286
+ }
287
+ }
288
+ const shippedFacts = shippedFactsOf(config.plugins);
289
+ const runs = [];
290
+ for (const [id, readBy] of [...readers].sort(([a], [b]) => compareText(a, b))) {
291
+ const target = readTarget(config.plugins, id);
292
+ if (target.kind !== "found")
293
+ continue;
294
+ const facts = factsKey(config, gate, shippedFacts);
295
+ runs.push({
296
+ id,
297
+ analysis: target.analysis,
298
+ key: analysisKey({ id, analysis: target.analysis, facts }),
299
+ readers: [...readBy].sort(compareText),
300
+ gate,
301
+ });
302
+ }
303
+ return runs;
304
+ }
183
305
  /** The rule's options with each shared list joined with the other rule's (`RuleInfo.sharedOptions`). */
184
306
  function withSharedOptions(config, plugin, rule, options) {
185
307
  const shared = Object.entries(rule.meta.sharedOptions ?? {});
@@ -195,7 +317,7 @@ function withSharedOptions(config, plugin, rule, options) {
195
317
  return merged;
196
318
  }
197
319
  /** A rule with the settings it runs under, and the key its cached results are kept under. */
198
- function entryOf(config, plugin, name, rule, severity, addons) {
320
+ function entryOf(config, plugin, name, rule, severity, addons, gate) {
199
321
  const id = `${plugin}/${name}`;
200
322
  const options = withSharedOptions(config, plugin, rule, config.ruleOptions[id] ?? defaultOptions(rule.meta.options));
201
323
  const active = {
@@ -208,14 +330,16 @@ function entryOf(config, plugin, name, rule, severity, addons) {
208
330
  options,
209
331
  facts: config.facts,
210
332
  shippedFacts: shippedFactsOf(config.plugins),
333
+ gate,
211
334
  };
212
335
  return {
213
336
  ...active,
214
- key: ruleKey({ ...active, facts: { config: active.facts, shipped: active.shippedFacts } }),
337
+ key: ruleKey({ ...active, facts: factsKey(config, gate, active.shippedFacts) }),
215
338
  };
216
339
  }
217
340
  function ruleSets(config, selection) {
218
341
  const rolledOut = rolloutSet(config, selection);
342
+ const gate = gateOf(config);
219
343
  const anywhere = [];
220
344
  const known = new Map();
221
345
  for (const plugin of config.plugins) {
@@ -233,7 +357,7 @@ function ruleSets(config, selection) {
233
357
  // A rule that only an override turns on has no config severity; project findings take
234
358
  // their own from the file they are in, so this one is never shown.
235
359
  const severity = base === "off" ? rule.meta.defaultSeverity : base;
236
- anywhere.push(entryOf(config, plugin.name, name, codeOf(id, rule), severity, addons));
360
+ anywhere.push(entryOf(config, plugin.name, name, codeOf(id, rule), severity, addons, gate));
237
361
  }
238
362
  }
239
363
  anywhere.sort((a, b) => compareText(a.id, b.id));
@@ -244,7 +368,9 @@ function ruleSets(config, selection) {
244
368
  const settings = new Map();
245
369
  return {
246
370
  anywhere,
371
+ analyses: analysisRuns(config, anywhere, gate),
247
372
  perFile,
373
+ gate,
248
374
  forFile(file) {
249
375
  if (!perFile)
250
376
  return anywhere;
@@ -260,14 +386,14 @@ function ruleSets(config, selection) {
260
386
  if (setting === "off") {
261
387
  if (entry.rule.summarize === undefined)
262
388
  return [];
263
- const quiet = entryOf(config, entry.plugin, entry.name, entry.rule, entry.severity, []);
389
+ const quiet = entryOf(config, entry.plugin, entry.name, entry.rule, entry.severity, [], gate);
264
390
  return [{ ...quiet, key: `${quiet.key}:quiet`, quiet: true }];
265
391
  }
266
392
  const prefix = `${entry.plugin}/`;
267
393
  const addons = addonsWith(config, applied)
268
394
  .filter((one) => one.startsWith(prefix))
269
395
  .map((one) => one.slice(prefix.length));
270
- return [entryOf(config, entry.plugin, entry.name, entry.rule, setting, addons)];
396
+ return [entryOf(config, entry.plugin, entry.name, entry.rule, setting, addons, gate)];
271
397
  });
272
398
  variants.set(key, found);
273
399
  }
@@ -401,7 +527,8 @@ function declarationsAt(against) {
401
527
  return [...new Set(against.map(declarationId))];
402
528
  }
403
529
  function fileContext(entry, sourceFile, types, findings, ledger = [], marks = []) {
404
- const { id, addons, options, facts, shippedFacts } = entry;
530
+ const { id, addons, options } = entry;
531
+ const { facts, shippedFacts, withheldFacts } = entry.gate.at(sourceFile.fileName);
405
532
  return {
406
533
  file: sourceFile.fileName,
407
534
  ledger,
@@ -414,6 +541,7 @@ function fileContext(entry, sourceFile, types, findings, ledger = [], marks = []
414
541
  options,
415
542
  facts,
416
543
  shippedFacts,
544
+ withheldFacts,
417
545
  report(problem) {
418
546
  const finding = problemFinding(entry, {
419
547
  message: problem.message,
@@ -434,7 +562,7 @@ function fileContext(entry, sourceFile, types, findings, ledger = [], marks = []
434
562
  if (finding !== undefined)
435
563
  findings.push(finding);
436
564
  },
437
- unknown({ message, hint, node, against }) {
565
+ unknown({ message, hint, node, against, needs, unnamed }) {
438
566
  const guarantees = declarationsAgainst(against, types);
439
567
  findings.push({
440
568
  kind: "unknown",
@@ -444,14 +572,26 @@ function fileContext(entry, sourceFile, types, findings, ledger = [], marks = []
444
572
  location: nodeLocation(node),
445
573
  ...listedFlag(entry),
446
574
  ...(guarantees.length > 0 ? { guarantees } : {}),
575
+ ...(needs === undefined || needs.length === 0 ? {} : { needs }),
576
+ ...(unnamed === undefined || unnamed.length === 0 ? {} : { unnamed }),
447
577
  });
448
578
  },
449
579
  };
450
580
  }
451
- function projectContext(entry, findings, marks = []) {
581
+ function projectContext(entry, findings, marks, read, unstated) {
452
582
  const { id, options } = entry;
453
583
  return {
454
584
  options,
585
+ analyses: read.analyses,
586
+ analysisSummaries: read.summaries,
587
+ unstated({ location, needs, unnamed }) {
588
+ unstated.push({
589
+ ruleId: id,
590
+ location,
591
+ ...(needs === undefined || needs.length === 0 ? {} : { needs }),
592
+ ...(unnamed === undefined || unnamed.length === 0 ? {} : { unnamed }),
593
+ });
594
+ },
455
595
  read(ref, outcome) {
456
596
  marks.push({ ref: ref.id, trait: ref.trait, outcome });
457
597
  },
@@ -471,7 +611,7 @@ function projectContext(entry, findings, marks = []) {
471
611
  if (finding !== undefined)
472
612
  findings.push(finding);
473
613
  },
474
- unknown({ message, hint, location, against }) {
614
+ unknown({ message, hint, location, against, needs, unnamed }) {
475
615
  const guarantees = declarationsAt(against);
476
616
  findings.push({
477
617
  kind: "unknown",
@@ -481,6 +621,8 @@ function projectContext(entry, findings, marks = []) {
481
621
  location,
482
622
  ...listedFlag(entry),
483
623
  ...(guarantees.length > 0 ? { guarantees } : {}),
624
+ ...(needs === undefined || needs.length === 0 ? {} : { needs }),
625
+ ...(unnamed === undefined || unnamed.length === 0 ? {} : { unnamed }),
484
626
  });
485
627
  },
486
628
  };
@@ -545,6 +687,12 @@ function atTheirFiles(sets, entry, found, silenced) {
545
687
  return [{ ...finding, severity: own ?? setting }];
546
688
  });
547
689
  }
690
+ /** A project rule's unstated places, without those in files the config turns the rule off in. */
691
+ function unstatedAtTheirFiles(sets, entry, found) {
692
+ if (!sets.perFile)
693
+ return found;
694
+ return found.filter((one) => sets.settingAt(entry.id, one.location.file) !== "off");
695
+ }
548
696
  /**
549
697
  * Where a project rule's failure is reported: the configured tsconfig when there is one, else the
550
698
  * first project's (a glob names no single file).
@@ -580,6 +728,29 @@ function runOnFile(entry, sourceFile, types, same, ledger) {
580
728
  return { result: { findings }, failed: true };
581
729
  }
582
730
  }
731
+ /**
732
+ * Runs an analysis's `summarize` on one file, as `runOnFile` a rule's: the error when it threw
733
+ * (such a result is not cached, and the analysis fails for this check).
734
+ */
735
+ function runAnalysisOnFile(run, sourceFile, types, same) {
736
+ try {
737
+ const value = run.analysis.summarize({
738
+ file: sourceFile.fileName,
739
+ sourceFile,
740
+ types,
741
+ ...run.gate.at(sourceFile.fileName),
742
+ });
743
+ if (value === undefined)
744
+ return { result: { findings: [] }, failed: false };
745
+ const made = summaryOf(value);
746
+ const summary = same.get(made.hash) ?? made;
747
+ same.set(summary.hash, summary);
748
+ return { result: { findings: [], summary }, failed: false };
749
+ }
750
+ catch (error) {
751
+ return { failed: true, error };
752
+ }
753
+ }
583
754
  /**
584
755
  * The first of the two phases of running the rules (then `runProjectPhase`): every active rule
585
756
  * over the own files of `units`. With `rollout` on and the `configured` selection, this reads the
@@ -601,11 +772,20 @@ export function drain(steps) {
601
772
  return next.value;
602
773
  }
603
774
  }
775
+ /** Units built already, kept after the phase (`release` lets nothing go). */
776
+ export function builtSources(units) {
777
+ return units.map((unit) => ({
778
+ tsconfig: unit.tsconfig,
779
+ built: unit,
780
+ open: () => unit,
781
+ release: () => undefined,
782
+ }));
783
+ }
604
784
  /** `runFilePhase`, one file per step. */
605
- export function filePhaseRun(config, cwd, units, selection = { kind: "configured" }, cache, ignores = true, timing) {
785
+ export function filePhaseRun(config, cwd, units, selection = { kind: "configured" }, cache, ignores = true, timing, slicing) {
606
786
  const nextFiles = new Map();
607
787
  return {
608
- steps: filePhaseSteps(config, cwd, units, selection, nextFiles, cache, ignores, timing),
788
+ steps: filePhaseSteps(config, cwd, units, selection, nextFiles, cache, ignores, timing, slicing),
609
789
  abandon: () => {
610
790
  if (cache === undefined || nextFiles.size === 0)
611
791
  return;
@@ -618,12 +798,16 @@ export function filePhaseRun(config, cwd, units, selection = { kind: "configured
618
798
  }
619
799
  function* filePhaseSteps(config, cwd, units, selection,
620
800
  /** This run's cache entries, by file; read by `abandon` when the run stops early. */
621
- nextFiles, cache, ignores, timing) {
622
- const total = units.reduce((sum, unit) => sum + unit.files.length, 0);
801
+ nextFiles, cache, ignores, timing, slicing) {
802
+ // A project built when the phase reaches it adds its files then.
803
+ let total = units.reduce((sum, source) => sum + (source.built?.files.length ?? 0), 0);
623
804
  const sets = ruleSets(config, selection);
624
805
  const rules = sets.anywhere;
625
806
  const testFiles = config.replacesDefaultExclude
626
- ? defaults.exclude.map((pattern) => ({ pattern, matches: picomatch(pattern, { dot: true }) }))
807
+ ? defaultExcludes(config).map((pattern) => ({
808
+ pattern,
809
+ matches: picomatch(pattern, { dot: true }),
810
+ }))
627
811
  : undefined;
628
812
  const testsByPattern = new Map();
629
813
  const findings = [];
@@ -643,15 +827,26 @@ nextFiles, cache, ignores, timing) {
643
827
  summaries.set(entry.id, new Map());
644
828
  }
645
829
  }
646
- for (const unit of units) {
830
+ const analysisSummaries = new Map(sets.analyses.map((run) => [run.id, new Map()]));
831
+ const analysisFailures = new Map();
832
+ const opened = [];
833
+ for (const source of slicing?.reversed === true ? [...units].reverse() : units) {
834
+ const unit = timing === undefined ? source.open() : timed(timing, "program", () => source.open());
835
+ if (source.built === undefined)
836
+ total += unit.files.length;
647
837
  fileCount += unit.files.length;
648
- for (const file of unit.files) {
838
+ const perChecker = slicing?.filesPerChecker(unit.tsconfig);
839
+ const files = slicing?.reversed === true ? [...unit.files].reverse() : unit.files;
840
+ for (const [at, file] of files.entries()) {
841
+ if (perChecker !== undefined && at > 0 && at % perChecker === 0)
842
+ unit.renewChecker();
649
843
  if (testFiles !== undefined) {
650
844
  const relative = path.relative(cwd, file).split(path.sep).join("/");
651
845
  const hit = testFiles.find((entry) => entry.matches(relative));
652
846
  if (hit !== undefined)
653
847
  testsByPattern.set(hit.pattern, (testsByPattern.get(hit.pattern) ?? 0) + 1);
654
848
  }
849
+ cache?.progress?.started(file);
655
850
  const fingerprint = cache === undefined
656
851
  ? undefined
657
852
  : timing === undefined
@@ -664,8 +859,13 @@ nextFiles, cache, ignores, timing) {
664
859
  ? before
665
860
  : undefined;
666
861
  const reusable = holding?.rules;
667
- // Results of rules that did not run this time stay while the file's inputs are the same.
862
+ // Results of rules that did not run this time stay while the file's inputs are the same,
863
+ // and while a recent run used their rule (`pruneUnused`).
668
864
  const results = new Map(reusable ?? []);
865
+ if (cache !== undefined) {
866
+ useKey(cache, SYNTAX_RULE_ID);
867
+ useKey(cache, IMPORTS_RULE_ID);
868
+ }
669
869
  let syntax = results.get(SYNTAX_RULE_ID);
670
870
  if (syntax === undefined) {
671
871
  syntax = { findings: syntaxFinding(unit, file, cwd) };
@@ -726,6 +926,8 @@ nextFiles, cache, ignores, timing) {
726
926
  cache.changed = true;
727
927
  ledgerRefs.push(...ledger.refs);
728
928
  for (const entry of sets.forFile(file)) {
929
+ if (cache !== undefined)
930
+ useKey(cache, entry.key);
729
931
  let result = reusable?.get(entry.key);
730
932
  if (result === undefined) {
731
933
  const sourceFile = timing === undefined
@@ -762,19 +964,62 @@ nextFiles, cache, ignores, timing) {
762
964
  if (result.summary !== undefined)
763
965
  summaries.get(entry.id)?.set(file, result.summary);
764
966
  }
967
+ for (const run of sets.analyses) {
968
+ if (cache !== undefined)
969
+ useKey(cache, run.key);
970
+ let result = reusable?.get(run.key);
971
+ if (result === undefined) {
972
+ const sourceFile = timing === undefined
973
+ ? boundSourceFile(unit, file)
974
+ : timed(timing, "program", () => boundSourceFile(unit, file));
975
+ if (sourceFile === undefined)
976
+ continue;
977
+ fileTypes ??= unit.typesFor(file);
978
+ const types = fileTypes;
979
+ const ran = timing === undefined
980
+ ? runAnalysisOnFile(run, sourceFile, types, sameSummaries)
981
+ : timing.fileSide(run.id, "project", () => runAnalysisOnFile(run, sourceFile, timing.timedTypes(types), sameSummaries));
982
+ if (cache !== undefined)
983
+ cache.changed = true;
984
+ if (ran.failed) {
985
+ results.delete(run.key);
986
+ if (!analysisFailures.has(run.id)) {
987
+ analysisFailures.set(run.id, { file, error: ran.error });
988
+ }
989
+ yield { phase: "files", done, total, file, rule: run.id };
990
+ continue;
991
+ }
992
+ result = ran.result;
993
+ results.set(run.key, result);
994
+ yield { phase: "files", done, total, file, rule: run.id };
995
+ }
996
+ else {
997
+ timing?.reused(run.id, "project");
998
+ }
999
+ if (result.summary !== undefined)
1000
+ analysisSummaries.get(run.id)?.set(file, result.summary);
1001
+ }
765
1002
  if (fingerprint !== undefined) {
766
- nextFiles.set(file, {
1003
+ const next = {
767
1004
  fingerprint,
768
1005
  rules: results,
769
1006
  reads: readsAfter(unit, file, holding, results),
770
- });
1007
+ };
1008
+ nextFiles.set(file, next);
1009
+ cache?.progress?.finished(file, next);
771
1010
  }
772
1011
  done += 1;
773
1012
  yield { phase: "files", done, total };
774
1013
  }
1014
+ if (timing?.secondPass === true)
1015
+ secondPass(unit, sets, timing);
1016
+ // Everything the run needs of this program, asked before it is let go.
1017
+ opened.push(unitNotes(unit, rules, config.facts));
1018
+ timing?.filesDone();
1019
+ source.release();
775
1020
  }
776
- if (timing?.secondPass === true)
777
- secondPass(units, sets, timing);
1021
+ if (slicing?.reversed === true)
1022
+ opened.reverse();
778
1023
  if (cache !== undefined) {
779
1024
  // Only the files of this run: a deleted or excluded file's results go.
780
1025
  if (cache.files.size !== nextFiles.size)
@@ -787,15 +1032,17 @@ nextFiles, cache, ignores, timing) {
787
1032
  sets,
788
1033
  findings,
789
1034
  summaries,
1035
+ analysisSummaries,
1036
+ analysisFailures,
790
1037
  directives,
791
1038
  fileCount,
792
1039
  testsByPattern: testFiles === undefined ? undefined : testsByPattern,
793
1040
  tsconfigLocation: { file: failureFile(config, cwd, units), start: 0, end: 0 },
794
- projects: units.length > 1
795
- ? units.map((unit) => ({ tsconfig: unit.tsconfig, files: unit.files.length }))
1041
+ projects: opened.length > 1
1042
+ ? opened.map((unit) => ({ tsconfig: unit.tsconfig, files: unit.files.length }))
796
1043
  : undefined,
797
- notes: notesOf(units, rules),
798
- looseNulls: looseNullFiles(units),
1044
+ notes: notesOf(opened, config.facts, sets.gate),
1045
+ looseNulls: looseNullFiles(opened),
799
1046
  silenced,
800
1047
  stated,
801
1048
  ledger: {
@@ -821,8 +1068,17 @@ export function* projectPhaseSteps(config, phase, started, keepSummaries, cache,
821
1068
  const { sets, findings, summaries, directives, fileCount, testsByPattern, tsconfigLocation } = phase;
822
1069
  const silenced = [...phase.silenced];
823
1070
  const marks = [...phase.ledger.marks];
1071
+ const unstated = [];
824
1072
  const rules = sets.anywhere;
825
1073
  const total = rules.filter((entry) => entry.rule.kind === "project" && summaries.has(entry.id)).length;
1074
+ const analysisOf = solvedAnalyses(sets.analyses, phase.analysisSummaries, phase.analysisFailures, cache, timing);
1075
+ // An analysis's summaries, for the editor contributions and `silentReason` of its publisher.
1076
+ for (const run of sets.analyses) {
1077
+ keepSummaries?.set(run.id, () => {
1078
+ const found = analysisOf(run.id);
1079
+ return found?.kind === "solved" ? found.summaries() : new Map();
1080
+ });
1081
+ }
826
1082
  let done = 0;
827
1083
  let previous;
828
1084
  for (const entry of rules) {
@@ -846,37 +1102,50 @@ export function* projectPhaseSteps(config, phase, started, keepSummaries, cache,
846
1102
  previous = entry.id;
847
1103
  // In file order, so a rule cannot depend on the order the files were visited.
848
1104
  const sorted = [...fileSummaries].sort(([a], [b]) => compareText(a, b));
849
- const inputs = sha1(sorted.map(([file, summary]) => `${file}\u0000${summary.hash}`).join("\n"));
1105
+ const read = readAnalyses(config, entry, analysisOf, tsconfigLocation);
1106
+ if (read.kind === "not-run") {
1107
+ keepSummaries?.set(entry.id, () => summaryMap(sorted));
1108
+ findings.push(...atTheirFiles(sets, entry, read.findings, silenced));
1109
+ continue;
1110
+ }
1111
+ const inputs = sha1([
1112
+ ...sorted.map(([file, summary]) => `${file}\u0000${summary.hash}`),
1113
+ ...read.fingerprints.map((print) => `\u0001${print}`),
1114
+ ].join("\n"));
850
1115
  const before = cache?.projects.get(entry.key);
851
1116
  if (before?.inputs === inputs) {
852
1117
  findings.push(...atTheirFiles(sets, entry, before.findings, silenced));
1118
+ unstated.push(...unstatedAtTheirFiles(sets, entry, before.unstated ?? []));
853
1119
  marks.push(...withRule(entry.id, before.marks ?? []));
854
1120
  // Built only if a hover asks: a CLI run whose summaries are unchanged never parses them.
855
1121
  keepSummaries?.set(entry.id, () => (before.summaries ??= summaryMap(sorted)));
856
1122
  continue;
857
1123
  }
858
1124
  const own = [];
859
- const read = [];
1125
+ const settled = [];
1126
+ const ownUnstated = [];
860
1127
  const rule = entry.rule;
861
1128
  const runCheck = () => {
862
1129
  const asJson = summaryMap(sorted);
863
1130
  keepSummaries?.set(entry.id, () => asJson);
864
- rule.check(asJson, projectContext(entry, own, read));
1131
+ rule.check(asJson, projectContext(entry, own, settled, { analyses: read.values(), summaries: read.summaries }, ownUnstated));
865
1132
  return asJson;
866
1133
  };
867
1134
  try {
868
1135
  const asJson = timing === undefined ? runCheck() : timing.projectSide(entry.id, runCheck);
869
- const settledMarks = sortedMarks(read);
1136
+ const settledMarks = sortedMarks(settled);
870
1137
  marks.push(...withRule(entry.id, settledMarks));
871
1138
  if (cache !== undefined) {
872
1139
  cache.projects.set(entry.key, {
873
1140
  inputs,
874
1141
  findings: own,
1142
+ ...(ownUnstated.length === 0 ? {} : { unstated: ownUnstated }),
875
1143
  ...(settledMarks.length === 0 ? {} : { marks: settledMarks }),
876
1144
  summaries: asJson,
877
1145
  });
878
1146
  cache.changed = true;
879
1147
  }
1148
+ unstated.push(...unstatedAtTheirFiles(sets, entry, ownUnstated));
880
1149
  }
881
1150
  catch (error) {
882
1151
  own.push(failureFinding(entry, tsconfigLocation, error));
@@ -884,6 +1153,9 @@ export function* projectPhaseSteps(config, phase, started, keepSummaries, cache,
884
1153
  }
885
1154
  findings.push(...atTheirFiles(sets, entry, own, silenced));
886
1155
  }
1156
+ unstated.sort((a, b) => compareText(a.location.file, b.location.file) ||
1157
+ a.location.start - b.location.start ||
1158
+ compareText(a.ruleId, b.ruleId));
887
1159
  const covered = applyIgnores(withLooseNullFixes(oneCauseOneMessage(findings, rules), rules, phase.looseNulls), directives, ignoreScope(config, rules));
888
1160
  covered.findings.sort(compareFindings);
889
1161
  const { shown, hidden } = capped
@@ -901,6 +1173,7 @@ export function* projectPhaseSteps(config, phase, started, keepSummaries, cache,
901
1173
  ...withTagRules(phase.ledger.tagRules),
902
1174
  },
903
1175
  ...(phase.notes === undefined ? {} : { notes: phase.notes }),
1176
+ ...(unstated.length === 0 ? {} : { unstated }),
904
1177
  stats: {
905
1178
  files: fileCount,
906
1179
  durationMs: Math.round(performance.now() - started),
@@ -908,7 +1181,7 @@ export function* projectPhaseSteps(config, phase, started, keepSummaries, cache,
908
1181
  ? {}
909
1182
  : {
910
1183
  testFiles: [...testsByPattern.values()].reduce((sum, count) => sum + count, 0),
911
- testFilesByPattern: Object.fromEntries(defaults.exclude.flatMap((pattern) => {
1184
+ testFilesByPattern: Object.fromEntries(defaultExcludes(config).flatMap((pattern) => {
912
1185
  const count = testsByPattern.get(pattern);
913
1186
  return count === undefined ? [] : [[pattern, count]];
914
1187
  })),
@@ -917,6 +1190,143 @@ export function* projectPhaseSteps(config, phase, started, keepSummaries, cache,
917
1190
  },
918
1191
  };
919
1192
  }
1193
+ /** A rule asked for the summaries of an analysis it may not read them of. */
1194
+ class AnalysisSummariesError extends Error {
1195
+ constructor(ruleId, id) {
1196
+ super(`${ruleId} asked for the summaries of ${id}: a rule reads the summaries only of an analysis it lists in \`reads\` and its own plugin publishes`);
1197
+ this.name = "AnalysisSummariesError";
1198
+ }
1199
+ }
1200
+ /** Whether `id` (`"<plugin>/<name>"`) is an analysis of `plugin`. */
1201
+ function publishes(plugin, id) {
1202
+ return id.slice(0, id.indexOf("/")) === plugin;
1203
+ }
1204
+ /**
1205
+ * Each analysis of the run, solved at most once and only when a rule asks: an analysis whose
1206
+ * summaries are as the cache last saw them keeps its fingerprint, and is solved again only when a
1207
+ * rule that reads it must run.
1208
+ */
1209
+ function solvedAnalyses(runs, summaries, failures, cache, timing) {
1210
+ const done = new Map();
1211
+ const byId = new Map(runs.map((run) => [run.id, run]));
1212
+ return (id) => {
1213
+ const known = done.get(id);
1214
+ if (known !== undefined)
1215
+ return known;
1216
+ const run = byId.get(id);
1217
+ if (run === undefined)
1218
+ return undefined;
1219
+ // A file it could not summarize: solved without that file, it would be wrong, not partial.
1220
+ const failed = failures.get(id);
1221
+ if (failed !== undefined) {
1222
+ const solved = { kind: "failed", error: failed.error, file: failed.file };
1223
+ done.set(id, solved);
1224
+ return solved;
1225
+ }
1226
+ const sorted = [...(summaries.get(id) ?? [])].sort(([a], [b]) => compareText(a, b));
1227
+ const inputs = sha1(sorted.map(([file, summary]) => `${file}\u0000${summary.hash}`).join("\n"));
1228
+ const before = cache?.analyses.get(run.key);
1229
+ const kept = before?.inputs === inputs ? before : undefined;
1230
+ // One map for `solve` and the publisher's rules, kept with the entry while it holds.
1231
+ let map;
1232
+ const summariesNow = () => {
1233
+ map ??= kept === undefined ? summaryMap(sorted) : (kept.summaries ??= summaryMap(sorted));
1234
+ return map;
1235
+ };
1236
+ const solve = () => {
1237
+ const solveNow = () => deepFreeze(run.analysis.solve(summariesNow()));
1238
+ return timing === undefined ? solveNow() : timing.projectSide(id, solveNow);
1239
+ };
1240
+ let solved;
1241
+ try {
1242
+ if (kept !== undefined) {
1243
+ const entry = kept;
1244
+ solved = {
1245
+ kind: "solved",
1246
+ fingerprint: entry.fingerprint,
1247
+ value: () => (entry.value ??= solve()),
1248
+ inputs,
1249
+ summaries: summariesNow,
1250
+ };
1251
+ }
1252
+ else {
1253
+ const value = solve();
1254
+ const fingerprint = sha1(JSON.stringify(value));
1255
+ cache?.analyses.set(run.key, { inputs, fingerprint, value, summaries: summariesNow() });
1256
+ if (cache !== undefined)
1257
+ cache.changed = true;
1258
+ solved = {
1259
+ kind: "solved",
1260
+ fingerprint,
1261
+ value: () => value,
1262
+ inputs,
1263
+ summaries: summariesNow,
1264
+ };
1265
+ }
1266
+ }
1267
+ catch (error) {
1268
+ cache?.analyses.delete(run.key);
1269
+ solved = { kind: "failed", error };
1270
+ }
1271
+ done.set(id, solved);
1272
+ return solved;
1273
+ };
1274
+ }
1275
+ /**
1276
+ * What a project rule reads (`ProjectRule.reads`): the fingerprints of its analyses for its cache
1277
+ * inputs and their values for its check, or the findings it reports instead of running: one "not
1278
+ * checked" finding for each analysis the config's plugins do not publish (SW4), or a failure.
1279
+ */
1280
+ function readAnalyses(config, entry, analysisOf, location) {
1281
+ const reads = entry.rule.kind === "project" ? (entry.rule.reads ?? []) : [];
1282
+ const missing = [];
1283
+ const solved = [];
1284
+ for (const id of reads) {
1285
+ const found = analysisOf(id);
1286
+ if (found === undefined) {
1287
+ const target = readTarget(config.plugins, id);
1288
+ if (target.kind === "found")
1289
+ continue;
1290
+ missing.push({
1291
+ kind: "unknown",
1292
+ ruleId: entry.id,
1293
+ ...missingAnalysis(entry.id, id, target),
1294
+ location,
1295
+ ...listedFlag(entry),
1296
+ });
1297
+ }
1298
+ else if (found.kind === "failed") {
1299
+ const at = found.file === undefined ? location : { file: found.file, start: 0, end: 0 };
1300
+ const failure = failureFinding(entry, at, found.error);
1301
+ missing.push({ ...failure, message: `${failure.message} (in analysis ${id})` });
1302
+ }
1303
+ else if (publishes(entry.plugin, id)) {
1304
+ // Its own plugin's rule may read the summaries, so its results hold only while they do.
1305
+ solved.push({
1306
+ id,
1307
+ fingerprint: `${found.fingerprint}\u0000${found.inputs}`,
1308
+ value: found.value,
1309
+ summaries: found.summaries,
1310
+ });
1311
+ }
1312
+ else {
1313
+ solved.push({ id, fingerprint: found.fingerprint, value: found.value });
1314
+ }
1315
+ }
1316
+ if (missing.length > 0)
1317
+ return { kind: "not-run", findings: missing };
1318
+ return {
1319
+ kind: "run",
1320
+ fingerprints: solved.map((one) => `${one.id}\u0000${one.fingerprint}`),
1321
+ values: () => Object.fromEntries(solved.map((one) => [one.id, one.value()])),
1322
+ summaries: (id) => {
1323
+ const summaries = solved.find((one) => one.id === id)?.summaries;
1324
+ if (summaries === undefined)
1325
+ throw new AnalysisSummariesError(entry.id, id);
1326
+ return summaries();
1327
+ },
1328
+ };
1329
+ }
920
1330
  /**
921
1331
  * One cause, one message (`RuleMeta.yieldsTo`): a finding is left out when a rule it yields to
922
1332
  * reports a problem where the finding's `about` is. `about` itself is dropped from every finding.
@@ -1018,19 +1428,17 @@ function limitPerRuleAndFile(sorted) {
1018
1428
  * cost with the type checker warm (`RuleCost.warmMs`), for benchmarks. In file order, as the check
1019
1429
  * ran them, so a rule's memo of the last file is as cold as it was then.
1020
1430
  */
1021
- function secondPass(units, sets, timing) {
1022
- for (const unit of units) {
1023
- for (const file of unit.files) {
1024
- const sourceFile = unit.sourceFile(file);
1025
- if (sourceFile === undefined)
1026
- continue;
1027
- const same = new Map();
1028
- const types = timing.timedTypes(unit.typesFor(file));
1029
- for (const entry of sets.forFile(file)) {
1030
- timing.warmSide(entry.id, entry.rule.kind, () => {
1031
- runOnFile(entry, sourceFile, types, same, []);
1032
- });
1033
- }
1431
+ function secondPass(unit, sets, timing) {
1432
+ for (const file of unit.files) {
1433
+ const sourceFile = unit.sourceFile(file);
1434
+ if (sourceFile === undefined)
1435
+ continue;
1436
+ const same = new Map();
1437
+ const types = timing.timedTypes(unit.typesFor(file));
1438
+ for (const entry of sets.forFile(file)) {
1439
+ timing.warmSide(entry.id, entry.rule.kind, () => {
1440
+ runOnFile(entry, sourceFile, types, same, []);
1441
+ });
1034
1442
  }
1035
1443
  }
1036
1444
  }
@@ -1142,7 +1550,14 @@ export function silentReasons(config, selection, summaries) {
1142
1550
  const own = summaries.get(entry.id);
1143
1551
  if (own === undefined)
1144
1552
  continue;
1145
- const reason = entry.rule.silentReason?.(own(), { options: entry.options });
1553
+ const reason = entry.rule.silentReason?.(own(), {
1554
+ options: entry.options,
1555
+ analysisSummaries: (id) => {
1556
+ if (!publishes(entry.plugin, id))
1557
+ throw new AnalysisSummariesError(entry.id, id);
1558
+ return summaries.get(id)?.() ?? new Map();
1559
+ },
1560
+ });
1146
1561
  if (reason !== undefined)
1147
1562
  reasons.set(entry.id, reason);
1148
1563
  }