Skip to content

Commit 12b90df

Browse files
cushonError Prone Team
authored and
Error Prone Team
committed
Fix one of the classic blunders in UnnecessaryStringBuilder
`VariableTree#getType` doesn't have a position for variables with inferred types. PiperOrigin-RevId: 540607208
1 parent a86e28b commit 12b90df

File tree

2 files changed

+30
-6
lines changed

2 files changed

+30
-6
lines changed

core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryStringBuilder.java

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
import com.sun.source.util.TreePathScanner;
4848
import com.sun.tools.javac.code.Symbol;
4949
import com.sun.tools.javac.code.Type;
50+
import com.sun.tools.javac.util.Position;
5051
import java.util.ArrayList;
5152
import java.util.List;
5253
import javax.lang.model.element.ElementKind;
@@ -124,12 +125,13 @@ public Description matchNewClass(NewClassTree tree, VisitorState state) {
124125
if (leaf instanceof VariableTree) {
125126
VariableTree variableTree = (VariableTree) leaf;
126127
if (isRewritableVariable(variableTree, state)) {
127-
return describeMatch(
128-
variableTree,
129-
SuggestedFix.builder()
130-
.replace(variableTree.getType(), "String")
131-
.replace(variableTree.getInitializer(), replacement(state, parts))
132-
.build());
128+
SuggestedFix.Builder fix = SuggestedFix.builder();
129+
if (state.getEndPosition(variableTree.getType()) != Position.NOPOS) {
130+
// If the variable is declared with `var`, there's no declaration type to change
131+
fix.replace(variableTree.getType(), "String");
132+
}
133+
fix.replace(variableTree.getInitializer(), replacement(state, parts));
134+
return describeMatch(variableTree, fix.build());
133135
}
134136
}
135137
return NO_MATCH;

core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryStringBuilderTest.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,4 +142,26 @@ public void needsParens() {
142142
"}")
143143
.doTest();
144144
}
145+
146+
@Test
147+
public void varType() {
148+
refactoringHelper
149+
.addInputLines(
150+
"Test.java",
151+
"abstract class Test {",
152+
" void f() {",
153+
" var sb = new StringBuilder().append(\"hello\");",
154+
" System.err.println(sb);",
155+
" }",
156+
"}")
157+
.addOutputLines(
158+
"Test.java",
159+
"abstract class Test {",
160+
" void f() {",
161+
" var sb = \"hello\";",
162+
" System.err.println(sb);",
163+
" }",
164+
"}")
165+
.doTest();
166+
}
145167
}

0 commit comments

Comments
 (0)