Skip to content

Commit

Permalink
Fix interleaved comments in class decorators
Browse files Browse the repository at this point in the history
I wrote this fix a while ago but it conflicted with the class heuristic, now that #2660 fixes it, we can ship this one as well!

Fixes #1460
Fixes #2507
  • Loading branch information
vjeux committed Aug 24, 2017
1 parent 05b4422 commit ae5c896
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/comments.js
Expand Up @@ -192,6 +192,12 @@ function attach(comments, ast, text) {
comment
) ||
handleTryStatementComments(enclosingNode, followingNode, comment) ||
handleClassComments(
enclosingNode,
precedingNode,
followingNode,
comment
) ||
handleImportSpecifierComments(enclosingNode, comment) ||
handleObjectPropertyComments(enclosingNode, comment) ||
handleForComments(enclosingNode, precedingNode, comment) ||
Expand Down Expand Up @@ -246,6 +252,12 @@ function attach(comments, ast, text) {
followingNode,
comment
) ||
handleClassComments(
enclosingNode,
precedingNode,
followingNode,
comment
) ||
handleLabeledStatementComments(enclosingNode, comment) ||
handleCallExpressionComments(precedingNode, enclosingNode, comment) ||
handlePropertyComments(enclosingNode, comment) ||
Expand Down Expand Up @@ -551,6 +563,32 @@ function handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) {
return false;
}

function handleClassComments(
enclosingNode,
precedingNode,
followingNode,
comment
) {
if (
enclosingNode &&
(enclosingNode.type === "ClassDeclaration" ||
enclosingNode.type === "ClassExpression") &&
(enclosingNode.decorators && enclosingNode.decorators.length > 0) &&
!(followingNode && followingNode.type === "Decorator")
) {
if (!enclosingNode.decorators || enclosingNode.decorators.length === 0) {
addLeadingComment(enclosingNode, comment);
} else {
addTrailingComment(
enclosingNode.decorators[enclosingNode.decorators.length - 1],
comment
);
}
return true;
}
return false;
}

function handleMethodNameComments(text, enclosingNode, precedingNode, comment) {
// This is only needed for estree parsers (flow, typescript) to attach
// after a method name:
Expand Down
14 changes: 14 additions & 0 deletions tests/decorators/__snapshots__/jsfmt.spec.js.snap
Expand Up @@ -25,6 +25,13 @@ class X {
],
})
export class AppModule {}
// A
@Foo()
// B
@Bar()
// C
export class Bar{}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var x = 100;
Expand All @@ -48,6 +55,13 @@ class X {}
})
export class AppModule {}
// A
@Foo()
// B
@Bar()
// C
export class Bar {}
`;

exports[`methods.js 1`] = `
Expand Down
7 changes: 7 additions & 0 deletions tests/decorators/comments.js
Expand Up @@ -22,3 +22,10 @@ class X {
],
})
export class AppModule {}

// A
@Foo()
// B
@Bar()
// C
export class Bar{}

0 comments on commit ae5c896

Please sign in to comment.