From 7d1ae8350444dd434124a7c7d0be40f8f5e1c245 Mon Sep 17 00:00:00 2001 From: ghm Date: Fri, 26 Jan 2024 08:44:51 -0800 Subject: [PATCH] Fix a crash in `UnnecessaryStringBuilder` Fixes external #4195 PiperOrigin-RevId: 601777043 --- .../bugpatterns/UnnecessaryStringBuilder.java | 3 +++ .../bugpatterns/UnnecessaryStringBuilderTest.java | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryStringBuilder.java b/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryStringBuilder.java index 57dd19f8846..c09e011b86d 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryStringBuilder.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryStringBuilder.java @@ -117,6 +117,9 @@ public Description matchNewClass(NewClassTree tree, VisitorState state) { } } ASTHelpers.TargetType target = ASTHelpers.targetType(state.withPath(path)); + if (target == null) { + return NO_MATCH; + } if (!isUsedAsStringBuilder(state, target)) { return describeMatch( path.getLeaf(), SuggestedFix.replace(path.getLeaf(), replacement(state, parts))); diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryStringBuilderTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryStringBuilderTest.java index a022aae7247..fc96ab21d2d 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryStringBuilderTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryStringBuilderTest.java @@ -164,4 +164,17 @@ public void varType() { "}") .doTest(); } + + @Test + public void unusedReturnValue() { + testHelper + .addSourceLines( + "Test.java", + "class Test {", + " void f() {", + " new StringBuilder().append(\"foo\");", + " }", + "}") + .doTest(); + } }