@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
|
@@ -50,7 +50,7 @@ export async function submit(order: string, show: (text: string) => void): Promi
|
|
|
50
50
|
}
|
|
51
51
|
\`\`\`
|
|
52
52
|
|
|
53
|
-
A quick fix adds \`else { throw e; }\` to an \`if\` chain. For a \`switch (true)\`, add \`default: throw e;\` yourself; the message shows it. Wrapping the error with \`{ cause: e }\`, or any statement after the chain, counts too, since it runs for every error.
|
|
53
|
+
A quick fix adds \`else { throw e; }\` to an \`if\` chain. The message offers three readings: rethrow, handle the rest in the last branch, or, when dropping them is on purpose, an \`else\` (or \`default:\`) with a comment that says why: a branch with only a comment is taken as the drop, stated, and reported no more. For a \`switch (true)\`, add \`default: throw e;\` yourself; the message shows it. Wrapping the error with \`{ cause: e }\`, or any statement after the chain, counts too, since it runs for every error.
|
|
54
54
|
|
|
55
55
|
## Why it matters
|
|
56
56
|
|
|
@@ -123,6 +123,11 @@ function dispatchOf(statement, variable, sourceFile) {
|
|
|
123
123
|
start: statement,
|
|
124
124
|
classes,
|
|
125
125
|
rest: realStatements(end.elseStatement),
|
|
126
|
+
emptyBranch: end.elseStatement !== undefined &&
|
|
127
|
+
ts.isBlock(end.elseStatement) &&
|
|
128
|
+
realStatements(end.elseStatement).length === 0
|
|
129
|
+
? end.elseStatement
|
|
130
|
+
: undefined,
|
|
126
131
|
openChainEnd: end.elseStatement === undefined ? end : undefined,
|
|
127
132
|
kind: "if",
|
|
128
133
|
};
|
|
@@ -138,6 +143,11 @@ function dispatchOf(statement, variable, sourceFile) {
|
|
|
138
143
|
start: statement,
|
|
139
144
|
classes,
|
|
140
145
|
rest: (fallback?.statements ?? []).filter((inner) => !ts.isEmptyStatement(inner)),
|
|
146
|
+
emptyBranch: fallback !== undefined &&
|
|
147
|
+
ts.isDefaultClause(fallback) &&
|
|
148
|
+
fallback.statements.every((inner) => ts.isEmptyStatement(inner))
|
|
149
|
+
? fallback
|
|
150
|
+
: undefined,
|
|
141
151
|
openChainEnd: undefined,
|
|
142
152
|
kind: "switch",
|
|
143
153
|
};
|
|
@@ -155,11 +165,69 @@ function ignoringHeadline(classes, variable) {
|
|
|
155
165
|
function headline(classes) {
|
|
156
166
|
return fitted((cut) => `\`catch\` ignores errors other than ${codeList(classes, cut)}`);
|
|
157
167
|
}
|
|
168
|
+
/** The three readings of a chain with no branch for the rest: rethrow, handle, or drop on purpose. */
|
|
158
169
|
function hint(dispatch, variable) {
|
|
159
170
|
if (dispatch.kind === "switch") {
|
|
160
|
-
return
|
|
171
|
+
return [
|
|
172
|
+
"one of",
|
|
173
|
+
withExample("- end the switch with a case that rethrows the rest, so they reach the caller", [
|
|
174
|
+
"default:",
|
|
175
|
+
` throw ${variable};`,
|
|
176
|
+
]),
|
|
177
|
+
withExample("- or handle the rest in a `default` case, where the `…` is", [
|
|
178
|
+
"default:",
|
|
179
|
+
" …",
|
|
180
|
+
]),
|
|
181
|
+
withExample("- or, if dropping the rest is on purpose, state it in a `default` case", [
|
|
182
|
+
"default:",
|
|
183
|
+
" // other errors are dropped because …",
|
|
184
|
+
]),
|
|
185
|
+
].join("\n");
|
|
186
|
+
}
|
|
187
|
+
return [
|
|
188
|
+
"one of",
|
|
189
|
+
withExample("- end the chain with a branch that rethrows the rest, so they reach the caller", [
|
|
190
|
+
"} else {",
|
|
191
|
+
` throw ${variable};`,
|
|
192
|
+
"}",
|
|
193
|
+
]),
|
|
194
|
+
withExample("- or handle the rest in an `else`, where the `…` is", ["} else {", " …", "}"]),
|
|
195
|
+
withExample("- or, if dropping the rest is on purpose, state it in an `else` with a comment", [
|
|
196
|
+
"} else {",
|
|
197
|
+
" // other errors are dropped because …",
|
|
198
|
+
"}",
|
|
199
|
+
]),
|
|
200
|
+
].join("\n");
|
|
201
|
+
}
|
|
202
|
+
/** The hint for a last branch that does not use the error, when `restUsesError` asks it to. */
|
|
203
|
+
function restHint(variable) {
|
|
204
|
+
return [
|
|
205
|
+
"one of",
|
|
206
|
+
withExample("- rethrow the rest, so they reach the caller", [`throw ${variable};`]),
|
|
207
|
+
`- or use \`${variable}\` in the branch that handles the rest: report it, record it or wrap it`,
|
|
208
|
+
"- or, if that branch is right for every other error, set the rule's `restUsesError` option to `false`",
|
|
209
|
+
].join("\n");
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Whether the last branch is empty on purpose: an `else { … }` or a `default:` with no statement,
|
|
213
|
+
* and a comment that says why. A branch with nothing in it at all is a forgotten one.
|
|
214
|
+
*/
|
|
215
|
+
function dropsOnPurpose(dispatch, sourceFile) {
|
|
216
|
+
const branch = dispatch.emptyBranch;
|
|
217
|
+
if (branch === undefined)
|
|
218
|
+
return false;
|
|
219
|
+
let inside;
|
|
220
|
+
if (ts.isBlock(branch)) {
|
|
221
|
+
inside = branch.getText(sourceFile).slice(1, -1);
|
|
222
|
+
}
|
|
223
|
+
else {
|
|
224
|
+
// A comment after `default:` belongs to what follows it: read up to the next clause or the `}`.
|
|
225
|
+
const clauses = branch.parent.clauses;
|
|
226
|
+
const next = clauses[clauses.indexOf(branch) + 1];
|
|
227
|
+
const end = next === undefined ? branch.parent.getEnd() - 1 : next.getStart(sourceFile);
|
|
228
|
+
inside = sourceFile.text.slice(branch.getStart(sourceFile), end).replace(/^default\s*:/, "");
|
|
161
229
|
}
|
|
162
|
-
return
|
|
230
|
+
return /\/\/|\/\*/.test(inside);
|
|
163
231
|
}
|
|
164
232
|
/** The whitespace at the start of the line that holds `position`. */
|
|
165
233
|
function indentationAt(position, text) {
|
|
@@ -204,15 +272,16 @@ function checkCatch(clause, ctx) {
|
|
|
204
272
|
// A branch for the rest, or any statement that runs for every error after the chain.
|
|
205
273
|
const after = statements.slice(index + 1).filter((statement) => !ts.isEmptyStatement(statement));
|
|
206
274
|
const rest = [...dispatch.rest, ...after];
|
|
275
|
+
// An empty last branch with a comment is the drop, stated: nothing is guessed.
|
|
276
|
+
if (rest.length === 0 && dropsOnPurpose(dispatch, ctx.sourceFile))
|
|
277
|
+
return;
|
|
207
278
|
if (rest.length > 0) {
|
|
208
279
|
if (!ctx.options.restUsesError || mentions(rest, variable))
|
|
209
280
|
return;
|
|
210
281
|
ctx.report({
|
|
211
282
|
node: dispatch.start.getFirstToken(ctx.sourceFile) ?? dispatch.start,
|
|
212
283
|
message: ignoringHeadline(classes, variable),
|
|
213
|
-
hint:
|
|
214
|
-
`throw ${variable};`,
|
|
215
|
-
]),
|
|
284
|
+
hint: restHint(variable),
|
|
216
285
|
});
|
|
217
286
|
return;
|
|
218
287
|
}
|
|
@@ -58,7 +58,7 @@ export function post(text: string, remaining: number, show: (text: string) => vo
|
|
|
58
58
|
}
|
|
59
59
|
\`\`\`
|
|
60
60
|
|
|
61
|
-
The message shows the branch in the shape of your \`catch\`, and links to the call that throws each class. There is no quick fix.
|
|
61
|
+
The message shows the branch in the shape of your \`catch\`, and links to the call that throws each class. It keeps an \`else\` or \`default\` you already have: the branch goes before it, and the other readings are to make it rethrow, to use the error in it (then the rest is handled), or to list the class under \`ignoreClasses\`. There is no quick fix.
|
|
62
62
|
|
|
63
63
|
## Why it matters
|
|
64
64
|
|
|
@@ -72,14 +72,14 @@ What counts as handled: \`e instanceof X\` handles \`X\` and every class that ex
|
|
|
72
72
|
- errors stateward cannot see: from a package it cannot read, a callback, or a dynamic call. The message notes each call it could not see into, with the reason, and \`errors/catch-hides-unexpected\` makes sure the rest is not dropped;
|
|
73
73
|
- a class whose \`extends\` cannot be followed, or a branch whose test is not only \`instanceof\` (\`e instanceof A && e.code === 1\`, \`isAbort(e)\`, \`e.name === "AbortError"\`): it does not guess what that branch handles;
|
|
74
74
|
- errors from the JavaScript engine itself, such as reading a property of \`undefined\`;
|
|
75
|
-
- built-ins other than \`JSON.parse\`, \`JSON.stringify\`, \`new URL\`, \`decodeURIComponent\`, \`decodeURI\`, \`structuredClone\`, \`atob\`, \`fetch\`, \`toFixed\`, \`Array(n)\` and \`BigInt\`: they are taken not to throw;
|
|
75
|
+
- built-ins other than \`JSON.parse\`, \`JSON.stringify\`, \`new URL\`, \`decodeURIComponent\`, \`decodeURI\`, \`structuredClone\`, \`atob\`, \`fetch\`, reading a \`Response\` body (\`json()\`, \`text()\`, …), \`toFixed\`, \`Array(n)\` and \`BigInt\`: they are taken not to throw;
|
|
76
76
|
- promises kept in a \`let\`, a parameter or a property; getters, setters and generators.
|
|
77
77
|
|
|
78
78
|
## Getting the best from it
|
|
79
79
|
|
|
80
80
|
What the \`try\` can throw is worked out from \`throw new X(…)\` in the functions it calls, in any file; their \`@throws {X}\` tags (also on a function with no body, such as \`declare function\` or a \`.d.ts\` of your own); the built-ins above; and the packages it calls (\`stateward deps\` shows how well each package's errors are known). So throw classes, not strings, and document what a function throws with \`@throws\`. Declare a package's errors under \`facts\` in the config: \`facts: { "config-lib": { load: { throws: ["ConfigError"] } } }\`.
|
|
81
81
|
|
|
82
|
-
An error boundary's fallback is checked the same way: what the components below the boundary throw while rendering and in their effects, down to the next boundary, is its \`try\` (the hover on the boundary lists it). A fallback (react-error-boundary's \`FallbackComponent\`, \`fallbackRender\` or \`onError\`, or a boundary class's \`getDerivedStateFromError\`) that branches with \`if\` / \`else if\`, \`switch (true)\` or \`? :\` on \`error instanceof X\` needs a branch for each class the boundary can catch, or a branch for the rest that does more than return \`null\` or nothing. A fallback that does not branch on \`instanceof\`, whose tests are not only \`instanceof\`, or that is passed as anything other than a function written in place or the name of one of your functions, is left alone.
|
|
82
|
+
An error boundary's fallback is checked the same way: what the components below the boundary throw while rendering and in their effects, down to the next boundary, is its \`try\` (the hover on the boundary lists it). A fallback (react-error-boundary's \`FallbackComponent\`, \`fallbackRender\` or \`onError\`, or a boundary class's \`getDerivedStateFromError\`) that branches with \`if\` / \`else if\`, \`switch (true)\` or \`? :\` on \`error instanceof X\` needs a branch for each class the boundary can catch, or a branch for the rest that does more than return \`null\` or nothing. The message shows both, written for the kind of fallback (for a boundary class's \`getDerivedStateFromError\` it describes the branch for the rest, since the state is yours), and the \`ignoreClasses\` option with the class named. A fallback that does not branch on \`instanceof\`, whose tests are not only \`instanceof\`, or that is passed as anything other than a function written in place or the name of one of your functions, is left alone.
|
|
83
83
|
|
|
84
84
|
## Turn it on or off
|
|
85
85
|
|
|
@@ -96,26 +96,69 @@ function headline(names, via) {
|
|
|
96
96
|
return `\`catch\` does not handle ${codeList(names, cut)} ${source}`;
|
|
97
97
|
});
|
|
98
98
|
}
|
|
99
|
-
/**
|
|
100
|
-
|
|
99
|
+
/**
|
|
100
|
+
* The ways to handle a class the `catch` does not test, in the shape of the catch (M22): a branch
|
|
101
|
+
* for it (placed so the existing `else` or `default` stays), a rethrow for what is not handled,
|
|
102
|
+
* the generic branch using the error, or the class listed under `ignoreClasses`.
|
|
103
|
+
*/
|
|
104
|
+
function hint(names, variable, shape, hasFallback) {
|
|
105
|
+
const count = names.length;
|
|
106
|
+
const [handler = ""] = names;
|
|
101
107
|
const branch = count === 1 ? "it" : "each";
|
|
108
|
+
const ignore = count === 1
|
|
109
|
+
? `- or, if \`${handler}\` needs no branch, list it under the rule's \`ignoreClasses\` option`
|
|
110
|
+
: "- or, for the classes that need no branch, list them under the rule's `ignoreClasses` option";
|
|
111
|
+
const used = (where) => `- or, if the ${where} is right for ${count === 1 ? "it" : "them"}, use \`${variable}\` there: read it, log it or report it`;
|
|
102
112
|
switch (shape) {
|
|
103
113
|
case "switch":
|
|
104
|
-
return
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
114
|
+
return [
|
|
115
|
+
"one of",
|
|
116
|
+
hasFallback
|
|
117
|
+
? withExample(`- add a branch for ${branch}, before the \`default\` you have`, [
|
|
118
|
+
`case ${variable} instanceof ${handler}:`,
|
|
119
|
+
" …",
|
|
120
|
+
"default: // yours, unchanged",
|
|
121
|
+
])
|
|
122
|
+
: withExample(`- add a branch for ${branch}, and rethrow what you do not handle`, [
|
|
123
|
+
`case ${variable} instanceof ${handler}:`,
|
|
124
|
+
" …",
|
|
125
|
+
"default:",
|
|
126
|
+
` throw ${variable};`,
|
|
127
|
+
]),
|
|
128
|
+
...(hasFallback
|
|
129
|
+
? [
|
|
130
|
+
withExample("- or rethrow what you do not handle, in the `default` you have", [
|
|
131
|
+
"default:",
|
|
132
|
+
` throw ${variable};`,
|
|
133
|
+
]),
|
|
134
|
+
used("`default`"),
|
|
135
|
+
]
|
|
136
|
+
: []),
|
|
137
|
+
ignore,
|
|
138
|
+
].join("\n");
|
|
110
139
|
case "else":
|
|
111
|
-
return
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
140
|
+
return [
|
|
141
|
+
"one of",
|
|
142
|
+
withExample(`- add a branch for ${branch}, before the \`else\` you have`, [
|
|
143
|
+
`} else if (${variable} instanceof ${handler}) {`,
|
|
144
|
+
" …",
|
|
145
|
+
"} else { // yours, unchanged",
|
|
146
|
+
]),
|
|
147
|
+
withExample("- or rethrow what you do not handle, in the `else` you have", [
|
|
148
|
+
"} else {",
|
|
149
|
+
` throw ${variable};`,
|
|
150
|
+
"}",
|
|
151
|
+
]),
|
|
152
|
+
used("`else`"),
|
|
153
|
+
ignore,
|
|
154
|
+
].join("\n");
|
|
117
155
|
case "if":
|
|
118
|
-
return
|
|
156
|
+
return [
|
|
157
|
+
"one of",
|
|
158
|
+
withExample(`- add a branch for ${branch}, and rethrow what you do not handle after the chain`, [`if (${variable} instanceof ${handler}) {`, " …", "}", `throw ${variable};`]),
|
|
159
|
+
`- or, if what the chain does not handle is right for ${count === 1 ? "it" : "them"}, use \`${variable}\` after the chain: read it, log it or report it`,
|
|
160
|
+
ignore,
|
|
161
|
+
].join("\n");
|
|
119
162
|
default: {
|
|
120
163
|
const unreachable = shape;
|
|
121
164
|
return unreachable;
|
|
@@ -160,7 +203,7 @@ function report(seen, classes, ignored, emit) {
|
|
|
160
203
|
}
|
|
161
204
|
emit({
|
|
162
205
|
message: headline(missing.map((one) => className(one.id, classes)), via),
|
|
163
|
-
hint: hint(missing.
|
|
206
|
+
hint: hint(missing.map((one) => catchName(one.id, classes)), handler.variable, handler.dispatch === "switch" ? "switch" : handler.otherwise === null ? "if" : "else", handler.otherwise !== null),
|
|
164
207
|
location: { file: seen.file, start: handler.at[0], end: handler.at[1] },
|
|
165
208
|
related,
|
|
166
209
|
});
|
|
@@ -21,7 +21,7 @@ export async function send(file: string, saved: string): Promise<void> {
|
|
|
21
21
|
}
|
|
22
22
|
\`\`\`
|
|
23
23
|
|
|
24
|
-
Give the cleanup its own \`try\` / \`catch\`,
|
|
24
|
+
Give the cleanup its own \`try\` / \`catch\` inside the \`finally\`, so it still runs when the \`try\` fails (move it out of the \`finally\` only if it should run when the \`try\` succeeds):
|
|
25
25
|
|
|
26
26
|
\`\`\`ts example-good
|
|
27
27
|
declare function upload(file: string): Promise<void>;
|
|
@@ -130,7 +130,42 @@ function headline(cause) {
|
|
|
130
130
|
return "a `throw` in `finally` replaces the original error";
|
|
131
131
|
return fitted((cut) => `a throw in \`finally\` replaces the original error: ${cause.subject(cut)}`);
|
|
132
132
|
}
|
|
133
|
-
|
|
133
|
+
/** The longest statement written out in an example. */
|
|
134
|
+
const STATEMENT_MAX = 70;
|
|
135
|
+
/**
|
|
136
|
+
* The fix: catch it inside the `finally` (the statement as written, when wrapping it keeps the
|
|
137
|
+
* code working), or move it out after the `try` statement. A `throw` has nothing to catch around.
|
|
138
|
+
*/
|
|
139
|
+
function hint(cause, ctx) {
|
|
140
|
+
const statement = ts.findAncestor(cause.node, ts.isStatement);
|
|
141
|
+
const text = statement?.getText(ctx.sourceFile) ?? "";
|
|
142
|
+
const wrappable = cause.kind !== "throw" &&
|
|
143
|
+
statement !== undefined &&
|
|
144
|
+
ts.isExpressionStatement(statement) &&
|
|
145
|
+
!text.includes("\n") &&
|
|
146
|
+
text.length <= STATEMENT_MAX;
|
|
147
|
+
const out = "- or, if it should run only when the `try` succeeds, move it out of the `finally`, after the `try` statement";
|
|
148
|
+
const cannot = "- or, if it cannot throw here, state it with `// stateward-ignore errors/finally-can-throw: <why>`";
|
|
149
|
+
if (cause.kind === "throw") {
|
|
150
|
+
return [
|
|
151
|
+
"one of",
|
|
152
|
+
"- move the `throw` out of the `finally`, after the `try` statement: it then happens only when the `try` succeeds, and the original error is kept",
|
|
153
|
+
"- or, if the `throw` should replace the original error, state it with `// stateward-ignore errors/finally-can-throw: <why>`",
|
|
154
|
+
].join("\n");
|
|
155
|
+
}
|
|
156
|
+
return [
|
|
157
|
+
"one of",
|
|
158
|
+
wrappable
|
|
159
|
+
? withExample("- catch it inside the `finally`, so the original error is kept", [
|
|
160
|
+
"finally {",
|
|
161
|
+
` try { ${text} } catch (e) { … }`,
|
|
162
|
+
"}",
|
|
163
|
+
])
|
|
164
|
+
: "- catch it inside the `finally`, around the call that can throw, so the original error is kept",
|
|
165
|
+
out,
|
|
166
|
+
cannot,
|
|
167
|
+
].join("\n");
|
|
168
|
+
}
|
|
134
169
|
/** `shown` holds what is already reported: a `finally` inside a `finally` is looked at twice. */
|
|
135
170
|
function checkFinally(block, shown, ctx) {
|
|
136
171
|
let found;
|
|
@@ -143,7 +178,12 @@ function checkFinally(block, shown, ctx) {
|
|
|
143
178
|
if (found === undefined || shown.has(found.node))
|
|
144
179
|
return;
|
|
145
180
|
shown.add(found.node);
|
|
146
|
-
ctx.report({
|
|
181
|
+
ctx.report({
|
|
182
|
+
node: found.node,
|
|
183
|
+
message: headline(found),
|
|
184
|
+
hint: hint(found, ctx),
|
|
185
|
+
findingKind: found.kind,
|
|
186
|
+
});
|
|
147
187
|
}
|
|
148
188
|
export const finallyCanThrow = defineRule({
|
|
149
189
|
kind: "file",
|
|
@@ -21,6 +21,13 @@ export declare function builtinName(id: string): string;
|
|
|
21
21
|
export declare function builtinCatchName(id: string): string;
|
|
22
22
|
/** Methods of the platform's interfaces, as `<interface>.<method>`, that throw synchronously. */
|
|
23
23
|
export declare const THROWING_MEMBERS: ReadonlyMap<string, readonly string[]>;
|
|
24
|
+
/**
|
|
25
|
+
* Methods of the platform's interfaces, as `<interface>.<method>`, that return a promise which
|
|
26
|
+
* can reject. `Response.json()` rejects with a `SyntaxError` for a body that is not JSON; every
|
|
27
|
+
* way to read a body rejects with a `TypeError` when the body was already read or the connection
|
|
28
|
+
* fails while it is read.
|
|
29
|
+
*/
|
|
30
|
+
export declare const REJECTING_MEMBERS: ReadonlyMap<string, readonly string[]>;
|
|
24
31
|
/** Global functions that throw synchronously. */
|
|
25
32
|
export declare const THROWING_GLOBALS: ReadonlyMap<string, readonly string[]>;
|
|
26
33
|
/** Global constructors that throw. */
|
|
@@ -61,6 +61,26 @@ export const THROWING_MEMBERS = new Map([
|
|
|
61
61
|
["JSON.stringify", [TYPE]],
|
|
62
62
|
// A digit count outside 0 to 100.
|
|
63
63
|
["Number.toFixed", [RANGE]],
|
|
64
|
+
["Number.toPrecision", [RANGE]],
|
|
65
|
+
["Number.toExponential", [RANGE]],
|
|
66
|
+
// A radix outside 2 to 36 (with no radix it cannot throw).
|
|
67
|
+
["Number.toString", [RANGE]],
|
|
68
|
+
// A name or value that is not a valid header, or headers that cannot be changed.
|
|
69
|
+
["Headers.set", [TYPE]],
|
|
70
|
+
["Headers.append", [TYPE]],
|
|
71
|
+
]);
|
|
72
|
+
/**
|
|
73
|
+
* Methods of the platform's interfaces, as `<interface>.<method>`, that return a promise which
|
|
74
|
+
* can reject. `Response.json()` rejects with a `SyntaxError` for a body that is not JSON; every
|
|
75
|
+
* way to read a body rejects with a `TypeError` when the body was already read or the connection
|
|
76
|
+
* fails while it is read.
|
|
77
|
+
*/
|
|
78
|
+
export const REJECTING_MEMBERS = new Map([
|
|
79
|
+
["Body.json", [SYNTAX, TYPE]],
|
|
80
|
+
...["text", "arrayBuffer", "blob", "formData", "bytes"].map((method) => [
|
|
81
|
+
`Body.${method}`,
|
|
82
|
+
[TYPE],
|
|
83
|
+
]),
|
|
64
84
|
]);
|
|
65
85
|
/** Global functions that throw synchronously. */
|
|
66
86
|
export const THROWING_GLOBALS = new Map([
|
|
@@ -420,6 +420,11 @@ function summaryOf(state, file) {
|
|
|
420
420
|
addons: [],
|
|
421
421
|
facts: {},
|
|
422
422
|
shippedFacts: {},
|
|
423
|
+
// A package's code has no stated declarations of the project: nothing to mark.
|
|
424
|
+
ledger: [],
|
|
425
|
+
read() {
|
|
426
|
+
// Nothing is listed, so nothing is marked.
|
|
427
|
+
},
|
|
423
428
|
report() {
|
|
424
429
|
// A package's source is read for facts, never reported on.
|
|
425
430
|
},
|
|
@@ -11,6 +11,7 @@ export declare const REASON: {
|
|
|
11
11
|
readonly madeError: "an error made by a call";
|
|
12
12
|
readonly promise: "a promise that is not followed";
|
|
13
13
|
readonly heldPromise: "promise held in a variable";
|
|
14
|
+
readonly accessor: "a getter or setter runs here";
|
|
14
15
|
};
|
|
15
16
|
/** Why a callback handed to a call of the platform that is not in the tables adds `unknown`. */
|
|
16
17
|
export declare function mayRunReason(callee: string): string;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import ts from "@stateward/core/typescript";
|
|
2
2
|
import { isFunctionBoundary, scanRunning, stripParentheses } from "../syntax.js";
|
|
3
3
|
import { oneLine, shorten } from "../text.js";
|
|
4
|
-
import { ANY_REJECTS, ARRAY_LENGTH, BUILTIN_ERRORS, DEFERRED_CALLERS, FETCH_ABORT, FETCH_REJECTS, MAPPING_METHODS, SYNC_CALLBACKS, THROWING_CONSTRUCTORS, THROWING_GLOBALS, THROWING_MEMBERS, builtinId, isNonThrowingReactHook, } from "./builtins.js";
|
|
4
|
+
import { ANY_REJECTS, ARRAY_LENGTH, BUILTIN_ERRORS, DEFERRED_CALLERS, FETCH_ABORT, FETCH_REJECTS, MAPPING_METHODS, SYNC_CALLBACKS, THROWING_CONSTRUCTORS, THROWING_GLOBALS, REJECTING_MEMBERS, THROWING_MEMBERS, builtinId, isNonThrowingReactHook, } from "./builtins.js";
|
|
5
|
+
/** How many `const` names are followed to the error they hold (`const err = new X()`). */
|
|
6
|
+
const HELD_DEPTH = 3;
|
|
5
7
|
/** Why something adds `unknown`, as the hover and the messages show it. */
|
|
6
8
|
export const REASON = {
|
|
7
9
|
noDeclaration: "no declaration",
|
|
@@ -12,6 +14,7 @@ export const REASON = {
|
|
|
12
14
|
madeError: "an error made by a call",
|
|
13
15
|
promise: "a promise that is not followed",
|
|
14
16
|
heldPromise: "promise held in a variable",
|
|
17
|
+
accessor: "a getter or setter runs here",
|
|
15
18
|
};
|
|
16
19
|
/** Why a callback handed to a call of the platform that is not in the tables adds `unknown`. */
|
|
17
20
|
export function mayRunReason(callee) {
|
|
@@ -337,7 +340,7 @@ export function summarizeThrows(ctx, packages) {
|
|
|
337
340
|
const signatures = ts.isFunctionDeclaration(declaration) || ts.isMethodDeclaration(declaration)
|
|
338
341
|
? signaturesOf(declaration)
|
|
339
342
|
: [];
|
|
340
|
-
const doc = docOf(...(signatures.length > 0 ? signatures : [declaration]));
|
|
343
|
+
const doc = docOf(declaration, ...(signatures.length > 0 ? signatures : [declaration]));
|
|
341
344
|
if (doc === null)
|
|
342
345
|
return undefined;
|
|
343
346
|
const span = spanOf(at);
|
|
@@ -421,6 +424,12 @@ export function summarizeThrows(ctx, packages) {
|
|
|
421
424
|
return call(e, walk, false);
|
|
422
425
|
if (ts.isNewExpression(e))
|
|
423
426
|
return construct(e, walk);
|
|
427
|
+
if (ts.isPropertyAccessExpression(e) && runsAccessor(e)) {
|
|
428
|
+
// `box.value`, `box.value = 1`: a getter or setter of the project runs here.
|
|
429
|
+
expression(e.expression, walk);
|
|
430
|
+
walk.sink.push(unknownLeaf(REASON.accessor, textOf(e, sourceFile), e));
|
|
431
|
+
return [];
|
|
432
|
+
}
|
|
424
433
|
if (ts.isConditionalExpression(e)) {
|
|
425
434
|
expression(e.condition, walk);
|
|
426
435
|
const branch = { ...walk, conditional: true };
|
|
@@ -431,6 +440,11 @@ export function summarizeThrows(ctx, packages) {
|
|
|
431
440
|
});
|
|
432
441
|
return [];
|
|
433
442
|
};
|
|
443
|
+
/**
|
|
444
|
+
* Whether reading or writing the property may run a getter or setter with a body in the project:
|
|
445
|
+
* its own, or one a class gives for an interface's member the value may be.
|
|
446
|
+
*/
|
|
447
|
+
const runsAccessor = (access) => types.readMayRunAccessor(access);
|
|
434
448
|
/** What the `const` that `name` refers to holds, when it is one this file summarized. */
|
|
435
449
|
const heldBy = (name) => {
|
|
436
450
|
const symbol = types.symbolAt(name);
|
|
@@ -627,6 +641,27 @@ export function summarizeThrows(ctx, packages) {
|
|
|
627
641
|
const receiver = ts.isPropertyAccessExpression(callee) ? callee.expression : undefined;
|
|
628
642
|
const resolved = resolve(name);
|
|
629
643
|
const args = node.arguments;
|
|
644
|
+
if (resolved?.kind === "platform" &&
|
|
645
|
+
receiver !== undefined &&
|
|
646
|
+
(resolved.name === "call" || resolved.name === "apply") &&
|
|
647
|
+
(resolved.owner === "Function" || resolved.owner === "CallableFunction")) {
|
|
648
|
+
// `failB.call(null)`, `failB.apply(null, [])`: the function itself runs.
|
|
649
|
+
const target = calledName(stripParentheses(receiver));
|
|
650
|
+
const runs = target === undefined ? undefined : resolve(target);
|
|
651
|
+
evaluateArguments(node, walk);
|
|
652
|
+
const shown = textOf(receiver, sourceFile);
|
|
653
|
+
if (runs?.kind === "function") {
|
|
654
|
+
if (runs.generator)
|
|
655
|
+
return [];
|
|
656
|
+
const at = spanOf(receiver);
|
|
657
|
+
if (!runs.async)
|
|
658
|
+
walk.sink.push({ k: "call", id: runs.id, part: "throws", text: shown, at });
|
|
659
|
+
return [{ k: "call", id: runs.id, part: "rejects", text: shown, at }];
|
|
660
|
+
}
|
|
661
|
+
const leaf = unknownLeaf(REASON.dynamic, text, callee);
|
|
662
|
+
walk.sink.push(leaf);
|
|
663
|
+
return [leaf];
|
|
664
|
+
}
|
|
630
665
|
if (resolved?.kind === "platform") {
|
|
631
666
|
const key = resolved.owner === null ? resolved.name : `${resolved.owner}.${resolved.name}`;
|
|
632
667
|
if (resolved.owner === "Promise") {
|
|
@@ -693,10 +728,16 @@ export function summarizeThrows(ctx, packages) {
|
|
|
693
728
|
if (key === "fetch") {
|
|
694
729
|
return classLeaves(signalOf(args[1]) ? [...FETCH_REJECTS, FETCH_ABORT] : FETCH_REJECTS, `${text}(…)`, node);
|
|
695
730
|
}
|
|
731
|
+
const rejects = REJECTING_MEMBERS.get(key);
|
|
732
|
+
if (rejects !== undefined)
|
|
733
|
+
return classLeaves(rejects, `${text}(…)`, node);
|
|
696
734
|
const throws = resolved.owner === null
|
|
697
735
|
? (THROWING_GLOBALS.get(key) ??
|
|
698
736
|
(key === "Array" && args.length === 1 ? ARRAY_LENGTH : []))
|
|
699
|
-
:
|
|
737
|
+
: // `n.toString()` with no radix cannot throw; with one, it may.
|
|
738
|
+
key === "Number.toString" && args.length === 0
|
|
739
|
+
? []
|
|
740
|
+
: (THROWING_MEMBERS.get(key) ?? []);
|
|
700
741
|
walk.sink.push(...classLeaves(throws, `${text}(…)`, node));
|
|
701
742
|
return mapping && MAPPING_METHODS.has(key) ? mapped : [];
|
|
702
743
|
}
|
|
@@ -837,9 +878,49 @@ export function summarizeThrows(ctx, packages) {
|
|
|
837
878
|
? node.getStart(sourceFile)
|
|
838
879
|
: undefined;
|
|
839
880
|
};
|
|
881
|
+
/** `Object.assign(target, …)`: it returns `target`. */
|
|
882
|
+
const isObjectAssign = (call) => {
|
|
883
|
+
const callee = stripParentheses(call.expression);
|
|
884
|
+
return (ts.isPropertyAccessExpression(callee) &&
|
|
885
|
+
ts.isIdentifier(callee.expression) &&
|
|
886
|
+
callee.expression.text === "Object" &&
|
|
887
|
+
callee.name.text === "assign");
|
|
888
|
+
};
|
|
889
|
+
/**
|
|
890
|
+
* The class of the error a value is, when the code makes it in plain sight: `new X(…)`,
|
|
891
|
+
* `Object.assign(new X(), …)`, or a `const` holding one (`const err = new X(); throw err`).
|
|
892
|
+
*/
|
|
893
|
+
const madeClass = (value, depth) => {
|
|
894
|
+
const e = unwrap(value);
|
|
895
|
+
if (ts.isNewExpression(e))
|
|
896
|
+
return classRef(stripParentheses(e.expression));
|
|
897
|
+
if (ts.isCallExpression(e) && isObjectAssign(e)) {
|
|
898
|
+
const [target] = e.arguments;
|
|
899
|
+
return target === undefined ? undefined : madeClass(target, depth);
|
|
900
|
+
}
|
|
901
|
+
if (!ts.isIdentifier(e) || depth >= HELD_DEPTH)
|
|
902
|
+
return undefined;
|
|
903
|
+
const symbol = types.symbolAt(e);
|
|
904
|
+
const node = symbol === undefined ? undefined : types.declarationOf(symbol)?.node;
|
|
905
|
+
if (node === undefined ||
|
|
906
|
+
!ts.isVariableDeclaration(node) ||
|
|
907
|
+
node.initializer === undefined ||
|
|
908
|
+
!ts.isVariableDeclarationList(node.parent) ||
|
|
909
|
+
(node.parent.flags & ts.NodeFlags.Const) === 0) {
|
|
910
|
+
return undefined;
|
|
911
|
+
}
|
|
912
|
+
return madeClass(node.initializer, depth + 1);
|
|
913
|
+
};
|
|
840
914
|
/** What `throw <value>` (or `reject(value)`) throws; its own calls go to the sink. */
|
|
841
915
|
const thrown = (value, walk) => {
|
|
842
916
|
const e = stripParentheses(value);
|
|
917
|
+
if (ts.isCallExpression(e) && isObjectAssign(e)) {
|
|
918
|
+
const id = madeClass(e, 0);
|
|
919
|
+
if (id !== undefined) {
|
|
920
|
+
evaluateArguments(e, walk);
|
|
921
|
+
return [{ k: "class", id, text: null, at: spanOf(e) }];
|
|
922
|
+
}
|
|
923
|
+
}
|
|
843
924
|
if (ts.isNewExpression(e) || ts.isCallExpression(e)) {
|
|
844
925
|
const id = classRef(stripParentheses(e.expression));
|
|
845
926
|
if (id !== undefined) {
|
|
@@ -857,6 +938,9 @@ export function summarizeThrows(ctx, packages) {
|
|
|
857
938
|
const of = caughtVariable(e);
|
|
858
939
|
if (of !== undefined)
|
|
859
940
|
return [{ k: "rethrow", of, maybe: walk.conditional, at: spanOf(e) }];
|
|
941
|
+
const id = madeClass(e, 0);
|
|
942
|
+
if (id !== undefined)
|
|
943
|
+
return [{ k: "class", id, text: null, at: spanOf(e) }];
|
|
860
944
|
}
|
|
861
945
|
expression(e, walk);
|
|
862
946
|
return [unknownLeaf(REASON.thrownValue, `throw ${textOf(e, sourceFile)}`, e)];
|
|
@@ -1145,7 +1229,7 @@ export function summarizeThrows(ctx, packages) {
|
|
|
1145
1229
|
return plain();
|
|
1146
1230
|
};
|
|
1147
1231
|
// ---- @throws --------------------------------------------------------------------------------
|
|
1148
|
-
const docOf = (...nodes) => {
|
|
1232
|
+
const docOf = (declared, ...nodes) => {
|
|
1149
1233
|
const tags = new Set(nodes.flatMap((node) => ts.getJSDocTags(node)));
|
|
1150
1234
|
const entries = [];
|
|
1151
1235
|
const untyped = [];
|
|
@@ -1177,7 +1261,10 @@ export function summarizeThrows(ctx, packages) {
|
|
|
1177
1261
|
else
|
|
1178
1262
|
add(type);
|
|
1179
1263
|
}
|
|
1180
|
-
|
|
1264
|
+
const start = ts.isPropertyDeclaration(declared) || ts.isPropertyAssignment(declared)
|
|
1265
|
+
? declared.name.getStart()
|
|
1266
|
+
: declared.getStart();
|
|
1267
|
+
return found ? { entries, untyped, declared: start } : null;
|
|
1181
1268
|
};
|
|
1182
1269
|
// ---- functions ------------------------------------------------------------------------------
|
|
1183
1270
|
const functions = [];
|
|
@@ -1197,7 +1284,7 @@ export function summarizeThrows(ctx, packages) {
|
|
|
1197
1284
|
statement(body, walk);
|
|
1198
1285
|
else
|
|
1199
1286
|
scope.returns.push(...flowing(body, walk));
|
|
1200
|
-
const doc = name === undefined ? null : docOf(declaration, fn);
|
|
1287
|
+
const doc = name === undefined ? null : docOf(declaration, declaration, fn);
|
|
1201
1288
|
functions.push({
|
|
1202
1289
|
id: symbol.id,
|
|
1203
1290
|
name: symbol.name,
|
|
@@ -1219,7 +1306,7 @@ export function summarizeThrows(ctx, packages) {
|
|
|
1219
1306
|
*/
|
|
1220
1307
|
const bodylessFact = (name, node) => {
|
|
1221
1308
|
const symbol = types.symbolAt(name);
|
|
1222
|
-
const doc = docOf(...signaturesOf(node));
|
|
1309
|
+
const doc = docOf(node, ...signaturesOf(node));
|
|
1223
1310
|
if (symbol === undefined || doc === null)
|
|
1224
1311
|
return;
|
|
1225
1312
|
functions.push({
|
|
@@ -147,6 +147,11 @@ export type Doc = {
|
|
|
147
147
|
readonly entries: readonly DocEntry[];
|
|
148
148
|
/** A tag without a type (`@throws when …`): it says the function throws, not what. */
|
|
149
149
|
readonly untyped: readonly Span[];
|
|
150
|
+
/**
|
|
151
|
+
* Where the declaration the tags are on starts, as the reference ledger names it (a property by
|
|
152
|
+
* its name): a finding about the tags is against that declaration.
|
|
153
|
+
*/
|
|
154
|
+
readonly declared: number;
|
|
150
155
|
};
|
|
151
156
|
export type FunctionFact = {
|
|
152
157
|
readonly id: string;
|
|
@@ -176,7 +176,11 @@ function readDoc(value) {
|
|
|
176
176
|
return { id: entry.id, name: entry.name, at };
|
|
177
177
|
});
|
|
178
178
|
const untyped = each(f.untyped, spanOf);
|
|
179
|
-
|
|
179
|
+
if (typeof f.declared !== "number")
|
|
180
|
+
return undefined;
|
|
181
|
+
return entries === undefined || untyped === undefined
|
|
182
|
+
? undefined
|
|
183
|
+
: { entries, untyped, declared: f.declared };
|
|
180
184
|
}
|
|
181
185
|
function readFunction(value) {
|
|
182
186
|
const f = fieldsOf(value);
|
package/dist/narrow-try.d.ts
CHANGED
|
@@ -38,6 +38,8 @@ type TryShape = {
|
|
|
38
38
|
readonly at: Span;
|
|
39
39
|
/** The `catch` tests the error or rethrows it: bugs already get through. */
|
|
40
40
|
readonly passesBugsOn: boolean;
|
|
41
|
+
/** The name the `catch` gives the error (`catch (e)`), or null when it binds none. */
|
|
42
|
+
readonly variable: string | null;
|
|
41
43
|
/** The `catch` block ends with `return` or `throw`. */
|
|
42
44
|
readonly catchExits: boolean;
|
|
43
45
|
readonly hasFinally: boolean;
|