Fix another bug with constructor-like declarations
Previously: 9cbe62dc7fac7ad6956100ef180358b571c8654c, 3a840543cb5eef880a4caffd51c5d60eef79af47
Constructor-like declarations that don't match the enclosing class name are
parsed as methods with a null return type. When the formatter sees a line break
immediately before the name of a method, it +4 indents the rest of the method
signature. When a constructor-like declaration has javadoc, the break between
the javadoc and the method name was causing the indent to be performed.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=114124758
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 5cc0e3b..8ea4b45 100644
--- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java
+++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java
@@ -1293,7 +1293,9 @@
}
boolean openedNameAndTypeScope = false;
- if (!node.isConstructor()) {
+ // constructor-like declarations that don't match the name of the enclosing class are
+ // parsed as method declarations with a null return type
+ if (!node.isConstructor() && node.getReturnType2() != null) {
if (!first) {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", ZERO,
Optional.of(breakBeforeType));
@@ -1304,9 +1306,7 @@
builder.open(Indent.If.make(breakBeforeType, plusFour, ZERO));
openedNameAndTypeScope = true;
}
- if (node.getReturnType2() != null) {
- node.getReturnType2().accept(this);
- }
+ node.getReturnType2().accept(this);
}
if (!first) {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", ZERO,
diff --git a/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java b/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java
index f2749c2..3d48f7e 100644
--- a/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java
+++ b/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java
@@ -1124,4 +1124,23 @@
assertEquals("bad output", expectedFormatLine1, output);
}
}
+
+ @Test
+ public void commentBeforeBadConstructor() throws Exception {
+ String[] lines = {
+ "class D {", //
+ " /** */",
+ " F() {}",
+ "}",
+ };
+ String output = new Formatter().formatSource(Joiner.on('\n').join(lines));
+ String[] expected = {
+ "class D {", //
+ " /** */",
+ " F() {}",
+ "}",
+ "",
+ };
+ assertThat(output).isEqualTo(Joiner.on('\n').join(expected));
+ }
}