Skip to content

Commit

Permalink
Fix one of the classic blunders in UnnecessaryStringBuilder
Browse files Browse the repository at this point in the history
`VariableTree#getType` doesn't have a position for variables with inferred
types.

PiperOrigin-RevId: 540607208
  • Loading branch information
cushon authored and Error Prone Team committed Jun 15, 2023
1 parent a86e28b commit 12b90df
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.util.Position;
import java.util.ArrayList;
import java.util.List;
import javax.lang.model.element.ElementKind;
Expand Down Expand Up @@ -124,12 +125,13 @@ public Description matchNewClass(NewClassTree tree, VisitorState state) {
if (leaf instanceof VariableTree) {
VariableTree variableTree = (VariableTree) leaf;
if (isRewritableVariable(variableTree, state)) {
return describeMatch(
variableTree,
SuggestedFix.builder()
.replace(variableTree.getType(), "String")
.replace(variableTree.getInitializer(), replacement(state, parts))
.build());
SuggestedFix.Builder fix = SuggestedFix.builder();
if (state.getEndPosition(variableTree.getType()) != Position.NOPOS) {
// If the variable is declared with `var`, there's no declaration type to change
fix.replace(variableTree.getType(), "String");
}
fix.replace(variableTree.getInitializer(), replacement(state, parts));
return describeMatch(variableTree, fix.build());
}
}
return NO_MATCH;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,26 @@ public void needsParens() {
"}")
.doTest();
}

@Test
public void varType() {
refactoringHelper
.addInputLines(
"Test.java",
"abstract class Test {",
" void f() {",
" var sb = new StringBuilder().append(\"hello\");",
" System.err.println(sb);",
" }",
"}")
.addOutputLines(
"Test.java",
"abstract class Test {",
" void f() {",
" var sb = \"hello\";",
" System.err.println(sb);",
" }",
"}")
.doTest();
}
}

0 comments on commit 12b90df

Please sign in to comment.