@stateward/plugin-errors 1.2.1 → 1.3.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 (56) hide show
  1. package/README.md +9 -8
  2. package/dist/catch-hides-unexpected.d.ts +4 -1
  3. package/dist/catch-hides-unexpected.js +87 -11
  4. package/dist/catch-misses-error.d.ts +1 -1
  5. package/dist/catch-misses-error.js +63 -20
  6. package/dist/finally-can-throw.js +46 -6
  7. package/dist/index.d.ts +3 -1
  8. package/dist/index.js +1 -0
  9. package/dist/inference/analysis.d.ts +109 -0
  10. package/dist/inference/analysis.js +170 -0
  11. package/dist/inference/builtins.d.ts +7 -2
  12. package/dist/inference/builtins.js +20 -33
  13. package/dist/inference/deps.js +2 -2
  14. package/dist/inference/needs.d.ts +16 -0
  15. package/dist/inference/needs.js +27 -0
  16. package/dist/inference/packages.d.ts +24 -32
  17. package/dist/inference/packages.js +156 -675
  18. package/dist/inference/project.d.ts +2 -2
  19. package/dist/inference/project.js +3 -2
  20. package/dist/inference/solve.d.ts +29 -4
  21. package/dist/inference/solve.js +34 -5
  22. package/dist/inference/summarize.d.ts +28 -15
  23. package/dist/inference/summarize.js +339 -135
  24. package/dist/inference/summary.d.ts +46 -5
  25. package/dist/inference/summary.js +89 -13
  26. package/dist/inference/unreachable.d.ts +5 -0
  27. package/dist/inference/unreachable.js +160 -0
  28. package/dist/must-handle-error.d.ts +2 -1
  29. package/dist/must-handle-error.js +4 -4
  30. package/dist/narrow-try.d.ts +2 -0
  31. package/dist/narrow-try.js +62 -7
  32. package/dist/plugin.d.ts +12 -2
  33. package/dist/plugin.js +4 -2
  34. package/dist/react/fallbacks.js +35 -14
  35. package/dist/react/tree.d.ts +10 -0
  36. package/dist/react/tree.js +54 -7
  37. package/dist/refactors.js +35 -2
  38. package/dist/render-throw-without-boundary.d.ts +13 -4
  39. package/dist/render-throw-without-boundary.js +100 -10
  40. package/dist/result-ignored.d.ts +4 -1
  41. package/dist/result-ignored.js +51 -10
  42. package/dist/result-type.d.ts +2 -0
  43. package/dist/result-type.js +8 -2
  44. package/dist/result-unchecked.d.ts +4 -1
  45. package/dist/result-unchecked.js +320 -96
  46. package/dist/rules.meta.d.ts +29 -14
  47. package/dist/rules.meta.js +19 -14
  48. package/dist/syntax.d.ts +0 -13
  49. package/dist/syntax.js +0 -79
  50. package/dist/text.d.ts +15 -2
  51. package/dist/text.js +28 -5
  52. package/dist/throws-doc-mismatch.d.ts +1 -1
  53. package/dist/throws-doc-mismatch.js +59 -5
  54. package/dist/throws-reads.d.ts +3 -0
  55. package/dist/throws-reads.js +108 -0
  56. package/package.json +2 -2
@@ -5,7 +5,13 @@ export declare const RULES: {
5
5
  readonly description: "A `catch` that tests some error classes and has no last branch ignores every other error, bugs included; rethrowing the rest keeps them visible.";
6
6
  readonly summary: "a `catch` that handles some error classes with `instanceof` and ignores the rest";
7
7
  readonly defaultSeverity: "error";
8
- readonly tier: "core";
8
+ readonly tier: "addon";
9
+ readonly addon: "catch-hides-unexpected";
10
+ readonly offByDefault: {
11
+ readonly since: "1.3";
12
+ readonly right: 4;
13
+ readonly checked: 7;
14
+ };
9
15
  readonly group: "catch";
10
16
  readonly options: {
11
17
  readonly restUsesError: {
@@ -81,6 +87,9 @@ export declare const RULES: {
81
87
  readonly description: "Error classes a `@throws` never needs to list (TypeError, *AbortError), as a catch names them.";
82
88
  };
83
89
  };
90
+ readonly proves: {
91
+ readonly tags: readonly ["throws"];
92
+ };
84
93
  };
85
94
  };
86
95
  readonly "render-throw-without-boundary": {
@@ -134,18 +143,6 @@ export declare const RULES: {
134
143
  readonly listUnknowns: true;
135
144
  };
136
145
  };
137
- readonly "narrow-try": {
138
- readonly kind: "project";
139
- readonly meta: {
140
- readonly description: "A bug in code inside a `try` meant for another call is caught and reported as that call's failure; moving the code after the `try` keeps the two apart.";
141
- readonly summary: "calls to your own code inside a `try` after the call it is for, so their bugs look like its failure";
142
- readonly defaultSeverity: "warning";
143
- readonly tier: "addon";
144
- readonly addon: "narrow-try";
145
- readonly group: "catch";
146
- readonly needsJsDoc: true;
147
- };
148
- };
149
146
  readonly "result-ignored": {
150
147
  readonly kind: "file";
151
148
  readonly meta: {
@@ -180,9 +177,27 @@ export declare const RULES: {
180
177
  readonly description: "A call that returns its failure instead of throwing never reaches the `catch`; without a check, the code after it runs as if the call worked.";
181
178
  readonly summary: "a call that fails in its value (an RTK Query trigger, a Result) used as if it had worked";
182
179
  readonly defaultSeverity: "warning";
183
- readonly tier: "core";
180
+ readonly tier: "addon";
181
+ readonly addon: "result-unchecked";
182
+ readonly offByDefault: {
183
+ readonly since: "1.3";
184
+ readonly right: 0;
185
+ readonly checked: 5;
186
+ };
184
187
  readonly group: "callers";
185
188
  readonly heuristic: true;
189
+ readonly options: {
190
+ readonly failureNames: {
191
+ readonly kind: "strings";
192
+ readonly default: readonly [];
193
+ readonly description: "Names (or globs like isErr*) that are true when the call failed, besides the result's own `error`: a property of the result (`isError`), or a function called with it (`isFailure(result)`). Its type does not say what such a name means.";
194
+ };
195
+ readonly successNames: {
196
+ readonly kind: "strings";
197
+ readonly default: readonly [];
198
+ readonly description: "Names (or globs) that are true when the call worked, besides the result's own `data`, `ok` and `success`: a property of the result (`isSuccess`, `value`), or a function called with it (`isOk(result)`).";
199
+ };
200
+ };
186
201
  };
187
202
  };
188
203
  };
@@ -5,7 +5,9 @@ export const RULES = {
5
5
  description: "A `catch` that tests some error classes and has no last branch ignores every other error, bugs included; rethrowing the rest keeps them visible.",
6
6
  summary: "a `catch` that handles some error classes with `instanceof` and ignores the rest",
7
7
  defaultSeverity: "error",
8
- tier: "core",
8
+ tier: "addon",
9
+ addon: "catch-hides-unexpected",
10
+ offByDefault: { since: "1.3", right: 4, checked: 7 },
9
11
  group: "catch",
10
12
  options: {
11
13
  restUsesError: {
@@ -81,6 +83,7 @@ export const RULES = {
81
83
  description: "Error classes a `@throws` never needs to list (TypeError, *AbortError), as a catch names them.",
82
84
  },
83
85
  },
86
+ proves: { tags: ["throws"] },
84
87
  },
85
88
  },
86
89
  "render-throw-without-boundary": {
@@ -129,18 +132,6 @@ export const RULES = {
129
132
  listUnknowns: true,
130
133
  },
131
134
  },
132
- "narrow-try": {
133
- kind: "project",
134
- meta: {
135
- description: "A bug in code inside a `try` meant for another call is caught and reported as that call's failure; moving the code after the `try` keeps the two apart.",
136
- summary: "calls to your own code inside a `try` after the call it is for, so their bugs look like its failure",
137
- defaultSeverity: "warning",
138
- tier: "addon",
139
- addon: "narrow-try",
140
- group: "catch",
141
- needsJsDoc: true,
142
- },
143
- },
144
135
  "result-ignored": {
145
136
  kind: "file",
146
137
  meta: {
@@ -175,9 +166,23 @@ export const RULES = {
175
166
  description: "A call that returns its failure instead of throwing never reaches the `catch`; without a check, the code after it runs as if the call worked.",
176
167
  summary: "a call that fails in its value (an RTK Query trigger, a Result) used as if it had worked",
177
168
  defaultSeverity: "warning",
178
- tier: "core",
169
+ tier: "addon",
170
+ addon: "result-unchecked",
171
+ offByDefault: { since: "1.3", right: 0, checked: 5 },
179
172
  group: "callers",
180
173
  heuristic: true,
174
+ options: {
175
+ failureNames: {
176
+ kind: "strings",
177
+ default: [],
178
+ description: "Names (or globs like isErr*) that are true when the call failed, besides the result's own `error`: a property of the result (`isError`), or a function called with it (`isFailure(result)`). Its type does not say what such a name means.",
179
+ },
180
+ successNames: {
181
+ kind: "strings",
182
+ default: [],
183
+ description: "Names (or globs) that are true when the call worked, besides the result's own `data`, `ok` and `success`: a property of the result (`isSuccess`, `value`), or a function called with it (`isOk(result)`).",
184
+ },
185
+ },
181
186
  },
182
187
  },
183
188
  };
package/dist/syntax.d.ts CHANGED
@@ -25,17 +25,4 @@ export declare function sameFileFunction(callee: ts.Expression, ctx: FileContext
25
25
  export declare function isBuiltinGlobal(name: ts.Identifier, ctx: FileContext): boolean;
26
26
  /** Whether the function has a `throw` that no `try` / `catch` of its own catches. */
27
27
  export declare function throwsUncaught(fn: DeclaredFunction): boolean;
28
- /**
29
- * Whether a `catch` tests what it caught before handling it: `e instanceof X`, `e.name === …`,
30
- * `"status" in e`, or a type guard `isApiError(e)`, in an `if`, a `switch` or a `?:`. Such a catch
31
- * says which errors it expects; `errors/catch-hides-unexpected` checks what it does with the rest.
32
- */
33
- export declare function testsCaught(clause: ts.CatchClause): boolean;
34
- /**
35
- * Whether `call`, in `clause`, hands the caught error to a callback the function around it was
36
- * given (`reject(e)`, `next(e)`, `onError(e)`): the caller gets it, as with a rethrow.
37
- */
38
- export declare function handsOnCaught(call: ts.CallExpression, clause: ts.CatchClause): boolean;
39
- /** Whether `test` holds for `root` or a node under it, without entering nested functions or classes. */
40
- export declare function someRunning(root: ts.Node, test: (node: ts.Node) => boolean): boolean;
41
28
  //# sourceMappingURL=syntax.d.ts.map
package/dist/syntax.js CHANGED
@@ -89,83 +89,4 @@ export function throwsUncaught(fn) {
89
89
  });
90
90
  return thrown;
91
91
  }
92
- /**
93
- * Whether a `catch` tests what it caught before handling it: `e instanceof X`, `e.name === …`,
94
- * `"status" in e`, or a type guard `isApiError(e)`, in an `if`, a `switch` or a `?:`. Such a catch
95
- * says which errors it expects; `errors/catch-hides-unexpected` checks what it does with the rest.
96
- */
97
- export function testsCaught(clause) {
98
- const declaration = clause.variableDeclaration;
99
- if (declaration === undefined || !ts.isIdentifier(declaration.name))
100
- return false;
101
- const variable = declaration.name.text;
102
- const isVariable = (node) => {
103
- const inner = stripParentheses(node);
104
- return ts.isIdentifier(inner) && inner.text === variable;
105
- };
106
- const tests = (condition) => {
107
- if (ts.isBinaryExpression(condition)) {
108
- const operator = condition.operatorToken.kind;
109
- if (operator === ts.SyntaxKind.InstanceOfKeyword && isVariable(condition.left))
110
- return true;
111
- if (operator === ts.SyntaxKind.InKeyword && isVariable(condition.right))
112
- return true;
113
- }
114
- if (ts.isPropertyAccessExpression(condition) && isVariable(condition.expression))
115
- return true;
116
- if (ts.isCallExpression(condition) && condition.arguments.some(isVariable))
117
- return true;
118
- return ts.forEachChild(condition, (child) => (tests(child) ? true : undefined)) === true;
119
- };
120
- let found = false;
121
- const walk = (node) => {
122
- if (found || isFunctionBoundary(node))
123
- return;
124
- if (ts.isIfStatement(node) && tests(node.expression))
125
- found = true;
126
- if (ts.isConditionalExpression(node) && tests(node.condition))
127
- found = true;
128
- if (ts.isSwitchStatement(node)) {
129
- found ||=
130
- tests(node.expression) ||
131
- node.caseBlock.clauses.some((one) => ts.isCaseClause(one) && tests(one.expression));
132
- }
133
- ts.forEachChild(node, walk);
134
- };
135
- walk(clause.block);
136
- return found;
137
- }
138
- /** A parameter of a function around `node` with this name: `reject`, `next`, `onError`. */
139
- function isParameterOfEnclosing(name, node) {
140
- for (let parent = node.parent; !ts.isSourceFile(parent); parent = parent.parent) {
141
- if (ts.isFunctionLike(parent) &&
142
- parent.parameters.some((parameter) => ts.isIdentifier(parameter.name) && parameter.name.text === name)) {
143
- return true;
144
- }
145
- }
146
- return false;
147
- }
148
- /**
149
- * Whether `call`, in `clause`, hands the caught error to a callback the function around it was
150
- * given (`reject(e)`, `next(e)`, `onError(e)`): the caller gets it, as with a rethrow.
151
- */
152
- export function handsOnCaught(call, clause) {
153
- const declaration = clause.variableDeclaration;
154
- if (declaration === undefined || !ts.isIdentifier(declaration.name))
155
- return false;
156
- const variable = declaration.name.text;
157
- const callee = stripParentheses(call.expression);
158
- return (ts.isIdentifier(callee) &&
159
- isParameterOfEnclosing(callee.text, clause) &&
160
- call.arguments.some((argument) => {
161
- const inner = stripParentheses(argument);
162
- return ts.isIdentifier(inner) && inner.text === variable;
163
- }));
164
- }
165
- /** Whether `test` holds for `root` or a node under it, without entering nested functions or classes. */
166
- export function someRunning(root, test) {
167
- const walk = (node) => (node === root || !isFunctionBoundary(node)) &&
168
- (test(node) || ts.forEachChild(node, (child) => (walk(child) ? true : undefined)) === true);
169
- return walk(root);
170
- }
171
92
  //# sourceMappingURL=syntax.js.map
package/dist/text.d.ts CHANGED
@@ -2,10 +2,13 @@
2
2
  export declare const HEADLINE_MAX = 100;
3
3
  /** The first line of a fix is at most this long. */
4
4
  export declare const HINT_MAX = 140;
5
- /** The text on one line: all whitespace becomes a single space. */
6
- export declare function oneLine(text: string): string;
7
5
  /** The text as it is, or its first `max - 1` characters and `…` when it is longer than `max`. */
8
6
  export declare function shorten(text: string, max: number): string;
7
+ /**
8
+ * The text as it is, or `…` and its last `max - 1` characters when it is longer than `max`: for a
9
+ * called function, whose name is at the end (`…delete().from` of a long chain).
10
+ */
11
+ export declare function shortenStart(text: string, max: number): string;
9
12
  /**
10
13
  * Builds a message whose inserted names are shown whole, on one line: a developer's name is never
11
14
  * cut. A headline that is longer than the limit because of its names is allowed to be.
@@ -19,4 +22,14 @@ export declare function fitted(build: (cut: (text: string) => string) => string)
19
22
  export declare function codeList(names: readonly string[], cut: (text: string) => string): string;
20
23
  /** A fix line followed by a code example, each example line indented by 4 spaces. */
21
24
  export declare function withExample(line: string, example: readonly string[]): string;
25
+ /** One way to fix a finding: what to do, in lowercase, and the code that does it when it can be shown. */
26
+ export type Way = {
27
+ readonly text: string;
28
+ readonly example?: readonly string[];
29
+ };
30
+ /**
31
+ * A fix hint of several ways (`one of`, a `- ` line each, every one after the first starting with
32
+ * `or`), or the one way as a first line with its example.
33
+ */
34
+ export declare function waysHint(ways: readonly Way[]): string;
22
35
  //# sourceMappingURL=text.d.ts.map
package/dist/text.js CHANGED
@@ -1,24 +1,30 @@
1
+ import { codeOnOneLine } from "@stateward/core";
1
2
  /** A headline is at most this long. */
2
3
  export const HEADLINE_MAX = 100;
3
4
  /** The first line of a fix is at most this long. */
4
5
  export const HINT_MAX = 140;
5
- /** The text on one line: all whitespace becomes a single space. */
6
- export function oneLine(text) {
7
- return text.replace(/\s+/g, " ").trim();
8
- }
9
6
  /** The text as it is, or its first `max - 1` characters and `…` when it is longer than `max`. */
10
7
  export function shorten(text, max) {
11
8
  if (text.length <= max)
12
9
  return text;
13
10
  return `${text.slice(0, max - 1)}…`;
14
11
  }
12
+ /**
13
+ * The text as it is, or `…` and its last `max - 1` characters when it is longer than `max`: for a
14
+ * called function, whose name is at the end (`…delete().from` of a long chain).
15
+ */
16
+ export function shortenStart(text, max) {
17
+ if (text.length <= max)
18
+ return text;
19
+ return `…${text.slice(text.length - (max - 1))}`;
20
+ }
15
21
  /**
16
22
  * Builds a message whose inserted names are shown whole, on one line: a developer's name is never
17
23
  * cut. A headline that is longer than the limit because of its names is allowed to be.
18
24
  * `build` applies the given `cut` to every name it inserts.
19
25
  */
20
26
  export function fitted(build) {
21
- return build(oneLine);
27
+ return build(codeOnOneLine);
22
28
  }
23
29
  /** The names that a list shows, at most this many; the rest are counted. */
24
30
  const MAX_LISTED = 3;
@@ -40,4 +46,21 @@ export function codeList(names, cut) {
40
46
  export function withExample(line, example) {
41
47
  return [line, ...example.map((text) => ` ${text}`)].join("\n");
42
48
  }
49
+ /**
50
+ * A fix hint of several ways (`one of`, a `- ` line each, every one after the first starting with
51
+ * `or`), or the one way as a first line with its example.
52
+ */
53
+ export function waysHint(ways) {
54
+ const [only] = ways;
55
+ if (ways.length === 1 && only !== undefined) {
56
+ return only.example === undefined ? only.text : withExample(`${only.text}:`, only.example);
57
+ }
58
+ return [
59
+ "one of",
60
+ ...ways.flatMap((way, index) => [
61
+ `- ${index === 0 ? "" : "or "}${way.text}${way.example === undefined ? "" : ":"}`,
62
+ ...(way.example ?? []).map((line) => ` ${line}`),
63
+ ]),
64
+ ].join("\n");
65
+ }
43
66
  //# sourceMappingURL=text.js.map
@@ -3,5 +3,5 @@ export declare const GROUP = "callers";
3
3
  export declare const throwsDocMismatch: import("@stateward/core").ProjectRule<import("./index.js").ThrowsSummary, {
4
4
  severities: import("@stateward/core").SeveritiesOption<"missing" | "extra">;
5
5
  ignoreClasses: import("@stateward/core").StringsOption;
6
- }, "callers">;
6
+ }, "callers", Readonly<Record<string, import("@stateward/core").Json>>>;
7
7
  //# sourceMappingURL=throws-doc-mismatch.d.ts.map
@@ -1,8 +1,11 @@
1
1
  import { defineRule, matchesName, option } from "@stateward/core";
2
2
  import { catchName, className } from "./inference/format.js";
3
3
  import { analyse, collected, evaluated, relation } from "./inference/solve.js";
4
+ import { REASON } from "./inference/summarize.js";
5
+ import { decidingFacts } from "./inference/needs.js";
4
6
  import { summarizeOnce } from "./inference/project.js";
5
7
  import { codeList, fitted } from "./text.js";
8
+ import { markThrowsReferences } from "./throws-reads.js";
6
9
  /** The group the rule belongs to in the docs and in `stateward status`. */
7
10
  export const GROUP = "callers";
8
11
  const EXPLAIN = `# errors/throws-doc-mismatch
@@ -41,10 +44,11 @@ The message links to the call that throws each missing class. There is no quick
41
44
 
42
45
  - A listed class that comes from a call stateward cannot see into (a package, a callback, a dynamic call): it names the call. Remove the class from the tag if the function cannot throw it, or declare the package's errors under \`facts\` in the config (\`facts: { "config-lib": { load: { throws: ["ConfigError"] } } }\`).
43
46
  - A name in the tag that is not a class in scope: import the class, or use a name in scope.
47
+ - A place it cannot follow in a function with a typed tag: a call through an alias (\`const f = auth; f(text)\`), a callback, a function with no body, an error made by a call (\`throw makeError()\`), a getter or setter that runs. It may throw a class the tag does not list, so it is listed as "not checked: the call \`f(…)\` cannot be followed" (the tag is never taken at its word). A tagged generator, and a \`@throws\` without a class, are "not checked" in \`stateward guarantees\`.
44
48
 
45
49
  ## What it does not catch
46
50
 
47
- It compares the tag with what the function can throw (its own \`throw new X(…)\`, the functions it calls, and the built-ins stateward knows) and reports a class in the tag that the function cannot throw (neither it nor a subclass), and a class it can throw that the tag does not cover. On a function that returns a promise, \`@throws\` means what the promise rejects with. It is silent on:
51
+ It compares the tag with what the function can throw (its own \`throw new X(…)\`, an error kept in a \`const\` or built with \`Object.assign(new X(), …)\`, the functions it calls, also through \`.call\` and \`.apply\`, and the built-ins stateward knows) and reports a class in the tag that the function cannot throw (neither it nor a subclass), and a class it can throw that the tag does not cover. On a function that returns a promise, \`@throws\` means what the promise rejects with. It is silent on:
48
52
 
49
53
  - a function without \`@throws\`, or a tag without a type (\`@throws when the id is empty\`): that only says the function throws;
50
54
  - a class that a surrounding \`try\` may catch: only classes that surely escape are reported as missing;
@@ -75,7 +79,16 @@ const OPTIONS = {
75
79
  description: "Error classes a `@throws` never needs to list (TypeError, *AbortError), as a catch names them.",
76
80
  }),
77
81
  };
78
- function check(entry, analysis, ctx) {
82
+ /** Whether a source that cannot be followed is a call: a name with no body to read, a callback, an alias. */
83
+ function isCall(source) {
84
+ return (source.reason === REASON.noDeclaration ||
85
+ source.reason === REASON.noBody ||
86
+ source.reason === REASON.callback ||
87
+ source.reason === REASON.dynamic ||
88
+ source.reason.startsWith("package ") ||
89
+ source.reason.startsWith("callback passed to"));
90
+ }
91
+ function check(entry, analysis, ctx, reported) {
79
92
  const doc = entry.fact.doc;
80
93
  if (doc === null)
81
94
  return;
@@ -94,7 +107,13 @@ function check(entry, analysis, ctx) {
94
107
  all.unknowns.set(key, source);
95
108
  }
96
109
  const name = entry.fact.name;
110
+ // Every finding about the tag is against the declaration it is on (the reference ledger's id).
111
+ const against = [
112
+ { file: entry.file, start: doc.declared, end: doc.declared },
113
+ ];
97
114
  const firstUnknown = [...all.unknowns.values()][0];
115
+ // The listed classes that cannot be checked because of an unknown already say what it is.
116
+ let saidUnknown = false;
98
117
  for (const item of doc.entries) {
99
118
  const location = locationOf(entry.file, item.at);
100
119
  if (item.id === null) {
@@ -102,6 +121,7 @@ function check(entry, analysis, ctx) {
102
121
  message: fitted((cut) => `not checked: \`@throws\` names \`${cut(item.name)}\`: no class of that name is in scope`),
103
122
  hint: "name an error class that is in scope in this file, or import it",
104
123
  location,
124
+ against,
105
125
  });
106
126
  continue;
107
127
  }
@@ -111,10 +131,14 @@ function check(entry, analysis, ctx) {
111
131
  continue;
112
132
  const listed = className(id, classes);
113
133
  if (firstUnknown !== undefined) {
134
+ saidUnknown = true;
114
135
  ctx.unknown({
115
136
  message: fitted((cut) => `not checked: whether \`${cut(name)}\` throws \`${cut(listed)}\`: what \`${cut(firstUnknown.text)}\` throws is not known (${firstUnknown.reason})`),
116
137
  hint: `remove \`${listed}\` from the tag if \`${name}\` cannot throw it; otherwise add \`@throws\` where it comes from`,
117
138
  location,
139
+ against,
140
+ // Every call the function cannot follow decides it, not only the one the message names.
141
+ ...decidingFacts(all.unknowns.values()),
118
142
  });
119
143
  continue;
120
144
  }
@@ -123,10 +147,30 @@ function check(entry, analysis, ctx) {
123
147
  hint: `remove \`${listed}\` from the tag, or throw it where it can happen`,
124
148
  location,
125
149
  findingKind: "extra",
150
+ against,
126
151
  });
127
152
  }
128
153
  if (doc.untyped.length > 0 || doc.entries.some((item) => item.id === null))
129
154
  return;
155
+ // A place the proof cannot follow may throw a class the tag does not list: not checked, never
156
+ // silent, and never taken at the tag's word (a call, a thrown value of unknown class, a getter).
157
+ for (const source of all.unknowns.values()) {
158
+ const key = `${entry.fact.id}\u0000${source.file}\u0000${String(source.start)}`;
159
+ if (saidUnknown || reported.has(key))
160
+ continue;
161
+ reported.add(key);
162
+ ctx.unknown({
163
+ message: fitted((cut) => isCall(source)
164
+ ? `not checked: the call \`${cut(source.text)}(…)\` cannot be followed (${source.reason})`
165
+ : `not checked: what \`${cut(source.text)}\` throws is not known (${source.reason}), so \`@throws\` of \`${cut(name)}\` cannot be checked`),
166
+ hint: fitted((cut) => source.fact?.kind === "untyped"
167
+ ? `import the module with \`import … from\`, so its types load and the call can be named in \`facts\`; then \`${cut(name)}\`'s tag can be checked`
168
+ : `call the function itself, or state what it throws with \`@throws\` on it or \`facts\`, so \`${cut(name)}\`'s tag can be checked`),
169
+ location: locationOf(source.file, [source.start, source.end]),
170
+ against,
171
+ ...decidingFacts([source]),
172
+ });
173
+ }
130
174
  const missing = [];
131
175
  for (const [id, info] of all.classes) {
132
176
  if (!info.certain || matchesName(catchName(id, classes), ctx.options.ignoreClasses))
@@ -151,10 +195,15 @@ function check(entry, analysis, ctx) {
151
195
  const tagNames = [...new Set(missing.map((one) => catchName(one.id, classes)))].sort();
152
196
  ctx.report({
153
197
  message: fitted((cut) => `\`@throws\` of \`${cut(name)}\` does not list ${codeList(names, cut)}`),
154
- hint: `add ${missing.length === 1 ? "it" : "them"} to the tag: \`@throws {${tagNames.join(" | ")}}\``,
198
+ hint: [
199
+ "one of",
200
+ fitted((cut) => `- catch ${missing.length === 1 ? "it" : "them"} inside \`${cut(name)}\`, if ${missing.length === 1 ? "it escapes" : "they escape"} by mistake`),
201
+ `- or add ${missing.length === 1 ? "it" : "them"} to the tag, if callers are to handle ${missing.length === 1 ? "it" : "them"}: \`@throws {${tagNames.join(" | ")}}\``,
202
+ ].join("\n"),
155
203
  location: locationOf(entry.file, entry.fact.at),
156
204
  related: missing.flatMap((one) => (one.related === undefined ? [] : [one.related])).slice(0, 3),
157
205
  findingKind: "missing",
206
+ against,
158
207
  });
159
208
  }
160
209
  export const throwsDocMismatch = defineRule({
@@ -168,12 +217,17 @@ export const throwsDocMismatch = defineRule({
168
217
  needsJsDoc: true,
169
218
  options: OPTIONS,
170
219
  explain: EXPLAIN,
220
+ proves: { tags: ["throws"] },
221
+ },
222
+ summarize: (ctx) => {
223
+ markThrowsReferences(ctx);
224
+ return summarizeOnce(ctx);
171
225
  },
172
- summarize: (ctx) => summarizeOnce(ctx),
173
226
  check(summaries, ctx) {
174
227
  const analysis = analyse(summaries);
228
+ const reported = new Set();
175
229
  for (const entry of analysis.functions.values())
176
- check(entry, analysis, ctx);
230
+ check(entry, analysis, ctx, reported);
177
231
  },
178
232
  });
179
233
  //# sourceMappingURL=throws-doc-mismatch.js.map
@@ -0,0 +1,3 @@
1
+ import type { FileContext } from "@stateward/core";
2
+ export declare function markThrowsReferences(ctx: FileContext): void;
3
+ //# sourceMappingURL=throws-reads.d.ts.map
@@ -0,0 +1,108 @@
1
+ import ts from "@stateward/core/typescript";
2
+ /**
3
+ * The references of `@throws` the reference ledger lists in one file, marked for
4
+ * `errors/throws-doc-mismatch`: the tag on a function it reads is decided (the project side
5
+ * reports what the function can throw against it); a tag it cannot check is not checked, with
6
+ * why; a call, an alias, an argument or an import only uses what the function's body proves.
7
+ */
8
+ /** The trait a `@throws` tag states in the reference ledger. */
9
+ const TRAIT = "@throws";
10
+ /** The function a declaration holds, written in place. */
11
+ function heldFunction(node) {
12
+ if (!(ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node)))
13
+ return undefined;
14
+ let value = node.initializer;
15
+ while (value !== undefined && ts.isParenthesizedExpression(value))
16
+ value = value.expression;
17
+ return value !== undefined && (ts.isArrowFunction(value) || ts.isFunctionExpression(value))
18
+ ? value
19
+ : undefined;
20
+ }
21
+ /** A declaration a tag can be on, as the reference ledger lists it. */
22
+ function isTaggable(node) {
23
+ return (ts.isFunctionDeclaration(node) ||
24
+ ts.isMethodDeclaration(node) ||
25
+ ts.isMethodSignature(node) ||
26
+ ts.isVariableDeclaration(node) ||
27
+ ts.isPropertyDeclaration(node) ||
28
+ ts.isPropertySignature(node) ||
29
+ ts.isTypeAliasDeclaration(node));
30
+ }
31
+ function nameOf(node) {
32
+ return isTaggable(node) && node.name !== undefined ? node.name.getText() : "it";
33
+ }
34
+ /** What the tag on a declaration leaves to read: decided when the project side reads it all. */
35
+ function tagOutcome(node, tags) {
36
+ const name = nameOf(node);
37
+ const fn = ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node) ? node : heldFunction(node);
38
+ if (fn === undefined) {
39
+ return ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node)
40
+ ? {
41
+ kind: "unchecked",
42
+ reason: `\`${name}\` holds a value that is not a function written here: assign it an arrow function, written in place`,
43
+ }
44
+ : {
45
+ kind: "unchecked",
46
+ reason: `\`${name}\` has no body to read: put the tag on a function written with its body`,
47
+ };
48
+ }
49
+ if (fn.asteriskToken !== undefined) {
50
+ return {
51
+ kind: "unchecked",
52
+ reason: `\`${name}\` is a generator, and stateward does not check what it throws while it is iterated: tag a plain function instead, and call it from the generator`,
53
+ };
54
+ }
55
+ if (fn.body === undefined) {
56
+ return {
57
+ kind: "unchecked",
58
+ reason: `\`${name}\` has no body to read: put the tag on a function written with its body`,
59
+ };
60
+ }
61
+ const typed = tags.some((tag) => ts.isJSDocThrowsTag(tag) && tag.typeExpression !== undefined);
62
+ return typed
63
+ ? { kind: "decided" }
64
+ : {
65
+ kind: "unchecked",
66
+ reason: `\`@throws\` of \`${name}\` names no class, so what it states cannot be checked: name the class in braces, as \`@throws {ParseError}\``,
67
+ };
68
+ }
69
+ export function markThrowsReferences(ctx) {
70
+ const refs = ctx.ledger.filter((ref) => ref.trait === TRAIT);
71
+ if (refs.length === 0)
72
+ return;
73
+ const { sourceFile } = ctx;
74
+ const tagged = new Map();
75
+ const visit = (node) => {
76
+ ts.forEachChild(node, visit);
77
+ if (!isTaggable(node))
78
+ return;
79
+ const held = heldFunction(node);
80
+ const tags = [
81
+ ...ts.getJSDocTags(node),
82
+ ...(held === undefined ? [] : ts.getJSDocTags(held)),
83
+ ].filter((tag) => tag.tagName.text === "throws");
84
+ const [first] = tags;
85
+ if (first !== undefined)
86
+ tagged.set(first.getStart(sourceFile), tagOutcome(node, tags));
87
+ };
88
+ visit(sourceFile);
89
+ for (const ref of refs)
90
+ ctx.read(ref, outcomeOf(ref, tagged));
91
+ }
92
+ function outcomeOf(ref, tagged) {
93
+ if (ref.form === "tag") {
94
+ return (tagged.get(ref.location.start) ?? {
95
+ kind: "unchecked",
96
+ reason: `\`${ref.text}\` is on a declaration that is not read for the tag: put it on a function, or on a \`const\` that holds an arrow function`,
97
+ });
98
+ }
99
+ // Giving the name another function changes what it throws: not read.
100
+ if (ref.form === "write") {
101
+ return {
102
+ kind: "unchecked",
103
+ reason: `\`${ref.text}\` (a write) is a use of \`${ref.name}\` that stateward does not read for \`@throws\`: give the name one function, where it is declared`,
104
+ };
105
+ }
106
+ return { kind: "irrelevant" };
107
+ }
108
+ //# sourceMappingURL=throws-reads.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stateward/plugin-errors",
3
- "version": "1.2.1",
3
+ "version": "1.3.0",
4
4
  "description": "stateward rules for errors: errors are handled where they can happen.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -32,6 +32,6 @@
32
32
  "!dist/**/*.tsbuildinfo"
33
33
  ],
34
34
  "dependencies": {
35
- "@stateward/core": "1.2.1"
35
+ "@stateward/core": "1.3.0"
36
36
  }
37
37
  }