Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,8 @@ private boolean visitArrayInitializer(List<? extends ExpressionTree> expressions
boolean allowFilledElementsOnOwnLine = shortItems || !inMemberValuePair;

builder.open(plusTwo);
tokenBreakTrailingComment("{", plusTwo);
// Same as visitBlock (#1260): avoid double plusTwo when elements are present.
tokenBreakTrailingComment("{", expressions.isEmpty() ? plusTwo : ZERO);
boolean hasTrailingComma = hasTrailingToken(builder.getInput(), expressions, ",");
builder.breakOp(hasTrailingComma ? FillMode.FORCED : FillMode.UNIFIED, "", ZERO);
if (allowFilledElementsOnOwnLine) {
Expand Down Expand Up @@ -2317,7 +2318,12 @@ private void visitBlock(
} else {
builder.open(ZERO);
builder.open(plusTwo);
tokenBreakTrailingComment("{", plusTwo);
// Inside plusTwo already. Empty blocks still need plusTwo so a trailing comment on "{"
// lands inside the braces; non-empty blocks use ZERO so the comment lines up with
// statements (otherwise the first format over-indents and a second pass corrects it —
// #1260).
tokenBreakTrailingComment(
"{", node.getStatements().isEmpty() ? plusTwo : ZERO);
if (allowLeadingBlankLine == AllowLeadingBlankLine.NO) {
builder.blankLineWanted(BlankLineWanted.NO);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -669,4 +669,40 @@ void f() {
}
""");
}

@Test
public void trailingCommentAfterOpenBraceIsIdempotent() throws Exception {
// Regression for #1260: trailing block comments on "{" were indented an extra
// plusTwo when the opener was already inside an open(plusTwo) level.
String input =
"""
class T {
void f() {
{ /* c */ int x = 1; }
}

int[] a = { /* c */ 1 };
}
""";
String once = new Formatter().formatSource(input);
String twice = new Formatter().formatSource(once);
assertThat(once).isEqualTo(twice);
assertThat(once)
.isEqualTo(
"""
class T {
void f() {
{
/* c */
int x = 1;
}
}

int[] a = {
/* c */
1
};
}
""");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class I1260 {
void block() {
{ /* trailing on open brace */ int x = 1; }
}

void switchCase() {
switch (0) {
case 1: { /* Break so we don't hit fall-through warning: */ break;/* ignore STRING */
}
}
}

int[] array = { /* trailing on array brace */ 1, 2 };
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class I1260 {
void block() {
{
/* trailing on open brace */
int x = 1;
}
}

void switchCase() {
switch (0) {
case 1:
{
/* Break so we don't hit fall-through warning: */
break; /* ignore STRING */
}
}
}

int[] array = {
/* trailing on array brace */
1, 2
};
}
Loading