From d2ee28e8576e5b23cb7538078e1b75484af9c15a Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Wed, 20 Sep 2023 11:57:51 -0700 Subject: [PATCH] Fix a crash in TimeUnitConversionChecker Motivated by ``` thread.join((timeUnit != null ? timeUnit : TimeUnit.MILLISECONDS).toMillis(time)); ``` https://github.com/apache/httpcomponents-client/blame/160bac0cbb2b388018c4e794c120ba719ddd2887/httpclient5/src/main/java/org/apache/hc/client5/http/impl/IdleConnectionEvictor.java#L98 PiperOrigin-RevId: 567037317 --- .../time/TimeUnitConversionChecker.java | 7 ++++++- .../time/TimeUnitConversionCheckerTest.java | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/time/TimeUnitConversionChecker.java b/core/src/main/java/com/google/errorprone/bugpatterns/time/TimeUnitConversionChecker.java index 142beb2a830..5be09329940 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/time/TimeUnitConversionChecker.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/time/TimeUnitConversionChecker.java @@ -32,6 +32,7 @@ import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; +import com.sun.tools.javac.code.Symbol; import java.util.concurrent.TimeUnit; /** Check for problematic or suspicious TimeUnit conversion calls. */ @@ -73,7 +74,11 @@ public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState // TimeUnit SECONDS = TimeUnit.MINUTES; // long about2500 = SECONDS.toSeconds(42); // but... I think that's bad enough to ignore here :) - String timeUnitName = ASTHelpers.getSymbol(receiverOfConversion).getSimpleName().toString(); + Symbol receiverOfConversionSymbol = ASTHelpers.getSymbol(receiverOfConversion); + if (receiverOfConversionSymbol == null) { + return Description.NO_MATCH; + } + String timeUnitName = receiverOfConversionSymbol.getSimpleName().toString(); Optional receiver = Enums.getIfPresent(TimeUnit.class, timeUnitName); if (!receiver.isPresent()) { return Description.NO_MATCH; diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/time/TimeUnitConversionCheckerTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/time/TimeUnitConversionCheckerTest.java index d928fd12a6d..3364c04bd29 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/time/TimeUnitConversionCheckerTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/time/TimeUnitConversionCheckerTest.java @@ -168,4 +168,18 @@ public void largeUnitToSmallUnit_succeeds() { "}") .doTest(); } + + @Test + public void receiverExpression() { + helper + .addSourceLines( + "TestClass.java", + "import java.util.concurrent.TimeUnit;", + "public class TestClass {", + " long f(TimeUnit timeUnit, long time) {", + " return (timeUnit != null ? timeUnit : TimeUnit.MILLISECONDS).toMillis(time);", + " }", + "}") + .doTest(); + } }