-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
fix(eslint-plugin): [return-await] clean up in-try-catch detection and make autofixes safe #9031
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
kirkwaiblinger
merged 7 commits into
typescript-eslint:main
from
kirkwaiblinger:return-await-bugs
May 31, 2024
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
3d6ed66
[no-return-await] Clean up the logic for in-try-catch detection and m…
kirkwaiblinger 189a6b4
spell
kirkwaiblinger 2abfe6a
snapshot
kirkwaiblinger dd1adda
Merge branch 'main' into return-await-bugs
kirkwaiblinger 1777ac9
nicer diff
kirkwaiblinger 3bda3a5
adjust unreachable case
kirkwaiblinger c23b3a6
Merge branch 'main' into return-await-bugs
kirkwaiblinger File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -149,6 +149,7 @@ | |
"tsvfs", | ||
"typedef", | ||
"typedefs", | ||
"unawaited", | ||
"unfixable", | ||
"unoptimized", | ||
"unprefixed", | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,6 +10,7 @@ import { | |
isAwaitKeyword, | ||
isTypeAnyType, | ||
isTypeUnknownType, | ||
nullThrows, | ||
} from '../util'; | ||
import { getOperatorPrecedence } from '../util/getOperatorPrecedence'; | ||
|
||
|
@@ -41,6 +42,10 @@ export default createRule({ | |
'Returning an awaited promise is not allowed in this context.', | ||
requiredPromiseAwait: | ||
'Returning an awaited promise is required in this context.', | ||
requiredPromiseAwaitSuggestion: | ||
'Add `await` before the expression. Use caution as this may impact control flow.', | ||
disallowedPromiseAwaitSuggestion: | ||
'Remove `await` before the expression. Use caution as this may impact control flow.', | ||
}, | ||
schema: [ | ||
{ | ||
|
@@ -68,64 +73,90 @@ export default createRule({ | |
scopeInfoStack.pop(); | ||
} | ||
|
||
function inTry(node: ts.Node): boolean { | ||
let ancestor = node.parent as ts.Node | undefined; | ||
|
||
while (ancestor && !ts.isFunctionLike(ancestor)) { | ||
if (ts.isTryStatement(ancestor)) { | ||
return true; | ||
} | ||
|
||
ancestor = ancestor.parent; | ||
/** | ||
* Tests whether a node is inside of an explicit error handling context | ||
* (try/catch/finally) in a way that throwing an exception will have an | ||
* impact on the program's control flow. | ||
*/ | ||
function affectsExplicitErrorHandling(node: ts.Node): boolean { | ||
// If an error-handling block is followed by another error-handling block, | ||
// control flow is affected by whether promises in it are awaited or not. | ||
// Otherwise, we need to check recursively for nested try statements until | ||
// we get to the top level of a function or the program. If by then, | ||
// there's no offending error-handling blocks, it doesn't affect control | ||
// flow. | ||
const tryAncestorResult = findContainingTryStatement(node); | ||
if (tryAncestorResult == null) { | ||
return false; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
function inCatch(node: ts.Node): boolean { | ||
let ancestor = node.parent as ts.Node | undefined; | ||
const { tryStatement, block } = tryAncestorResult; | ||
|
||
while (ancestor && !ts.isFunctionLike(ancestor)) { | ||
if (ts.isCatchClause(ancestor)) { | ||
switch (block) { | ||
case 'try': | ||
// Try blocks are always followed by either a catch or finally, | ||
// so exceptions thrown here always affect control flow. | ||
return true; | ||
} | ||
|
||
ancestor = ancestor.parent; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
function isReturnPromiseInFinally(node: ts.Node): boolean { | ||
let ancestor = node.parent as ts.Node | undefined; | ||
case 'catch': | ||
// Exceptions thrown in catch blocks followed by a finally block affect | ||
// control flow. | ||
if (tryStatement.finallyBlock != null) { | ||
return true; | ||
} | ||
|
||
while (ancestor && !ts.isFunctionLike(ancestor)) { | ||
if ( | ||
ts.isTryStatement(ancestor.parent) && | ||
ts.isBlock(ancestor) && | ||
ancestor.parent.end === ancestor.end | ||
) { | ||
return true; | ||
// Otherwise recurse. | ||
return affectsExplicitErrorHandling(tryStatement); | ||
case 'finally': | ||
return affectsExplicitErrorHandling(tryStatement); | ||
default: { | ||
const __never: never = block; | ||
throw new Error(`Unexpected block type: ${String(__never)}`); | ||
} | ||
ancestor = ancestor.parent; | ||
} | ||
} | ||
|
||
return false; | ||
interface FindContainingTryStatementResult { | ||
tryStatement: ts.TryStatement; | ||
block: 'try' | 'catch' | 'finally'; | ||
} | ||
|
||
function hasFinallyBlock(node: ts.Node): boolean { | ||
/** | ||
* A try _statement_ is the whole thing that encompasses try block, | ||
* catch clause, and finally block. This function finds the nearest | ||
* enclosing try statement (if present) for a given node, and reports which | ||
* part of the try statement the node is in. | ||
*/ | ||
function findContainingTryStatement( | ||
node: ts.Node, | ||
): FindContainingTryStatementResult | undefined { | ||
let child = node; | ||
let ancestor = node.parent as ts.Node | undefined; | ||
|
||
while (ancestor && !ts.isFunctionLike(ancestor)) { | ||
if (ts.isTryStatement(ancestor)) { | ||
return !!ancestor.finallyBlock; | ||
let block: 'try' | 'catch' | 'finally' | undefined; | ||
if (child === ancestor.tryBlock) { | ||
block = 'try'; | ||
} else if (child === ancestor.catchClause) { | ||
block = 'catch'; | ||
} else if (child === ancestor.finallyBlock) { | ||
block = 'finally'; | ||
} | ||
|
||
return { | ||
tryStatement: ancestor, | ||
block: nullThrows( | ||
block, | ||
'Child of a try statement must be a try block, catch clause, or finally block', | ||
), | ||
}; | ||
} | ||
child = ancestor; | ||
ancestor = ancestor.parent; | ||
} | ||
return false; | ||
} | ||
|
||
// function findTokensToRemove() | ||
return undefined; | ||
} | ||
|
||
function removeAwait( | ||
fixer: TSESLint.RuleFixer, | ||
|
@@ -202,33 +233,35 @@ export default createRule({ | |
if (isAwait && !isThenable) { | ||
// any/unknown could be thenable; do not auto-fix | ||
const useAutoFix = !(isTypeAnyType(type) || isTypeUnknownType(type)); | ||
const fix = (fixer: TSESLint.RuleFixer): TSESLint.RuleFix | null => | ||
removeAwait(fixer, node); | ||
|
||
context.report({ | ||
messageId: 'nonPromiseAwait', | ||
node, | ||
...(useAutoFix | ||
? { fix } | ||
: { | ||
suggest: [ | ||
{ | ||
messageId: 'nonPromiseAwait', | ||
fix, | ||
}, | ||
], | ||
}), | ||
...fixOrSuggest(useAutoFix, { | ||
messageId: 'nonPromiseAwait', | ||
fix: fixer => removeAwait(fixer, node), | ||
}), | ||
}); | ||
return; | ||
} | ||
|
||
const affectsErrorHandling = affectsExplicitErrorHandling(expression); | ||
const useAutoFix = !affectsErrorHandling; | ||
|
||
if (option === 'always') { | ||
if (!isAwait && isThenable) { | ||
context.report({ | ||
messageId: 'requiredPromiseAwait', | ||
node, | ||
fix: fixer => | ||
insertAwait(fixer, node, isHigherPrecedenceThanAwait(expression)), | ||
...fixOrSuggest(useAutoFix, { | ||
messageId: 'requiredPromiseAwaitSuggestion', | ||
fix: fixer => | ||
insertAwait( | ||
fixer, | ||
node, | ||
isHigherPrecedenceThanAwait(expression), | ||
), | ||
}), | ||
}); | ||
} | ||
|
||
|
@@ -240,35 +273,39 @@ export default createRule({ | |
context.report({ | ||
messageId: 'disallowedPromiseAwait', | ||
node, | ||
fix: fixer => removeAwait(fixer, node), | ||
...fixOrSuggest(useAutoFix, { | ||
messageId: 'disallowedPromiseAwaitSuggestion', | ||
fix: fixer => removeAwait(fixer, node), | ||
}), | ||
}); | ||
} | ||
|
||
return; | ||
} | ||
|
||
if (option === 'in-try-catch') { | ||
const isInTryCatch = inTry(expression) || inCatch(expression); | ||
if (isAwait && !isInTryCatch) { | ||
if (isAwait && !affectsErrorHandling) { | ||
context.report({ | ||
messageId: 'disallowedPromiseAwait', | ||
node, | ||
fix: fixer => removeAwait(fixer, node), | ||
...fixOrSuggest(useAutoFix, { | ||
messageId: 'disallowedPromiseAwaitSuggestion', | ||
fix: fixer => removeAwait(fixer, node), | ||
}), | ||
}); | ||
} else if (!isAwait && isInTryCatch) { | ||
if (inCatch(expression) && !hasFinallyBlock(expression)) { | ||
return; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
} | ||
|
||
if (isReturnPromiseInFinally(expression)) { | ||
return; | ||
} | ||
|
||
} else if (!isAwait && affectsErrorHandling) { | ||
context.report({ | ||
messageId: 'requiredPromiseAwait', | ||
node, | ||
fix: fixer => | ||
insertAwait(fixer, node, isHigherPrecedenceThanAwait(expression)), | ||
...fixOrSuggest(useAutoFix, { | ||
messageId: 'requiredPromiseAwaitSuggestion', | ||
fix: fixer => | ||
insertAwait( | ||
fixer, | ||
node, | ||
isHigherPrecedenceThanAwait(expression), | ||
), | ||
}), | ||
}); | ||
} | ||
|
||
|
@@ -321,3 +358,12 @@ export default createRule({ | |
}; | ||
}, | ||
}); | ||
|
||
function fixOrSuggest<MessageId extends string>( | ||
useFix: boolean, | ||
suggestion: TSESLint.SuggestionReportDescriptor<MessageId>, | ||
): | ||
| { fix: TSESLint.ReportFixFunction } | ||
| { suggest: TSESLint.SuggestionReportDescriptor<MessageId>[] } { | ||
return useFix ? { fix: suggestion.fix } : { suggest: [suggestion] }; | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Praise] I like this :) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The thought is that one day (soon) there will be a
|| affectsExplicitResourceManagement(expression)
🙏 #7889/#9044