Skip to content

Commit d11d362

Browse files
committed
fix: avoid unwrapping empty array initializer with comments
1 parent 9e931a9 commit d11d362

File tree

3 files changed

+17
-7
lines changed

3 files changed

+17
-7
lines changed

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

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -249,14 +249,16 @@ export function printArrayInitializer<
249249
T extends JavaNonTerminal,
250250
P extends IterProperties<T["children"]>
251251
>(path: AstPath<T>, print: JavaPrintFn, options: JavaParserOptions, child: P) {
252-
const list: Doc[] = [];
253-
if (child && child in path.node.children) {
254-
list.push(call(path, print, child));
255-
if (options.trailingComma !== "none") {
256-
list.push(ifBreak(","));
257-
}
252+
if (!(child && child in path.node.children)) {
253+
const danglingComments = printDanglingComments(path);
254+
return danglingComments.length
255+
? ["{", indent([hardline, ...danglingComments]), hardline, "}"]
256+
: "{}";
257+
}
258+
const list = [call(path, print, child)];
259+
if (options.trailingComma !== "none") {
260+
list.push(ifBreak(","));
258261
}
259-
list.push(...printDanglingComments(path));
260262
return list.length ? group(["{", indent([line, ...list]), line, "}"]) : "{}";
261263
}
262264

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,8 @@ class Array {
44
Class<?> aaaaaaaaaaaaaaaa = new Aaaaaaaaaaaaaaaa<Bbbbbbbbbbbbbbbb>[1].getClass();
55
Class<?> aaaaaaaaaaaaaaaa = new Aaaaaaaaaaaaaaaa[1111111111111111111].getClass();
66
Class<?> aaaaaaaaaaaaaaaa = new Aaaaaaaaaaaaaaaa[]{ new Aaaaaaaaaaaaaaaa() }.getClass();
7+
8+
String[] DATA = {
9+
// nothing yet
10+
};
711
}

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,8 @@ class Array {
1010
Class<?> aaaaaaaaaaaaaaaa = new Aaaaaaaaaaaaaaaa[] {
1111
new Aaaaaaaaaaaaaaaa(),
1212
}.getClass();
13+
14+
String[] DATA = {
15+
// nothing yet
16+
};
1317
}

0 commit comments

Comments
 (0)