Skip to content

Commit

Permalink
[Formatter][Unnamed patterns/variables] leading space added to condit…
Browse files Browse the repository at this point in the history
…ional statements following an unnamed variable (#3073)

* Fixes #3070
  • Loading branch information
srikanth-sankaran authored Oct 14, 2024
1 parent 0037ab1 commit 11f45e6
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16396,4 +16396,72 @@ public void testGH1473c() throws JavaModelException {
String input = getCompilationUnit("Formatter", "", "testGH1473", "in.java").getSource();
formatSource(input, getCompilationUnit("Formatter", "", "testGH1473", "C_out.java").getSource());
}
// https://github.com/eclipse-jdt/eclipse.jdt.core/issues/3070
// [Formatter] leading space added to conditional statements following an unnamed variable
public void testIssue3070() {
setComplianceLevel(CompilerOptions.VERSION_23);
String source =
"""
class Example {
private void foo() {
var a = false;

try {
} catch (Exception _) { // <- the unnamed variable triggers the issue
}

if (a) { // <- no leading space before the variable name
}
}
}
""";
formatSource(source,
"""
class Example {
private void foo() {
var a = false;

try {
} catch (Exception _) { // <- the unnamed variable triggers the issue
}

if (a) { // <- no leading space before the variable name
}
}
}
""");
}
public void testIssue3070_2() {
setComplianceLevel(CompilerOptions.VERSION_23);
String source =
"""
class Example {
private void foo() {
var a = false;

try {
} catch (Exception e) { // <- the unnamed variable triggers the issue
}

if (a) { // <- no leading space before the variable name
}
}
}
""";
formatSource(source,
"""
class Example {
private void foo() {
var a = false;

try {
} catch (Exception e) { // <- the unnamed variable triggers the issue
}

if (a) { // <- no leading space before the variable name
}
}
}
""");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import static org.eclipse.jdt.internal.compiler.parser.TerminalTokens.TokenNameNotAToken;
import static org.eclipse.jdt.internal.compiler.parser.TerminalTokens.TokenNameStringLiteral;
import static org.eclipse.jdt.internal.compiler.parser.TerminalTokens.TokenNameTextBlock;
import static org.eclipse.jdt.internal.compiler.parser.TerminalTokens.TokenNameUNDERSCORE;

import java.util.ArrayList;
import java.util.HashMap;
Expand Down Expand Up @@ -175,6 +176,9 @@ public int findIndex(int positionInSource, int tokenType, boolean forward) {
if (tokenType == TerminalTokens.getRestrictedKeyword(toString(t)))
break;
}
if (t.tokenType == TokenNameUNDERSCORE && tokenType == TokenNameIdentifier) {
break;
}
index += forward ? 1 : -1;
}
return index;
Expand Down

0 comments on commit 11f45e6

Please sign in to comment.