Skip to content

Commit

Permalink
NonCanonicalType: flag uses of non-canonical type names, such as Immu…
Browse files Browse the repository at this point in the history
…tableMap.Entry.

This doesn't handle the tricky generic case yet. It also doesn't handle non-canonical references to member variables or methods: I suspect those are often intentional, and trying to rail against them will be harder.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=289080208
  • Loading branch information
graememorgan authored and netdpb committed Jan 10, 2020
1 parent 311267d commit 65e5dff
Show file tree
Hide file tree
Showing 5 changed files with 201 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.errorprone.bugpatterns;

import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFixes.qualifyType;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getSymbol;

import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MemberSelectTreeMatcher;
import com.google.errorprone.bugpatterns.StaticImports.StaticImportInfo;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;

/** Flags types being referred to by their non-canonical name. */
@BugPattern(
name = "NonCanonicalType",
summary = "This type is referred to by a non-canonical name, which may be misleading.",
severity = WARNING)
public final class NonCanonicalType extends BugChecker implements MemberSelectTreeMatcher {
@Override
public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) {
// Only match on the outermost member select.
if (state.getPath().getParentPath().getLeaf() instanceof MemberSelectTree) {
return NO_MATCH;
}
StaticImportInfo importInfo = StaticImports.tryCreate(tree, state);
if (importInfo == null || !importInfo.members().isEmpty()) {
return NO_MATCH;
}
// Skip generated code. There are some noisy cases in AutoValue.
if (importInfo.canonicalName().contains("$")) {
return NO_MATCH;
}
String nonCanonicalName = getNonCanonicalName(tree);
if (importInfo.canonicalName().equals(nonCanonicalName)) {
return NO_MATCH;
}
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
SuggestedFix fix =
fixBuilder
.replace(tree, qualifyType(state, fixBuilder, importInfo.canonicalName()))
.build();
return describeMatch(tree, fix);
}

/**
* Find the non-canonical name which is being used to refer to this type. We can't just use {@code
* getSymbol}, given that points to the same symbol as the canonical name.
*/
private static String getNonCanonicalName(ExpressionTree tree) {
switch (tree.getKind()) {
case IDENTIFIER:
return getSymbol(tree).getQualifiedName().toString();
case MEMBER_SELECT:
MemberSelectTree memberSelectTree = (MemberSelectTree) tree;
Symbol expressionSymbol = getSymbol(memberSelectTree.getExpression());
if (!(expressionSymbol instanceof TypeSymbol)) {
return getSymbol(tree).getQualifiedName().toString();
}
return getNonCanonicalName(memberSelectTree.getExpression())
+ "."
+ memberSelectTree.getIdentifier();
default:
throw new AssertionError();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@
package com.google.errorprone.bugpatterns;

import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.util.ASTHelpers.getSymbol;

import com.google.auto.value.AutoValue;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.VisitorState;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
Expand Down Expand Up @@ -103,7 +104,13 @@ public static StaticImportInfo tryCreate(ImportTree tree, VisitorState state) {
// so there's nothing to do here.
return null;
}
Symbol importedType = ASTHelpers.getSymbol(access.getExpression());
return tryCreate(access, state);
}

@Nullable
public static StaticImportInfo tryCreate(MemberSelectTree access, VisitorState state) {
Name identifier = (Name) access.getIdentifier();
Symbol importedType = getSymbol(access.getExpression());
if (importedType == null) {
return null;
}
Expand All @@ -114,14 +121,12 @@ public static StaticImportInfo tryCreate(ImportTree tree, VisitorState state) {
if (canonicalType == null) {
return null;
}
Symbol.TypeSymbol baseType;
{
Symbol sym = ASTHelpers.getSymbol(access.getExpression());
if (!(sym instanceof Symbol.TypeSymbol)) {
return null;
}
baseType = (Symbol.TypeSymbol) sym;

Symbol sym = getSymbol(access.getExpression());
if (!(sym instanceof Symbol.TypeSymbol)) {
return null;
}
Symbol.TypeSymbol baseType = (Symbol.TypeSymbol) sym;
Symbol.PackageSymbol pkgSym =
((JCTree.JCCompilationUnit) state.getPath().getCompilationUnit()).packge;
ImmutableSet<Symbol> members = lookup(baseType, baseType, identifier, types, pkgSym);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@
import com.google.errorprone.bugpatterns.NonAtomicVolatileUpdate;
import com.google.errorprone.bugpatterns.NonCanonicalStaticImport;
import com.google.errorprone.bugpatterns.NonCanonicalStaticMemberImport;
import com.google.errorprone.bugpatterns.NonCanonicalType;
import com.google.errorprone.bugpatterns.NonFinalCompileTimeConstant;
import com.google.errorprone.bugpatterns.NonOverridingEquals;
import com.google.errorprone.bugpatterns.NonRuntimeAnnotation;
Expand Down Expand Up @@ -723,6 +724,7 @@ public static ScannerSupplier errorChecks() {
NarrowingCompoundAssignment.class,
NestedInstanceOfConditions.class,
NonAtomicVolatileUpdate.class,
NonCanonicalType.class,
NonOverridingEquals.class,
NullableConstructor.class,
NullablePrimitive.class,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.errorprone.bugpatterns;

import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link NonCanonicalType}. */
@RunWith(JUnit4.class)
public final class NonCanonicalTypeTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(NonCanonicalType.class, getClass());

@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.common.collect.ImmutableMap;",
"class Test {",
" void test() {",
" // BUG: Diagnostic contains: Map.Entry",
" ImmutableMap.Entry<?, ?> entry = null;",
" }",
"}")
.doTest();
}

@Test
public void positiveWithGenerics() {
compilationHelper
.addSourceLines(
"A.java", //
"class A<T> {",
" class B {}",
"}")
.addSourceLines(
"AString.java", //
"class AString extends A<String> {}")
.addSourceLines(
"Test.java",
"class Test {",
// TODO(b/116104523): This should be flagged.
" AString.B test() {",
" return null;",
" }",
"}")
.doTest();
}

@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.Map;",
"class Test {",
" void test() {",
" Map.Entry<?, ?> entry = null;",
" }",
"}")
.doTest();
}
}
17 changes: 17 additions & 0 deletions docs/bugpattern/NonCanonicalType.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
Types being referred to by non-canonical names can be confusing. For example,

```java
public final class Entries {
private final ImmutableList<ImmutableMap.Entry<String, Long>> entries;

public Entries(Map<String, Long> map) {
this.entries = ImmutableList.copyOf(map.entrySet());
}
}
```

There is nothing special about `ImmutableMap.Entry`; it is precisely the same
type as `Map.Entry`. This example makes it look deceptively as though
`ImmutableList<ImmutableMap.Entry<?, ?>>` is an immutable type and therefore
safe to store indefinitely, when really it offers no more safety than
`ImmutableList<Map.Entry<?, ?>>`.

0 comments on commit 65e5dff

Please sign in to comment.