google / google-java-format

Reformats Java source code to comply with Google Java Style.
Other
5.58k stars 855 forks source link

Comments before 'case' of 'switch' make formating weird #1123

Closed romani closed 2 months ago

romani commented 2 months ago
/var/tmp$ cat Test.java 
public class Test {
  void method(int i, int j, boolean cond) {
    while (true) {
      switch (i) {
        case 0: // no problem
        case 1:
          i++;
          break;
        case 2:
          i++;
        /*fall through*/ case 3:
          i++;
          break;
      }
    }
  }
}

/var/tmp$ java -jar google-java-format-1.22.0-all-deps.jar Test.java > TestUpdated.java

diff:

/var/tmp$ diff -u Test.java TestUpdated.java 
--- Test.java   2024-07-26 21:52:16.871580578 -0700
+++ TestUpdated.java    2024-07-26 21:52:24.399697339 -0700
@@ -8,7 +8,7 @@
           break;
         case 2:
           i++;
-        /*fall through*/ case 3:
+          /*fall through*/ case 3:
           i++;
           break;
       }

result file is weirdly formatted for case 3:

rivanov@p5510:/var/tmp$ cat TestUpdated.java 
public class Test {
  void method(int i, int j, boolean cond) {
    while (true) {
      switch (i) {
        case 0: // no problem
        case 1:
          i++;
          break;
        case 2:
          i++;
          /*fall through*/ case 3:
          i++;
          break;
      }
    }
  }
}
cushon commented 2 months ago

This was recently fixed in https://github.com/google/google-java-format/commit/f7543b2a7d3b9c5b8214b33e8762e9550f5ab20f. That change will be included in the next release of the formatter.

After that change, it emits:

public class Test {
  void method(int i, int j, boolean cond) {
    while (true) {
      switch (i) {
        case 0: // no problem
        case 1:
          i++;
          break;
        case 2:
          i++;
        /*fall through*/ case 3:
          i++;
          break;
      }
    }
  }
}