Skip to content

Commit 13a7a12

Browse files
cushonError Prone Team
authored andcommitted
Fix a crash in LenientFormatStringUtils
Handle `Preconditions.checkNotNull`, which isn't a format method. PiperOrigin-RevId: 834207706
1 parent 7e6e113 commit 13a7a12

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

core/src/main/java/com/google/errorprone/bugpatterns/formatstring/LenientFormatStringUtils.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import com.google.errorprone.VisitorState;
2525
import com.google.errorprone.matchers.Matcher;
2626
import com.sun.source.tree.ExpressionTree;
27+
import com.sun.source.tree.MethodInvocationTree;
2728

2829
/** Utilities relating to lenient format strings. */
2930
public final class LenientFormatStringUtils {
@@ -35,7 +36,11 @@ public final class LenientFormatStringUtils {
3536
public static int getLenientFormatStringPosition(ExpressionTree tree, VisitorState state) {
3637
for (LenientFormatMethod method : LENIENT_FORMATTING_METHODS) {
3738
if (method.matcher().matches(tree, state)) {
38-
return method.formatStringPosition;
39+
if (tree instanceof MethodInvocationTree methodInvocation
40+
&& method.formatStringPosition < methodInvocation.getArguments().size()) {
41+
// e.g. Preconditions.checkNotNull(String) isn't a format method
42+
return method.formatStringPosition;
43+
}
3944
}
4045
}
4146
return -1;

core/src/test/java/com/google/errorprone/bugpatterns/formatstring/InlineFormatStringTest.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,4 +266,23 @@ void f() {
266266
""")
267267
.doTest();
268268
}
269+
270+
@Test
271+
public void nonFormatMethod() {
272+
compilationHelper
273+
.addSourceLines(
274+
"Test.java",
275+
"""
276+
import com.google.common.base.Preconditions;
277+
278+
class Test {
279+
void f(Object obj) {
280+
String format = "hello %s";
281+
Preconditions.checkNotNull(format);
282+
Preconditions.checkNotNull(obj, format);
283+
}
284+
}
285+
""")
286+
.doTest();
287+
}
269288
}

0 commit comments

Comments
 (0)