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

Add 'Remove unnecessary await' suggestion and fix #32363

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26403,7 +26403,11 @@ namespace ts {
* The runtime behavior of the `await` keyword.
*/
function checkAwaitedType(type: Type, errorNode: Node, diagnosticMessage: DiagnosticMessage, arg0?: string | number): Type {
return getAwaitedType(type, errorNode, diagnosticMessage, arg0) || errorType;
const awaitedType = getAwaitedType(type, errorNode, diagnosticMessage, arg0);
if (awaitedType === type && !(type.flags & TypeFlags.AnyOrUnknown)) {
addErrorOrSuggestion(/*isError*/ false, createDiagnosticForNode(errorNode, Diagnostics.await_has_no_effect_on_the_type_of_this_expression));
}
return awaitedType || errorType;
}

function getAwaitedType(type: Type, errorNode?: Node, diagnosticMessage?: DiagnosticMessage, arg0?: string | number): Type | undefined {
Expand Down
13 changes: 13 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -4635,6 +4635,11 @@
"category": "Suggestion",
"code": 80006
},
"'await' has no effect on the type of this expression.": {
"category": "Suggestion",
"code": 80007
},

"Add missing 'super()' call": {
"category": "Message",
"code": 90001
Expand Down Expand Up @@ -5095,6 +5100,14 @@
"category": "Message",
"code": 95085
},
"Remove unnecessary 'await'": {
"category": "Message",
"code": 95086
},
"Remove all unnecessary uses of 'await'": {
"category": "Message",
"code": 95087
},

"No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer.": {
"category": "Error",
Expand Down
33 changes: 33 additions & 0 deletions src/services/codefixes/removeUnnecessaryAwait.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/* @internal */
namespace ts.codefix {
const fixId = "removeUnnecessaryAwait";
const errorCodes = [
Diagnostics.await_has_no_effect_on_the_type_of_this_expression.code,
];

registerCodeFix({
errorCodes,
getCodeActions: (context) => {
const changes = textChanges.ChangeTracker.with(context, t => makeChange(t, context.sourceFile, context.span));
if (changes.length > 0) {
return [createCodeFixAction(fixId, changes, Diagnostics.Remove_unnecessary_await, fixId, Diagnostics.Remove_all_unnecessary_uses_of_await)];
}
},
fixIds: [fixId],
getAllCodeActions: context => {
return codeFixAll(context, errorCodes, (changes, diag) => makeChange(changes, diag.file, diag));
},
});

function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, span: TextSpan) {
const awaitKeyword = tryCast(getTokenAtPosition(sourceFile, span.start), (node): node is AwaitKeywordToken => node.kind === SyntaxKind.AwaitKeyword);
const awaitExpression = awaitKeyword && tryCast(awaitKeyword.parent, isAwaitExpression);
if (!awaitExpression) {
return;
}

const parenthesizedExpression = tryCast(awaitExpression.parent, isParenthesizedExpression);
const removeParens = parenthesizedExpression && (isIdentifier(awaitExpression.expression) || isCallExpression(awaitExpression.expression));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@andrewbranch it seems you dropped the code necessary to avoid changing the parsing of NewExpression.

However, there's a whole category of exceptions that's not handled here: if the parenthesized AwaitExpression is at the start of the statement, the fixed code could parse as declaration instead of expression:

(await function(){}());
(await class {static fn(){}}.fn());
(await {fn() {}}.fn());

These cases are already handled in factory.ts, see the uses of getLeftmostExpression

changeTracker.replaceNode(sourceFile, removeParens ? parenthesizedExpression || awaitExpression : awaitExpression, awaitExpression.expression);
}
}
1 change: 1 addition & 0 deletions src/services/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
"codefixes/useDefaultImport.ts",
"codefixes/fixAddModuleReferTypeMissingTypeof.ts",
"codefixes/convertToMappedObjectType.ts",
"codefixes/removeUnnecessaryAwait.ts",
"refactors/convertExport.ts",
"refactors/convertImport.ts",
"refactors/extractSymbol.ts",
Expand Down
40 changes: 40 additions & 0 deletions tests/cases/fourslash/codeFixRemoveUnnecessaryAwait.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/// <reference path="fourslash.ts" />
////declare class C { foo(): void }
////declare function foo(): string;
////async function f() {
//// await "";
//// await 0;
//// (await foo()).toLowerCase();
//// (await 0).toFixed();
//// (await new C).foo();
////}

verify.codeFix({
description: ts.Diagnostics.Remove_unnecessary_await.message,
index: 0,
newFileContent:
`declare class C { foo(): void }
declare function foo(): string;
async function f() {
"";
await 0;
(await foo()).toLowerCase();
(await 0).toFixed();
(await new C).foo();
}`
});

verify.codeFixAll({
fixAllDescription: ts.Diagnostics.Remove_all_unnecessary_uses_of_await.message,
fixId: "removeUnnecessaryAwait",
newFileContent:
`declare class C { foo(): void }
declare function foo(): string;
async function f() {
"";
0;
foo().toLowerCase();
(0).toFixed();
(new C).foo();
}`
});
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@

// @allowNonTsExtensions: true
// @Filename: test123.js
// @lib: es5
////export function /**/MyClass() {
////}
////MyClass.prototype.foo = async function() {
//// await 2;
//// await Promise.resolve();
////}
////MyClass.bar = async function() {
//// await 3;
//// await Promise.resolve();
////}

verify.codeFix({
Expand All @@ -18,10 +19,10 @@ verify.codeFix({
constructor() {
}
async foo() {
await 2;
await Promise.resolve();
}
static async bar() {
await 3;
await Promise.resolve();
}
}
`,
Expand Down