@stateward/plugin-errors 1.2.1 → 1.2.2
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.
- package/dist/catch-hides-unexpected.js +75 -6
- package/dist/catch-misses-error.js +62 -19
- package/dist/finally-can-throw.js +43 -3
- package/dist/inference/builtins.d.ts +7 -0
- package/dist/inference/builtins.js +20 -0
- package/dist/inference/packages.js +5 -0
- package/dist/inference/summarize.d.ts +1 -0
- package/dist/inference/summarize.js +94 -7
- package/dist/inference/summary.d.ts +5 -0
- package/dist/inference/summary.js +5 -1
- package/dist/narrow-try.d.ts +2 -0
- package/dist/narrow-try.js +62 -7
- package/dist/react/fallbacks.js +35 -14
- package/dist/react/tree.d.ts +10 -0
- package/dist/react/tree.js +47 -4
- package/dist/refactors.js +35 -2
- package/dist/render-throw-without-boundary.js +100 -10
- package/dist/result-ignored.js +51 -10
- package/dist/result-type.d.ts +2 -0
- package/dist/result-type.js +6 -0
- package/dist/result-unchecked.js +185 -39
- package/dist/rules.meta.d.ts +3 -0
- package/dist/rules.meta.js +1 -0
- package/dist/text.d.ts +10 -0
- package/dist/text.js +17 -0
- package/dist/throws-doc-mismatch.js +53 -5
- package/dist/throws-reads.d.ts +3 -0
- package/dist/throws-reads.js +108 -0
- package/package.json +2 -2
package/dist/result-unchecked.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import ts from "@stateward/core/typescript";
|
|
2
2
|
import { defineRule } from "@stateward/core";
|
|
3
|
-
import { example, resultShapeOf, shorten } from "./result-type.js";
|
|
3
|
+
import { example, freeName, resultShapeOf, shorten } from "./result-type.js";
|
|
4
|
+
import { oneLine } from "./text.js";
|
|
4
5
|
const EXPLAIN = `# errors/result-unchecked
|
|
5
6
|
|
|
6
7
|
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.
|
|
@@ -36,7 +37,9 @@ export async function submit(values: string): Promise<void> {
|
|
|
36
37
|
}
|
|
37
38
|
\`\`\`
|
|
38
39
|
|
|
39
|
-
For an RTK Query trigger, add \`.unwrap()\` so a failure throws: \`await deletePlan(id).unwrap()\`. Where the result is dropped, a quick fix adds it.
|
|
40
|
+
For an RTK Query trigger, add \`.unwrap()\` so a failure throws: \`await deletePlan(id).unwrap()\`. Where the result is dropped, a quick fix adds it; outside a \`try\` with a \`catch\` the thrown failure needs one around it, or a caller that catches. The message names three readings: the \`.unwrap()\`, a check (\`if ("error" in result) throw result.error;\` inside a \`try\`, so the \`catch\` and its rollback run; a stop outside one), and an \`else\` for the success path when the lines after the call should run either way.
|
|
41
|
+
|
|
42
|
+
Where the check is there and the code goes on after it, the message offers two readings: end the branch that handles the failure (a \`return\` in a function that returns nothing, a \`throw\` of the error inside a \`try\` with a \`catch\` so its rollback runs, and in words where the function returns a value), or an \`else\` for the success path when the lines after the \`if\` should run either way. Where only \`data\` is taken out of the result, there is nothing to check: the message says to keep the whole result, check it, then take \`data\` out of it.
|
|
40
43
|
|
|
41
44
|
## Why it matters
|
|
42
45
|
|
|
@@ -120,27 +123,89 @@ function callText(call, ctx) {
|
|
|
120
123
|
? `${shorten(call.expression.getText(ctx.sourceFile), CALL_MAX)}(…)`
|
|
121
124
|
: whole;
|
|
122
125
|
}
|
|
123
|
-
/**
|
|
124
|
-
function
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
126
|
+
/** Whether the function returns a value anywhere in its own body (not in a nested function). */
|
|
127
|
+
function returnsValue(body) {
|
|
128
|
+
return inBody(body, (one) => ts.isReturnStatement(one) && one.expression !== undefined);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* How the code stops where `node` is: inside a `try` with a `catch` it throws (a `return` would
|
|
132
|
+
* skip the `catch` and its rollback); in a function that returns nothing it returns; otherwise
|
|
133
|
+
* what to return depends on the function, which the example leaves to its writer.
|
|
134
|
+
*/
|
|
135
|
+
function exitOf(node, ctx) {
|
|
136
|
+
for (let child = node; !ts.isSourceFile(child); child = child.parent) {
|
|
137
|
+
if (isFunctionLike(child))
|
|
138
|
+
break;
|
|
139
|
+
const parent = child.parent;
|
|
140
|
+
if (ts.isTryStatement(parent) &&
|
|
141
|
+
parent.tryBlock === child &&
|
|
142
|
+
parent.catchClause !== undefined) {
|
|
143
|
+
return "throw";
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const fn = ts.findAncestor(node.parent, ts.isFunctionLike);
|
|
147
|
+
if (fn === undefined)
|
|
148
|
+
return "other";
|
|
149
|
+
if (fn.type !== undefined) {
|
|
150
|
+
const returnType = fn.type.getText(ctx.sourceFile).replace(/\s+/g, "");
|
|
151
|
+
return returnType === "void" || returnType === "Promise<void>" ? "return" : "other";
|
|
152
|
+
}
|
|
153
|
+
const body = ts.isFunctionDeclaration(fn) ||
|
|
154
|
+
ts.isFunctionExpression(fn) ||
|
|
155
|
+
ts.isArrowFunction(fn) ||
|
|
156
|
+
ts.isMethodDeclaration(fn)
|
|
157
|
+
? fn.body
|
|
158
|
+
: undefined;
|
|
159
|
+
return body !== undefined && ts.isBlock(body) && !returnsValue(body) ? "return" : "other";
|
|
160
|
+
}
|
|
161
|
+
/** What ends the branch that handles a failure, as one statement, or `{ … }` when it cannot be written. */
|
|
162
|
+
function stopStatement(exit, error) {
|
|
163
|
+
if (exit === "return")
|
|
164
|
+
return "return;";
|
|
165
|
+
return exit === "throw" && error !== undefined ? `throw ${error};` : "{ … }";
|
|
166
|
+
}
|
|
167
|
+
/** The condition that is true when the call failed, in the result's own shape and names, and the error it holds. */
|
|
168
|
+
function failureTest(tracked) {
|
|
169
|
+
const errorAlias = tracked.errorName ?? [...tracked.aliases].find(([, kind]) => kind === "error")?.[0];
|
|
170
|
+
if (tracked.whole === undefined && errorAlias !== undefined) {
|
|
171
|
+
return { test: errorAlias, error: tracked.errorName };
|
|
172
|
+
}
|
|
128
173
|
const name = tracked.whole ?? "result";
|
|
129
174
|
switch (tracked.kind) {
|
|
130
175
|
case "trigger":
|
|
131
|
-
return `
|
|
176
|
+
return { test: `"error" in ${name}`, error: `${name}.error` };
|
|
132
177
|
case "ok":
|
|
133
|
-
return
|
|
178
|
+
return { test: `!${name}.ok`, error: `${name}.error` };
|
|
134
179
|
case "success":
|
|
135
|
-
return
|
|
180
|
+
return { test: `!${name}.success`, error: `${name}.error` };
|
|
136
181
|
case "isErr":
|
|
137
|
-
return
|
|
182
|
+
return { test: `${name}.isErr()`, error: undefined };
|
|
138
183
|
default: {
|
|
139
184
|
const unreachable = tracked.kind;
|
|
140
185
|
return unreachable;
|
|
141
186
|
}
|
|
142
187
|
}
|
|
143
188
|
}
|
|
189
|
+
/** The line that stops when the call failed, in the result's own shape and names. */
|
|
190
|
+
function checkLine(tracked, exit) {
|
|
191
|
+
const { test, error } = failureTest(tracked);
|
|
192
|
+
return `if (${test}) ${stopStatement(exit, error)}`;
|
|
193
|
+
}
|
|
194
|
+
/** The sentence that says what the check does when the call failed. */
|
|
195
|
+
function stopsWith(exit) {
|
|
196
|
+
switch (exit) {
|
|
197
|
+
case "return":
|
|
198
|
+
return "return when it failed";
|
|
199
|
+
case "throw":
|
|
200
|
+
return "throw its error when it failed, so the `catch` runs";
|
|
201
|
+
case "other":
|
|
202
|
+
return "stop when it failed (return what the function returns, or throw)";
|
|
203
|
+
default: {
|
|
204
|
+
const unreachable = exit;
|
|
205
|
+
return unreachable;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
144
209
|
/** Whether an identifier is a name read as a value (not `x.name`, not a property's key). */
|
|
145
210
|
function isValueName(node) {
|
|
146
211
|
const parent = node.parent;
|
|
@@ -425,13 +490,7 @@ function checkTry(statement, ctx) {
|
|
|
425
490
|
ctx.report({
|
|
426
491
|
node: inner,
|
|
427
492
|
message: `code after the call runs even when \`${calleeText(call, ctx)}(…)\` failed, and the \`catch\` does not`,
|
|
428
|
-
hint:
|
|
429
|
-
'add `.unwrap()` so a failure reaches the `catch` (quick fix), or check `"error" in result` and return:',
|
|
430
|
-
example([
|
|
431
|
-
`const result = await ${callText(call, ctx)};`,
|
|
432
|
-
`if ("error" in result) return;`,
|
|
433
|
-
]),
|
|
434
|
-
].join("\n"),
|
|
493
|
+
hint: triggerHint(inner, call, "catch", ctx),
|
|
435
494
|
fixes: [unwrapFix(call, "Add `.unwrap()` so a failure reaches the `catch`", ctx)],
|
|
436
495
|
});
|
|
437
496
|
}
|
|
@@ -442,14 +501,35 @@ function checkTry(statement, ctx) {
|
|
|
442
501
|
// The statement, as `errors/result-ignored` reports it, so that rule can yield to this one.
|
|
443
502
|
node: inner,
|
|
444
503
|
message: `\`catch\` never runs for \`${calleeText(call, ctx)}(…)\`: it does not throw when it fails`,
|
|
445
|
-
hint:
|
|
446
|
-
'add `.unwrap()` (quick fix), or check `"error" in result` and return, so the code after it does not run on failure:',
|
|
447
|
-
example([`const result = await ${callText(call, ctx)};`, `if ("error" in result) return;`]),
|
|
448
|
-
].join("\n"),
|
|
504
|
+
hint: triggerHint(inner, call, "catch", ctx),
|
|
449
505
|
fixes: [unwrapFix(call, "Add `.unwrap()` so a failure reaches the `catch`", ctx)],
|
|
450
506
|
});
|
|
451
507
|
}
|
|
452
508
|
}
|
|
509
|
+
/** The three readings of a trigger whose failure is not checked: stop, throw it, or go on on purpose. */
|
|
510
|
+
function triggerHint(statement, call, where, ctx) {
|
|
511
|
+
const fn = ts.findAncestor(statement.parent, ts.isFunctionLike);
|
|
512
|
+
const name = freeName(fn ?? ctx.sourceFile, ctx.sourceFile, ["result", "outcome", "response"]);
|
|
513
|
+
const stored = `const ${name} = await ${callText(call, ctx)};`;
|
|
514
|
+
const stop = stopStatement(where === "catch" ? "throw" : exitOf(statement, ctx), `${name}.error`);
|
|
515
|
+
const ways = where === "catch"
|
|
516
|
+
? [
|
|
517
|
+
"- add `.unwrap()` so a failure throws into the `catch` (quick fix)",
|
|
518
|
+
"- or check the result and throw its error into the `catch`",
|
|
519
|
+
example([stored, `if ("error" in ${name}) ${stop}`]),
|
|
520
|
+
]
|
|
521
|
+
: [
|
|
522
|
+
"- add `.unwrap()` so a failure throws (quick fix), and put the call in a `try` with a `catch`: nothing else catches it",
|
|
523
|
+
"- or check the result, and stop there",
|
|
524
|
+
example([stored, `if ("error" in ${name}) ${stop}`]),
|
|
525
|
+
];
|
|
526
|
+
return [
|
|
527
|
+
"one of",
|
|
528
|
+
...ways,
|
|
529
|
+
"- or, if the lines after it should run either way, say so with an `else` for the success path",
|
|
530
|
+
example([`if ("error" in ${name}) { … } else { … }`]),
|
|
531
|
+
].join("\n");
|
|
532
|
+
}
|
|
453
533
|
function unwrapFix(call, title, ctx) {
|
|
454
534
|
const at = call.getEnd();
|
|
455
535
|
return {
|
|
@@ -528,10 +608,7 @@ function checkDropped(statement, ctx) {
|
|
|
528
608
|
ctx.report({
|
|
529
609
|
node: statement,
|
|
530
610
|
message: `code after the call runs even when \`${calleeText(call, ctx)}(…)\` failed`,
|
|
531
|
-
hint:
|
|
532
|
-
'add `.unwrap()` so a failure throws (quick fix), or check `"error" in result` and return:',
|
|
533
|
-
example([`const result = await ${callText(call, ctx)};`, `if ("error" in result) return;`]),
|
|
534
|
-
].join("\n"),
|
|
611
|
+
hint: triggerHint(statement, call, "outside", ctx),
|
|
535
612
|
fixes: [unwrapFix(call, "Add `.unwrap()` so a failure stops the function", ctx)],
|
|
536
613
|
});
|
|
537
614
|
}
|
|
@@ -544,6 +621,7 @@ function trackedOf(declaration, call, kind, ctx) {
|
|
|
544
621
|
if (!ts.isObjectBindingPattern(declaration.name))
|
|
545
622
|
return undefined;
|
|
546
623
|
const aliases = new Map();
|
|
624
|
+
let errorName;
|
|
547
625
|
for (const element of declaration.name.elements) {
|
|
548
626
|
if (element.dotDotDotToken !== undefined || !ts.isIdentifier(element.name))
|
|
549
627
|
return undefined;
|
|
@@ -553,8 +631,19 @@ function trackedOf(declaration, call, kind, ctx) {
|
|
|
553
631
|
const alias = ALIAS_KINDS.get(key.text);
|
|
554
632
|
if (alias !== undefined)
|
|
555
633
|
aliases.set(element.name.text, alias);
|
|
634
|
+
if (key.text === "error")
|
|
635
|
+
errorName = element.name.text;
|
|
556
636
|
}
|
|
557
|
-
return aliases.size === 0
|
|
637
|
+
return aliases.size === 0
|
|
638
|
+
? undefined
|
|
639
|
+
: {
|
|
640
|
+
whole: undefined,
|
|
641
|
+
aliases,
|
|
642
|
+
...(errorName === undefined ? {} : { errorName }),
|
|
643
|
+
pattern: declaration.name.getText(),
|
|
644
|
+
callee,
|
|
645
|
+
kind,
|
|
646
|
+
};
|
|
558
647
|
}
|
|
559
648
|
function goesOnHeadline(tracked, after) {
|
|
560
649
|
const what = after === "if" ? "the `if`" : "the call";
|
|
@@ -631,6 +720,50 @@ function storedOutcome(rest, tracked) {
|
|
|
631
720
|
}
|
|
632
721
|
return { kind: "none" };
|
|
633
722
|
}
|
|
723
|
+
/** Whether `error` of the whole result can be read inside the branch of `test`: the test narrows the result. */
|
|
724
|
+
function narrowsWhole(test, tracked) {
|
|
725
|
+
const code = strip(test);
|
|
726
|
+
if (ts.isPrefixUnaryExpression(code) && code.operator === ts.SyntaxKind.ExclamationToken) {
|
|
727
|
+
return narrowsWhole(code.operand, tracked);
|
|
728
|
+
}
|
|
729
|
+
if (ts.isBinaryExpression(code)) {
|
|
730
|
+
const operator = code.operatorToken.kind;
|
|
731
|
+
if (operator === ts.SyntaxKind.InKeyword)
|
|
732
|
+
return true;
|
|
733
|
+
if (operator === ts.SyntaxKind.AmpersandAmpersandToken)
|
|
734
|
+
return narrowsWhole(code.left, tracked);
|
|
735
|
+
return false;
|
|
736
|
+
}
|
|
737
|
+
return ts.isPropertyAccessExpression(code) && isWhole(code.expression, tracked);
|
|
738
|
+
}
|
|
739
|
+
/** The two readings of an `if` that reads the failure and goes on: end the branch, or say the lines run either way. */
|
|
740
|
+
function goesOnHint(test, tracked, ctx) {
|
|
741
|
+
const exit = exitOf(test, ctx);
|
|
742
|
+
const condition = shorten(test.getText(ctx.sourceFile), CONDITION_MAX);
|
|
743
|
+
const error = tracked.whole === undefined
|
|
744
|
+
? tracked.errorName
|
|
745
|
+
: narrowsWhole(test, tracked)
|
|
746
|
+
? `${tracked.whole}.error`
|
|
747
|
+
: undefined;
|
|
748
|
+
const stop = stopStatement(exit, error);
|
|
749
|
+
const how = exit === "return"
|
|
750
|
+
? "with `return`"
|
|
751
|
+
: exit === "throw"
|
|
752
|
+
? "by throwing its error, so the `catch` and its rollback run"
|
|
753
|
+
: "with a `return` of what the function returns, or a `throw`";
|
|
754
|
+
return [
|
|
755
|
+
"one of",
|
|
756
|
+
`- end the branch that handles the failure ${how}`,
|
|
757
|
+
example([
|
|
758
|
+
`if (${condition}) {`,
|
|
759
|
+
" // … what it shows now",
|
|
760
|
+
...(stop === "{ … }" ? [] : [` ${stop}`]),
|
|
761
|
+
"}",
|
|
762
|
+
]),
|
|
763
|
+
"- or, if the lines after the `if` should run either way, say so with an `else` for the success path",
|
|
764
|
+
example([`if (${condition}) { … } else { … }`]),
|
|
765
|
+
].join("\n");
|
|
766
|
+
}
|
|
634
767
|
/** Case (b): reports what `storedOutcome` found. */
|
|
635
768
|
function followStored(statement, before, rest, tracked, call, ctx) {
|
|
636
769
|
const outcome = storedOutcome(rest, tracked);
|
|
@@ -641,7 +774,7 @@ function followStored(statement, before, rest, tracked, call, ctx) {
|
|
|
641
774
|
ctx.unknown({
|
|
642
775
|
node: outcome.test,
|
|
643
776
|
message: `not checked: whether the \`if\` tests that \`${tracked.callee}(…)\` failed: it does not test the result itself`,
|
|
644
|
-
hint: `test the result itself, as in \`${checkLine(tracked)}\`, so the check can be followed`,
|
|
777
|
+
hint: `test the result itself, as in \`${checkLine(tracked, exitOf(outcome.test, ctx))}\`, so the check can be followed`,
|
|
645
778
|
});
|
|
646
779
|
return;
|
|
647
780
|
case "goes-on": {
|
|
@@ -651,15 +784,7 @@ function followStored(statement, before, rest, tracked, call, ctx) {
|
|
|
651
784
|
ctx.report({
|
|
652
785
|
node: outcome.test,
|
|
653
786
|
message: goesOnHeadline(tracked, "if"),
|
|
654
|
-
hint:
|
|
655
|
-
"end the branch that handles the failure with `return` (or `throw`):",
|
|
656
|
-
example([
|
|
657
|
-
`if (${shorten(outcome.test.getText(ctx.sourceFile), CONDITION_MAX)}) {`,
|
|
658
|
-
" // … what it shows now",
|
|
659
|
-
" return;",
|
|
660
|
-
"}",
|
|
661
|
-
]),
|
|
662
|
-
].join("\n"),
|
|
787
|
+
hint: goesOnHint(outcome.test, tracked, ctx),
|
|
663
788
|
});
|
|
664
789
|
return;
|
|
665
790
|
}
|
|
@@ -669,12 +794,33 @@ function followStored(statement, before, rest, tracked, call, ctx) {
|
|
|
669
794
|
const data = tracked.whole === undefined
|
|
670
795
|
? ([...tracked.aliases].find(([, kind]) => kind === "data")?.[0] ?? "data")
|
|
671
796
|
: `${tracked.whole}.data`;
|
|
797
|
+
const exit = exitOf(statement, ctx);
|
|
798
|
+
const hasError = tracked.whole !== undefined ||
|
|
799
|
+
[...tracked.aliases.values()].some((kind) => kind === "error");
|
|
800
|
+
if (hasError) {
|
|
801
|
+
ctx.report({
|
|
802
|
+
node: statement,
|
|
803
|
+
message: goesOnHeadline(tracked, "statement"),
|
|
804
|
+
hint: [
|
|
805
|
+
`check that it worked before reading \`${data}\`, and ${stopsWith(exit)}:`,
|
|
806
|
+
example([checkLine(tracked, exit)]),
|
|
807
|
+
].join("\n"),
|
|
808
|
+
});
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
// Only `data` was taken out: there is nothing to test, so the whole result is kept first.
|
|
812
|
+
const name = freeName(ts.findAncestor(statement.parent, ts.isFunctionLike) ?? ctx.sourceFile, ctx.sourceFile, ["result", "outcome", "response"]);
|
|
813
|
+
const pattern = tracked.pattern === undefined ? "{ data }" : oneLine(tracked.pattern);
|
|
672
814
|
ctx.report({
|
|
673
815
|
node: statement,
|
|
674
816
|
message: goesOnHeadline(tracked, "statement"),
|
|
675
817
|
hint: [
|
|
676
|
-
`check
|
|
677
|
-
example([
|
|
818
|
+
`keep the whole result and check it before reading \`${data}\`, and ${stopsWith(exit)}:`,
|
|
819
|
+
example([
|
|
820
|
+
`const ${name} = await ${callText(call, ctx)};`,
|
|
821
|
+
checkLine({ ...tracked, whole: name }, exit),
|
|
822
|
+
`const ${pattern} = ${name};`,
|
|
823
|
+
]),
|
|
678
824
|
].join("\n"),
|
|
679
825
|
});
|
|
680
826
|
return;
|
package/dist/rules.meta.d.ts
CHANGED
|
@@ -81,6 +81,9 @@ export declare const RULES: {
|
|
|
81
81
|
readonly description: "Error classes a `@throws` never needs to list (TypeError, *AbortError), as a catch names them.";
|
|
82
82
|
};
|
|
83
83
|
};
|
|
84
|
+
readonly proves: {
|
|
85
|
+
readonly tags: readonly ["throws"];
|
|
86
|
+
};
|
|
84
87
|
};
|
|
85
88
|
};
|
|
86
89
|
readonly "render-throw-without-boundary": {
|
package/dist/rules.meta.js
CHANGED
package/dist/text.d.ts
CHANGED
|
@@ -19,4 +19,14 @@ export declare function fitted(build: (cut: (text: string) => string) => string)
|
|
|
19
19
|
export declare function codeList(names: readonly string[], cut: (text: string) => string): string;
|
|
20
20
|
/** A fix line followed by a code example, each example line indented by 4 spaces. */
|
|
21
21
|
export declare function withExample(line: string, example: readonly string[]): string;
|
|
22
|
+
/** One way to fix a finding: what to do, in lowercase, and the code that does it when it can be shown. */
|
|
23
|
+
export type Way = {
|
|
24
|
+
readonly text: string;
|
|
25
|
+
readonly example?: readonly string[];
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* A fix hint of several ways (`one of`, a `- ` line each, every one after the first starting with
|
|
29
|
+
* `or`), or the one way as a first line with its example.
|
|
30
|
+
*/
|
|
31
|
+
export declare function waysHint(ways: readonly Way[]): string;
|
|
22
32
|
//# sourceMappingURL=text.d.ts.map
|
package/dist/text.js
CHANGED
|
@@ -40,4 +40,21 @@ export function codeList(names, cut) {
|
|
|
40
40
|
export function withExample(line, example) {
|
|
41
41
|
return [line, ...example.map((text) => ` ${text}`)].join("\n");
|
|
42
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* A fix hint of several ways (`one of`, a `- ` line each, every one after the first starting with
|
|
45
|
+
* `or`), or the one way as a first line with its example.
|
|
46
|
+
*/
|
|
47
|
+
export function waysHint(ways) {
|
|
48
|
+
const [only] = ways;
|
|
49
|
+
if (ways.length === 1 && only !== undefined) {
|
|
50
|
+
return only.example === undefined ? only.text : withExample(`${only.text}:`, only.example);
|
|
51
|
+
}
|
|
52
|
+
return [
|
|
53
|
+
"one of",
|
|
54
|
+
...ways.flatMap((way, index) => [
|
|
55
|
+
`- ${index === 0 ? "" : "or "}${way.text}${way.example === undefined ? "" : ":"}`,
|
|
56
|
+
...(way.example ?? []).map((line) => ` ${line}`),
|
|
57
|
+
]),
|
|
58
|
+
].join("\n");
|
|
59
|
+
}
|
|
43
60
|
//# sourceMappingURL=text.js.map
|
|
@@ -1,8 +1,10 @@
|
|
|
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";
|
|
4
5
|
import { summarizeOnce } from "./inference/project.js";
|
|
5
6
|
import { codeList, fitted } from "./text.js";
|
|
7
|
+
import { markThrowsReferences } from "./throws-reads.js";
|
|
6
8
|
/** The group the rule belongs to in the docs and in `stateward status`. */
|
|
7
9
|
export const GROUP = "callers";
|
|
8
10
|
const EXPLAIN = `# errors/throws-doc-mismatch
|
|
@@ -41,10 +43,11 @@ The message links to the call that throws each missing class. There is no quick
|
|
|
41
43
|
|
|
42
44
|
- 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
45
|
- A name in the tag that is not a class in scope: import the class, or use a name in scope.
|
|
46
|
+
- 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
47
|
|
|
45
48
|
## What it does not catch
|
|
46
49
|
|
|
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:
|
|
50
|
+
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
51
|
|
|
49
52
|
- a function without \`@throws\`, or a tag without a type (\`@throws when the id is empty\`): that only says the function throws;
|
|
50
53
|
- a class that a surrounding \`try\` may catch: only classes that surely escape are reported as missing;
|
|
@@ -75,7 +78,16 @@ const OPTIONS = {
|
|
|
75
78
|
description: "Error classes a `@throws` never needs to list (TypeError, *AbortError), as a catch names them.",
|
|
76
79
|
}),
|
|
77
80
|
};
|
|
78
|
-
|
|
81
|
+
/** Whether a source that cannot be followed is a call: a name with no body to read, a callback, an alias. */
|
|
82
|
+
function isCall(source) {
|
|
83
|
+
return (source.reason === REASON.noDeclaration ||
|
|
84
|
+
source.reason === REASON.noBody ||
|
|
85
|
+
source.reason === REASON.callback ||
|
|
86
|
+
source.reason === REASON.dynamic ||
|
|
87
|
+
source.reason.startsWith("package ") ||
|
|
88
|
+
source.reason.startsWith("callback passed to"));
|
|
89
|
+
}
|
|
90
|
+
function check(entry, analysis, ctx, reported) {
|
|
79
91
|
const doc = entry.fact.doc;
|
|
80
92
|
if (doc === null)
|
|
81
93
|
return;
|
|
@@ -94,7 +106,13 @@ function check(entry, analysis, ctx) {
|
|
|
94
106
|
all.unknowns.set(key, source);
|
|
95
107
|
}
|
|
96
108
|
const name = entry.fact.name;
|
|
109
|
+
// Every finding about the tag is against the declaration it is on (the reference ledger's id).
|
|
110
|
+
const against = [
|
|
111
|
+
{ file: entry.file, start: doc.declared, end: doc.declared },
|
|
112
|
+
];
|
|
97
113
|
const firstUnknown = [...all.unknowns.values()][0];
|
|
114
|
+
// The listed classes that cannot be checked because of an unknown already say what it is.
|
|
115
|
+
let saidUnknown = false;
|
|
98
116
|
for (const item of doc.entries) {
|
|
99
117
|
const location = locationOf(entry.file, item.at);
|
|
100
118
|
if (item.id === null) {
|
|
@@ -102,6 +120,7 @@ function check(entry, analysis, ctx) {
|
|
|
102
120
|
message: fitted((cut) => `not checked: \`@throws\` names \`${cut(item.name)}\`: no class of that name is in scope`),
|
|
103
121
|
hint: "name an error class that is in scope in this file, or import it",
|
|
104
122
|
location,
|
|
123
|
+
against,
|
|
105
124
|
});
|
|
106
125
|
continue;
|
|
107
126
|
}
|
|
@@ -111,10 +130,12 @@ function check(entry, analysis, ctx) {
|
|
|
111
130
|
continue;
|
|
112
131
|
const listed = className(id, classes);
|
|
113
132
|
if (firstUnknown !== undefined) {
|
|
133
|
+
saidUnknown = true;
|
|
114
134
|
ctx.unknown({
|
|
115
135
|
message: fitted((cut) => `not checked: whether \`${cut(name)}\` throws \`${cut(listed)}\`: what \`${cut(firstUnknown.text)}\` throws is not known (${firstUnknown.reason})`),
|
|
116
136
|
hint: `remove \`${listed}\` from the tag if \`${name}\` cannot throw it; otherwise add \`@throws\` where it comes from`,
|
|
117
137
|
location,
|
|
138
|
+
against,
|
|
118
139
|
});
|
|
119
140
|
continue;
|
|
120
141
|
}
|
|
@@ -123,10 +144,27 @@ function check(entry, analysis, ctx) {
|
|
|
123
144
|
hint: `remove \`${listed}\` from the tag, or throw it where it can happen`,
|
|
124
145
|
location,
|
|
125
146
|
findingKind: "extra",
|
|
147
|
+
against,
|
|
126
148
|
});
|
|
127
149
|
}
|
|
128
150
|
if (doc.untyped.length > 0 || doc.entries.some((item) => item.id === null))
|
|
129
151
|
return;
|
|
152
|
+
// A place the proof cannot follow may throw a class the tag does not list: not checked, never
|
|
153
|
+
// silent, and never taken at the tag's word (a call, a thrown value of unknown class, a getter).
|
|
154
|
+
for (const source of all.unknowns.values()) {
|
|
155
|
+
const key = `${entry.fact.id}\u0000${source.file}\u0000${String(source.start)}`;
|
|
156
|
+
if (saidUnknown || reported.has(key))
|
|
157
|
+
continue;
|
|
158
|
+
reported.add(key);
|
|
159
|
+
ctx.unknown({
|
|
160
|
+
message: fitted((cut) => isCall(source)
|
|
161
|
+
? `not checked: the call \`${cut(source.text)}(…)\` cannot be followed (${source.reason})`
|
|
162
|
+
: `not checked: what \`${cut(source.text)}\` throws is not known (${source.reason}), so \`@throws\` of \`${cut(name)}\` cannot be checked`),
|
|
163
|
+
hint: fitted((cut) => `call the function itself, or state what it throws with \`@throws\` on it or \`facts\`, so \`${cut(name)}\`'s tag can be checked`),
|
|
164
|
+
location: locationOf(source.file, [source.start, source.end]),
|
|
165
|
+
against,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
130
168
|
const missing = [];
|
|
131
169
|
for (const [id, info] of all.classes) {
|
|
132
170
|
if (!info.certain || matchesName(catchName(id, classes), ctx.options.ignoreClasses))
|
|
@@ -151,10 +189,15 @@ function check(entry, analysis, ctx) {
|
|
|
151
189
|
const tagNames = [...new Set(missing.map((one) => catchName(one.id, classes)))].sort();
|
|
152
190
|
ctx.report({
|
|
153
191
|
message: fitted((cut) => `\`@throws\` of \`${cut(name)}\` does not list ${codeList(names, cut)}`),
|
|
154
|
-
hint:
|
|
192
|
+
hint: [
|
|
193
|
+
"one of",
|
|
194
|
+
fitted((cut) => `- catch ${missing.length === 1 ? "it" : "them"} inside \`${cut(name)}\`, if ${missing.length === 1 ? "it escapes" : "they escape"} by mistake`),
|
|
195
|
+
`- or add ${missing.length === 1 ? "it" : "them"} to the tag, if callers are to handle ${missing.length === 1 ? "it" : "them"}: \`@throws {${tagNames.join(" | ")}}\``,
|
|
196
|
+
].join("\n"),
|
|
155
197
|
location: locationOf(entry.file, entry.fact.at),
|
|
156
198
|
related: missing.flatMap((one) => (one.related === undefined ? [] : [one.related])).slice(0, 3),
|
|
157
199
|
findingKind: "missing",
|
|
200
|
+
against,
|
|
158
201
|
});
|
|
159
202
|
}
|
|
160
203
|
export const throwsDocMismatch = defineRule({
|
|
@@ -168,12 +211,17 @@ export const throwsDocMismatch = defineRule({
|
|
|
168
211
|
needsJsDoc: true,
|
|
169
212
|
options: OPTIONS,
|
|
170
213
|
explain: EXPLAIN,
|
|
214
|
+
proves: { tags: ["throws"] },
|
|
215
|
+
},
|
|
216
|
+
summarize: (ctx) => {
|
|
217
|
+
markThrowsReferences(ctx);
|
|
218
|
+
return summarizeOnce(ctx);
|
|
171
219
|
},
|
|
172
|
-
summarize: (ctx) => summarizeOnce(ctx),
|
|
173
220
|
check(summaries, ctx) {
|
|
174
221
|
const analysis = analyse(summaries);
|
|
222
|
+
const reported = new Set();
|
|
175
223
|
for (const entry of analysis.functions.values())
|
|
176
|
-
check(entry, analysis, ctx);
|
|
224
|
+
check(entry, analysis, ctx, reported);
|
|
177
225
|
},
|
|
178
226
|
});
|
|
179
227
|
//# sourceMappingURL=throws-doc-mismatch.js.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.
|
|
3
|
+
"version": "1.2.2",
|
|
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.
|
|
35
|
+
"@stateward/core": "1.2.2"
|
|
36
36
|
}
|
|
37
37
|
}
|