Skip to content

Commit cefcbce

Browse files
committed
fix: print class type arguments and dots in the proper order
1 parent ec18b2f commit cefcbce

File tree

3 files changed

+31
-18
lines changed

3 files changed

+31
-18
lines changed

packages/prettier-plugin-java/src/printers/helpers.ts

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -304,26 +304,30 @@ export function printClassType(
304304
path: AstPath<JavaNonTerminal & { children: ClassTypeCtx }>,
305305
print: JavaPrintFn
306306
) {
307-
return flatMap(
308-
path,
309-
childPath => {
310-
const { node, isLast } = childPath;
311-
const child = [print(childPath)];
312-
if (isTerminal(node)) {
313-
if (!isLast) {
314-
child.push(".");
307+
const { children } = path.node;
308+
return definedKeys(children, ["annotation", "Identifier", "typeArguments"])
309+
.flatMap(child =>
310+
children[child]!.map((node, index) => ({
311+
child,
312+
index,
313+
startOffset: parser.locStart(node)
314+
}))
315+
)
316+
.sort((a, b) => a.startOffset - b.startOffset)
317+
.flatMap(({ child, index: childIndex }, index, array) => {
318+
const node = children[child]![childIndex];
319+
const next = array.at(index + 1);
320+
const nextNode = next && children[next.child]![next.index];
321+
const docs = [call(path, print, child, childIndex)];
322+
if (nextNode) {
323+
if (isNonTerminal(node)) {
324+
docs.push(node.name === "annotation" ? " " : ".");
325+
} else if (isTerminal(nextNode) || nextNode.name === "annotation") {
326+
docs.push(".");
315327
}
316-
} else if (node.name === "annotation") {
317-
child.push(" ");
318328
}
319-
return child;
320-
},
321-
definedKeys(path.node.children, [
322-
"annotation",
323-
"Identifier",
324-
"typeArguments"
325-
])
326-
);
329+
return docs;
330+
});
327331
}
328332

329333
export function isBinaryExpression(expression: ExpressionCstNode) {

packages/prettier-plugin-java/test/unit-test/types/_input.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,8 @@ public void dataTypes() {
2323
String stringVariable;
2424
}
2525

26+
public void complexTypes() {
27+
@A B.C<D>.@E @F G.H h;
28+
}
29+
2630
}

packages/prettier-plugin-java/test/unit-test/types/_output.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,9 @@ public void dataTypes() {
2222
Boolean booleanVariable;
2323
String stringVariable;
2424
}
25+
26+
public void complexTypes() {
27+
@A
28+
B.C<D>.@E @F G.H h;
29+
}
2530
}

0 commit comments

Comments
 (0)