@stateward/core 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/backend/fingerprints.d.ts +22 -2
  2. package/dist/backend/fingerprints.js +160 -18
  3. package/dist/backend/program-record.d.ts +1 -1
  4. package/dist/backend/qualified-ids.d.ts +6 -0
  5. package/dist/backend/qualified-ids.js +66 -10
  6. package/dist/backend/typescript6.d.ts +28 -9
  7. package/dist/backend/typescript6.js +564 -28
  8. package/dist/baseline.js +10 -0
  9. package/dist/cache.d.ts +5 -4
  10. package/dist/cache.js +2 -2
  11. package/dist/checker.d.ts +14 -2
  12. package/dist/checker.js +40 -12
  13. package/dist/config-file.d.ts +6 -0
  14. package/dist/config-file.js +21 -2
  15. package/dist/config.d.ts +3 -1
  16. package/dist/config.js +164 -17
  17. package/dist/define.d.ts +2 -1
  18. package/dist/disk-cache.d.ts +24 -2
  19. package/dist/disk-cache.js +43 -5
  20. package/dist/engine.d.ts +27 -3
  21. package/dist/engine.js +224 -57
  22. package/dist/guarantee-markers.d.ts +10 -0
  23. package/dist/guarantee-markers.js +66 -0
  24. package/dist/guarantees.d.ts +44 -0
  25. package/dist/guarantees.js +84 -0
  26. package/dist/hint-lines.d.ts +24 -0
  27. package/dist/hint-lines.js +36 -0
  28. package/dist/ignores.d.ts +2 -4
  29. package/dist/ignores.js +31 -16
  30. package/dist/implementation.js +2 -1
  31. package/dist/index.d.ts +5 -1
  32. package/dist/index.js +4 -0
  33. package/dist/internal.d.ts +8 -3
  34. package/dist/internal.js +6 -3
  35. package/dist/package-facts.d.ts +52 -0
  36. package/dist/package-facts.js +213 -0
  37. package/dist/plan.d.ts +17 -0
  38. package/dist/plan.js +22 -5
  39. package/dist/release.d.ts +68 -0
  40. package/dist/release.js +172 -0
  41. package/dist/renamed.d.ts +29 -0
  42. package/dist/renamed.js +48 -0
  43. package/dist/rollout.js +3 -1
  44. package/dist/testing-tsc.d.ts +11 -0
  45. package/dist/testing-tsc.js +125 -0
  46. package/dist/testing.d.ts +1 -0
  47. package/dist/testing.js +61 -8
  48. package/dist/types.d.ts +261 -2
  49. package/package.json +1 -1
@@ -9,10 +9,32 @@ import type { ResultCache } from "./cache.js";
9
9
  */
10
10
  /** Where `stateward check` and the language server keep their cache, unless STATEWARD_CACHE_DIR says otherwise. */
11
11
  export declare const CACHE_SUBDIR: string;
12
- /** The cache folder for a project: STATEWARD_CACHE_DIR, else node_modules/.cache/stateward when node_modules exists. */
12
+ /** The folder beside the project used when there is neither node_modules nor a user cache folder. */
13
+ export declare const PROJECT_CACHE_DIR = ".stateward-cache";
14
+ /** What `defaultCacheDir` reads of the machine: the home folder ("" when unknown) and the platform. */
15
+ export type CacheMachine = {
16
+ readonly home: string;
17
+ readonly platform: NodeJS.Platform;
18
+ };
19
+ /**
20
+ * The user's cache folder of the platform: XDG_CACHE_HOME or ~/.cache on Linux and others,
21
+ * ~/Library/Caches on macOS, LOCALAPPDATA on Windows; undefined when none is known.
22
+ */
23
+ export declare function userCacheDir(env: {
24
+ XDG_CACHE_HOME?: string | undefined;
25
+ LOCALAPPDATA?: string | undefined;
26
+ }, machine?: CacheMachine): string | undefined;
27
+ /**
28
+ * The cache folder for a project: STATEWARD_CACHE_DIR; else node_modules/.cache/stateward when
29
+ * node_modules exists; else a folder of the user's cache folder named after the project's path
30
+ * (an app checked before its packages are installed, user trial 1.0.2); else
31
+ * `.stateward-cache` in the project.
32
+ */
13
33
  export declare function defaultCacheDir(project: string, env: {
14
34
  STATEWARD_CACHE_DIR?: string | undefined;
15
- }): string | undefined;
35
+ XDG_CACHE_HOME?: string | undefined;
36
+ LOCALAPPDATA?: string | undefined;
37
+ }, machine?: CacheMachine): string;
16
38
  /** The results cache's size limit unless STATEWARD_CACHE_MAX_MB sets another. */
17
39
  export declare const RESULTS_CACHE_DEFAULT_MB = 200;
18
40
  /** The size limit of a results cache folder in bytes: STATEWARD_CACHE_MAX_MB, else 200 MB. */
@@ -1,5 +1,6 @@
1
1
  import { createHash, randomBytes } from "node:crypto";
2
2
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, rmdirSync, unlinkSync, writeFileSync, } from "node:fs";
3
+ import { homedir } from "node:os";
3
4
  import path from "node:path";
4
5
  import { emptyCache, parseSnapshot, toSnapshot } from "./cache.js";
5
6
  import { cacheEntries, dropLeastRecentlyUsed, limitBytes, markUsed } from "./disk-limits.js";
@@ -15,14 +16,51 @@ import { statewardVersion } from "./package-cache.js";
15
16
  */
16
17
  /** Where `stateward check` and the language server keep their cache, unless STATEWARD_CACHE_DIR says otherwise. */
17
18
  export const CACHE_SUBDIR = path.join("node_modules", ".cache", "stateward");
18
- /** The cache folder for a project: STATEWARD_CACHE_DIR, else node_modules/.cache/stateward when node_modules exists. */
19
- export function defaultCacheDir(project, env) {
19
+ /** The folder beside the project used when there is neither node_modules nor a user cache folder. */
20
+ export const PROJECT_CACHE_DIR = ".stateward-cache";
21
+ function thisMachine() {
22
+ let home = "";
23
+ try {
24
+ home = homedir();
25
+ }
26
+ catch {
27
+ // No home folder (a service account): the project's own folder is used.
28
+ }
29
+ return { home, platform: process.platform };
30
+ }
31
+ /**
32
+ * The user's cache folder of the platform: XDG_CACHE_HOME or ~/.cache on Linux and others,
33
+ * ~/Library/Caches on macOS, LOCALAPPDATA on Windows; undefined when none is known.
34
+ */
35
+ export function userCacheDir(env, machine = thisMachine()) {
36
+ const given = (value) => value !== undefined && path.isAbsolute(value) ? value : undefined;
37
+ if (machine.platform === "win32")
38
+ return given(env.LOCALAPPDATA);
39
+ if (machine.home === "")
40
+ return given(env.XDG_CACHE_HOME);
41
+ if (machine.platform === "darwin")
42
+ return path.join(machine.home, "Library", "Caches");
43
+ return given(env.XDG_CACHE_HOME) ?? path.join(machine.home, ".cache");
44
+ }
45
+ /**
46
+ * The cache folder for a project: STATEWARD_CACHE_DIR; else node_modules/.cache/stateward when
47
+ * node_modules exists; else a folder of the user's cache folder named after the project's path
48
+ * (an app checked before its packages are installed, user trial 1.0.2); else
49
+ * `.stateward-cache` in the project.
50
+ */
51
+ export function defaultCacheDir(project, env, machine = thisMachine()) {
20
52
  const override = env.STATEWARD_CACHE_DIR;
21
53
  if (override !== undefined && override !== "")
22
54
  return path.resolve(project, override);
23
- return existsSync(path.join(project, "node_modules"))
24
- ? path.join(project, CACHE_SUBDIR)
25
- : undefined;
55
+ if (existsSync(path.join(project, "node_modules")))
56
+ return path.join(project, CACHE_SUBDIR);
57
+ const user = userCacheDir(env, machine);
58
+ if (user === undefined)
59
+ return path.join(project, PROJECT_CACHE_DIR);
60
+ const resolved = path.resolve(project);
61
+ const key = createHash("sha256").update(resolved).digest("hex").slice(0, 16);
62
+ const name = path.basename(resolved).replace(/[^\w.-]/g, "_") || "project";
63
+ return path.join(user, "stateward", "results", `${name}-${key}`);
26
64
  }
27
65
  /** The results cache's size limit unless STATEWARD_CACHE_MAX_MB sets another. */
28
66
  export const RESULTS_CACHE_DEFAULT_MB = 200;
package/dist/engine.d.ts CHANGED
@@ -2,7 +2,7 @@ import type { CachedSummary, ResultCache } from "./cache.js";
2
2
  import type { IgnoreDirective } from "./ignores.js";
3
3
  import type { ProjectUnit } from "./backend/typescript6.js";
4
4
  import type { TimingRecorder } from "./timing.js";
5
- import type { PackageFactsConfig, CheckResult, Config, Finding, HiddenFindings, Json, Location, Options, Rule, RuleSelection, RuleSetting, Severity } from "./types.js";
5
+ import type { PackageFactsConfig, CheckNotes, CheckResult, Config, Finding, HiddenFindings, Json, Location, Options, Rule, RuleSelection, RuleSetting, Severity } from "./types.js";
6
6
  /** More findings of one rule in one file than this are counted, not listed. */
7
7
  export declare const MAX_FINDINGS_PER_RULE_PER_FILE = 20;
8
8
  /**
@@ -12,6 +12,12 @@ export declare const MAX_FINDINGS_PER_RULE_PER_FILE = 20;
12
12
  export declare const SYNTAX_RULE_ID = "stateward/syntax";
13
13
  /** The id of the finding for a file with imports that do not resolve; cached like the syntax one. */
14
14
  export declare const IMPORTS_RULE_ID = "stateward/imports";
15
+ /** The remedy said once when a project checks without `strictNullChecks`. */
16
+ export declare const STRICT_NULLS_REMEDY = "set `strict: true` or `strictNullChecks: true` in tsconfig.json";
17
+ /** Added to the fix line of a finding whose fix relies on `strictNullChecks` in a project without it. */
18
+ export declare const LOOSE_NULLS_FIX = "`strictNullChecks` is off in this project, so TypeScript does not check `null` and `undefined` in this fix: set `strict: true` or `strictNullChecks: true` in tsconfig.json";
19
+ /** Why rules that read a library by its types could not run: "React's types are not installed (…)". */
20
+ export declare function missingTypesReason(library: string): string;
15
21
  type ActiveRule = {
16
22
  id: string;
17
23
  /** The plugin's name and the rule's name within it: `id` is "<plugin>/<name>". */
@@ -24,6 +30,8 @@ type ActiveRule = {
24
30
  options: Options;
25
31
  /** The config's facts about packages, for every rule: part of its cache key. */
26
32
  facts: PackageFactsConfig;
33
+ /** The facts the loaded plugins ship (`Plugin.facts`): part of its cache key too. */
34
+ shippedFacts: PackageFactsConfig;
27
35
  };
28
36
  /**
29
37
  * The rules a run uses, with the settings of the files they run on. A rule that is on in the
@@ -64,6 +72,10 @@ export type FilePhase = {
64
72
  tsconfig: string;
65
73
  files: number;
66
74
  }[] | undefined;
75
+ /** What the run cannot check as a whole (`CheckResult.notes`). */
76
+ readonly notes: CheckNotes | undefined;
77
+ /** The own files of the projects without `strictNullChecks`. */
78
+ readonly looseNulls: ReadonlySet<string>;
67
79
  };
68
80
  /**
69
81
  * The first of the two phases of running the rules (then `runProjectPhase`): every active rule
@@ -131,12 +143,24 @@ export declare function projectRuleIds(config: Config): ReadonlySet<string>;
131
143
  * rule id, from the summaries of a full check; rules with no reason are left out.
132
144
  */
133
145
  export declare function silentReasons(config: Config, selection: RuleSelection, summaries: ReadonlyMap<string, () => ReadonlyMap<string, Json>>): ReadonlyMap<string, string>;
146
+ /**
147
+ * What a fast pass may take from the cache instead of running the rules: the results the cache
148
+ * holds for each of `files` whose dependency fingerprint and reads are as they were then (the
149
+ * same test as a full pass's). Asking for a fingerprint computes those of the whole program
150
+ * once, so a caller names only the files it expects to be unchanged (an editor's file just opened).
151
+ */
152
+ export type FastReuse = {
153
+ readonly cache: ResultCache;
154
+ readonly files: ReadonlySet<string>;
155
+ };
134
156
  /**
135
157
  * Runs the file rules (not the project rules) over the own files of `units` that are in `files`
136
158
  * and returns findings for those files only. A project rule needs every file's summary, so it
137
- * does not run here. A rule that throws becomes a `failure`, as in `runFilePhase`.
159
+ * does not run here. A rule that throws becomes a `failure`, as in `runFilePhase`. With `reuse`, a
160
+ * rule whose result the cache holds for a reusable file is not run (`FastReuse`): an unchanged
161
+ * file costs no type checking.
138
162
  */
139
- export declare function runFileRules(config: Config, cwd: string, units: readonly ProjectUnit[], files: ReadonlySet<string>, started: number, capped?: boolean, ignores?: boolean): CheckResult;
163
+ export declare function runFileRules(config: Config, cwd: string, units: readonly ProjectUnit[], files: ReadonlySet<string>, started: number, capped?: boolean, ignores?: boolean, reuse?: FastReuse): CheckResult;
140
164
  /**
141
165
  * The markdown behind `stateward explain`, or undefined for an unknown rule id. A lazy rule's
142
166
  * text is in its module, which is loaded for it.
package/dist/engine.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import path from "node:path";
2
2
  import { readRollout } from "./rollout.js";
3
- import { ruleKey, sha1, summaryOf, summaryValue } from "./cache.js";
3
+ import { ruleKey, sha1, summaryOf, summaryText, summaryValue } from "./cache.js";
4
4
  import { defaultOptions } from "./options.js";
5
5
  import { codeOf, loadRule } from "./lazy.js";
6
- import { IGNORE_EXPLAIN, IGNORE_RULE_ID, applyIgnores, fileDirectives, readFileDirectives, } from "./ignores.js";
6
+ import { IGNORE_EXPLAIN, IGNORE_RULE_ID, applyIgnores, fileDirectives } from "./ignores.js";
7
7
  import { addonsWith, appliedOverrides, ruleIsOn, ruleSetting, ruleSettingWith, } from "./severity.js";
8
8
  import { matchingOverrides } from "./overrides.js";
9
9
  import { defaults } from "./config.js";
@@ -27,8 +27,8 @@ function syntaxFinding(unit, file, cwd) {
27
27
  {
28
28
  kind: "unknown",
29
29
  ruleId: SYNTAX_RULE_ID,
30
- message: `\`${name}\` has a syntax error, so findings in it may be missing or wrong`,
31
- hint: `${error.message} at line ${String(error.line)}:${String(error.column)}; fix it and check again`,
30
+ message: `not checked: \`${name}\`: it has a syntax error`,
31
+ hint: `fix the syntax error at line ${String(error.line)}:${String(error.column)} (${error.message}), then check again`,
32
32
  location: { file, start: error.start, end: error.end },
33
33
  },
34
34
  ];
@@ -45,34 +45,29 @@ function squeeze(text, max) {
45
45
  return `${text.slice(0, head)}…${text.slice(text.length - (keep - head))}`;
46
46
  }
47
47
  /**
48
- * The headline of an imports finding, in at most 100 characters: with the file's path when it fits
49
- * (the location shows it anyway), without it when not, and the specifier shortened last.
48
+ * The headline of an imports finding (M19), in at most 100 characters: the specifier is shortened
49
+ * in the middle when it does not fit; the location shows the file.
50
50
  */
51
- function importsMessage(name, specifier, untyped) {
52
- const what = untyped
53
- ? "which has no types, so findings using it may be wrong"
54
- : "which does not resolve, so findings using it may be wrong";
55
- const short = untyped
56
- ? "has no types, so findings using it here may be wrong"
57
- : "does not resolve, so findings using it here may be wrong";
58
- const forms = (spec) => [
59
- `\`${name}\` imports \`${spec}\`, ${what}`,
60
- `imports \`${spec}\`, ${what}`,
61
- `\`${spec}\` ${short}`,
62
- ];
63
- const fits = forms(specifier).find((form) => form.length <= MAX_HEADLINE);
64
- if (fits !== undefined)
65
- return fits;
66
- const room = MAX_HEADLINE - `\`\` ${short}`.length;
67
- return `\`${squeeze(specifier, room)}\` ${short}`;
51
+ function importsMessage(specifier, untyped) {
52
+ const relative = specifier.startsWith(".") || specifier.startsWith("/");
53
+ const why = untyped
54
+ ? "it has no types"
55
+ : relative
56
+ ? "the file is not found"
57
+ : "the package is not installed";
58
+ const form = (spec) => `not checked: code using \`${spec}\`: ${why}`;
59
+ const whole = form(specifier);
60
+ if (whole.length <= MAX_HEADLINE)
61
+ return whole;
62
+ const room = MAX_HEADLINE - form("").length;
63
+ return form(squeeze(specifier, room));
68
64
  }
69
65
  /** The one `unknown` finding for a file whose imports do not resolve (types from them are unknown). */
70
66
  function importsFinding(unit, file, cwd) {
71
67
  const [first, ...rest] = unit.unresolvedImports(file);
72
68
  if (first === undefined)
73
69
  return [];
74
- const name = path.relative(cwd, file).split(path.sep).join("/");
75
- const more = rest.length > 0 ? `; ${String(rest.length)} more unresolved in this file` : "";
70
+ const more = rest.length > 0 ? `; ${String(rest.length)} more unresolved in the file` : "";
76
71
  // Imports resolve by the project's options: a file two projects list says which one decided.
77
72
  const project = unit.listedElsewhere(file)
78
73
  ? ` (checked as part of \`${path.relative(cwd, unit.tsconfig).split(path.sep).join("/")}\`)`
@@ -83,7 +78,7 @@ function importsFinding(unit, file, cwd) {
83
78
  {
84
79
  kind: "unknown",
85
80
  ruleId: IMPORTS_RULE_ID,
86
- message: importsMessage(name, first.specifier, untyped),
81
+ message: importsMessage(first.specifier, untyped),
87
82
  hint: untyped
88
83
  ? `install its types (\`${types}\`) or declare the module${more}${project}`
89
84
  : `install the project's packages (or build its workspace packages) and check again${more}${project}`,
@@ -91,6 +86,65 @@ function importsFinding(unit, file, cwd) {
91
86
  },
92
87
  ];
93
88
  }
89
+ /** The remedy said once when a project checks without `strictNullChecks`. */
90
+ export const STRICT_NULLS_REMEDY = "set `strict: true` or `strictNullChecks: true` in tsconfig.json";
91
+ /** Added to the fix line of a finding whose fix relies on `strictNullChecks` in a project without it. */
92
+ export const LOOSE_NULLS_FIX = `\`strictNullChecks\` is off in this project, so TypeScript does not check \`null\` and \`undefined\` in this fix: ${STRICT_NULLS_REMEDY}`;
93
+ /** Why rules that read a library by its types could not run: "React's types are not installed (…)". */
94
+ export function missingTypesReason(library) {
95
+ return `${library}'s types are not installed (install the app's dependencies)`;
96
+ }
97
+ /**
98
+ * What the run cannot check as a whole (`CheckResult.notes`): the rules among `rules` whose
99
+ * library's types do not resolve in some project with files, and the projects without
100
+ * `strictNullChecks`. Undefined when there is nothing to say.
101
+ */
102
+ function notesOf(units, rules) {
103
+ const missing = new Map();
104
+ const looseNulls = [];
105
+ for (const unit of units) {
106
+ if (unit.files.length === 0)
107
+ continue;
108
+ if (!unit.strictNullChecks)
109
+ looseNulls.push(unit.tsconfig);
110
+ for (const entry of rules) {
111
+ const needs = entry.rule.meta.needsTypes;
112
+ if (needs === undefined || needs.modules.some((module) => unit.typesResolve(module)))
113
+ continue;
114
+ const ids = missing.get(needs.library) ?? new Set();
115
+ ids.add(entry.id);
116
+ missing.set(needs.library, ids);
117
+ }
118
+ }
119
+ if (missing.size === 0 && looseNulls.length === 0)
120
+ return undefined;
121
+ const missingTypes = [...missing]
122
+ .sort(([a], [b]) => compareText(a, b))
123
+ .map(([library, ids]) => ({
124
+ library,
125
+ reason: missingTypesReason(library),
126
+ rules: [...ids].sort(compareText),
127
+ }));
128
+ return { missingTypes, looseNulls };
129
+ }
130
+ /** The own files of the projects without `strictNullChecks`. */
131
+ function looseNullFiles(units) {
132
+ return new Set(units.flatMap((unit) => (unit.strictNullChecks ? [] : unit.files)));
133
+ }
134
+ /**
135
+ * `findings` with `LOOSE_NULLS_FIX` added to the fix line of each problem whose rule's fix needs
136
+ * `strictNullChecks` (`RuleInfo.fixNeedsStrictNulls`) in a file of a project without it.
137
+ */
138
+ function withLooseNullFixes(findings, rules, loose) {
139
+ if (loose.size === 0)
140
+ return findings;
141
+ const affected = new Set(rules.filter((entry) => entry.rule.meta.fixNeedsStrictNulls === true).map((entry) => entry.id));
142
+ if (affected.size === 0)
143
+ return findings;
144
+ return findings.map((finding) => finding.kind === "problem" && affected.has(finding.ruleId) && loose.has(finding.location.file)
145
+ ? { ...finding, hint: `${finding.hint}\n${LOOSE_NULLS_FIX}` }
146
+ : finding);
147
+ }
94
148
  /** What ignore comments may name, and what ran: the config's rules and what stateward reports itself. */
95
149
  function ignoreScope(config, ran) {
96
150
  const known = new Set([SYNTAX_RULE_ID, IMPORTS_RULE_ID]);
@@ -105,6 +159,19 @@ function ignoreScope(config, ran) {
105
159
  };
106
160
  }
107
161
  const FAILURE_HINT = "report this to the rule's authors; the rest of the check ran normally";
162
+ /**
163
+ * The facts every loaded plugin ships, joined in plugin order: per package, per function; a later
164
+ * plugin's line for the same function wins.
165
+ */
166
+ function shippedFactsOf(plugins) {
167
+ const joined = {};
168
+ for (const plugin of plugins) {
169
+ for (const [name, functions] of Object.entries(plugin.facts ?? {})) {
170
+ joined[name] = { ...joined[name], ...functions };
171
+ }
172
+ }
173
+ return joined;
174
+ }
108
175
  function nodeLocation(node) {
109
176
  return { file: node.getSourceFile().fileName, start: node.getStart(), end: node.getEnd() };
110
177
  }
@@ -138,8 +205,12 @@ function entryOf(config, plugin, name, rule, severity, addons) {
138
205
  addons,
139
206
  options,
140
207
  facts: config.facts,
208
+ shippedFacts: shippedFactsOf(config.plugins),
209
+ };
210
+ return {
211
+ ...active,
212
+ key: ruleKey({ ...active, facts: { config: active.facts, shipped: active.shippedFacts } }),
141
213
  };
142
- return { ...active, key: ruleKey(active) };
143
214
  }
144
215
  function ruleSets(config, selection) {
145
216
  const rolledOut = rolloutSet(config, selection);
@@ -286,7 +357,11 @@ function problemFinding(entry, problem) {
286
357
  kind: "problem",
287
358
  ruleId: entry.id,
288
359
  severity: setting ??
289
- (problem.severity === undefined ? entry.severity : lower(problem.severity, entry.severity)),
360
+ (problem.stated === true
361
+ ? "error"
362
+ : problem.severity === undefined
363
+ ? entry.severity
364
+ : lower(problem.severity, entry.severity)),
290
365
  message: problem.message,
291
366
  hint: problem.hint,
292
367
  location: problem.location,
@@ -297,7 +372,7 @@ function problemFinding(entry, problem) {
297
372
  };
298
373
  }
299
374
  function fileContext(entry, sourceFile, types, findings) {
300
- const { id, addons, options, facts } = entry;
375
+ const { id, addons, options, facts, shippedFacts } = entry;
301
376
  return {
302
377
  file: sourceFile.fileName,
303
378
  sourceFile,
@@ -305,6 +380,7 @@ function fileContext(entry, sourceFile, types, findings) {
305
380
  addons,
306
381
  options,
307
382
  facts,
383
+ shippedFacts,
308
384
  report(problem) {
309
385
  const finding = problemFinding(entry, {
310
386
  message: problem.message,
@@ -317,6 +393,7 @@ function fileContext(entry, sourceFile, types, findings) {
317
393
  fixes: problem.fixes ?? [],
318
394
  ...(problem.findingKind === undefined ? {} : { findingKind: problem.findingKind }),
319
395
  ...(problem.severity === undefined ? {} : { severity: problem.severity }),
396
+ ...(problem.stated === true ? { stated: true } : {}),
320
397
  ...(problem.about === undefined ? {} : { about: nodeLocation(problem.about) }),
321
398
  });
322
399
  if (finding !== undefined)
@@ -481,8 +558,9 @@ nextFiles, cache, ignores, timing) {
481
558
  let fileCount = 0;
482
559
  let done = 0;
483
560
  for (const entry of rules) {
484
- if (entry.rule.kind === "project")
561
+ if (entry.rule.kind === "project" || entry.rule.summarize !== undefined) {
485
562
  summaries.set(entry.id, new Map());
563
+ }
486
564
  }
487
565
  for (const unit of units) {
488
566
  fileCount += unit.files.length;
@@ -577,7 +655,7 @@ nextFiles, cache, ignores, timing) {
577
655
  nextFiles.set(file, {
578
656
  fingerprint,
579
657
  rules: results,
580
- reads: readsAfter(unit, file, holding),
658
+ reads: readsAfter(unit, file, holding, results),
581
659
  });
582
660
  }
583
661
  done += 1;
@@ -605,6 +683,8 @@ nextFiles, cache, ignores, timing) {
605
683
  projects: units.length > 1
606
684
  ? units.map((unit) => ({ tsconfig: unit.tsconfig, files: unit.files.length }))
607
685
  : undefined,
686
+ notes: notesOf(units, rules),
687
+ looseNulls: looseNullFiles(units),
608
688
  };
609
689
  }
610
690
  /** The rules' project sides: each project rule's check over the summaries, and the result. */
@@ -623,8 +703,14 @@ export function* projectPhaseSteps(config, phase, started, keepSummaries, cache,
623
703
  let previous;
624
704
  for (const entry of rules) {
625
705
  const fileSummaries = summaries.get(entry.id);
626
- if (entry.rule.kind !== "project" || fileSummaries === undefined)
706
+ if (fileSummaries === undefined)
707
+ continue;
708
+ if (entry.rule.kind !== "project") {
709
+ // A file rule's summaries are for the editor's contributions only (`FileRule.summarize`).
710
+ const sorted = [...fileSummaries].sort(([a], [b]) => compareText(a, b));
711
+ keepSummaries?.set(entry.id, () => summaryMap(sorted));
627
712
  continue;
713
+ }
628
714
  if (done > 0)
629
715
  yield {
630
716
  phase: "project",
@@ -665,7 +751,7 @@ export function* projectPhaseSteps(config, phase, started, keepSummaries, cache,
665
751
  }
666
752
  findings.push(...atTheirFiles(sets, entry, own));
667
753
  }
668
- const covered = applyIgnores(oneCauseOneMessage(findings, rules), directives, ignoreScope(config, rules));
754
+ const covered = applyIgnores(withLooseNullFixes(oneCauseOneMessage(findings, rules), rules, phase.looseNulls), directives, ignoreScope(config, rules));
669
755
  covered.findings.sort(compareFindings);
670
756
  const { shown, hidden } = capped
671
757
  ? limitPerRuleAndFile(withUnknownsShown(covered.findings, config.unknowns))
@@ -674,6 +760,7 @@ export function* projectPhaseSteps(config, phase, started, keepSummaries, cache,
674
760
  findings: shown,
675
761
  hidden,
676
762
  ignored: covered.ignored,
763
+ ...(phase.notes === undefined ? {} : { notes: phase.notes }),
677
764
  stats: {
678
765
  files: fileCount,
679
766
  durationMs: Math.round(performance.now() - started),
@@ -719,10 +806,44 @@ export function limitFindings(sorted) {
719
806
  const { shown, hidden } = limitPerRuleAndFile(sorted);
720
807
  return { findings: shown, hidden };
721
808
  }
809
+ /**
810
+ * Which findings the per-rule, per-file cap keeps first: failures, then errors, warnings, infos,
811
+ * and places not checked last. Kept in position order, a file's first 20 "not checked" places of a
812
+ * rule could hide an error of the same rule further down, and the check would pass.
813
+ */
814
+ function capRank(finding) {
815
+ switch (finding.kind) {
816
+ case "failure":
817
+ return 0;
818
+ case "problem":
819
+ switch (finding.severity) {
820
+ case "error":
821
+ return 1;
822
+ case "warning":
823
+ return 2;
824
+ case "info":
825
+ return 3;
826
+ default: {
827
+ const unreachable = finding.severity;
828
+ return unreachable;
829
+ }
830
+ }
831
+ case "unknown":
832
+ return 4;
833
+ default: {
834
+ const unreachable = finding;
835
+ return unreachable;
836
+ }
837
+ }
838
+ }
722
839
  function limitPerRuleAndFile(sorted) {
723
840
  const seen = new Map();
724
- const shown = [];
725
- for (const finding of sorted) {
841
+ const kept = new Set();
842
+ // Decide in priority order (stable within a rank), then list what is kept in position order.
843
+ const byRank = sorted
844
+ .map((finding, index) => ({ finding, index }))
845
+ .sort((a, b) => capRank(a.finding) - capRank(b.finding) || a.index - b.index);
846
+ for (const { finding } of byRank) {
726
847
  const key = JSON.stringify([finding.location.file, finding.ruleId]);
727
848
  const entry = seen.get(key) ?? {
728
849
  file: finding.location.file,
@@ -733,12 +854,13 @@ function limitPerRuleAndFile(sorted) {
733
854
  seen.set(key, entry);
734
855
  if (entry.listed < MAX_FINDINGS_PER_RULE_PER_FILE) {
735
856
  entry.listed++;
736
- shown.push(finding);
857
+ kept.add(finding);
737
858
  }
738
859
  else {
739
860
  entry.count++;
740
861
  }
741
862
  }
863
+ const shown = sorted.filter((finding) => kept.has(finding));
742
864
  const hidden = [...seen.values()]
743
865
  .filter((entry) => entry.count > 0)
744
866
  .map(({ file, ruleId, count }) => ({ file, ruleId, count }))
@@ -766,27 +888,45 @@ function secondPass(units, sets, timing) {
766
888
  }
767
889
  }
768
890
  }
769
- /** Whether every file a cached entry read the syntax of is as it was then. */
891
+ /** Whether everything a cached entry read of other files (declarations, files) is as it was then. */
770
892
  function readsHold(unit, reads) {
771
- for (const [file, print] of reads) {
772
- if (unit.readFingerprint(file) !== print)
893
+ for (const [read, print] of reads) {
894
+ if (unit.readFingerprint(read) !== print)
773
895
  return false;
774
896
  }
775
897
  return true;
776
898
  }
899
+ /** A print no read has: what could not be hashed never holds. */
900
+ const NO_PRINT = "";
777
901
  /**
778
902
  * The reads of a file's entry after this run: those of the entry it kept (its rules that did not
779
- * run read them), with what the rules that ran on it in this program read, each with its text hash.
903
+ * run read them), with what the rules that ran on it in this program read, each with its hash
904
+ * (`ProjectUnit.readsOf`). A declaration is read by its id, unless the file's results name the
905
+ * file it is in: a rule that keeps another file's offsets (a location, a summary's span) changes
906
+ * with any edit above them, so the whole file is read.
780
907
  */
781
- function readsAfter(unit, file, kept) {
908
+ function readsAfter(unit, file, kept, results) {
782
909
  const reads = new Map(kept?.reads ?? []);
783
- for (const read of unit.readsOf(file)) {
784
- const print = unit.readFingerprint(read);
785
- if (print !== undefined)
786
- reads.set(read, print);
910
+ let text;
911
+ const mentioned = (readFile) => {
912
+ text ??= resultsText(results);
913
+ return text.includes(readFile);
914
+ };
915
+ for (const read of unit.readsOf(file, mentioned)) {
916
+ reads.set(read, unit.readFingerprint(read) ?? NO_PRINT);
787
917
  }
788
918
  return reads;
789
919
  }
920
+ /** The findings and summaries of a file's results, as text: what the results could name. */
921
+ function resultsText(results) {
922
+ const parts = [];
923
+ for (const result of results.values()) {
924
+ parts.push(JSON.stringify(result.findings));
925
+ if (result.summary !== undefined)
926
+ parts.push(summaryText(result.summary));
927
+ }
928
+ return parts.join("\n");
929
+ }
790
930
  /** The parsed file, its program bound first (rules need parents): building the program if it is lazy. */
791
931
  function boundSourceFile(unit, file) {
792
932
  unit.bind();
@@ -807,7 +947,7 @@ function runFileSide(rule, ctx) {
807
947
  switch (rule.kind) {
808
948
  case "file":
809
949
  rule.check(ctx);
810
- return undefined;
950
+ return rule.summarize?.(ctx);
811
951
  case "project":
812
952
  return rule.summarize(ctx);
813
953
  default: {
@@ -853,12 +993,27 @@ export function silentReasons(config, selection, summaries) {
853
993
  }
854
994
  return reasons;
855
995
  }
996
+ /** The cached results of `file` when its fingerprint and reads hold, else undefined. */
997
+ function holdingResults(unit, file, cache) {
998
+ const entry = cache.files.get(file);
999
+ if (entry === undefined)
1000
+ return undefined;
1001
+ const fingerprint = unit.fingerprint(file);
1002
+ if (fingerprint === undefined || entry.fingerprint !== fingerprint)
1003
+ return undefined;
1004
+ if (!readsHold(unit, entry.reads))
1005
+ return undefined;
1006
+ // A copy: the fast pass never writes the cache (what it computes is for these files only).
1007
+ return new Map(entry.rules);
1008
+ }
856
1009
  /**
857
1010
  * Runs the file rules (not the project rules) over the own files of `units` that are in `files`
858
1011
  * and returns findings for those files only. A project rule needs every file's summary, so it
859
- * does not run here. A rule that throws becomes a `failure`, as in `runFilePhase`.
1012
+ * does not run here. A rule that throws becomes a `failure`, as in `runFilePhase`. With `reuse`, a
1013
+ * rule whose result the cache holds for a reusable file is not run (`FastReuse`): an unchanged
1014
+ * file costs no type checking.
860
1015
  */
861
- export function runFileRules(config, cwd, units, files, started, capped = true, ignores = true) {
1016
+ export function runFileRules(config, cwd, units, files, started, capped = true, ignores = true, reuse) {
862
1017
  // The same rules a full pass runs (rollout included), so the fast pass never shows a rule
863
1018
  // the developer has not turned on.
864
1019
  const sets = ruleSets(config, { kind: "configured" });
@@ -870,24 +1025,36 @@ export function runFileRules(config, cwd, units, files, started, capped = true,
870
1025
  for (const file of unit.files) {
871
1026
  if (!files.has(file))
872
1027
  continue;
873
- unit.bind();
874
- const sourceFile = unit.sourceFile(file);
875
- if (sourceFile === undefined)
876
- continue;
1028
+ const results = (reuse?.files.has(file) === true ? holdingResults(unit, file, reuse.cache) : undefined) ??
1029
+ new Map();
877
1030
  fileCount++;
878
- findings.push(...syntaxFinding(unit, file, cwd), ...importsFinding(unit, file, cwd));
1031
+ const syntax = results.get(SYNTAX_RULE_ID)?.findings ?? syntaxFinding(unit, file, cwd);
1032
+ const imports = results.get(IMPORTS_RULE_ID)?.findings ?? importsFinding(unit, file, cwd);
1033
+ findings.push(...syntax, ...imports);
879
1034
  if (ignores) {
880
- const read = readFileDirectives(unit, file);
1035
+ const read = fileDirectives(unit, file, results).directives;
881
1036
  if (read.length > 0)
882
1037
  directives.set(file, read);
883
1038
  }
884
1039
  const startOfFile = { file, start: 0, end: 0 };
885
- const types = unit.typesFor(file);
1040
+ let types;
886
1041
  for (const entry of sets.forFile(file)) {
887
1042
  if (entry.rule.kind !== "file")
888
1043
  continue;
1044
+ const result = results.get(entry.key);
1045
+ if (result !== undefined) {
1046
+ findings.push(...result.findings);
1047
+ continue;
1048
+ }
1049
+ // Rules need parents: bind before the first one runs. A file whose results all come from
1050
+ // the cache asks nothing of the program (a recorded one is then never built).
1051
+ const sourceFile = boundSourceFile(unit, file);
1052
+ if (sourceFile === undefined)
1053
+ break;
1054
+ types ??= unit.typesFor(file);
889
1055
  try {
890
- runFileSide(entry.rule, fileContext(entry, sourceFile, types, findings));
1056
+ // The fast pass keeps no summaries: a file rule's are read after a full check.
1057
+ entry.rule.check(fileContext(entry, sourceFile, types, findings));
891
1058
  }
892
1059
  catch (error) {
893
1060
  findings.push(failureFinding(entry, startOfFile, error));
@@ -896,7 +1063,7 @@ export function runFileRules(config, cwd, units, files, started, capped = true,
896
1063
  }
897
1064
  }
898
1065
  // Only the file rules ran, so an ignore of a project rule is not judged here.
899
- const covered = applyIgnores(oneCauseOneMessage(findings, rules), directives, ignoreScope(config, rules));
1066
+ const covered = applyIgnores(withLooseNullFixes(oneCauseOneMessage(findings, rules), rules, looseNullFiles(units)), directives, ignoreScope(config, rules));
900
1067
  covered.findings.sort(compareFindings);
901
1068
  const { shown, hidden } = capped
902
1069
  ? limitPerRuleAndFile(withUnknownsShown(covered.findings, config.unknowns))