Skip to content

Commit

Permalink
Don't crash when someone declares a StringBuffer using var.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 449835264
  • Loading branch information
amalloy authored and Error Prone Team committed May 19, 2022
1 parent 9ff2d42 commit 97a7dbc
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.util.Position;
import java.util.Optional;
import javax.annotation.Nullable;

Expand Down Expand Up @@ -344,11 +345,13 @@ public Void visitIdentifier(IdentifierTree tree, Void unused) {
if (escape[0]) {
return Optional.empty();
}
return Optional.of(
SuggestedFix.builder()
.replace(newClassTree.getIdentifier(), "StringBuilder")
.replace(varTree.getType(), "StringBuilder")
.build());
SuggestedFix.Builder fix =
SuggestedFix.builder().replace(newClassTree.getIdentifier(), "StringBuilder");
if (ASTHelpers.getStartPosition(varTree.getType()) != Position.NOPOS) {
// If the variable is declared with `var`, there's no declaration type to change
fix = fix.replace(varTree.getType(), "StringBuilder");
}
return Optional.of(fix.build());
}

private static TreePath findEnclosingMethod(VisitorState state) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,28 @@ public void stringBufferRefactoringTest() {
.doTest();
}

@Test
public void stringBufferRefactoringTest_usingVar() {
BugCheckerRefactoringTestHelper.newInstance(JdkObsolete.class, getClass())
.addInputLines(
"in/Test.java", //
"class Test {",
" String f() {",
" var sb = new StringBuffer();",
" return sb.append(42).toString();",
" }",
"}")
.addOutputLines(
"out/Test.java", //
"class Test {",
" String f() {",
" var sb = new StringBuilder();",
" return sb.append(42).toString();",
" }",
"}")
.doTest();
}

/** A test input. */
public interface Lib {
Enumeration<Integer> foos();
Expand Down

0 comments on commit 97a7dbc

Please sign in to comment.