Skip to content

Commit

Permalink
Retain trailing comments in array expressions (babel#10369)
Browse files Browse the repository at this point in the history
* Retain trailing comments in array expressions

This is a proposed fix for babel#10368
with a simple test.

* Move lastElement in the block where it's used

* Test trailing comment after array expression

* Don't move comments after the array expression

* Retain trailing comment after the array expression
  • Loading branch information
banga authored and Shrey Banga committed Aug 28, 2019
1 parent 1abe1c7 commit e94ffc6
Show file tree
Hide file tree
Showing 3 changed files with 747 additions and 1 deletion.
28 changes: 27 additions & 1 deletion packages/babel-parser/src/parser/comments.js
Expand Up @@ -86,7 +86,7 @@ export default class CommentsParser extends BaseParser {

// Attach comments that follow a trailing comma on the last
// property in an object literal or a trailing comma in function arguments
// as trailing comments
// or a trailing comma in array expressions as trailing comments
if (firstChild && this.state.leadingComments.length > 0) {
const lastComment = last(this.state.leadingComments);

Expand Down Expand Up @@ -137,6 +137,32 @@ export default class CommentsParser extends BaseParser {
}
}
}
} else if (node.type === "ArrayExpression" && node.elements.length > 0) {
if (this.state.commentPreviousNode) {
for (j = 0; j < this.state.leadingComments.length; j++) {
if (
this.state.leadingComments[j].end <
this.state.commentPreviousNode.end
) {
this.state.leadingComments.splice(j, 1);
j--;
}
}

const lastElement = last(node.elements);
lastElement.trailingComments = [];
while (this.state.leadingComments.length) {
const leadingComment = this.state.leadingComments.shift();
if (leadingComment.end < node.end) {
lastElement.trailingComments.push(leadingComment);
} else {
if (node.trailingComments === undefined) {
node.trailingComments = [];
}
node.trailingComments.push(leadingComment);
}
}
}
}
}

Expand Down
@@ -0,0 +1,18 @@
const nonTrailing = [
"One", // One
// Two
"Two" // Three
// Four
]

const trailingAfterComma = [
"One", // One
// Two
"Two", // Three
// Four
]

const trailingAfterArray = [
"One", // One
// Two
] // Three

0 comments on commit e94ffc6

Please sign in to comment.