Skip to content

Fix: convertFunctionToEs6Class cannot recognize x.prototype = {} pattern #35219

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
Apr 30, 2020
Merged
Show file tree
Hide file tree
Changes from 4 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
158 changes: 114 additions & 44 deletions src/services/codefixes/convertFunctionToEs6Class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,43 +57,82 @@ namespace ts.codefix {
const memberElements: ClassElement[] = [];
// all instance members are stored in the "member" array of symbol
if (symbol.members) {
symbol.members.forEach(member => {
symbol.members.forEach((member, key) => {
if (key === "constructor") {
// fn.prototype.constructor = fn
changes.delete(sourceFile, member.valueDeclaration.parent);
return;
}
const memberElement = createClassElement(member, /*modifiers*/ undefined);
if (memberElement) {
memberElements.push(memberElement);
memberElements.push(...memberElement);
}
});
}

// all static members are stored in the "exports" array of symbol
if (symbol.exports) {
symbol.exports.forEach(member => {
const memberElement = createClassElement(member, [createToken(SyntaxKind.StaticKeyword)]);
if (memberElement) {
memberElements.push(memberElement);
if (member.name === "prototype") {
const firstDeclaration = member.declarations[0];
// only one "x.prototype = { ... }" will pass
if (member.declarations.length === 1 &&
isPropertyAccessExpression(firstDeclaration) &&
isBinaryExpression(firstDeclaration.parent) &&
firstDeclaration.parent.operatorToken.kind === SyntaxKind.EqualsToken &&
isObjectLiteralExpression(firstDeclaration.parent.right)
) {
const prototypes = firstDeclaration.parent.right;
const memberElement = createClassElement(prototypes.symbol, /** modifiers */ undefined);
if (memberElement) {
memberElements.push(...memberElement);
}
}
}
else {
const memberElement = createClassElement(member, [createToken(SyntaxKind.StaticKeyword)]);
if (memberElement) {
memberElements.push(...memberElement);
}
}
});
}

return memberElements;

function shouldConvertDeclaration(_target: PropertyAccessExpression, source: Expression) {
function shouldConvertDeclaration(_target: PropertyAccessExpression | ObjectLiteralExpression, source: Expression) {
// Right now the only thing we can convert are function expressions - other values shouldn't get
// transformed. We can update this once ES public class properties are available.
return isFunctionLike(source);
if (isPropertyAccessExpression(_target)) {
if (isConstructorAssignment(_target)) return true;
return isFunctionLike(source);
}
else {
return every(_target.properties, x => {
// a() {}
if (isMethodDeclaration(x) || isGetOrSetAccessorDeclaration(x)) return true;
// a: function() {}
if (isPropertyAssignment(x) && isFunctionLike(x.initializer) && !!x.name) return true;
// x.prototype.constructor = fn
if (isConstructorAssignment(x)) return true;
return false;
});
}
}

function createClassElement(symbol: Symbol, modifiers: Modifier[] | undefined): ClassElement | undefined {
function createClassElement(symbol: Symbol, modifiers: Modifier[] | undefined): ClassElement[] {
// Right now the only thing we can convert are function expressions, which are marked as methods
if (!(symbol.flags & SymbolFlags.Method)) {
return;
// or { x: y } type prototype assignments, which are marked as ObjectLiteral
const members: ClassElement[] = [];
if (!(symbol.flags & SymbolFlags.Method) && !(symbol.flags & SymbolFlags.ObjectLiteral)) {
return members;
}

const memberDeclaration = symbol.valueDeclaration as PropertyAccessExpression;
const memberDeclaration = symbol.valueDeclaration as PropertyAccessExpression | ObjectLiteralExpression;
const assignmentBinaryExpression = memberDeclaration.parent as BinaryExpression;

if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) {
return;
return members;
}

// delete the entire statement if this expression is the sole expression to take care of the semicolon at the end
Expand All @@ -102,51 +141,76 @@ namespace ts.codefix {
changes.delete(sourceFile, nodeToDelete);

if (!assignmentBinaryExpression.right) {
return createProperty([], modifiers, symbol.name, /*questionToken*/ undefined,
/*type*/ undefined, /*initializer*/ undefined);
members.push(createProperty([], modifiers, symbol.name, /*questionToken*/ undefined,
/*type*/ undefined, /*initializer*/ undefined));
return members;
}

switch (assignmentBinaryExpression.right.kind) {
case SyntaxKind.FunctionExpression: {
const functionExpression = assignmentBinaryExpression.right as FunctionExpression;
const fullModifiers = concatenate(modifiers, getModifierKindFromSource(functionExpression, SyntaxKind.AsyncKeyword));
const method = createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}

case SyntaxKind.ArrowFunction: {
const arrowFunction = assignmentBinaryExpression.right as ArrowFunction;
const arrowFunctionBody = arrowFunction.body;
let bodyBlock: Block;

// case 1: () => { return [1,2,3] }
if (arrowFunctionBody.kind === SyntaxKind.Block) {
bodyBlock = arrowFunctionBody as Block;
}
// case 2: () => [1,2,3]
else {
bodyBlock = createBlock([createReturn(arrowFunctionBody)]);
}
const fullModifiers = concatenate(modifiers, getModifierKindFromSource(arrowFunction, SyntaxKind.AsyncKeyword));
const method = createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
return createFunctionLikeExpressionMember(members, <FunctionExpression | ArrowFunction>assignmentBinaryExpression.right, (<PropertyAccessExpression>memberDeclaration).name);
case SyntaxKind.ObjectLiteralExpression: {
return map(
(<ObjectLiteralExpression>assignmentBinaryExpression.right).properties,
property => {
if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property)) {
// MethodDeclaration and AccessorDeclaration can appear in a class directly
return members.concat(property);
}
// Drop constructor assignments
if (isConstructorAssignment(property)) return members;
return createFunctionLikeExpressionMember(members, <FunctionExpression | ArrowFunction>(<PropertyAssignment>property).initializer, property.name!);
}
).reduce((x, y) => x.concat(y));
}

default: {
// Don't try to declare members in JavaScript files
if (isSourceFileJS(sourceFile)) {
return;
return members;
}
const prop = createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
const prop = createProperty(/*decorators*/ undefined, modifiers, (<PropertyAccessExpression>memberDeclaration).name, /*questionToken*/ undefined,
/*type*/ undefined, assignmentBinaryExpression.right);
copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
return prop;
members.push(prop);
return members;
}
}

type MethodName = Parameters<typeof createMethod>[3];

function createFunctionLikeExpressionMember(members: readonly ClassElement[], expression: FunctionExpression | ArrowFunction, name: MethodName) {
if (isFunctionExpression(expression)) return createFunctionExpressionMember(members, expression, name);
else return createArrowFunctionExpressionMember(members, expression, name);
}

function createFunctionExpressionMember(members: readonly ClassElement[], functionExpression: FunctionExpression, name: MethodName) {
const fullModifiers = concatenate(modifiers, getModifierKindFromSource(functionExpression, SyntaxKind.AsyncKeyword));
const method = createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return members.concat(method);
}

function createArrowFunctionExpressionMember(members: readonly ClassElement[], arrowFunction: ArrowFunction, name: MethodName) {
const arrowFunctionBody = arrowFunction.body;
let bodyBlock: Block;

// case 1: () => { return [1,2,3] }
if (arrowFunctionBody.kind === SyntaxKind.Block) {
bodyBlock = arrowFunctionBody as Block;
}
// case 2: () => [1,2,3]
else {
bodyBlock = createBlock([createReturn(arrowFunctionBody)]);
}
const fullModifiers = concatenate(modifiers, getModifierKindFromSource(arrowFunction, SyntaxKind.AsyncKeyword));
const method = createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return members.concat(method);
}
}
}

Expand Down Expand Up @@ -189,4 +253,10 @@ namespace ts.codefix {
function getModifierKindFromSource(source: Node, kind: SyntaxKind): readonly Modifier[] | undefined {
return filter(source.modifiers, modifier => modifier.kind === kind);
}

function isConstructorAssignment(x: ObjectLiteralElementLike | PropertyAccessExpression) {
if (!x.name) return false;
if (isIdentifier(x.name) && x.name.text === "constructor") return true;
return false;
}
}
31 changes: 31 additions & 0 deletions tests/cases/fourslash/convertFunctionToEs6Class-propertyMember.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// @allowNonTsExtensions: true
// @Filename: test123.js

/// <reference path="./fourslash.ts" />

//// // Comment
//// function /*1*/fn() {
//// this.baz = 10;
//// }
//// fn.prototype = {
//// /** JSDoc */
//// bar: function () {
//// console.log('hello world');
//// }
//// }

verify.codeFix({
description: "Convert function to an ES2015 class",
newFileContent:
`// Comment
class fn {
constructor() {
this.baz = 10;
}
/** JSDoc */
bar() {
console.log('hello world');
}
}
`,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// @allowNonTsExtensions: true
// @Filename: test123.js

/// <reference path="./fourslash.ts" />

//// // Comment
//// function /*1*/fn() {
//// this.baz = 10;
//// }
//// fn.prototype = {
//// /** JSDoc */
//// get bar() {
//// return this.baz;
//// }
//// }

verify.codeFix({
description: "Convert function to an ES2015 class",
newFileContent:
`// Comment
class fn {
constructor() {
this.baz = 10;
}
/** JSDoc */
get bar() {
return this.baz;
}
}
`,
});
29 changes: 29 additions & 0 deletions tests/cases/fourslash/convertFunctionToEs6Class-prototypeMethod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// @allowNonTsExtensions: true
// @Filename: test123.js

/// <reference path="./fourslash.ts" />

//// // Comment
//// function /*1*/fn() {
//// this.baz = 10;
//// }
//// fn.prototype = {
//// bar() {
//// console.log('hello world');
//// }
//// }

verify.codeFix({
description: "Convert function to an ES2015 class",
newFileContent:
`// Comment
class fn {
constructor() {
this.baz = 10;
}
bar() {
console.log('hello world');
}
}
`,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// @allowNonTsExtensions: true
// @Filename: test123.js

/// <reference path="./fourslash.ts" />

//// // Comment
//// function /*1*/fn() {
//// this.baz = 10;
//// }
//// fn.prototype = {
//// constructor: fn
//// }

verify.codeFix({
description: "Convert function to an ES2015 class",
newFileContent:
`// Comment
class fn {
constructor() {
this.baz = 10;
}
}
`,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// @allowNonTsExtensions: true
// @Filename: test123.js

/// <reference path="./fourslash.ts" />

//// // Comment
//// function /*1*/fn() {
//// this.baz = 10;
//// }
//// fn.prototype.constructor = fn

verify.codeFix({
description: "Convert function to an ES2015 class",
newFileContent:
`// Comment
class fn {
constructor() {
this.baz = 10;
}
}
`,
});