Skip to content
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

fix(eslint-plugin): [return-await] correct autofixer in binary expression #4401

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 24 additions & 7 deletions packages/eslint-plugin/src/rules/return-await.ts
Expand Up @@ -4,8 +4,10 @@ import {
TSESTree,
} from '@typescript-eslint/experimental-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 @@ -153,15 +155,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 @@ -212,7 +227,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 @@ -251,7 +267,8 @@ export default util.createRule({
context.report({
messageId: 'requiredPromiseAwait',
node,
fix: fixer => insertAwait(fixer, node),
fix: fixer =>
insertAwait(fixer, node, isHigherPrecedenceThanAwait(expression)),
});
}

Expand Down