Skip to content

Commit 9ef6af0

Browse files
committed
fix: indent non-block switch rule bodies with leading comments
1 parent dfec507 commit 9ef6af0

File tree

4 files changed

+37
-6
lines changed

4 files changed

+37
-6
lines changed

packages/prettier-plugin-java/src/printers/blocks-and-statements.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { builders } from "prettier/doc";
33
import {
44
call,
55
definedKeys,
6+
hasLeadingComments,
67
indentInParentheses,
78
isBinaryExpression,
89
isEmptyStatement,
@@ -190,11 +191,13 @@ export default {
190191
"expression",
191192
"throwStatement"
192193
]);
193-
const parts = [
194-
call(path, print, "switchLabel"),
195-
" -> ",
196-
call(path, print, bodyKey)
197-
];
194+
const body = call(path, print, bodyKey);
195+
const parts = [call(path, print, "switchLabel"), " ->"];
196+
if (bodyKey !== "block" && hasLeadingComments(children[bodyKey]![0])) {
197+
parts.push(indent([hardline, body]));
198+
} else {
199+
parts.push(" ", body);
200+
}
198201
if (children.Semicolon) {
199202
parts.push(";");
200203
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ export function printComment(node: JavaTerminal) {
233233
}
234234

235235
export function hasLeadingComments(node: JavaNode) {
236-
return node.comments?.some(({ leading }) => leading);
236+
return node.comments?.some(({ leading }) => leading) ?? false;
237237
}
238238

239239
export function indentInParentheses(

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,4 +171,18 @@ static String shouldFormatSwitchBlocksWithEmptyLastBlock(Object o) {
171171
log.info("Done !");
172172

173173
}
174+
175+
void switchRulesWithComments() {
176+
switch (a) {
177+
case b ->
178+
// comment
179+
c;
180+
case Dd d ->
181+
// comment
182+
e;
183+
case f ->
184+
// comment
185+
throw new RuntimeException();
186+
}
187+
}
174188
}

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,4 +219,18 @@ static String shouldFormatSwitchBlocksWithEmptyLastBlock(Object o) {
219219

220220
log.info("Done !");
221221
}
222+
223+
void switchRulesWithComments() {
224+
switch (a) {
225+
case b ->
226+
// comment
227+
c;
228+
case Dd d ->
229+
// comment
230+
e;
231+
case f ->
232+
// comment
233+
throw new RuntimeException();
234+
}
235+
}
222236
}

0 commit comments

Comments
 (0)