Search in sources :

Example 1 with TypeSymbol

use of com.sun.tools.javac.code.Symbol.TypeSymbol in project lombok by rzwitserloot.

the class HandleExtensionMethod method getExtension.

public Extension getExtension(final JavacNode typeNode, final ClassType extensionMethodProviderType) {
    List<MethodSymbol> extensionMethods = new ArrayList<MethodSymbol>();
    TypeSymbol tsym = extensionMethodProviderType.asElement();
    if (tsym != null)
        for (Symbol member : tsym.getEnclosedElements()) {
            if (member.getKind() != ElementKind.METHOD)
                continue;
            MethodSymbol method = (MethodSymbol) member;
            if ((method.flags() & (STATIC | PUBLIC)) == 0)
                continue;
            if (method.params().isEmpty())
                continue;
            extensionMethods.add(method);
        }
    return new Extension(extensionMethods, tsym);
}
Also used : MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) Symbol(com.sun.tools.javac.code.Symbol) ArrayList(java.util.ArrayList) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol)

Example 2 with TypeSymbol

use of com.sun.tools.javac.code.Symbol.TypeSymbol in project error-prone by google.

the class ThreadSafety method getAnnotation.

private AnnotationInfo getAnnotation(Symbol sym, VisitorState state, String annotation, @Nullable Class<? extends Annotation> elementAnnotation) {
    if (sym == null) {
        return null;
    }
    Symbol annosym = state.getSymbolFromString(annotation);
    Optional<Compound> attr = sym.getAnnotationMirrors().stream().filter(a -> a.getAnnotationType().asElement().equals(annosym)).findAny();
    if (attr.isPresent()) {
        ImmutableList<String> containerElements = containerOf(state, attr.get());
        if (elementAnnotation != null && containerElements.isEmpty()) {
            containerElements = sym.getTypeParameters().stream().filter(p -> p.getAnnotation(elementAnnotation) != null).map(p -> p.getSimpleName().toString()).collect(toImmutableList());
        }
        return AnnotationInfo.create(sym.getQualifiedName().toString(), containerElements);
    }
    // @ThreadSafe is inherited from supertypes
    if (!(sym instanceof ClassSymbol)) {
        return null;
    }
    Type superClass = ((ClassSymbol) sym).getSuperclass();
    AnnotationInfo superAnnotation = getInheritedAnnotation(superClass.asElement(), state);
    if (superAnnotation == null) {
        return null;
    }
    // If an annotated super-type was found, look for any type arguments to the super-type that
    // are in the super-type's containerOf spec, and where the arguments are type parameters
    // of the current class.
    // E.g. for `Foo<X> extends Super<X>` if `Super<Y>` is annotated
    // `@ThreadSafeContainerAnnotation Y`
    // then `Foo<X>` is has X implicitly annotated `@ThreadSafeContainerAnnotation X`
    ImmutableList.Builder<String> containerOf = ImmutableList.builder();
    for (int i = 0; i < superClass.getTypeArguments().size(); i++) {
        Type arg = superClass.getTypeArguments().get(i);
        TypeVariableSymbol formal = superClass.asElement().getTypeParameters().get(i);
        if (!arg.hasTag(TypeTag.TYPEVAR)) {
            continue;
        }
        TypeSymbol argSym = arg.asElement();
        if (argSym.owner == sym && superAnnotation.containerOf().contains(formal.getSimpleName().toString())) {
            containerOf.add(argSym.getSimpleName().toString());
        }
    }
    return AnnotationInfo.create(superAnnotation.typeName(), containerOf.build());
}
Also used : Iterables(com.google.common.collect.Iterables) Arrays(java.util.Arrays) ClassType(com.sun.tools.javac.code.Type.ClassType) ArrayType(com.sun.tools.javac.code.Type.ArrayType) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) TypeVar(com.sun.tools.javac.code.Type.TypeVar) ArrayList(java.util.ArrayList) VisitorState(com.google.errorprone.VisitorState) ConsPStack(org.pcollections.ConsPStack) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ImmutableList(com.google.common.collect.ImmutableList) TypeTag(com.sun.tools.javac.code.TypeTag) Map(java.util.Map) ClassTree(com.sun.source.tree.ClassTree) Nullable(javax.annotation.Nullable) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) SimpleAnnotationValueVisitor8(javax.lang.model.util.SimpleAnnotationValueVisitor8) ImmutableSet(com.google.common.collect.ImmutableSet) ElementKind(javax.lang.model.element.ElementKind) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Collection(java.util.Collection) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Compound(com.sun.tools.javac.code.Attribute.Compound) Symbol(com.sun.tools.javac.code.Symbol) Set(java.util.Set) Target(java.lang.annotation.Target) Streams(com.google.common.collect.Streams) ElementType(java.lang.annotation.ElementType) Field(java.lang.reflect.Field) WildcardType(com.sun.tools.javac.code.Type.WildcardType) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Violation(com.google.errorprone.bugpatterns.threadsafety.ThreadSafety.Violation) CanBeStaticAnalyzer(com.google.errorprone.bugpatterns.CanBeStaticAnalyzer) TypeVariableSymbol(com.sun.tools.javac.code.Symbol.TypeVariableSymbol) List(java.util.List) Types(com.sun.tools.javac.code.Types) Attribute(com.sun.tools.javac.code.Attribute) AutoValue(com.google.auto.value.AutoValue) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) AnnotationValue(javax.lang.model.element.AnnotationValue) ASTHelpers(com.google.errorprone.util.ASTHelpers) Type(com.sun.tools.javac.code.Type) Joiner(com.google.common.base.Joiner) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) Symbol(com.sun.tools.javac.code.Symbol) TypeVariableSymbol(com.sun.tools.javac.code.Symbol.TypeVariableSymbol) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) ImmutableList(com.google.common.collect.ImmutableList) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Compound(com.sun.tools.javac.code.Attribute.Compound) ClassType(com.sun.tools.javac.code.Type.ClassType) ArrayType(com.sun.tools.javac.code.Type.ArrayType) ElementType(java.lang.annotation.ElementType) WildcardType(com.sun.tools.javac.code.Type.WildcardType) Type(com.sun.tools.javac.code.Type) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) TypeVariableSymbol(com.sun.tools.javac.code.Symbol.TypeVariableSymbol)

Example 3 with TypeSymbol

use of com.sun.tools.javac.code.Symbol.TypeSymbol in project error-prone by google.

the class ASTHelpers method findMatchingMethods.

/**
 * Finds all methods in any superclass of {@code startClass} with a certain {@code name} that
 * match the given {@code predicate}.
 *
 * @return The (possibly empty) set of methods in any superclass that match {@code predicate} and
 *     have the given {@code name}.
 */
public static Set<MethodSymbol> findMatchingMethods(Name name, final Predicate<MethodSymbol> predicate, Type startClass, Types types) {
    Filter<Symbol> matchesMethodPredicate = sym -> sym instanceof MethodSymbol && predicate.apply((MethodSymbol) sym);
    Set<MethodSymbol> matchingMethods = new HashSet<>();
    // Iterate over all classes and interfaces that startClass inherits from.
    for (Type superClass : types.closure(startClass)) {
        // Iterate over all the methods declared in superClass.
        TypeSymbol superClassSymbol = superClass.tsym;
        Scope superClassSymbols = superClassSymbol.members();
        if (superClassSymbols != null) {
            // Can be null if superClass is a type variable
            for (Symbol symbol : superClassSymbols.getSymbolsByName(name, matchesMethodPredicate, NON_RECURSIVE)) {
                // By definition of the filter, we know that the symbol is a MethodSymbol.
                matchingMethods.add((MethodSymbol) symbol);
            }
        }
    }
    return matchingMethods;
}
Also used : CompoundAssignmentTree(com.sun.source.tree.CompoundAssignmentTree) Arrays(java.util.Arrays) ClassType(com.sun.tools.javac.code.Type.ClassType) Nullness(com.google.errorprone.dataflow.nullnesspropagation.Nullness) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) AssignmentTree(com.sun.source.tree.AssignmentTree) LambdaExpressionTree(com.sun.source.tree.LambdaExpressionTree) Log(com.sun.tools.javac.util.Log) Matcher(com.google.errorprone.matchers.Matcher) JarURLConnection(java.net.JarURLConnection) ForLoopTree(com.sun.source.tree.ForLoopTree) EnumSet(java.util.EnumSet) ParenthesizedTree(com.sun.source.tree.ParenthesizedTree) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) Filter(com.sun.tools.javac.util.Filter) ConditionalExpressionTree(com.sun.source.tree.ConditionalExpressionTree) TreePath(com.sun.source.util.TreePath) JCLiteral(com.sun.tools.javac.tree.JCTree.JCLiteral) Compound(com.sun.tools.javac.code.Attribute.Compound) Symbol(com.sun.tools.javac.code.Symbol) Set(java.util.Set) MemberSelectTree(com.sun.source.tree.MemberSelectTree) TreeScanner(com.sun.source.util.TreeScanner) Stream(java.util.stream.Stream) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) Predicate(com.google.common.base.Predicate) Attribute(com.sun.tools.javac.code.Attribute) PackageSymbol(com.sun.tools.javac.code.Symbol.PackageSymbol) AutoValue(com.google.auto.value.AutoValue) JCIdent(com.sun.tools.javac.tree.JCTree.JCIdent) AnnotationValue(javax.lang.model.element.AnnotationValue) Flags(com.sun.tools.javac.code.Flags) JCClassDecl(com.sun.tools.javac.tree.JCTree.JCClassDecl) Scope(com.sun.tools.javac.code.Scope) ReturnTree(com.sun.source.tree.ReturnTree) UnaryTree(com.sun.source.tree.UnaryTree) VariableTree(com.sun.source.tree.VariableTree) TypeParameterTree(com.sun.source.tree.TypeParameterTree) ArrayList(java.util.ArrayList) VisitorState(com.google.errorprone.VisitorState) Kind(com.sun.source.tree.Tree.Kind) NewClassTree(com.sun.source.tree.NewClassTree) ParameterizedTypeTree(com.sun.source.tree.ParameterizedTypeTree) Tree(com.sun.source.tree.Tree) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) SimpleAnnotationValueVisitor8(javax.lang.model.util.SimpleAnnotationValueVisitor8) Enter(com.sun.tools.javac.comp.Enter) ExpressionTree(com.sun.source.tree.ExpressionTree) CharMatcher(com.google.common.base.CharMatcher) IOException(java.io.IOException) AnnotationMirror(javax.lang.model.element.AnnotationMirror) Types(com.sun.tools.javac.code.Types) JCMethodInvocation(com.sun.tools.javac.tree.JCTree.JCMethodInvocation) ArrayDeque(java.util.ArrayDeque) NON_RECURSIVE(com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE) ArrayAccessTree(com.sun.source.tree.ArrayAccessTree) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) JCFieldAccess(com.sun.tools.javac.tree.JCTree.JCFieldAccess) PackageTree(com.sun.source.tree.PackageTree) JCAnnotatedType(com.sun.tools.javac.tree.JCTree.JCAnnotatedType) TypeVar(com.sun.tools.javac.code.Type.TypeVar) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) TypeTag(com.sun.tools.javac.code.TypeTag) JCMemberReference(com.sun.tools.javac.tree.JCTree.JCMemberReference) IdentifierTree(com.sun.source.tree.IdentifierTree) URI(java.net.URI) ImmutableSet(com.google.common.collect.ImmutableSet) DeferredDiagnosticHandler(com.sun.tools.javac.util.Log.DeferredDiagnosticHandler) SwitchTree(com.sun.source.tree.SwitchTree) Collectors(java.util.stream.Collectors) Preconditions.checkState(com.google.common.base.Preconditions.checkState) TypeKind(javax.lang.model.type.TypeKind) Objects(java.util.Objects) JavacTrees(com.sun.tools.javac.api.JavacTrees) List(java.util.List) CompletionFailure(com.sun.tools.javac.code.Symbol.CompletionFailure) Suppliers(com.google.errorprone.suppliers.Suppliers) Annotation(java.lang.annotation.Annotation) ModifiersTree(com.sun.source.tree.ModifiersTree) Optional(java.util.Optional) WhileLoopTree(com.sun.source.tree.WhileLoopTree) JCTypeParameter(com.sun.tools.javac.tree.JCTree.JCTypeParameter) Name(com.sun.tools.javac.util.Name) Type(com.sun.tools.javac.code.Type) AnnotationTree(com.sun.source.tree.AnnotationTree) MethodTree(com.sun.source.tree.MethodTree) BinaryTree(com.sun.source.tree.BinaryTree) Deque(java.util.Deque) HashSet(java.util.HashSet) JCPackageDecl(com.sun.tools.javac.tree.JCTree.JCPackageDecl) JUNIT4_RUN_WITH_ANNOTATION(com.google.errorprone.matchers.JUnitMatchers.JUNIT4_RUN_WITH_ANNOTATION) JCNewClass(com.sun.tools.javac.tree.JCTree.JCNewClass) ClassTree(com.sun.source.tree.ClassTree) IfTree(com.sun.source.tree.IfTree) ElementKind(javax.lang.model.element.ElementKind) MemberReferenceTree(com.sun.source.tree.MemberReferenceTree) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) JCTree(com.sun.tools.javac.tree.JCTree) NullnessAnalysis(com.google.errorprone.dataflow.nullnesspropagation.NullnessAnalysis) JUnitMatchers(com.google.errorprone.matchers.JUnitMatchers) DoWhileLoopTree(com.sun.source.tree.DoWhileLoopTree) Resolve(com.sun.tools.javac.comp.Resolve) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) ClassType(com.sun.tools.javac.code.Type.ClassType) JCAnnotatedType(com.sun.tools.javac.tree.JCTree.JCAnnotatedType) Type(com.sun.tools.javac.code.Type) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) Scope(com.sun.tools.javac.code.Scope) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) Symbol(com.sun.tools.javac.code.Symbol) PackageSymbol(com.sun.tools.javac.code.Symbol.PackageSymbol) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 4 with TypeSymbol

use of com.sun.tools.javac.code.Symbol.TypeSymbol in project error-prone by google.

the class WrongParameterPackage method matchMethod.

@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
    MethodSymbol method = ASTHelpers.getSymbol(tree);
    if (method == null) {
        return Description.NO_MATCH;
    }
    ClassSymbol classSym = method.enclClass();
    if (classSym == null) {
        return Description.NO_MATCH;
    }
    TypeSymbol superClass = classSym.getSuperclass().tsym;
    if (superClass == null) {
        return Description.NO_MATCH;
    }
    for (Symbol s : superClass.members().getSymbols()) {
        if (s.name.contentEquals(method.name) && s.getKind() == ElementKind.METHOD) {
            MethodSymbol supermethod = (MethodSymbol) s;
            // if this method actually overrides the supermethod, then it's correct and not a match.
            if (method.overrides(supermethod, superClass, state.getTypes(), /* checkResult= */
            true)) {
                return Description.NO_MATCH;
            }
            // if this doesn't have the right number of parameters, look at other ones.
            if (supermethod.params().size() != method.params().size()) {
                continue;
            }
            for (int x = 0; x < method.params().size(); x++) {
                Type methodParamType = method.params().get(x).type;
                Type supermethodParamType = supermethod.params().get(x).type;
                if (methodParamType.tsym.name.contentEquals(supermethodParamType.tsym.name) && !state.getTypes().isSameType(methodParamType, supermethodParamType)) {
                    this.supermethod = supermethod;
                    return describe(tree, state);
                }
            }
        }
    }
    return Description.NO_MATCH;
}
Also used : Type(com.sun.tools.javac.code.Type) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) Symbol(com.sun.tools.javac.code.Symbol) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol)

Example 5 with TypeSymbol

use of com.sun.tools.javac.code.Symbol.TypeSymbol in project error-prone by google.

the class ForOverrideChecker method matchMethodInvocation.

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
    MethodSymbol method = ASTHelpers.getSymbol(tree);
    if (method == null) {
        return Description.NO_MATCH;
    }
    Type currentClass = getOutermostClass(state);
    if (method.isStatic() || method.isConstructor() || currentClass == null) {
        return Description.NO_MATCH;
    }
    // allow super.foo() calls to @ForOverride methods from overriding methods
    if (isSuperCall(currentClass, tree, state)) {
        MethodTree currentMethod = findDirectMethod(state.getPath());
        // currentMethod might be null if we are in a field initializer
        if (currentMethod != null) {
            // MethodSymbol.overrides doesn't check that names match, so we need to do that first.
            if (currentMethod.getName().equals(method.name)) {
                MethodSymbol currentMethodSymbol = ASTHelpers.getSymbol(currentMethod);
                if (currentMethodSymbol.overrides(method, (TypeSymbol) method.owner, state.getTypes(), /* checkResult= */
                true)) {
                    return Description.NO_MATCH;
                }
            }
        }
    }
    List<MethodSymbol> overriddenMethods = getOverriddenMethods(state, method);
    for (Symbol overriddenMethod : overriddenMethods) {
        Type declaringClass = overriddenMethod.outermostClass().asType();
        if (!declaringClass.equals(currentClass)) {
            String customMessage = MESSAGE_BASE + "must not be invoked directly " + "(except by the declaring class, " + declaringClass + ")";
            return buildDescription(tree).setMessage(customMessage).build();
        }
    }
    return Description.NO_MATCH;
}
Also used : Type(com.sun.tools.javac.code.Type) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) MethodTree(com.sun.source.tree.MethodTree) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) Symbol(com.sun.tools.javac.code.Symbol)

Aggregations

TypeSymbol (com.sun.tools.javac.code.Symbol.TypeSymbol)25 Type (com.sun.tools.javac.code.Type)15 Symbol (com.sun.tools.javac.code.Symbol)13 MethodSymbol (com.sun.tools.javac.code.Symbol.MethodSymbol)11 ClassSymbol (com.sun.tools.javac.code.Symbol.ClassSymbol)9 VisitorState (com.google.errorprone.VisitorState)5 ClassTree (com.sun.source.tree.ClassTree)5 MethodTree (com.sun.source.tree.MethodTree)5 ClassType (com.sun.tools.javac.code.Type.ClassType)5 JCTree (com.sun.tools.javac.tree.JCTree)5 Tree (com.sun.source.tree.Tree)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 ImmutableSet (com.google.common.collect.ImmutableSet)3 CompletionFailure (com.sun.tools.javac.code.Symbol.CompletionFailure)3 PackageSymbol (com.sun.tools.javac.code.Symbol.PackageSymbol)3 AutoValue (com.google.auto.value.AutoValue)2 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)2 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)2 BugPattern (com.google.errorprone.BugPattern)2