From 5a7b8d9b41a19aaf6cc917bc295ab5201cc2f328 Mon Sep 17 00:00:00 2001 From: ghm Date: Mon, 15 Apr 2024 05:11:01 -0700 Subject: [PATCH] NearbyCallers: scan the body of expression lambdas. PiperOrigin-RevId: 624922054 --- .../bugpatterns/time/NearbyCallers.java | 5 ++--- .../JavaDurationGetSecondsGetNanoTest.java | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/time/NearbyCallers.java b/core/src/main/java/com/google/errorprone/bugpatterns/time/NearbyCallers.java index 4f485341543..98a3646f9d9 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/time/NearbyCallers.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/time/NearbyCallers.java @@ -167,8 +167,7 @@ private static ImmutableList getNearbyTreesToScan(VisitorState state) { return ImmutableList.of(parent); case LAMBDA_EXPRESSION: - // if we reach a lambda tree, then don't scan anything since we don't know where/when that - // lambda will actually be executed. + // if we reach a lambda tree, just scan the lambda body itself // TODO(glorioso): for simple expression lambdas, consider looking for use sites and scan // *those* sites, but binding the lambda variable to its use site might be rough :( @@ -179,7 +178,7 @@ private static ImmutableList getNearbyTreesToScan(VisitorState state) { // long nanos = NANOS.apply(myDuration) + SECONDS.apply(myDuration) * 1_000_000L; // // how do we track myDuration through both layers? - return ImmutableList.of(); + return ImmutableList.of(((LambdaExpressionTree) parent).getBody()); case CLASS: // if we get all the way up to the class tree, then _only_ scan the other class-level diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/time/JavaDurationGetSecondsGetNanoTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/time/JavaDurationGetSecondsGetNanoTest.java index e8d2bf2ca10..a84f9034b65 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/time/JavaDurationGetSecondsGetNanoTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/time/JavaDurationGetSecondsGetNanoTest.java @@ -324,4 +324,22 @@ public void getNanoInLambda() { "}") .doTest(); } + + @Test + public void bothUsedWithinALambda() { + compilationHelper + .addSourceLines( + "test/TestCase.java", + "package test;", + "import com.google.common.collect.ImmutableMap;", + "import java.time.Duration;", + "import java.util.function.Supplier;", + "public class TestCase {", + " public static Supplier> foo(Duration duration) {", + " return () -> ImmutableMap.of(", + " \"seconds\", duration.getSeconds(), \"nanos\", duration.getNano());", + " }", + "}") + .doTest(); + } }