@stateward/core 1.0.1 → 1.1.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.
@@ -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>". */
@@ -64,6 +70,10 @@ export type FilePhase = {
64
70
  tsconfig: string;
65
71
  files: number;
66
72
  }[] | undefined;
73
+ /** What the run cannot check as a whole (`CheckResult.notes`). */
74
+ readonly notes: CheckNotes | undefined;
75
+ /** The own files of the projects without `strictNullChecks`. */
76
+ readonly looseNulls: ReadonlySet<string>;
67
77
  };
68
78
  /**
69
79
  * The first of the two phases of running the rules (then `runProjectPhase`): every active rule
@@ -131,12 +141,24 @@ export declare function projectRuleIds(config: Config): ReadonlySet<string>;
131
141
  * rule id, from the summaries of a full check; rules with no reason are left out.
132
142
  */
133
143
  export declare function silentReasons(config: Config, selection: RuleSelection, summaries: ReadonlyMap<string, () => ReadonlyMap<string, Json>>): ReadonlyMap<string, string>;
144
+ /**
145
+ * What a fast pass may take from the cache instead of running the rules: the results the cache
146
+ * holds for each of `files` whose dependency fingerprint and reads are as they were then (the
147
+ * same test as a full pass's). Asking for a fingerprint computes those of the whole program
148
+ * once, so a caller names only the files it expects to be unchanged (an editor's file just opened).
149
+ */
150
+ export type FastReuse = {
151
+ readonly cache: ResultCache;
152
+ readonly files: ReadonlySet<string>;
153
+ };
134
154
  /**
135
155
  * Runs the file rules (not the project rules) over the own files of `units` that are in `files`
136
156
  * 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`.
157
+ * does not run here. A rule that throws becomes a `failure`, as in `runFilePhase`. With `reuse`, a
158
+ * rule whose result the cache holds for a reusable file is not run (`FastReuse`): an unchanged
159
+ * file costs no type checking.
138
160
  */
139
- export declare function runFileRules(config: Config, cwd: string, units: readonly ProjectUnit[], files: ReadonlySet<string>, started: number, capped?: boolean, ignores?: boolean): CheckResult;
161
+ export declare function runFileRules(config: Config, cwd: string, units: readonly ProjectUnit[], files: ReadonlySet<string>, started: number, capped?: boolean, ignores?: boolean, reuse?: FastReuse): CheckResult;
140
162
  /**
141
163
  * The markdown behind `stateward explain`, or undefined for an unknown rule id. A lazy rule's
142
164
  * 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]);
@@ -577,7 +631,7 @@ nextFiles, cache, ignores, timing) {
577
631
  nextFiles.set(file, {
578
632
  fingerprint,
579
633
  rules: results,
580
- reads: readsAfter(unit, file, holding),
634
+ reads: readsAfter(unit, file, holding, results),
581
635
  });
582
636
  }
583
637
  done += 1;
@@ -605,6 +659,8 @@ nextFiles, cache, ignores, timing) {
605
659
  projects: units.length > 1
606
660
  ? units.map((unit) => ({ tsconfig: unit.tsconfig, files: unit.files.length }))
607
661
  : undefined,
662
+ notes: notesOf(units, rules),
663
+ looseNulls: looseNullFiles(units),
608
664
  };
609
665
  }
610
666
  /** The rules' project sides: each project rule's check over the summaries, and the result. */
@@ -665,7 +721,7 @@ export function* projectPhaseSteps(config, phase, started, keepSummaries, cache,
665
721
  }
666
722
  findings.push(...atTheirFiles(sets, entry, own));
667
723
  }
668
- const covered = applyIgnores(oneCauseOneMessage(findings, rules), directives, ignoreScope(config, rules));
724
+ const covered = applyIgnores(withLooseNullFixes(oneCauseOneMessage(findings, rules), rules, phase.looseNulls), directives, ignoreScope(config, rules));
669
725
  covered.findings.sort(compareFindings);
670
726
  const { shown, hidden } = capped
671
727
  ? limitPerRuleAndFile(withUnknownsShown(covered.findings, config.unknowns))
@@ -674,6 +730,7 @@ export function* projectPhaseSteps(config, phase, started, keepSummaries, cache,
674
730
  findings: shown,
675
731
  hidden,
676
732
  ignored: covered.ignored,
733
+ ...(phase.notes === undefined ? {} : { notes: phase.notes }),
677
734
  stats: {
678
735
  files: fileCount,
679
736
  durationMs: Math.round(performance.now() - started),
@@ -719,10 +776,44 @@ export function limitFindings(sorted) {
719
776
  const { shown, hidden } = limitPerRuleAndFile(sorted);
720
777
  return { findings: shown, hidden };
721
778
  }
779
+ /**
780
+ * Which findings the per-rule, per-file cap keeps first: failures, then errors, warnings, infos,
781
+ * and places not checked last. Kept in position order, a file's first 20 "not checked" places of a
782
+ * rule could hide an error of the same rule further down, and the check would pass.
783
+ */
784
+ function capRank(finding) {
785
+ switch (finding.kind) {
786
+ case "failure":
787
+ return 0;
788
+ case "problem":
789
+ switch (finding.severity) {
790
+ case "error":
791
+ return 1;
792
+ case "warning":
793
+ return 2;
794
+ case "info":
795
+ return 3;
796
+ default: {
797
+ const unreachable = finding.severity;
798
+ return unreachable;
799
+ }
800
+ }
801
+ case "unknown":
802
+ return 4;
803
+ default: {
804
+ const unreachable = finding;
805
+ return unreachable;
806
+ }
807
+ }
808
+ }
722
809
  function limitPerRuleAndFile(sorted) {
723
810
  const seen = new Map();
724
- const shown = [];
725
- for (const finding of sorted) {
811
+ const kept = new Set();
812
+ // Decide in priority order (stable within a rank), then list what is kept in position order.
813
+ const byRank = sorted
814
+ .map((finding, index) => ({ finding, index }))
815
+ .sort((a, b) => capRank(a.finding) - capRank(b.finding) || a.index - b.index);
816
+ for (const { finding } of byRank) {
726
817
  const key = JSON.stringify([finding.location.file, finding.ruleId]);
727
818
  const entry = seen.get(key) ?? {
728
819
  file: finding.location.file,
@@ -733,12 +824,13 @@ function limitPerRuleAndFile(sorted) {
733
824
  seen.set(key, entry);
734
825
  if (entry.listed < MAX_FINDINGS_PER_RULE_PER_FILE) {
735
826
  entry.listed++;
736
- shown.push(finding);
827
+ kept.add(finding);
737
828
  }
738
829
  else {
739
830
  entry.count++;
740
831
  }
741
832
  }
833
+ const shown = sorted.filter((finding) => kept.has(finding));
742
834
  const hidden = [...seen.values()]
743
835
  .filter((entry) => entry.count > 0)
744
836
  .map(({ file, ruleId, count }) => ({ file, ruleId, count }))
@@ -766,27 +858,45 @@ function secondPass(units, sets, timing) {
766
858
  }
767
859
  }
768
860
  }
769
- /** Whether every file a cached entry read the syntax of is as it was then. */
861
+ /** Whether everything a cached entry read of other files (declarations, files) is as it was then. */
770
862
  function readsHold(unit, reads) {
771
- for (const [file, print] of reads) {
772
- if (unit.readFingerprint(file) !== print)
863
+ for (const [read, print] of reads) {
864
+ if (unit.readFingerprint(read) !== print)
773
865
  return false;
774
866
  }
775
867
  return true;
776
868
  }
869
+ /** A print no read has: what could not be hashed never holds. */
870
+ const NO_PRINT = "";
777
871
  /**
778
872
  * 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.
873
+ * run read them), with what the rules that ran on it in this program read, each with its hash
874
+ * (`ProjectUnit.readsOf`). A declaration is read by its id, unless the file's results name the
875
+ * file it is in: a rule that keeps another file's offsets (a location, a summary's span) changes
876
+ * with any edit above them, so the whole file is read.
780
877
  */
781
- function readsAfter(unit, file, kept) {
878
+ function readsAfter(unit, file, kept, results) {
782
879
  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);
880
+ let text;
881
+ const mentioned = (readFile) => {
882
+ text ??= resultsText(results);
883
+ return text.includes(readFile);
884
+ };
885
+ for (const read of unit.readsOf(file, mentioned)) {
886
+ reads.set(read, unit.readFingerprint(read) ?? NO_PRINT);
787
887
  }
788
888
  return reads;
789
889
  }
890
+ /** The findings and summaries of a file's results, as text: what the results could name. */
891
+ function resultsText(results) {
892
+ const parts = [];
893
+ for (const result of results.values()) {
894
+ parts.push(JSON.stringify(result.findings));
895
+ if (result.summary !== undefined)
896
+ parts.push(summaryText(result.summary));
897
+ }
898
+ return parts.join("\n");
899
+ }
790
900
  /** The parsed file, its program bound first (rules need parents): building the program if it is lazy. */
791
901
  function boundSourceFile(unit, file) {
792
902
  unit.bind();
@@ -853,12 +963,27 @@ export function silentReasons(config, selection, summaries) {
853
963
  }
854
964
  return reasons;
855
965
  }
966
+ /** The cached results of `file` when its fingerprint and reads hold, else undefined. */
967
+ function holdingResults(unit, file, cache) {
968
+ const entry = cache.files.get(file);
969
+ if (entry === undefined)
970
+ return undefined;
971
+ const fingerprint = unit.fingerprint(file);
972
+ if (fingerprint === undefined || entry.fingerprint !== fingerprint)
973
+ return undefined;
974
+ if (!readsHold(unit, entry.reads))
975
+ return undefined;
976
+ // A copy: the fast pass never writes the cache (what it computes is for these files only).
977
+ return new Map(entry.rules);
978
+ }
856
979
  /**
857
980
  * Runs the file rules (not the project rules) over the own files of `units` that are in `files`
858
981
  * 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`.
982
+ * does not run here. A rule that throws becomes a `failure`, as in `runFilePhase`. With `reuse`, a
983
+ * rule whose result the cache holds for a reusable file is not run (`FastReuse`): an unchanged
984
+ * file costs no type checking.
860
985
  */
861
- export function runFileRules(config, cwd, units, files, started, capped = true, ignores = true) {
986
+ export function runFileRules(config, cwd, units, files, started, capped = true, ignores = true, reuse) {
862
987
  // The same rules a full pass runs (rollout included), so the fast pass never shows a rule
863
988
  // the developer has not turned on.
864
989
  const sets = ruleSets(config, { kind: "configured" });
@@ -870,22 +995,33 @@ export function runFileRules(config, cwd, units, files, started, capped = true,
870
995
  for (const file of unit.files) {
871
996
  if (!files.has(file))
872
997
  continue;
873
- unit.bind();
874
- const sourceFile = unit.sourceFile(file);
875
- if (sourceFile === undefined)
876
- continue;
998
+ const results = (reuse?.files.has(file) === true ? holdingResults(unit, file, reuse.cache) : undefined) ??
999
+ new Map();
877
1000
  fileCount++;
878
- findings.push(...syntaxFinding(unit, file, cwd), ...importsFinding(unit, file, cwd));
1001
+ const syntax = results.get(SYNTAX_RULE_ID)?.findings ?? syntaxFinding(unit, file, cwd);
1002
+ const imports = results.get(IMPORTS_RULE_ID)?.findings ?? importsFinding(unit, file, cwd);
1003
+ findings.push(...syntax, ...imports);
879
1004
  if (ignores) {
880
- const read = readFileDirectives(unit, file);
1005
+ const read = fileDirectives(unit, file, results).directives;
881
1006
  if (read.length > 0)
882
1007
  directives.set(file, read);
883
1008
  }
884
1009
  const startOfFile = { file, start: 0, end: 0 };
885
- const types = unit.typesFor(file);
1010
+ let types;
886
1011
  for (const entry of sets.forFile(file)) {
887
1012
  if (entry.rule.kind !== "file")
888
1013
  continue;
1014
+ const result = results.get(entry.key);
1015
+ if (result !== undefined) {
1016
+ findings.push(...result.findings);
1017
+ continue;
1018
+ }
1019
+ // Rules need parents: bind before the first one runs. A file whose results all come from
1020
+ // the cache asks nothing of the program (a recorded one is then never built).
1021
+ const sourceFile = boundSourceFile(unit, file);
1022
+ if (sourceFile === undefined)
1023
+ break;
1024
+ types ??= unit.typesFor(file);
889
1025
  try {
890
1026
  runFileSide(entry.rule, fileContext(entry, sourceFile, types, findings));
891
1027
  }
@@ -896,7 +1032,7 @@ export function runFileRules(config, cwd, units, files, started, capped = true,
896
1032
  }
897
1033
  }
898
1034
  // 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));
1035
+ const covered = applyIgnores(withLooseNullFixes(oneCauseOneMessage(findings, rules), rules, looseNullFiles(units)), directives, ignoreScope(config, rules));
900
1036
  covered.findings.sort(compareFindings);
901
1037
  const { shown, hidden } = capped
902
1038
  ? limitPerRuleAndFile(withUnknownsShown(covered.findings, config.unknowns))
@@ -0,0 +1,41 @@
1
+ import type { Finding, StatedGuarantee } from "./types.js";
2
+ type Problem = Extract<Finding, {
3
+ kind: "problem";
4
+ }>;
5
+ /**
6
+ * Where a stated guarantee stands after a check:
7
+ * - `proven`: its rule ran and reported nothing about it;
8
+ * - `unproven`: its rule reported these errors about it (each names the declaration);
9
+ * - `unused`: nothing uses it, so there is nothing to prove (a dead marker);
10
+ * - `off`: its rule is not on (the rollout has not reached it), so nothing proves it.
11
+ */
12
+ export type GuaranteeStatus = {
13
+ readonly kind: "proven";
14
+ } | {
15
+ readonly kind: "unproven";
16
+ readonly errors: readonly Problem[];
17
+ } | {
18
+ readonly kind: "unused";
19
+ } | {
20
+ readonly kind: "off";
21
+ };
22
+ export type GuaranteeProof = {
23
+ readonly stated: StatedGuarantee;
24
+ readonly status: GuaranteeStatus;
25
+ };
26
+ /**
27
+ * Each stated guarantee with its status, in file and offset order. `findings` are a check's
28
+ * (after ignore comments, before a baseline: an accepted error still leaves it unproven);
29
+ * `active` the rules that check ran. A finding is about a guarantee when it is a problem of the
30
+ * guarantee's rule, not an info, with a related note at the declaration.
31
+ */
32
+ export declare function proveGuarantees(stated: readonly StatedGuarantee[], findings: readonly Finding[], active: ReadonlySet<string>): GuaranteeProof[];
33
+ /**
34
+ * The status in a few words, the same in `stateward guarantees` and the editor: "proven for 3
35
+ * readers", "not proven: 2 errors", "unused: nothing reads it", "not checked: … is not on".
36
+ */
37
+ export declare function describeStatus(proof: GuaranteeProof): string;
38
+ /** The guarantee whose declaration covers `offset` of `file` (a TypeScript path), if any. */
39
+ export declare function guaranteeAt(proofs: readonly GuaranteeProof[], file: string, offset: number): GuaranteeProof | undefined;
40
+ export {};
41
+ //# sourceMappingURL=guarantees.d.ts.map
@@ -0,0 +1,68 @@
1
+ import { compareFindings } from "./engine.js";
2
+ function sameStart(a, b) {
3
+ return a.file === b.file && a.start === b.start;
4
+ }
5
+ function compareStated(a, b) {
6
+ if (a.location.file !== b.location.file)
7
+ return a.location.file < b.location.file ? -1 : 1;
8
+ return a.location.start - b.location.start || (a.guarantee < b.guarantee ? -1 : 1);
9
+ }
10
+ /**
11
+ * Each stated guarantee with its status, in file and offset order. `findings` are a check's
12
+ * (after ignore comments, before a baseline: an accepted error still leaves it unproven);
13
+ * `active` the rules that check ran. A finding is about a guarantee when it is a problem of the
14
+ * guarantee's rule, not an info, with a related note at the declaration.
15
+ */
16
+ export function proveGuarantees(stated, findings, active) {
17
+ const problems = findings
18
+ .filter((finding) => finding.kind === "problem")
19
+ .filter((finding) => finding.severity !== "info");
20
+ return [...stated].sort(compareStated).map((guarantee) => {
21
+ if (!active.has(guarantee.ruleId))
22
+ return { stated: guarantee, status: { kind: "off" } };
23
+ const errors = problems
24
+ .filter((finding) => finding.ruleId === guarantee.ruleId &&
25
+ finding.related.some((note) => sameStart(note.location, guarantee.location)))
26
+ .sort(compareFindings);
27
+ if (errors.length > 0)
28
+ return { stated: guarantee, status: { kind: "unproven", errors } };
29
+ if (guarantee.covered.length === 0)
30
+ return { stated: guarantee, status: { kind: "unused" } };
31
+ return { stated: guarantee, status: { kind: "proven" } };
32
+ });
33
+ }
34
+ function plural(count, noun) {
35
+ return `${String(count)} ${count === 1 ? noun : `${noun}s`}`;
36
+ }
37
+ /** "reader" for "readers": the noun of one covered place. */
38
+ function singular(covers) {
39
+ return covers.endsWith("s") ? covers.slice(0, -1) : covers;
40
+ }
41
+ /**
42
+ * The status in a few words, the same in `stateward guarantees` and the editor: "proven for 3
43
+ * readers", "not proven: 2 errors", "unused: nothing reads it", "not checked: … is not on".
44
+ */
45
+ export function describeStatus(proof) {
46
+ const { stated, status } = proof;
47
+ switch (status.kind) {
48
+ case "proven":
49
+ return `proven for ${plural(stated.covered.length, singular(stated.covers))}`;
50
+ case "unproven":
51
+ return `not proven: ${plural(status.errors.length, "error")}`;
52
+ case "unused":
53
+ return `unused: no ${singular(stated.covers)}, so nothing to prove; use it or drop the marker`;
54
+ case "off":
55
+ return `not checked: ${stated.ruleId} is not on`;
56
+ default: {
57
+ const unreachable = status;
58
+ return unreachable;
59
+ }
60
+ }
61
+ }
62
+ /** The guarantee whose declaration covers `offset` of `file` (a TypeScript path), if any. */
63
+ export function guaranteeAt(proofs, file, offset) {
64
+ return proofs.find(({ stated }) => stated.location.file === file &&
65
+ offset >= stated.location.start &&
66
+ offset <= stated.location.end);
67
+ }
68
+ //# sourceMappingURL=guarantees.js.map