Skip to content

Commit

Permalink
Ban usage of Stopwatch.elapsed() from non-desugared Android code.
Browse files Browse the repository at this point in the history
While `AndroidJdkLibsChecker` would already issue errors for code like `stopwatch.elapsed().toString()` (since that code includes a call to the banned `Duration.toString()`), it would not issue errors for cases in which callers, e.g., concatenate `stopwatch.elapsed()` into a string or pass `stopwatch.elapsed()` to another method, such as to log it.

The best approach here might be for the checker to automatically inspect all called methods for any reference to banned types in their parameter types or return types. However, that sounds like more implementation work, and it sounds like work that could require depot cleanup. (And maybe there are even reasons you've chosen not to take that approach?) So I figured it would be worth starting with this special case.

PiperOrigin-RevId: 376048914
  • Loading branch information
cpovirk authored and Error Prone Team committed May 26, 2021
1 parent 2fdb3e4 commit be2daa5
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ private static String packageName(String className) {
return className.substring(0, className.lastIndexOf('/') + 1);
}

private static final ImmutableSetMultimap<String, ClassMemberKey>
ADDITIONAL_MEMBERS_REQUIRING_DESUGAR =
ImmutableSetMultimap.<String, ClassMemberKey>builder()
.put("com/google/common/base/Stopwatch", ClassMemberKey.create("elapsed", ""))
.build();

private static class ClassSupportInfo {

private final ImmutableSet<String> allowedPackages;
Expand All @@ -95,7 +101,7 @@ private static class ClassSupportInfo {
allowedClasses = allowJava8 ? DESUGAR_ALLOWED_CLASSES : BASE_ALLOWED_CLASSES;
bannedClasses = BASE_BANNED_CLASSES;
allowedMembers = allowJava8 ? DESUGAR_ALLOWED_MEMBERS : ImmutableSetMultimap.of();
bannedMembers = allowJava8 ? DESUGAR_BANNED_MEMBERS : ImmutableSetMultimap.of();
bannedMembers = allowJava8 ? DESUGAR_BANNED_MEMBERS : ADDITIONAL_MEMBERS_REQUIRING_DESUGAR;
}

private boolean memberIsAllowed(Map.Entry<String, ClassMemberKey> member) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,21 @@ public void typeKind() {
.doTest();
}

@Test
public void stopwatchElapsed() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.base.Stopwatch;",
"public class Test {",
" Object o() {",
" // BUG: Diagnostic contains:",
" return Stopwatch.createStarted().elapsed();",
" }",
"}")
.doTest();
}

@Test
public void allowJava8Flag_packageAllowed() {
allowJava8Helper
Expand Down

0 comments on commit be2daa5

Please sign in to comment.