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 TSParameterProperty getting lost with transform-classes #8682

Merged
merged 3 commits into from Sep 14, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
109 changes: 58 additions & 51 deletions packages/babel-plugin-transform-typescript/src/index.js
Expand Up @@ -20,6 +20,8 @@ interface State {
programPath: any;
}

const PARSED_PARAMS = new WeakSet();

export default declare((api, { jsxPragma = "React" }) => {
api.assertVersion(7);

Expand Down Expand Up @@ -100,54 +102,6 @@ export default declare((api, { jsxPragma = "React" }) => {
return;
}

// Collect parameter properties
const parameterProperties = [];
for (const param of node.params) {
if (param.type === "TSParameterProperty") {
parameterProperties.push(param.parameter);
}
}

if (!parameterProperties.length) {
return;
}

const assigns = parameterProperties.map(p => {
let name;
if (t.isIdentifier(p)) {
name = p.name;
} else if (t.isAssignmentPattern(p) && t.isIdentifier(p.left)) {
name = p.left.name;
} else {
throw path.buildCodeFrameError(
"Parameter properties can not be destructuring patterns.",
);
}

const assign = t.assignmentExpression(
"=",
t.memberExpression(t.thisExpression(), t.identifier(name)),
t.identifier(name),
);
return t.expressionStatement(assign);
});

const statements = node.body.body;

const first = statements[0];
const startsWithSuperCall =
first !== undefined &&
t.isExpressionStatement(first) &&
t.isCallExpression(first.expression) &&
t.isSuper(first.expression.callee);

// Make sure to put parameter properties *after* the `super` call.
// TypeScript will enforce that a 'super()' call is the first statement
// when there are parameter properties.
node.body.body = startsWithSuperCall
? [first, ...assigns, ...statements.slice(1)]
: [...assigns, ...statements];

// Rest handled by Function visitor
},

Expand Down Expand Up @@ -190,10 +144,63 @@ export default declare((api, { jsxPragma = "React" }) => {
// We do this here instead of in a `ClassProperty` visitor because the class transform
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: this comment is slightly out of date, now that this block contains both ClassProperty and ClassMethod logic.

// would transform the class before we reached the class property.
path.get("body.body").forEach(child => {
if (child.isClassProperty()) {
child.node.typeAnnotation = null;
const childNode = child.node;

if (t.isClassMethod(childNode) && childNode.kind === "constructor") {
Copy link
Member

Choose a reason for hiding this comment

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

Nit: you can use t.isClassMethod(childNode, { kind: "constructor" })

// Collect parameter properties
const parameterProperties = [];
for (const param of childNode.params) {
if (
param.type === "TSParameterProperty" &&
!PARSED_PARAMS.has(param.parameter)
) {
PARSED_PARAMS.add(param.parameter);
Copy link
Contributor

Choose a reason for hiding this comment

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

Mostly out of curiosity - it looks like this is the only real functional change added to this block, to prevent duplicate parameters from being added to the parameterProperties list? What sort of case is this preventing? How would two different entries of childNode.params have the same parameter object?

Copy link
Member Author

Choose a reason for hiding this comment

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

It requires a bit of understanding of the class transformation:
https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-classes/src/index.js#L41

Ultimately, it prevents params from getting parsed twice since the class transform converts it to an expression.

parameterProperties.push(param.parameter);
}
}

if (parameterProperties.length) {
const assigns = parameterProperties.map(p => {
let name;
if (t.isIdentifier(p)) {
name = p.name;
} else if (t.isAssignmentPattern(p) && t.isIdentifier(p.left)) {
name = p.left.name;
} else {
throw path.buildCodeFrameError(
"Parameter properties can not be destructuring patterns.",
);
}

const assign = t.assignmentExpression(
"=",
t.memberExpression(t.thisExpression(), t.identifier(name)),
t.identifier(name),
);
return t.expressionStatement(assign);
});

const statements = childNode.body.body;

const first = statements[0];

const startsWithSuperCall =
first !== undefined &&
t.isExpressionStatement(first) &&
t.isCallExpression(first.expression) &&
t.isSuper(first.expression.callee);

// Make sure to put parameter properties *after* the `super` call.
// TypeScript will enforce that a 'super()' call is the first statement
// when there are parameter properties.
childNode.body.body = startsWithSuperCall
? [first, ...assigns, ...statements.slice(1)]
: [...assigns, ...statements];
}
} else if (child.isClassProperty()) {
childNode.typeAnnotation = null;

if (!child.node.value && !child.node.decorators) {
if (!childNode.value && !childNode.decorators) {
child.remove();
}
}
Expand Down
@@ -0,0 +1,5 @@
class Employee extends Person {
constructor(public name: string) {
super();
}
}
@@ -0,0 +1,3 @@
{
"plugins": ["transform-typescript", "transform-classes"]
}
@@ -0,0 +1,31 @@
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

let Employee =
/*#__PURE__*/
function (_Person) {
"use strict";

_inherits(Employee, _Person);

function Employee(name) {
var _this;

_classCallCheck(this, Employee);

_this = _possibleConstructorReturn(this, _getPrototypeOf(Employee).call(this));
_this.name = name;
return _this;
}

return Employee;
}(Person);
@@ -0,0 +1,3 @@
class Person {
constructor(public name: string) {}
}
@@ -0,0 +1,3 @@
{
"plugins": ["transform-typescript", "transform-classes"]
}
@@ -0,0 +1,15 @@
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

let Person =
/*#__PURE__*/
function () {
"use strict";

function Person(name) {
_classCallCheck(this, Person);

this.name = name;
}

return Person;
}();