Skip to content

Commit

Permalink
fix: no break in single-block switch case
Browse files Browse the repository at this point in the history
  • Loading branch information
jtkiesel committed Jan 16, 2024
1 parent 983a09d commit ad86a80
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -265,13 +265,20 @@ export class BlocksAndStatementPrettierVisitor extends BaseCstPrettierPrinter {

switchBlockStatementGroup(ctx: SwitchBlockStatementGroupCtx) {
const switchLabel = this.visit(ctx.switchLabel);

const blockStatements = this.visit(ctx.blockStatements);

const statements = ctx.blockStatements?.[0].children.blockStatement;
const hasSingleStatementBlock =
statements?.length === 1 &&
statements[0].children.statement?.[0].children
.statementWithoutTrailingSubstatement?.[0].children.block !== undefined;

return concat([
switchLabel,
ctx.Colon[0],
blockStatements && indent([hardline, blockStatements])
hasSingleStatementBlock
? concat([" ", blockStatements])
: blockStatements && indent([hardline, blockStatements])
]);
}

Expand Down
10 changes: 10 additions & 0 deletions packages/prettier-plugin-java/test/unit-test/switch/_input.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ public String shouldWrapEvenForSmallSwitchCases() {
switch (answer) { case "YES": return "YES"; default: return "NO"; }
}

void switchCaseWithBlock() {
switch (a) {
case 1: {}
case 2: { b(); }
case 3: { c(); } { d(); }
case 4: e(); { f(); }
case 5: { g(); } h();
}
}

// Switch rules
static void howManyAgain(int k) {
switch (k) {
Expand Down
26 changes: 26 additions & 0 deletions packages/prettier-plugin-java/test/unit-test/switch/_output.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,32 @@ public String shouldWrapEvenForSmallSwitchCases() {
}
}

void switchCaseWithBlock() {
switch (a) {
case 1: {}
case 2: {
b();
}
case 3:
{
c();
}
{
d();
}
case 4:
e();
{
f();
}
case 5:
{
g();
}
h();
}
}

// Switch rules
static void howManyAgain(int k) {
switch (k) {
Expand Down

0 comments on commit ad86a80

Please sign in to comment.