Skip to content

Add preceding semicolon on await insertion when parentheses are included #34627

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
merged 5 commits into from
Nov 19, 2019
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: 3 additions & 3 deletions src/harness/fourslash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2358,9 +2358,9 @@ namespace FourSlash {
if (!details) {
return this.raiseError(`No completions were found for the given name, source, and preferences.`);
}
const codeActions = details.codeActions!;
if (codeActions.length !== 1) {
this.raiseError(`Expected one code action, got ${codeActions.length}`);
const codeActions = details.codeActions;
if (codeActions?.length !== 1) {
this.raiseError(`Expected one code action, got ${codeActions?.length ?? 0}`);
}
const codeAction = ts.first(codeActions);

Expand Down
9 changes: 9 additions & 0 deletions src/services/codefixes/addMissingAwait.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ namespace ts.codefix {
sourceFile,
insertionSite.parent.expression,
createParen(createAwait(insertionSite.parent.expression)));
insertLeadingSemicolonIfNeeded(changeTracker, insertionSite.parent.expression, sourceFile);
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
insertLeadingSemicolonIfNeeded(changeTracker, insertionSite.parent.expression, sourceFile);
insertLeadingSemicolonIfNeeded(changeTracker, insertionSite.parent.expression, sourceFile);

Copy link
Member Author

@andrewbranch andrewbranch Nov 18, 2019

Choose a reason for hiding this comment

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

The current indentation is correct (the preceding three lines are arguments to replaceNode; this is not)

}
else if (contains(callableConstructableErrorCodes, errorCode) && isCallOrNewExpression(insertionSite.parent)) {
if (fixedDeclarations && isIdentifier(insertionSite)) {
Expand All @@ -266,6 +267,7 @@ namespace ts.codefix {
}
}
changeTracker.replaceNode(sourceFile, insertionSite, createParen(createAwait(insertionSite)));
insertLeadingSemicolonIfNeeded(changeTracker, insertionSite, sourceFile);
}
else {
if (fixedDeclarations && isVariableDeclaration(insertionSite.parent) && isIdentifier(insertionSite.parent.name)) {
Expand All @@ -277,4 +279,11 @@ namespace ts.codefix {
changeTracker.replaceNode(sourceFile, insertionSite, createAwait(insertionSite));
}
}

function insertLeadingSemicolonIfNeeded(changeTracker: textChanges.ChangeTracker, beforeNode: Node, sourceFile: SourceFile) {
const precedingToken = findPrecedingToken(beforeNode.pos, sourceFile);
if (precedingToken && positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) {
changeTracker.insertText(sourceFile, beforeNode.getStart(sourceFile), ";");
}
}
}
8 changes: 7 additions & 1 deletion src/services/completions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,13 @@ namespace ts.Completions {
}
if (origin && originIsPromise(origin) && propertyAccessToConvert) {
if (insertText === undefined) insertText = name;
const awaitText = `(await ${propertyAccessToConvert.expression.getText()})`;
const precedingToken = findPrecedingToken(propertyAccessToConvert.pos, sourceFile);
let awaitText = "";
if (precedingToken && positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) {
awaitText = ";";
}

awaitText += `(await ${propertyAccessToConvert.expression.getText()})`;
insertText = needsConvertPropertyAccess ? `${awaitText}${insertText}` : `${awaitText}${insertQuestionDot ? "?." : "."}${insertText}`;
replacementSpan = createTextSpanFromBounds(propertyAccessToConvert.getStart(sourceFile), propertyAccessToConvert.end);
}
Expand Down
9 changes: 1 addition & 8 deletions src/services/formatting/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -855,13 +855,6 @@ namespace ts.formatting {
}

function isSemicolonInsertionContext(context: FormattingContext): boolean {
const contextAncestor = findAncestor(context.currentTokenParent, ancestor => {
if (ancestor.end !== context.currentTokenSpan.end) {
return "quit";
}
return syntaxMayBeASICandidate(ancestor.kind);
});

return !!contextAncestor && isASICandidate(contextAncestor, context.sourceFile);
return positionIsASICandidate(context.currentTokenSpan.end, context.currentTokenParent, context.sourceFile);
}
}
13 changes: 12 additions & 1 deletion src/services/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2066,7 +2066,7 @@ namespace ts {
syntaxRequiresTrailingModuleBlockOrSemicolonOrASI,
syntaxRequiresTrailingSemicolonOrASI);

export function isASICandidate(node: Node, sourceFile: SourceFileLike): boolean {
function nodeIsASICandidate(node: Node, sourceFile: SourceFileLike): boolean {
const lastToken = node.getLastToken(sourceFile);
if (lastToken && lastToken.kind === SyntaxKind.SemicolonToken) {
return false;
Expand Down Expand Up @@ -2109,6 +2109,17 @@ namespace ts {
return startLine !== endLine;
}

export function positionIsASICandidate(pos: number, context: Node, sourceFile: SourceFileLike): boolean {
const contextAncestor = findAncestor(context, ancestor => {
if (ancestor.end !== pos) {
return "quit";
}
return syntaxMayBeASICandidate(ancestor.kind);
});

return !!contextAncestor && nodeIsASICandidate(contextAncestor, sourceFile);
}

export function probablyUsesSemicolons(sourceFile: SourceFile): boolean {
let withSemicolon = 0;
let withoutSemicolon = 0;
Expand Down
15 changes: 15 additions & 0 deletions tests/cases/fourslash/codeFixAddMissingAwait_propertyAccess2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/// <reference path="fourslash.ts" />
////async function fn(a: Promise<{ x: string }>) {
//// console.log(3)
//// a.x;
////}

verify.codeFix({
description: ts.Diagnostics.Add_await.message,
index: 0,
newFileContent:
`async function fn(a: Promise<{ x: string }>) {
console.log(3)
Copy link
Member

Choose a reason for hiding this comment

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

Shouldn't this have ; after console.log and on that line instead of next line ?

Copy link
Member Author

Choose a reason for hiding this comment

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

This is actually the typical preferred style for non-semicoloners. See https://standardjs.com/rules.html#semicolons

Copy link
Member Author

Choose a reason for hiding this comment

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

/cc @orta to confirm people actually do this?

Copy link
Member Author

Choose a reason for hiding this comment

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

Prettier does it this way, to which I give more credence than StandardJS anyway. I feel good about keeping it.

Copy link
Contributor

Choose a reason for hiding this comment

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

Yep, confirming, this is what I'm used to

;(await a).x;
}`
});
50 changes: 50 additions & 0 deletions tests/cases/fourslash/codeFixAddMissingAwait_signatures2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/// <reference path="fourslash.ts" />
////async function fn(a: Promise<() => void>, b: Promise<() => void> | (() => void), C: Promise<{ new(): any }>) {
//// a()
//// b()
//// new C()
////}

verify.codeFix({
description: ts.Diagnostics.Add_await.message,
index: 0,
newFileContent:
`async function fn(a: Promise<() => void>, b: Promise<() => void> | (() => void), C: Promise<{ new(): any }>) {
(await a)()
b()
new C()
}`
});

verify.codeFix({
description: ts.Diagnostics.Add_await.message,
index: 1,
newFileContent:
`async function fn(a: Promise<() => void>, b: Promise<() => void> | (() => void), C: Promise<{ new(): any }>) {
a()
;(await b)()
new C()
}`
});

verify.codeFix({
description: ts.Diagnostics.Add_await.message,
index: 2,
newFileContent:
`async function fn(a: Promise<() => void>, b: Promise<() => void> | (() => void), C: Promise<{ new(): any }>) {
a()
b()
new (await C)()
}`
});

verify.codeFixAll({
fixAllDescription: ts.Diagnostics.Fix_all_expressions_possibly_missing_await.message,
fixId: "addMissingAwait",
newFileContent:
`async function fn(a: Promise<() => void>, b: Promise<() => void> | (() => void), C: Promise<{ new(): any }>) {
(await a)()
;(await b)()
new (await C)()
}`
});
18 changes: 18 additions & 0 deletions tests/cases/fourslash/completionOfAwaitPromise7.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/// <reference path='fourslash.ts'/>

////async function foo(x: Promise<string>) {
//// console.log
//// [|x./**/|]
////}

const replacementSpan = test.ranges()[0];
verify.completions({
marker: "",
includes: [
"then",
{ name: "trim", insertText: ';(await x).trim', replacementSpan },
],
preferences: {
includeInsertTextCompletions: true,
},
});