google-java-format icon indicating copy to clipboard operation
google-java-format copied to clipboard

Comments are indented before case statements in enhanced switch

Open sKwil opened this issue 2 years ago • 5 comments

Placing single-line or block comments before case statements in an enhanced switch causes them to be indented. This seems to be in violation of 4.8.6.1 Block comment style.

Auto-formatted code:

public class T {
  public static void main(String[] args) {
    int a = 1;
    switch (a) {
      case 1 -> System.out.println("1");

        // This is a comment before a case statement
      case 2 -> System.out.println("2");

        /*
         * Block comment before a case stement
         */
      case 3 -> System.out.println("3");

        // Comment before the default statement
      default -> System.out.println("N/A");
    }
  }
}

sKwil avatar Jan 03 '23 18:01 sKwil

+1 As a general rule I would expect a line containing only a comment to have the same indentation as what comes after it.

kevinb9n avatar Jan 25 '23 23:01 kevinb9n

I remember some discussion about line comments in non--> switches, where it's a little harder to know what the comment was supposed to be attached to, and it might be part of the preceding statement group:

case 1:
  doSomething();
  // fall through
case 2:

... but that's just context for why we probably ended up with the current behaviour, I agree with revisiting this for -> switches.

cushon avatar Jan 28 '23 21:01 cushon

imho, even the fall through comment isn't conceptually attached to either group, but to the boundary between.

kevinb9n avatar Jan 30 '23 18:01 kevinb9n

(The internal bug is b/21900318)

// fall through might not be the best example for a comment that was conceptually attached to the preceding statement group

cushon avatar Jan 30 '23 18:01 cushon

Fwiw, I'd say // fall through is kind of a special case in that it somehow replaces a break, so it's more at a statement level rather than "attached" to any group; as a statement (kinda), it'd however put it into the preceding statement group.

tbroyer avatar Jan 30 '23 18:01 tbroyer