Skip to content

Commit 6876d98

Browse files
committed
Merge with master
2 parents 7d8bc25 + ed20f7d commit 6876d98

31 files changed

Lines changed: 438 additions & 46 deletions

src/parser/diagnosticMessages.json

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4402,5 +4402,17 @@
44024402
"Convert named imports to namespace import": {
44034403
"category": "Message",
44044404
"code": 95057
4405+
},
4406+
"Add or remove braces in an arrow function": {
4407+
"category": "Message",
4408+
"code": 95058
4409+
},
4410+
"Add braces to arrow function": {
4411+
"category": "Message",
4412+
"code": 95059
4413+
},
4414+
"Remove braces from arrow function": {
4415+
"category": "Message",
4416+
"code": 95060
44054417
}
44064418
}

src/services/codefixes/convertFunctionToEs6Class.ts

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -202,22 +202,6 @@ namespace ts.codefix {
202202
}
203203
}
204204

205-
function copyComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile) {
206-
forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, (pos, end, kind, htnl) => {
207-
if (kind === SyntaxKind.MultiLineCommentTrivia) {
208-
// Remove leading /*
209-
pos += 2;
210-
// Remove trailing */
211-
end -= 2;
212-
}
213-
else {
214-
// Remove leading //
215-
pos += 2;
216-
}
217-
addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl);
218-
});
219-
}
220-
221205
function getModifierKindFromSource(source: Node, kind: SyntaxKind): ReadonlyArray<Modifier> | undefined {
222206
return filter(source.modifiers, modifier => modifier.kind === kind);
223207
}

src/services/codefixes/fixUnusedIdentifier.ts

Lines changed: 14 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -148,20 +148,9 @@ namespace ts.codefix {
148148
return false;
149149
}
150150

151-
function tryDeleteDeclaration(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, deletedAncestors: NodeSet | undefined, checker: TypeChecker, isFixAll: boolean): void {
152-
switch (token.kind) {
153-
case SyntaxKind.Identifier:
154-
tryDeleteIdentifier(changes, sourceFile, <Identifier>token, deletedAncestors, checker, isFixAll);
155-
deleteAssignments(changes, sourceFile, token as Identifier, checker);
156-
break;
157-
case SyntaxKind.PropertyDeclaration:
158-
case SyntaxKind.NamespaceImport:
159-
if (deletedAncestors) deletedAncestors.add(token.parent);
160-
changes.deleteNode(sourceFile, token.parent);
161-
break;
162-
default:
163-
tryDeleteDefault(changes, sourceFile, token, deletedAncestors);
164-
}
151+
function tryDeleteDeclaration(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, deletedAncestors: NodeSet | undefined, checker: TypeChecker, isFixAll: boolean) {
152+
tryDeleteDeclarationWorker(changes, sourceFile, token, deletedAncestors, checker, isFixAll);
153+
if (isIdentifier(token)) deleteAssignments(changes, sourceFile, token, checker);
165154
}
166155

167156
function deleteAssignments(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Identifier, checker: TypeChecker) {
@@ -173,19 +162,8 @@ namespace ts.codefix {
173162
});
174163
}
175164

176-
function tryDeleteDefault(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, deletedAncestors: NodeSet | undefined): void {
177-
if (isDeclarationName(token)) {
178-
if (deletedAncestors) deletedAncestors.add(token.parent);
179-
changes.deleteNode(sourceFile, token.parent);
180-
}
181-
else if (isLiteralComputedPropertyDeclarationName(token)) {
182-
if (deletedAncestors) deletedAncestors.add(token.parent.parent);
183-
changes.deleteNode(sourceFile, token.parent.parent);
184-
}
185-
}
186-
187-
function tryDeleteIdentifier(changes: textChanges.ChangeTracker, sourceFile: SourceFile, identifier: Identifier, deletedAncestors: NodeSet | undefined, checker: TypeChecker, isFixAll: boolean): void {
188-
const parent = identifier.parent;
165+
function tryDeleteDeclarationWorker(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, deletedAncestors: NodeSet | undefined, checker: TypeChecker, isFixAll: boolean): void {
166+
const parent = token.parent;
189167
switch (parent.kind) {
190168
case SyntaxKind.VariableDeclaration:
191169
tryDeleteVariableDeclaration(changes, sourceFile, <VariableDeclaration>parent, deletedAncestors);
@@ -250,7 +228,7 @@ namespace ts.codefix {
250228

251229
// handle case where 'import a = A;'
252230
case SyntaxKind.ImportEqualsDeclaration:
253-
const importEquals = getAncestor(identifier, SyntaxKind.ImportEqualsDeclaration)!;
231+
const importEquals = getAncestor(token, SyntaxKind.ImportEqualsDeclaration)!;
254232
changes.deleteNode(sourceFile, importEquals);
255233
break;
256234

@@ -290,7 +268,14 @@ namespace ts.codefix {
290268
break;
291269

292270
default:
293-
tryDeleteDefault(changes, sourceFile, identifier, deletedAncestors);
271+
if (isDeclarationName(token)) {
272+
if (deletedAncestors) deletedAncestors.add(token.parent);
273+
changes.deleteNode(sourceFile, token.parent);
274+
}
275+
else if (isLiteralComputedPropertyDeclarationName(token)) {
276+
if (deletedAncestors) deletedAncestors.add(token.parent.parent);
277+
changes.deleteNode(sourceFile, token.parent.parent);
278+
}
294279
break;
295280
}
296281
}

src/services/goToDefinition.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ namespace ts.GoToDefinition {
3232
const sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration);
3333
// For a function, if this is the original function definition, return just sigInfo.
3434
// If this is the original constructor definition, parent is the class.
35-
if (typeChecker.getRootSymbols(symbol).some(s => calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s) ||
35+
if (typeChecker.getRootSymbols(symbol).some(s => symbolMatchesSignature(s, calledDeclaration)) ||
3636
// TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias
3737
symbol.declarations.some(d => isVariableDeclaration(d) && !!d.initializer && isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false))) {
3838
return [sigInfo];
@@ -93,6 +93,15 @@ namespace ts.GoToDefinition {
9393
return getDefinitionFromSymbol(typeChecker, symbol, node);
9494
}
9595

96+
/**
97+
* True if we should not add definitions for both the signature symbol and the definition symbol.
98+
* True for `const |f = |() => 0`, false for `function |f() {} const |g = f;`.
99+
*/
100+
function symbolMatchesSignature(s: Symbol, calledDeclaration: SignatureDeclaration) {
101+
return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent ||
102+
isVariableDeclaration(calledDeclaration.parent) && s === calledDeclaration.parent.symbol;
103+
}
104+
96105
export function getReferenceAtPosition(sourceFile: SourceFile, position: number, program: Program): { fileName: string, file: SourceFile } | undefined {
97106
const referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
98107
if (referencePath) {
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
/* @internal */
2+
namespace ts.refactor.addOrRemoveBracesToArrowFunction {
3+
const refactorName = "Add or remove braces in an arrow function";
4+
const refactorDescription = Diagnostics.Add_or_remove_braces_in_an_arrow_function.message;
5+
const addBracesActionName = "Add braces to arrow function";
6+
const removeBracesActionName = "Remove braces from arrow function";
7+
const addBracesActionDescription = Diagnostics.Add_braces_to_arrow_function.message;
8+
const removeBracesActionDescription = Diagnostics.Remove_braces_from_arrow_function.message;
9+
registerRefactor(refactorName, { getEditsForAction, getAvailableActions });
10+
11+
interface Info {
12+
func: ArrowFunction;
13+
expression: Expression | undefined;
14+
returnStatement?: ReturnStatement;
15+
addBraces: boolean;
16+
}
17+
18+
function getAvailableActions(context: RefactorContext): ApplicableRefactorInfo[] | undefined {
19+
const { file, startPosition } = context;
20+
const info = getConvertibleArrowFunctionAtPosition(file, startPosition);
21+
if (!info) return undefined;
22+
23+
return [{
24+
name: refactorName,
25+
description: refactorDescription,
26+
actions: [
27+
info.addBraces ?
28+
{
29+
name: addBracesActionName,
30+
description: addBracesActionDescription
31+
} : {
32+
name: removeBracesActionName,
33+
description: removeBracesActionDescription
34+
}
35+
]
36+
}];
37+
}
38+
39+
function getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined {
40+
const { file, startPosition } = context;
41+
const info = getConvertibleArrowFunctionAtPosition(file, startPosition);
42+
if (!info) return undefined;
43+
44+
const { expression, returnStatement, func } = info;
45+
46+
let body: ConciseBody;
47+
if (actionName === addBracesActionName) {
48+
const returnStatement = createReturn(expression);
49+
body = createBlock([returnStatement], /* multiLine */ true);
50+
suppressLeadingAndTrailingTrivia(body);
51+
copyComments(expression!, returnStatement, file, SyntaxKind.MultiLineCommentTrivia, /* hasTrailingNewLine */ true);
52+
}
53+
else if (actionName === removeBracesActionName && returnStatement) {
54+
const actualExpression = expression || createVoidZero();
55+
body = needsParentheses(actualExpression) ? createParen(actualExpression) : actualExpression;
56+
suppressLeadingAndTrailingTrivia(body);
57+
copyComments(returnStatement, body, file, SyntaxKind.MultiLineCommentTrivia, /* hasTrailingNewLine */ false);
58+
}
59+
else {
60+
Debug.fail("invalid action");
61+
}
62+
63+
const edits = textChanges.ChangeTracker.with(context, t => t.replaceNode(file, func.body, body));
64+
return { renameFilename: undefined, renameLocation: undefined, edits };
65+
}
66+
67+
function needsParentheses(expression: Expression) {
68+
return isBinaryExpression(expression) && expression.operatorToken.kind === SyntaxKind.CommaToken || isObjectLiteralExpression(expression);
69+
}
70+
71+
function getConvertibleArrowFunctionAtPosition(file: SourceFile, startPosition: number): Info | undefined {
72+
const node = getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
73+
const func = getContainingFunction(node);
74+
if (!func || !isArrowFunction(func) || (!rangeContainsRange(func, node) || rangeContainsRange(func.body, node))) return undefined;
75+
76+
if (isExpression(func.body)) {
77+
return {
78+
func,
79+
addBraces: true,
80+
expression: func.body
81+
};
82+
}
83+
else if (func.body.statements.length === 1) {
84+
const firstStatement = first(func.body.statements);
85+
if (isReturnStatement(firstStatement)) {
86+
return {
87+
func,
88+
addBraces: false,
89+
expression: firstStatement.expression,
90+
returnStatement: firstStatement
91+
};
92+
}
93+
}
94+
return undefined;
95+
}
96+
}

src/services/tsconfig.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@
7777
"refactors/extractSymbol.ts",
7878
"refactors/generateGetAccessorAndSetAccessor.ts",
7979
"refactors/moveToNewFile.ts",
80+
"refactors/addOrRemoveBracesToArrowFunction.ts",
8081
"sourcemaps.ts",
8182
"services.ts",
8283
"breakpoints.ts",

src/services/utilities.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1720,6 +1720,22 @@ namespace ts {
17201720
return lastPos;
17211721
}
17221722

1723+
export function copyComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean) {
1724+
forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, (pos, end, kind, htnl) => {
1725+
if (kind === SyntaxKind.MultiLineCommentTrivia) {
1726+
// Remove leading /*
1727+
pos += 2;
1728+
// Remove trailing */
1729+
end -= 2;
1730+
}
1731+
else {
1732+
// Remove leading //
1733+
pos += 2;
1734+
}
1735+
addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
1736+
});
1737+
}
1738+
17231739
function indexInTextChange(change: string, name: string): number {
17241740
if (startsWith(change, name)) return 0;
17251741
// Add a " " to avoid references inside words

tests/cases/fourslash/goToDefinitionSignatureAlias.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,17 @@
88
////[|/*useG*/g|]();
99
////[|/*useH*/h|]();
1010

11+
////const i = /*i*/() => 0;
12+
////const /*j*/j = i;
13+
14+
////[|/*useI*/i|]();
15+
////[|/*useJ*/j|]();
16+
1117
verify.goToDefinition({
1218
useF: "f",
1319
useG: ["g", "f"],
1420
useH: ["h", "f"],
21+
22+
useI: "i",
23+
useJ: ["j", "i"],
1524
});
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/// <reference path='fourslash.ts' />
2+
3+
//// const foo = /*a*/a/*b*/ => a + 1;
4+
5+
goTo.select("a", "b");
6+
edit.applyRefactor({
7+
refactorName: "Add or remove braces in an arrow function",
8+
actionName: "Add braces to arrow function",
9+
actionDescription: "Add braces to arrow function",
10+
newContent: `const foo = a => {
11+
return a + 1;
12+
};`,
13+
});
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/// <reference path='fourslash.ts' />
2+
3+
//// const foo = /*a*/a/*b*/ => { return (1, 2, 3); };
4+
5+
goTo.select("a", "b");
6+
edit.applyRefactor({
7+
refactorName: "Add or remove braces in an arrow function",
8+
actionName: "Remove braces from arrow function",
9+
actionDescription: "Remove braces from arrow function",
10+
newContent: `const foo = a => (1, 2, 3);`,
11+
});

0 commit comments

Comments
 (0)