Skip to content

Commit ad86a80

Browse files
committed
fix: no break in single-block switch case
1 parent 983a09d commit ad86a80

File tree

3 files changed

+45
-2
lines changed

3 files changed

+45
-2
lines changed

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

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -265,13 +265,20 @@ export class BlocksAndStatementPrettierVisitor extends BaseCstPrettierPrinter {
265265

266266
switchBlockStatementGroup(ctx: SwitchBlockStatementGroupCtx) {
267267
const switchLabel = this.visit(ctx.switchLabel);
268-
269268
const blockStatements = this.visit(ctx.blockStatements);
270269

270+
const statements = ctx.blockStatements?.[0].children.blockStatement;
271+
const hasSingleStatementBlock =
272+
statements?.length === 1 &&
273+
statements[0].children.statement?.[0].children
274+
.statementWithoutTrailingSubstatement?.[0].children.block !== undefined;
275+
271276
return concat([
272277
switchLabel,
273278
ctx.Colon[0],
274-
blockStatements && indent([hardline, blockStatements])
279+
hasSingleStatementBlock
280+
? concat([" ", blockStatements])
281+
: blockStatements && indent([hardline, blockStatements])
275282
]);
276283
}
277284

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,16 @@ public String shouldWrapEvenForSmallSwitchCases() {
4848
switch (answer) { case "YES": return "YES"; default: return "NO"; }
4949
}
5050

51+
void switchCaseWithBlock() {
52+
switch (a) {
53+
case 1: {}
54+
case 2: { b(); }
55+
case 3: { c(); } { d(); }
56+
case 4: e(); { f(); }
57+
case 5: { g(); } h();
58+
}
59+
}
60+
5161
// Switch rules
5262
static void howManyAgain(int k) {
5363
switch (k) {

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,32 @@ public String shouldWrapEvenForSmallSwitchCases() {
5353
}
5454
}
5555

56+
void switchCaseWithBlock() {
57+
switch (a) {
58+
case 1: {}
59+
case 2: {
60+
b();
61+
}
62+
case 3:
63+
{
64+
c();
65+
}
66+
{
67+
d();
68+
}
69+
case 4:
70+
e();
71+
{
72+
f();
73+
}
74+
case 5:
75+
{
76+
g();
77+
}
78+
h();
79+
}
80+
}
81+
5682
// Switch rules
5783
static void howManyAgain(int k) {
5884
switch (k) {

0 commit comments

Comments
 (0)