From b3c7c11015646055a8029366d2410f9b3016c530 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Mon, 5 Aug 2024 11:16:38 -0700 Subject: [PATCH] Fix inconsistency in formatting of comments in switch statements This was introduced by https://github.com/google/google-java-format/commit/f7543b2a7d3b9c5b8214b33e8762e9550f5ab20f, which only updated the logic for for JDK 17+. Fixes https://github.com/google/google-java-format/issues/1127 PiperOrigin-RevId: 659616575 --- .../java/JavaInputAstVisitor.java | 4 ++-- .../java/testdata/LegacySwitchComment.input | 17 +++++++++++++++++ .../java/testdata/LegacySwitchComment.output | 17 +++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/LegacySwitchComment.input create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/LegacySwitchComment.output diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index e00877e96..01f9a3e05 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -1875,10 +1875,10 @@ public Void visitCase(CaseTree node, Void unused) { markForPartialFormat(); builder.forcedBreak(); if (node.getExpression() == null) { - token("default", plusTwo); + token("default", ZERO); token(":"); } else { - token("case", plusTwo); + token("case", ZERO); builder.space(); scan(node.getExpression(), null); token(":"); diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/LegacySwitchComment.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/LegacySwitchComment.input new file mode 100644 index 000000000..07ce2f4d2 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/LegacySwitchComment.input @@ -0,0 +1,17 @@ +class T { + int test(String v) { + switch (v) { + // this is a line comment about "zero" + case "zero": + return 0; + case "one": + // this is a line comment about "one" + return 1; + // this is a line comment about "two" + case "two": + return 2; + default: + return -1; + } + } +} \ No newline at end of file diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/LegacySwitchComment.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/LegacySwitchComment.output new file mode 100644 index 000000000..70a0b6bea --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/LegacySwitchComment.output @@ -0,0 +1,17 @@ +class T { + int test(String v) { + switch (v) { + // this is a line comment about "zero" + case "zero": + return 0; + case "one": + // this is a line comment about "one" + return 1; + // this is a line comment about "two" + case "two": + return 2; + default: + return -1; + } + } +}