Skip to content

Commit

Permalink
Fix: remove extra leading comments at node level (fixes eslint#264)
Browse files Browse the repository at this point in the history
  • Loading branch information
kaicataldo committed Apr 18, 2016
1 parent cbd72bc commit 2a1703e
Showing 1 changed file with 14 additions and 38 deletions.
52 changes: 14 additions & 38 deletions lib/comment-attachment.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,40 +43,6 @@ var extra = {
bottomRightStack: []
};

/** Recursively remove leading comments that are incorrectly added when no
* expression exists between comment and the current node
* @param {node} node to recursively check
* @returns {void}
*/
function removeExtraLeadingComments(node) {
var i, j;

if (!node.body) {
return;
}

if (Array.isArray(node.body)) {
// i must start at 0 so that we can check all indices recursively
for (i = 0; i < node.body.length; i++) {
// i must be greater than 0 to perform the check on the previous node
if (i > 0 && node.body[i].leadingComments) {
for (j = 0; j < node.body[i].leadingComments.length; j++) {
if (node.body[i].leadingComments[j].range[1] < node.body[i - 1].range[1]) {
node.body[i].leadingComments.splice(j, 1);
}
}

if (node.body[i].leadingComments.length === 0) {
delete node.body[i].leadingComments;
}
}
removeExtraLeadingComments(node.body[i]);
}
} else {
removeExtraLeadingComments(node.body);
}
}

//------------------------------------------------------------------------------
// Public
//------------------------------------------------------------------------------
Expand All @@ -87,6 +53,7 @@ module.exports = {
extra.trailingComments = [];
extra.leadingComments = [];
extra.bottomRightStack = [];
extra.previousNode = null;
},

addComment: function(comment) {
Expand All @@ -97,11 +64,10 @@ module.exports = {
processComment: function(node) {
var lastChild,
trailingComments,
i;
i,
j;

if (node.type === astNodeTypes.Program) {
removeExtraLeadingComments(node);

if (node.body.length > 0) {
return;
}
Expand Down Expand Up @@ -162,8 +128,16 @@ module.exports = {
}
}
} else if (extra.leadingComments.length > 0) {

if (extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) {
if (extra.previousNode) {
for (j = 0; j < extra.leadingComments.length; j++) {
if (extra.leadingComments[j].end < extra.previousNode.start) {
extra.leadingComments.splice(j, 1);
j--;
}
}
}

node.leadingComments = extra.leadingComments;
extra.leadingComments = [];
} else {
Expand Down Expand Up @@ -209,6 +183,8 @@ module.exports = {
}
}

extra.previousNode = node;

if (trailingComments) {
node.trailingComments = trailingComments;
}
Expand Down

0 comments on commit 2a1703e

Please sign in to comment.