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 authored and clementdessoude committed Feb 13, 2024
1 parent a2fd2b7 commit 0f08bbf
Show file tree
Hide file tree
Showing 3 changed files with 111 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
35 changes: 35 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,41 @@ public String shouldWrapEvenForSmallSwitchCases() {
switch (answer) { case "YES": return "YES"; default: return "NO"; }
}

void switchCaseWithBlock1() {
switch (a) {
case 0: {}
default: {}
}
}

void switchCaseWithBlock2() {
switch (a) {
case 0: { b(); }
default: { c(); }
}
}

void switchCaseWithBlock3() {
switch (a) {
case 0: { b(); } { c(); }
default: { d(); } { e(); }
}
}

void switchCaseWithBlock4() {
switch (a) {
case 0: b(); { c(); }
default: d(); { e(); }
}
}

void switchCaseWithBlock5() {
switch (a) {
case 0: { b(); } c();
default: { d(); } e();
}
}

// Switch rules
static void howManyAgain(int k) {
switch (k) {
Expand Down
67 changes: 67 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,73 @@ public String shouldWrapEvenForSmallSwitchCases() {
}
}

void switchCaseWithBlock1() {
switch (a) {
case 0: {}
default: {}
}
}

void switchCaseWithBlock2() {
switch (a) {
case 0: {
b();
}
default: {
c();
}
}
}

void switchCaseWithBlock3() {
switch (a) {
case 0:
{
b();
}
{
c();
}
default:
{
d();
}
{
e();
}
}
}

void switchCaseWithBlock4() {
switch (a) {
case 0:
b();
{
c();
}
default:
d();
{
e();
}
}
}

void switchCaseWithBlock5() {
switch (a) {
case 0:
{
b();
}
c();
default:
{
d();
}
e();
}
}

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

0 comments on commit 0f08bbf

Please sign in to comment.