diff --git a/packages/prettier-plugin-java/src/printers/blocks-and-statements.ts b/packages/prettier-plugin-java/src/printers/blocks-and-statements.ts index cb61da2b..33da12a1 100644 --- a/packages/prettier-plugin-java/src/printers/blocks-and-statements.ts +++ b/packages/prettier-plugin-java/src/printers/blocks-and-statements.ts @@ -3,6 +3,7 @@ import { builders } from "prettier/doc"; import { call, definedKeys, + hasLeadingComments, indentInParentheses, isBinaryExpression, isEmptyStatement, @@ -190,11 +191,13 @@ export default { "expression", "throwStatement" ]); - const parts = [ - call(path, print, "switchLabel"), - " -> ", - call(path, print, bodyKey) - ]; + const body = call(path, print, bodyKey); + const parts = [call(path, print, "switchLabel"), " ->"]; + if (bodyKey !== "block" && hasLeadingComments(children[bodyKey]![0])) { + parts.push(indent([hardline, body])); + } else { + parts.push(" ", body); + } if (children.Semicolon) { parts.push(";"); } diff --git a/packages/prettier-plugin-java/src/printers/helpers.ts b/packages/prettier-plugin-java/src/printers/helpers.ts index c8001403..b3b1c418 100644 --- a/packages/prettier-plugin-java/src/printers/helpers.ts +++ b/packages/prettier-plugin-java/src/printers/helpers.ts @@ -233,7 +233,7 @@ export function printComment(node: JavaTerminal) { } export function hasLeadingComments(node: JavaNode) { - return node.comments?.some(({ leading }) => leading); + return node.comments?.some(({ leading }) => leading) ?? false; } export function indentInParentheses( diff --git a/packages/prettier-plugin-java/test/unit-test/switch/_input.java b/packages/prettier-plugin-java/test/unit-test/switch/_input.java index 388b1604..a1e7aa30 100644 --- a/packages/prettier-plugin-java/test/unit-test/switch/_input.java +++ b/packages/prettier-plugin-java/test/unit-test/switch/_input.java @@ -171,4 +171,18 @@ static String shouldFormatSwitchBlocksWithEmptyLastBlock(Object o) { log.info("Done !"); } + + void switchRulesWithComments() { + switch (a) { + case b -> + // comment + c; + case Dd d -> + // comment + e; + case f -> + // comment + throw new RuntimeException(); + } + } } diff --git a/packages/prettier-plugin-java/test/unit-test/switch/_output.java b/packages/prettier-plugin-java/test/unit-test/switch/_output.java index 5ca93408..effc8d4c 100644 --- a/packages/prettier-plugin-java/test/unit-test/switch/_output.java +++ b/packages/prettier-plugin-java/test/unit-test/switch/_output.java @@ -219,4 +219,18 @@ static String shouldFormatSwitchBlocksWithEmptyLastBlock(Object o) { log.info("Done !"); } + + void switchRulesWithComments() { + switch (a) { + case b -> + // comment + c; + case Dd d -> + // comment + e; + case f -> + // comment + throw new RuntimeException(); + } + } }