add parens on expressions with trailing comments - fixes #349

This commit is contained in:
Sebastian McKenzie
2015-01-02 00:57:48 +11:00
parent e3dc2355e8
commit 470c8fced0
4 changed files with 23 additions and 8 deletions

View File

@@ -148,6 +148,11 @@ CodeGenerator.prototype.print = function (node, parent, opts) {
};
if (this[node.type]) {
// only compute if this node needs parens if our parent has been changed
// since acorn would've wrapped us in a ParanthesizedExpression
var needsParens = n.needsParens(node, parent);
if (needsParens) this.push("(");
this.printLeadingComments(node, parent);
newline(true);
@@ -155,11 +160,6 @@ CodeGenerator.prototype.print = function (node, parent, opts) {
if (opts.before) opts.before();
this.map.mark(node, "start");
// only compute if this node needs parens if our parent has been changed
// since acorn would've wrapped us in a ParanthesizedExpression
var needsParens = n.needsParens(node, parent);
if (needsParens) this.push("(");
this[node.type](node, this.buildPrint(node), parent);
if (needsParens) this.push(")");

View File

@@ -60,6 +60,10 @@ Node.prototype.needsParens = function () {
if (!parent) return false;
if (t.isExpression(node) && node.leadingComments && node.leadingComments.length) {
return true;
}
if (t.isNewExpression(parent) && parent.callee === node) {
return t.isCallExpression(node) || _.some(node, function (val) {
return t.isCallExpression(val);

View File

@@ -297,19 +297,26 @@ t.isVar = function (node) {
return t.isVariableDeclaration(node, { kind: "var" }) && !node._let;
};
//
t.COMMENT_KEYS = ["leadingComments", "trailingComments"];
t.removeComments = function (child) {
delete child.leadingComments;
delete child.trailingComments;
_.each(t.COMMENT_KEYS, function (key) {
delete child[key];
});
return child;
};
t.inheritsComments = function (child, parent) {
_.each(["leadingComments", "trailingComments"], function (key) {
_.each(t.COMMENT_KEYS, function (key) {
child[key] = _.uniq(_.compact([].concat(child[key], parent[key])));
});
return child;
};
//
t.inherits = function (child, parent) {
child.loc = parent.loc;
child.end = parent.end;