Search in sources :

Example 26 with AnnotationMirror

use of javax.lang.model.element.AnnotationMirror in project LoganSquare by bluelinelabs.

the class MethodProcessor method isCallbackMethodAnnotationValid.

public boolean isCallbackMethodAnnotationValid(Element element, String annotationName) {
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
    if (enclosingElement.getAnnotation(JsonObject.class) == null) {
        error(enclosingElement, "%s: @%s methods can only be in classes annotated with @%s.", enclosingElement.getQualifiedName(), annotationName, JsonObject.class.getSimpleName());
        return false;
    }
    ExecutableElement executableElement = (ExecutableElement) element;
    if (executableElement.getParameters().size() > 0) {
        error(element, "%s: @%s methods must not take any parameters.", enclosingElement.getQualifiedName(), annotationName);
        return false;
    }
    List<? extends Element> allElements = enclosingElement.getEnclosedElements();
    int methodInstances = 0;
    for (Element enclosedElement : allElements) {
        for (AnnotationMirror am : enclosedElement.getAnnotationMirrors()) {
            if (am.getAnnotationType().asElement().getSimpleName().toString().equals(annotationName)) {
                methodInstances++;
            }
        }
    }
    if (methodInstances != 1) {
        error(element, "%s: There can only be one @%s method per class.", enclosingElement.getQualifiedName(), annotationName);
        return false;
    }
    return true;
}
Also used : AnnotationMirror(javax.lang.model.element.AnnotationMirror) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) JsonObject(com.bluelinelabs.logansquare.annotation.JsonObject)

Example 27 with AnnotationMirror

use of javax.lang.model.element.AnnotationMirror in project auto by google.

the class AutoValueProcessor method getFieldOfClasses.

/**
   * Returns the contents of a {@code Class[]}-typed field in an annotation.
   *
   * <p>This method is needed because directly reading the value of such a field from an
   * AnnotationMirror throws: <pre>
   * javax.lang.model.type.MirroredTypeException: Attempt to access Class object for TypeMirror Foo.
   * </pre>
   *
   * @param element The element on which the annotation is present. e.g. the class being processed
   *     by AutoValue.
   * @param annotation The class of the annotation to read from., e.g. {@link
   *     AutoValue.CopyAnnotations}.
   * @param fieldName The name of the field to read, e.g. "exclude".
   * @return a set of fully-qualified names of classes appearing in 'fieldName' on 'annotation' on
   *     'element'.
   */
private ImmutableSet<String> getFieldOfClasses(Element element, Class<? extends Annotation> annotation, String fieldName, Elements elementUtils) {
    TypeElement annotationElement = elementUtils.getTypeElement(annotation.getCanonicalName());
    if (annotationElement == null) {
        // This can happen if the annotation is on the -processorpath but not on the -classpath.
        return ImmutableSet.of();
    }
    TypeMirror annotationMirror = annotationElement.asType();
    for (AnnotationMirror annot : element.getAnnotationMirrors()) {
        if (!typeUtils.isSameType(annot.getAnnotationType(), annotationMirror)) {
            continue;
        }
        for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annot.getElementValues().entrySet()) {
            if (fieldName.contentEquals(entry.getKey().getSimpleName())) {
                ImmutableSet.Builder<String> result = ImmutableSet.builder();
                @SuppressWarnings("unchecked") List<AnnotationValue> annotationsToCopy = (List<AnnotationValue>) entry.getValue().getValue();
                for (AnnotationValue annotationValue : annotationsToCopy) {
                    String qualifiedName = ((TypeElement) ((DeclaredType) annotationValue.getValue()).asElement()).getQualifiedName().toString();
                    result.add(qualifiedName);
                }
                return result.build();
            }
        }
    }
    return ImmutableSet.of();
}
Also used : TypeElement(javax.lang.model.element.TypeElement) AnnotationMirror(javax.lang.model.element.AnnotationMirror) ImmutableSet(com.google.common.collect.ImmutableSet) TypeMirror(javax.lang.model.type.TypeMirror) AnnotationValue(javax.lang.model.element.AnnotationValue) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableBiMap(com.google.common.collect.ImmutableBiMap) DeclaredType(javax.lang.model.type.DeclaredType)

Example 28 with AnnotationMirror

use of javax.lang.model.element.AnnotationMirror in project auto by google.

the class FactoryDescriptorGenerator method generateDescriptor.

ImmutableSet<FactoryMethodDescriptor> generateDescriptor(Element element) {
    final AnnotationMirror mirror = Mirrors.getAnnotationMirror(element, AutoFactory.class).get();
    final Optional<AutoFactoryDeclaration> declaration = declarationFactory.createIfValid(element);
    if (!declaration.isPresent()) {
        return ImmutableSet.of();
    }
    return element.accept(new ElementKindVisitor6<ImmutableSet<FactoryMethodDescriptor>, Void>() {

        @Override
        protected ImmutableSet<FactoryMethodDescriptor> defaultAction(Element e, Void p) {
            throw new AssertionError("@AutoFactory applied to an impossible element");
        }

        @Override
        public ImmutableSet<FactoryMethodDescriptor> visitTypeAsClass(TypeElement type, Void p) {
            if (type.getModifiers().contains(ABSTRACT)) {
                // applied to an abstract factory
                messager.printMessage(ERROR, "Auto-factory doesn't support being applied to abstract classes.", type, mirror);
                return ImmutableSet.of();
            } else {
                // applied to the type to be created
                ImmutableSet<ExecutableElement> constructors = Elements2.getConstructors(type);
                if (constructors.isEmpty()) {
                    return generateDescriptorForDefaultConstructor(declaration.get(), type);
                } else {
                    return FluentIterable.from(constructors).transform(new Function<ExecutableElement, FactoryMethodDescriptor>() {

                        @Override
                        public FactoryMethodDescriptor apply(ExecutableElement constructor) {
                            return generateDescriptorForConstructor(declaration.get(), constructor);
                        }
                    }).toSet();
                }
            }
        }

        @Override
        public ImmutableSet<FactoryMethodDescriptor> visitTypeAsInterface(TypeElement type, Void p) {
            // applied to the factory interface
            messager.printMessage(ERROR, "Auto-factory doesn't support being applied to interfaces.", type, mirror);
            return ImmutableSet.of();
        }

        @Override
        public ImmutableSet<FactoryMethodDescriptor> visitExecutableAsConstructor(ExecutableElement e, Void p) {
            // applied to a constructor of a type to be created
            return ImmutableSet.of(generateDescriptorForConstructor(declaration.get(), e));
        }
    }, null);
}
Also used : TypeElement(javax.lang.model.element.TypeElement) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) ExecutableElement(javax.lang.model.element.ExecutableElement) AnnotationMirror(javax.lang.model.element.AnnotationMirror) AutoFactory(com.google.auto.factory.AutoFactory) ImmutableSet(com.google.common.collect.ImmutableSet)

Example 29 with AnnotationMirror

use of javax.lang.model.element.AnnotationMirror in project auto by google.

the class FactoryWriter method parameters.

/**
   * {@link ParameterSpec}s to match {@code parameters}. Note that the type of the {@link
   * ParameterSpec}s match {@link Parameter#type()} and not {@link Key#type()}.
   */
private static Iterable<ParameterSpec> parameters(Iterable<Parameter> parameters) {
    ImmutableList.Builder<ParameterSpec> builder = ImmutableList.builder();
    for (Parameter parameter : parameters) {
        ParameterSpec.Builder parameterBuilder = ParameterSpec.builder(TypeName.get(parameter.type()), parameter.name());
        for (AnnotationMirror annotation : Iterables.concat(parameter.nullable().asSet(), parameter.key().qualifier().asSet())) {
            parameterBuilder.addAnnotation(AnnotationSpec.get(annotation));
        }
        builder.add(parameterBuilder.build());
    }
    return builder.build();
}
Also used : AnnotationMirror(javax.lang.model.element.AnnotationMirror) ParameterSpec(com.squareup.javapoet.ParameterSpec) ImmutableList(com.google.common.collect.ImmutableList)

Example 30 with AnnotationMirror

use of javax.lang.model.element.AnnotationMirror in project auto by google.

the class Key method create.

/**
   * Constructs a key based on the type {@code type} and any {@link Qualifier}s in {@code
   * annotations}.
   *
   * <p>If {@code type} is a {@code Provider<T>}, the returned {@link Key}'s {@link #type()} is
   * {@code T}. If {@code type} is a primitive, the returned {@link Key}'s {@link #type()} is the
   * corresponding {@linkplain Types#boxedClass(PrimitiveType) boxed type}.
   *
   * <p>For example:
   * <table>
   *   <tr><th>Input type                <th>{@code Key.type()}
   *   <tr><td>{@code String}            <td>{@code String}
   *   <tr><td>{@code Provider<String>}  <td>{@code String}
   *   <tr><td>{@code int}               <td>{@code Integer}
   * </table>
   */
static Key create(TypeMirror type, Iterable<? extends AnnotationMirror> annotations, Types types) {
    ImmutableSet.Builder<AnnotationMirror> qualifiers = ImmutableSet.builder();
    for (AnnotationMirror annotation : annotations) {
        if (isAnnotationPresent(annotation.getAnnotationType().asElement(), Qualifier.class)) {
            qualifiers.add(annotation);
        }
    }
    // TODO(gak): check for only one qualifier rather than using the first
    Optional<AnnotationMirror> qualifier = FluentIterable.from(qualifiers.build()).first();
    TypeMirror keyType = isProvider(type) ? MoreTypes.asDeclared(type).getTypeArguments().get(0) : boxedType(type, types);
    return new AutoValue_Key(keyType, wrapOptionalInEquivalence(AnnotationMirrors.equivalence(), qualifier));
}
Also used : AnnotationMirror(javax.lang.model.element.AnnotationMirror) ImmutableSet(com.google.common.collect.ImmutableSet) TypeMirror(javax.lang.model.type.TypeMirror)

Aggregations

AnnotationMirror (javax.lang.model.element.AnnotationMirror)88 TypeElement (javax.lang.model.element.TypeElement)46 AnnotationValue (javax.lang.model.element.AnnotationValue)21 Element (javax.lang.model.element.Element)19 DeclaredType (javax.lang.model.type.DeclaredType)19 ExecutableElement (javax.lang.model.element.ExecutableElement)18 VariableElement (javax.lang.model.element.VariableElement)16 TypeMirror (javax.lang.model.type.TypeMirror)16 ArrayList (java.util.ArrayList)15 HashSet (java.util.HashSet)13 List (java.util.List)12 Map (java.util.Map)10 PackageElement (javax.lang.model.element.PackageElement)7 HashMap (java.util.HashMap)5 Nullable (javax.annotation.Nullable)5 IOException (java.io.IOException)4 MoreElements.getAnnotationMirror (com.google.auto.common.MoreElements.getAnnotationMirror)3 ImmutableList (com.google.common.collect.ImmutableList)3 ImmutableSet (com.google.common.collect.ImmutableSet)3 ClassName (com.squareup.javapoet.ClassName)3