Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(eslint-plugin): [return-await] correct autofixer in binary expres…
…sion (#4401)

* fix(eslint-plugin): return-await in binary expression

* fix(eslint-plugin): [return-await] add ( ) to Expressions with lower precedence than awaitExpressions

* fix(eslint-plugin): [return-await] add test
  • Loading branch information
islandryu committed Mar 1, 2022
1 parent a65713a commit 5fa2fad
Show file tree
Hide file tree
Showing 3 changed files with 509 additions and 7 deletions.
31 changes: 24 additions & 7 deletions packages/eslint-plugin/src/rules/return-await.ts
@@ -1,7 +1,9 @@
import { AST_NODE_TYPES, TSESLint, TSESTree } from '@typescript-eslint/utils';
import * as tsutils from 'tsutils';
import { isBinaryExpression } from 'tsutils';
import * as ts from 'typescript';
import * as util from '../util';
import { getOperatorPrecedence } from '../util/getOperatorPrecedence';

type FunctionNode =
| TSESTree.FunctionDeclaration
Expand Down Expand Up @@ -149,15 +151,28 @@ export default util.createRule({
function insertAwait(
fixer: TSESLint.RuleFixer,
node: TSESTree.Expression,
isHighPrecendence: boolean,
): TSESLint.RuleFix | TSESLint.RuleFix[] {
if (node.type !== AST_NODE_TYPES.TSAsExpression) {
if (isHighPrecendence) {
return fixer.insertTextBefore(node, 'await ');
} else {
return [
fixer.insertTextBefore(node, 'await ('),
fixer.insertTextAfter(node, ')'),
];
}
}

return [
fixer.insertTextBefore(node, 'await ('),
fixer.insertTextAfter(node, ')'),
];
function isHigherPrecedenceThanAwait(node: ts.Node): boolean {
const operator = isBinaryExpression(node)
? node.operatorToken.kind
: ts.SyntaxKind.Unknown;
const nodePrecedence = getOperatorPrecedence(node.kind, operator);
const awaitPrecedence = getOperatorPrecedence(
ts.SyntaxKind.AwaitExpression,
ts.SyntaxKind.Unknown,
);
return nodePrecedence > awaitPrecedence;
}

function test(node: TSESTree.Expression, expression: ts.Node): void {
Expand Down Expand Up @@ -208,7 +223,8 @@ export default util.createRule({
context.report({
messageId: 'requiredPromiseAwait',
node,
fix: fixer => insertAwait(fixer, node),
fix: fixer =>
insertAwait(fixer, node, isHigherPrecedenceThanAwait(expression)),
});
}

Expand Down Expand Up @@ -247,7 +263,8 @@ export default util.createRule({
context.report({
messageId: 'requiredPromiseAwait',
node,
fix: fixer => insertAwait(fixer, node),
fix: fixer =>
insertAwait(fixer, node, isHigherPrecedenceThanAwait(expression)),
});
}

Expand Down

0 comments on commit 5fa2fad

Please sign in to comment.