Search in sources :

Example 96 with Element

use of javax.lang.model.element.Element in project bazel by bazelbuild.

the class ElementUtils method enclosingClass.

/**
     * Returns the innermost type element enclosing the given element
     *
     * @param elem the enclosed element of a class
     * @return  the innermost type element
     */
public static TypeElement enclosingClass(final Element elem) {
    Element result = elem;
    while (result != null && !result.getKind().isClass() && !result.getKind().isInterface()) {
        /*@Nullable*/
        Element encl = result.getEnclosingElement();
        result = encl;
    }
    return (TypeElement) result;
}
Also used : TypeElement(javax.lang.model.element.TypeElement) PackageElement(javax.lang.model.element.PackageElement) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element)

Example 97 with Element

use of javax.lang.model.element.Element in project bazel by bazelbuild.

the class Resolver method findMethod.

/**
     * Finds the method element for a given name and list of expected parameter
     * types.
     *
     * <p>
     * The method adheres to all the rules of Java's scoping (while also
     * considering the imports) for name resolution.
     *
     * @param methodName
     *            Name of the method to find.
     * @param receiverType
     *            Type of the receiver of the method
     * @param path
     *            Tree path.
     * @return The method element (if found).
     */
public Element findMethod(String methodName, TypeMirror receiverType, TreePath path, java.util.List<TypeMirror> argumentTypes) {
    Log.DiagnosticHandler discardDiagnosticHandler = new Log.DiscardDiagnosticHandler(log);
    try {
        JavacScope scope = (JavacScope) trees.getScope(path);
        Env<AttrContext> env = scope.getEnv();
        Type site = (Type) receiverType;
        Name name = names.fromString(methodName);
        List<Type> argtypes = List.nil();
        for (TypeMirror a : argumentTypes) {
            argtypes = argtypes.append((Type) a);
        }
        List<Type> typeargtypes = List.nil();
        boolean allowBoxing = true;
        boolean useVarargs = false;
        boolean operator = true;
        try {
            // For some reason we have to set our own method context, which is rather ugly.
            // TODO: find a nicer way to do this.
            Object methodContext = buildMethodContext();
            Object oldContext = getField(resolve, "currentResolutionContext");
            setField(resolve, "currentResolutionContext", methodContext);
            Element result = wrapInvocation(FIND_METHOD, env, site, name, argtypes, typeargtypes, allowBoxing, useVarargs, operator);
            setField(resolve, "currentResolutionContext", oldContext);
            return result;
        } catch (Throwable t) {
            Error err = new AssertionError("Unexpected Reflection error");
            err.initCause(t);
            throw err;
        }
    } finally {
        log.popDiagnosticHandler(discardDiagnosticHandler);
    }
}
Also used : Log(com.sun.tools.javac.util.Log) VariableElement(javax.lang.model.element.VariableElement) Element(javax.lang.model.element.Element) JavacScope(com.sun.tools.javac.api.JavacScope) AttrContext(com.sun.tools.javac.comp.AttrContext) Name(com.sun.tools.javac.util.Name) Type(com.sun.tools.javac.code.Type) TypeMirror(javax.lang.model.type.TypeMirror)

Example 98 with Element

use of javax.lang.model.element.Element 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 99 with Element

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

the class AutoFactoryProcessor method doProcess.

private void doProcess(RoundEnvironment roundEnv) {
    for (Element element : roundEnv.getElementsAnnotatedWith(Provided.class)) {
        providedChecker.checkProvidedParameter(element);
    }
    ImmutableListMultimap.Builder<String, FactoryMethodDescriptor> indexedMethods = ImmutableListMultimap.builder();
    ImmutableSetMultimap.Builder<String, ImplementationMethodDescriptor> implementationMethodDescriptorsBuilder = ImmutableSetMultimap.builder();
    for (Element element : roundEnv.getElementsAnnotatedWith(AutoFactory.class)) {
        Optional<AutoFactoryDeclaration> declaration = declarationFactory.createIfValid(element);
        if (declaration.isPresent()) {
            String factoryName = declaration.get().getFactoryName();
            TypeElement extendingType = declaration.get().extendingType();
            implementationMethodDescriptorsBuilder.putAll(factoryName, implementationMethods(extendingType, element));
            for (TypeElement implementingType : declaration.get().implementingTypes()) {
                implementationMethodDescriptorsBuilder.putAll(factoryName, implementationMethods(implementingType, element));
            }
        }
        ImmutableSet<FactoryMethodDescriptor> descriptors = factoryDescriptorGenerator.generateDescriptor(element);
        for (FactoryMethodDescriptor descriptor : descriptors) {
            indexedMethods.put(descriptor.factoryName(), descriptor);
        }
    }
    ImmutableSetMultimap<String, ImplementationMethodDescriptor> implementationMethodDescriptors = implementationMethodDescriptorsBuilder.build();
    for (Entry<String, Collection<FactoryMethodDescriptor>> entry : indexedMethods.build().asMap().entrySet()) {
        ImmutableSet.Builder<TypeMirror> extending = ImmutableSet.builder();
        ImmutableSortedSet.Builder<TypeMirror> implementing = ImmutableSortedSet.orderedBy(new Comparator<TypeMirror>() {

            @Override
            public int compare(TypeMirror first, TypeMirror second) {
                String firstName = MoreTypes.asTypeElement(first).getQualifiedName().toString();
                String secondName = MoreTypes.asTypeElement(second).getQualifiedName().toString();
                return firstName.compareTo(secondName);
            }
        });
        boolean publicType = false;
        Boolean allowSubclasses = null;
        boolean skipCreation = false;
        for (FactoryMethodDescriptor methodDescriptor : entry.getValue()) {
            extending.add(methodDescriptor.declaration().extendingType().asType());
            for (TypeElement implementingType : methodDescriptor.declaration().implementingTypes()) {
                implementing.add(implementingType.asType());
            }
            publicType |= methodDescriptor.publicMethod();
            if (allowSubclasses == null) {
                allowSubclasses = methodDescriptor.declaration().allowSubclasses();
            } else if (!allowSubclasses.equals(methodDescriptor.declaration().allowSubclasses())) {
                skipCreation = true;
                messager.printMessage(Kind.ERROR, "Cannot mix allowSubclasses=true and allowSubclasses=false in one factory.", methodDescriptor.declaration().target(), methodDescriptor.declaration().mirror(), methodDescriptor.declaration().valuesMap().get("allowSubclasses"));
            }
        }
        if (!skipCreation) {
            try {
                factoryWriter.writeFactory(FactoryDescriptor.create(entry.getKey(), Iterables.getOnlyElement(extending.build()), implementing.build(), publicType, ImmutableSet.copyOf(entry.getValue()), implementationMethodDescriptors.get(entry.getKey()), allowSubclasses));
            } catch (IOException e) {
                messager.printMessage(Kind.ERROR, "failed");
            }
        }
    }
}
Also used : TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) ImmutableSet(com.google.common.collect.ImmutableSet) TypeMirror(javax.lang.model.type.TypeMirror) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) TypeElement(javax.lang.model.element.TypeElement) IOException(java.io.IOException) Collection(java.util.Collection)

Example 100 with Element

use of javax.lang.model.element.Element 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)

Aggregations

Element (javax.lang.model.element.Element)286 TypeElement (javax.lang.model.element.TypeElement)227 ExecutableElement (javax.lang.model.element.ExecutableElement)148 VariableElement (javax.lang.model.element.VariableElement)96 TypeMirror (javax.lang.model.type.TypeMirror)68 PackageElement (javax.lang.model.element.PackageElement)48 ArrayList (java.util.ArrayList)39 DeclaredType (javax.lang.model.type.DeclaredType)30 IOException (java.io.IOException)29 Map (java.util.Map)26 HashSet (java.util.HashSet)23 LinkedHashSet (java.util.LinkedHashSet)22 List (java.util.List)22 Set (java.util.Set)22 Test (org.junit.Test)21 ElementKind (javax.lang.model.element.ElementKind)20 AnnotationMirror (javax.lang.model.element.AnnotationMirror)19 Elements (javax.lang.model.util.Elements)18 HashMap (java.util.HashMap)16 LinkedHashMap (java.util.LinkedHashMap)15