Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 deletions src/comments.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { util, type AstPath, type Doc } from "prettier";
import { builders } from "prettier/doc";
import { SyntaxType, type CommentNode, type SyntaxNode } from "./node-types.ts";
import {
SyntaxType,
type ArrayAccessNode,
type CommentNode,
type FieldAccessNode,
type MethodInvocationNode,
type SyntaxNode
} from "./node-types.ts";
import parser from "./parser.ts";
import printer from "./printer.ts";
import {
Expand Down Expand Up @@ -190,18 +197,20 @@ function handleLabeledStatementComments(commentNode: CommentNode) {
function handleMemberChainComments(commentNode: CommentNode) {
const { enclosingNode, precedingNode, followingNode } = commentNode;
if (
precedingNode &&
(enclosingNode?.type === SyntaxType.FieldAccess ||
(enclosingNode?.type === SyntaxType.MethodInvocation &&
precedingNode?.end.row !== commentNode.start.row)) &&
(followingNode?.type === SyntaxType.Identifier ||
followingNode?.type === SyntaxType.TypeArguments)
precedingNode.end.row < commentNode.start.row)) &&
precedingNode === enclosingNode.objectNode
) {
util.addLeadingComment(enclosingNode, commentNode);
return true;
} else if (
followingNode &&
isMember(followingNode) &&
precedingNode !== enclosingNode &&
(!precedingNode ||
(precedingNode !== getMemberObject(followingNode) &&
precedingNode.end.row < commentNode.start.row)) &&
!isPrettierIgnore(commentNode)
) {
util.addDanglingComment(followingNode, commentNode, undefined);
Expand Down Expand Up @@ -291,6 +300,14 @@ function isMember(node: SyntaxNode) {
);
}

function getMemberObject(
node: ArrayAccessNode | FieldAccessNode | MethodInvocationNode
) {
return node.type === SyntaxType.ArrayAccess
? node.arrayNode
: node.objectNode;
}

const binaryOperators = new Set([
"<<",
">>",
Expand Down
23 changes: 23 additions & 0 deletions test/unit-test/member_chain/_input.java
Original file line number Diff line number Diff line change
Expand Up @@ -175,5 +175,28 @@ void argumentComment() {
a(
b.c() // comment
);

a(
b, // comment
c.d
);

a(
b, // comment
c.d[0]
);

a(
b, // comment
c.d()
);
}

void prettierIgnore() {
a ->
// prettier-ignore
b
.c().d()
.e().f();
}
}
23 changes: 23 additions & 0 deletions test/unit-test/member_chain/_output.java
Original file line number Diff line number Diff line change
Expand Up @@ -230,5 +230,28 @@ void argumentComment() {
a(
b.c() // comment
);

a(
b, // comment
c.d
);

a(
b, // comment
c.d[0]
);

a(
b, // comment
c.d()
);
}

void prettierIgnore() {
a ->
// prettier-ignore
b
.c().d()
.e().f();
}
}