move replacement node comment inheritance to traverse replacement

This commit is contained in:
Sebastian McKenzie
2014-12-29 01:26:11 +11:00
parent b49f6e33d6
commit d951082b09
2 changed files with 12 additions and 15 deletions

View File

@@ -1,26 +1,16 @@
var t = require("../../types");
var inheritsComments = function (node, nodes) {
if (nodes.length) {
t.inheritsComments(nodes[0], node);
}
};
exports.ImportDeclaration = function (node, parent, file) {
var nodes = [];
if (node.specifiers.length) {
if (!file.moduleFormatter.importSpecifier) return;
for (var i in node.specifiers) {
file.moduleFormatter.importSpecifier(node.specifiers[i], node, nodes, parent);
}
} else {
if (!file.moduleFormatter.importDeclaration) return;
file.moduleFormatter.importDeclaration(node, nodes, parent);
}
inheritsComments(node, nodes);
return nodes;
};
@@ -35,16 +25,12 @@ exports.ExportDeclaration = function (node, parent, file) {
declar.init = declar.init || t.identifier("undefined");
}
if (!file.moduleFormatter.exportDeclaration) return;
file.moduleFormatter.exportDeclaration(node, nodes, parent);
} else {
if (!file.moduleFormatter.exportSpecifier) return;
for (var i in node.specifiers) {
file.moduleFormatter.exportSpecifier(node.specifiers[i], node, nodes, parent);
}
}
inheritsComments(node, nodes);
return nodes;
};

View File

@@ -42,9 +42,20 @@ function traverse(parent, opts, scope) {
if (result != null) {
updated = true;
var isArray = _.isArray(result);
// inherit comments from original node to the first replacement node
var inheritTo = result;
if (isArray) inheritTo = result[0];
t.inheritsComments(inheritTo, node);
// replace the node
node = obj[key] = result;
if (_.isArray(result) && _.contains(t.STATEMENT_OR_BLOCK_KEYS, key) && !t.isBlockStatement(obj)) {
// we're replacing a statement or block node with an array of statements so we better
// ensure that it's a block
if (isArray && _.contains(t.STATEMENT_OR_BLOCK_KEYS, key) && !t.isBlockStatement(obj)) {
t.ensureBlock(obj, key);
}
}