prettier-java icon indicating copy to clipboard operation
prettier-java copied to clipboard

fix: break empty switch/rule, try/catch/finally, and if blocks

Open jtkiesel opened this issue 5 months ago • 0 comments

What changed with this PR:

Empty switch/case, try/catch/finally, and if/else blocks are now broken, to align more closely with Prettier TypeScript's behavior. One notable difference is that a single try statement can have multiple catch blocks in Java. For simplicity, I decided that if there are multiple catch blocks, all of them will break (even the last one).

Example

Input

void ifStatements() {
  if (a) {}
  if (a) {} else {}
  if (a) {} else if (b) {} else {}
}

void switchStatements() {
  switch (a) {}
  switch (a) {
    case 1: {}
    default: {}
  }
  switch (a) {
    case 1: {} {}
    default: {} {}
  }
  switch (a) {
    case 1 -> {}
    default -> {}
  }
}

void tryStatements() {
  try {} catch (Exception e) {}
  try (var a = new A()) {} catch (Exception e) {}
  try {} finally {}
  try (var a = new A()) {} finally {}
  try {} catch (Exception e) {} finally {}
  try (var a = new A()) {} catch (Exception e) {} finally {}
  try {} catch (Exception e) {} catch (Exception e) {}
  try (var a = new A()) {} catch (Exception e) {} catch (Exception e) {}
  try {} catch (Exception e) {} catch (Exception e) {} finally {}
  try (var a = new A()) {} catch (Exception e) {} catch (Exception e) {} finally {}
}

Output

void ifStatements() {
  if (a) {
  }
  if (a) {
  } else {
  }
  if (a) {
  } else if (b) {
  } else {
  }
}

void switchStatements() {
  switch (a) {
  }
  switch (a) {
    case 1: {
    }
    default: {
    }
  }
  switch (a) {
    case 1:
      {
      }
      {
      }
    default:
      {
      }
      {
      }
  }
  switch (a) {
    case 1 -> {
    }
    default -> {
    }
  }
}

void tryStatements() {
  try {
  } catch (Exception e) {}
  try (var a = new A()) {
  } catch (Exception e) {}
  try {
  } finally {
  }
  try (var a = new A()) {
  } finally {
  }
  try {
  } catch (Exception e) {
  } finally {
  }
  try (var a = new A()) {
  } catch (Exception e) {
  } finally {
  }
  try {
  } catch (Exception e) {
  } catch (Exception e) {
  }
  try (var a = new A()) {
  } catch (Exception e) {
  } catch (Exception e) {
  }
  try {
  } catch (Exception e) {
  } catch (Exception e) {
  } finally {
  }
  try (var a = new A()) {
  } catch (Exception e) {
  } catch (Exception e) {
  } finally {
  }
}

Relative issues or prs:

Closes #789

jtkiesel avatar Dec 01 '25 01:12 jtkiesel