Search in sources :

Example 1 with Modifier

use of javax.lang.model.element.Modifier in project epoxy by airbnb.

the class ProcessorUtils method implementsMethod.

/**
   * @return True if the clazz (or one of its superclasses) implements the given method. Returns
   * false if the method doesn't exist anywhere in the class hierarchy or it is abstract.
   */
static boolean implementsMethod(TypeElement clazz, MethodSpec method, Types typeUtils) {
    ExecutableElement methodOnClass = getMethodOnClass(clazz, method, typeUtils);
    if (methodOnClass == null) {
        return false;
    }
    Set<Modifier> modifiers = methodOnClass.getModifiers();
    return !modifiers.contains(Modifier.ABSTRACT);
}
Also used : ExecutableElement(javax.lang.model.element.ExecutableElement) Modifier(javax.lang.model.element.Modifier)

Example 2 with Modifier

use of javax.lang.model.element.Modifier in project epoxy by airbnb.

the class EpoxyProcessor method validateAccessibleViaGeneratedCode.

private void validateAccessibleViaGeneratedCode(Element attribute) {
    TypeElement enclosingElement = (TypeElement) attribute.getEnclosingElement();
    // Verify method modifiers.
    Set<Modifier> modifiers = attribute.getModifiers();
    if (modifiers.contains(PRIVATE) || modifiers.contains(STATIC)) {
        logError("%s annotations must not be on private or static fields. (class: %s, field: %s)", EpoxyAttribute.class.getSimpleName(), enclosingElement.getSimpleName(), attribute.getSimpleName());
    }
    // Nested classes must be static
    if (enclosingElement.getNestingKind().isNested()) {
        if (!enclosingElement.getModifiers().contains(STATIC)) {
            logError("Nested classes with %s annotations must be static. (class: %s, field: %s)", EpoxyAttribute.class.getSimpleName(), enclosingElement.getSimpleName(), attribute.getSimpleName());
        }
    }
    // Verify containing type.
    if (enclosingElement.getKind() != CLASS) {
        logError("%s annotations may only be contained in classes. (class: %s, field: %s)", EpoxyAttribute.class.getSimpleName(), enclosingElement.getSimpleName(), attribute.getSimpleName());
    }
    // Verify containing class visibility is not private.
    if (enclosingElement.getModifiers().contains(PRIVATE)) {
        logError("%s annotations may not be contained in private classes. (class: %s, field: %s)", EpoxyAttribute.class.getSimpleName(), enclosingElement.getSimpleName(), attribute.getSimpleName());
    }
}
Also used : TypeElement(javax.lang.model.element.TypeElement) Modifier(javax.lang.model.element.Modifier)

Example 3 with Modifier

use of javax.lang.model.element.Modifier in project javapoet by square.

the class MethodSpec method overriding.

/**
   * Returns a new method spec builder that overrides {@code method}.
   *
   * <p>This will copy its visibility modifiers, type parameters, return type, name, parameters, and
   * throws declarations. An {@link Override} annotation will be added.
   *
   * <p>Note that in JavaPoet 1.2 through 1.7 this method retained annotations from the method and
   * parameters of the overridden method. Since JavaPoet 1.8 annotations must be added separately.
   */
public static Builder overriding(ExecutableElement method) {
    checkNotNull(method, "method == null");
    Set<Modifier> modifiers = method.getModifiers();
    if (modifiers.contains(Modifier.PRIVATE) || modifiers.contains(Modifier.FINAL) || modifiers.contains(Modifier.STATIC)) {
        throw new IllegalArgumentException("cannot override method with modifiers: " + modifiers);
    }
    String methodName = method.getSimpleName().toString();
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName);
    methodBuilder.addAnnotation(Override.class);
    modifiers = new LinkedHashSet<>(modifiers);
    modifiers.remove(Modifier.ABSTRACT);
    // LinkedHashSet permits null as element for Java 7
    modifiers.remove(Util.DEFAULT);
    methodBuilder.addModifiers(modifiers);
    for (TypeParameterElement typeParameterElement : method.getTypeParameters()) {
        TypeVariable var = (TypeVariable) typeParameterElement.asType();
        methodBuilder.addTypeVariable(TypeVariableName.get(var));
    }
    methodBuilder.returns(TypeName.get(method.getReturnType()));
    methodBuilder.addParameters(ParameterSpec.parametersOf(method));
    methodBuilder.varargs(method.isVarArgs());
    for (TypeMirror thrownType : method.getThrownTypes()) {
        methodBuilder.addException(TypeName.get(thrownType));
    }
    return methodBuilder;
}
Also used : TypeVariable(javax.lang.model.type.TypeVariable) TypeMirror(javax.lang.model.type.TypeMirror) Modifier(javax.lang.model.element.Modifier) TypeParameterElement(javax.lang.model.element.TypeParameterElement)

Example 4 with Modifier

use of javax.lang.model.element.Modifier in project error-prone by google.

the class SuggestedFixes method addModifiers.

/** Add modifiers to the given class, method, or field declaration. */
@Nullable
public static SuggestedFix addModifiers(Tree tree, VisitorState state, Modifier... modifiers) {
    ModifiersTree originalModifiers = getModifiers(tree);
    if (originalModifiers == null) {
        return null;
    }
    Set<Modifier> toAdd = Sets.difference(new TreeSet<>(Arrays.asList(modifiers)), originalModifiers.getFlags());
    if (originalModifiers.getFlags().isEmpty()) {
        int pos = state.getEndPosition(originalModifiers) != Position.NOPOS ? state.getEndPosition(originalModifiers) + 1 : ((JCTree) tree).getStartPosition();
        int base = ((JCTree) tree).getStartPosition();
        java.util.Optional<Integer> insert = state.getTokensForNode(tree).stream().map(token -> token.pos() + base).filter(thisPos -> thisPos >= pos).findFirst();
        // shouldn't ever be able to get to the else
        int insertPos = insert.orElse(pos);
        return SuggestedFix.replace(insertPos, insertPos, Joiner.on(' ').join(toAdd) + " ");
    }
    // a map from modifiers to modifier position (or -1 if the modifier is being added)
    // modifiers are sorted in Google Java Style order
    Map<Modifier, Integer> modifierPositions = new TreeMap<>();
    for (Modifier mod : toAdd) {
        modifierPositions.put(mod, -1);
    }
    List<ErrorProneToken> tokens = state.getTokensForNode(originalModifiers);
    int base = ((JCTree) originalModifiers).getStartPosition();
    for (ErrorProneToken tok : tokens) {
        Modifier mod = getTokModifierKind(tok);
        if (mod != null) {
            modifierPositions.put(mod, base + tok.pos());
        }
    }
    SuggestedFix.Builder fix = SuggestedFix.builder();
    // walk the map of all modifiers, and accumulate a list of new modifiers to insert
    // beside an existing modifier
    List<Modifier> modifiersToWrite = new ArrayList<>();
    for (Modifier mod : modifierPositions.keySet()) {
        int p = modifierPositions.get(mod);
        if (p == -1) {
            modifiersToWrite.add(mod);
        } else if (!modifiersToWrite.isEmpty()) {
            fix.replace(p, p, Joiner.on(' ').join(modifiersToWrite) + " ");
            modifiersToWrite.clear();
        }
    }
    if (!modifiersToWrite.isEmpty()) {
        fix.postfixWith(originalModifiers, " " + Joiner.on(' ').join(modifiersToWrite));
    }
    return fix.build();
}
Also used : Arrays(java.util.Arrays) SimpleTypeVisitor8(javax.lang.model.util.SimpleTypeVisitor8) Modifier(javax.lang.model.element.Modifier) TreeScanner(com.sun.tools.javac.tree.TreeScanner) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) AssignmentTree(com.sun.source.tree.AssignmentTree) FluentIterable(com.google.common.collect.FluentIterable) Optional(com.google.common.base.Optional) Map(java.util.Map) NewArrayTree(com.sun.source.tree.NewArrayTree) ASTHelpers.getAnnotationWithSimpleName(com.google.errorprone.util.ASTHelpers.getAnnotationWithSimpleName) Builder(com.google.errorprone.fixes.SuggestedFix.Builder) ParenthesizedTree(com.sun.source.tree.ParenthesizedTree) ArrayType(javax.lang.model.type.ArrayType) TreePath(com.sun.source.util.TreePath) Function(com.google.common.base.Function) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) Position(com.sun.tools.javac.util.Position) ASTHelpers.getSymbol(com.google.errorprone.util.ASTHelpers.getSymbol) Symbol(com.sun.tools.javac.code.Symbol) Set(java.util.Set) Iterables.getLast(com.google.common.collect.Iterables.getLast) DocTreePath(com.sun.source.util.DocTreePath) Sets(com.google.common.collect.Sets) JavacTrees(com.sun.tools.javac.api.JavacTrees) List(java.util.List) Tokens(com.sun.tools.javac.parser.Tokens) ASTHelpers.getAnnotation(com.google.errorprone.util.ASTHelpers.getAnnotation) ModifiersTree(com.sun.source.tree.ModifiersTree) Type(com.sun.tools.javac.code.Type) Joiner(com.google.common.base.Joiner) AnnotationTree(com.sun.source.tree.AnnotationTree) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) CLASS(com.sun.tools.javac.code.TypeTag.CLASS) Deque(java.util.Deque) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) VisitorState(com.google.errorprone.VisitorState) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) DeclaredType(javax.lang.model.type.DeclaredType) Predicates(com.google.common.base.Predicates) NEW_ARRAY(com.sun.source.tree.Tree.Kind.NEW_ARRAY) StreamSupport(java.util.stream.StreamSupport) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) Nullable(javax.annotation.Nullable) ErrorProneToken(com.google.errorprone.util.ErrorProneToken) ElementKind(javax.lang.model.element.ElementKind) ExpressionTree(com.sun.source.tree.ExpressionTree) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) DCTree(com.sun.tools.javac.tree.DCTree) TreeMaker(com.sun.tools.javac.tree.TreeMaker) JCTree(com.sun.tools.javac.tree.JCTree) ASSIGNMENT(com.sun.source.tree.Tree.Kind.ASSIGNMENT) TypeMirror(javax.lang.model.type.TypeMirror) TreeMap(java.util.TreeMap) ASTHelpers.getModifiers(com.google.errorprone.util.ASTHelpers.getModifiers) PARENTHESIZED(com.sun.source.tree.Tree.Kind.PARENTHESIZED) DocTree(com.sun.source.doctree.DocTree) ArrayDeque(java.util.ArrayDeque) ModifiersTree(com.sun.source.tree.ModifiersTree) ArrayList(java.util.ArrayList) JCTree(com.sun.tools.javac.tree.JCTree) TreeMap(java.util.TreeMap) ErrorProneToken(com.google.errorprone.util.ErrorProneToken) Builder(com.google.errorprone.fixes.SuggestedFix.Builder) Modifier(javax.lang.model.element.Modifier) Nullable(javax.annotation.Nullable)

Example 5 with Modifier

use of javax.lang.model.element.Modifier in project error-prone by google.

the class FindIdentifiers method isVisible.

private static boolean isVisible(VarSymbol var, final TreePath path) {
    switch(var.getKind()) {
        case ENUM_CONSTANT:
        case FIELD:
            // TODO(eaftan): Switch collector to ImmutableList.toImmutableList() when released
            List<ClassSymbol> enclosingClasses = StreamSupport.stream(path.spliterator(), false).filter(tree -> tree instanceof ClassTree).map(ClassTree.class::cast).map(ASTHelpers::getSymbol).collect(Collectors.toCollection(ArrayList::new));
            if (!var.isStatic()) {
                // Instance fields are not visible if we are in a static context...
                if (inStaticContext(path)) {
                    return false;
                }
                // the enclosing static nested class (JLS 8.5.1).
                if (lowerThan(path, (curr, unused) -> curr instanceof ClassTree && ASTHelpers.getSymbol((ClassTree) curr).isStatic(), (curr, unused) -> curr instanceof ClassTree && ASTHelpers.getSymbol((ClassTree) curr).equals(var.owner))) {
                    return false;
                }
            }
            // fields (JLS 6.6.1).
            if (enclosingClasses.contains(ASTHelpers.enclosingClass(var))) {
                return true;
            }
            PackageSymbol enclosingPackage = ((JCCompilationUnit) path.getCompilationUnit()).packge;
            Set<Modifier> modifiers = var.getModifiers();
            // (JLS 6.6.1).
            if (Objects.equals(enclosingPackage, ASTHelpers.enclosingPackage(var))) {
                return !modifiers.contains(Modifier.PRIVATE);
            }
            // in the enclosing class or a superclass).
            return modifiers.contains(Modifier.PUBLIC) || modifiers.contains(Modifier.PROTECTED);
        case PARAMETER:
        case LOCAL_VARIABLE:
            // final or effectively final (JLS 8.1.3).
            if (lowerThan(path, (curr, parent) -> curr.getKind() == Kind.LAMBDA_EXPRESSION || (curr.getKind() == Kind.NEW_CLASS && ((NewClassTree) curr).getClassBody() != null) || (curr.getKind() == Kind.CLASS && parent.getKind() == Kind.BLOCK), (curr, unused) -> Objects.equals(var.owner, ASTHelpers.getSymbol(curr)))) {
                if ((var.flags() & (Flags.FINAL | Flags.EFFECTIVELY_FINAL)) == 0) {
                    return false;
                }
            }
            return true;
        case EXCEPTION_PARAMETER:
        case RESOURCE_VARIABLE:
            return true;
        default:
            throw new IllegalArgumentException("Unexpected variable type: " + var.getKind());
    }
}
Also used : MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) ClassType(com.sun.tools.javac.code.Type.ClassType) Modifier(javax.lang.model.element.Modifier) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) IdentifierTree(com.sun.source.tree.IdentifierTree) CatchTree(com.sun.source.tree.CatchTree) ForLoopTree(com.sun.source.tree.ForLoopTree) Method(java.lang.reflect.Method) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) TreePath(com.sun.source.util.TreePath) ImmutableSet(com.google.common.collect.ImmutableSet) Symbol(com.sun.tools.javac.code.Symbol) Set(java.util.Set) MemberSelectTree(com.sun.source.tree.MemberSelectTree) Env(com.sun.tools.javac.comp.Env) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) TreeScanner(com.sun.source.util.TreeScanner) Objects(java.util.Objects) List(java.util.List) WriteableScope(com.sun.tools.javac.code.Scope.WriteableScope) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) PackageSymbol(com.sun.tools.javac.code.Symbol.PackageSymbol) BlockTree(com.sun.source.tree.BlockTree) StatementTree(com.sun.source.tree.StatementTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) Flags(com.sun.tools.javac.code.Flags) Name(com.sun.tools.javac.util.Name) Scope(com.sun.tools.javac.code.Scope) Type(com.sun.tools.javac.code.Type) MethodTree(com.sun.source.tree.MethodTree) MemberEnter(com.sun.tools.javac.comp.MemberEnter) VariableTree(com.sun.source.tree.VariableTree) AttrContext(com.sun.tools.javac.comp.AttrContext) ArrayList(java.util.ArrayList) VisitorState(com.google.errorprone.VisitorState) BiPredicate(java.util.function.BiPredicate) Kind(com.sun.source.tree.Tree.Kind) ImmutableList(com.google.common.collect.ImmutableList) NewClassTree(com.sun.source.tree.NewClassTree) StreamSupport(java.util.stream.StreamSupport) ImportTree(com.sun.source.tree.ImportTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) Enter(com.sun.tools.javac.comp.Enter) ElementKind(javax.lang.model.element.ElementKind) KindSelector(com.sun.tools.javac.code.Kinds.KindSelector) TryTree(com.sun.source.tree.TryTree) Resolve(com.sun.tools.javac.comp.Resolve) JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) PackageSymbol(com.sun.tools.javac.code.Symbol.PackageSymbol) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) NewClassTree(com.sun.source.tree.NewClassTree) ClassTree(com.sun.source.tree.ClassTree) NewClassTree(com.sun.source.tree.NewClassTree) Modifier(javax.lang.model.element.Modifier)

Aggregations

Modifier (javax.lang.model.element.Modifier)21 TypeMirror (javax.lang.model.type.TypeMirror)7 TypeElement (javax.lang.model.element.TypeElement)6 Tree (com.sun.source.tree.Tree)5 AnnotationTree (com.sun.source.tree.AnnotationTree)4 ArrayList (java.util.ArrayList)4 Element (javax.lang.model.element.Element)4 ElementKind (javax.lang.model.element.ElementKind)4 ImmutableList (com.google.common.collect.ImmutableList)3 MethodTree (com.sun.source.tree.MethodTree)3 ModifiersTree (com.sun.source.tree.ModifiersTree)3 VariableTree (com.sun.source.tree.VariableTree)3 Nullable (javax.annotation.Nullable)3 ExecutableElement (javax.lang.model.element.ExecutableElement)3 Function (com.google.common.base.Function)2 ImmutableSet (com.google.common.collect.ImmutableSet)2 Sets (com.google.common.collect.Sets)2 VisitorState (com.google.errorprone.VisitorState)2 Builder (com.google.errorprone.fixes.SuggestedFix.Builder)2 ErrorProneToken (com.google.errorprone.util.ErrorProneToken)2