Search in sources :

Example 41 with ElementKind

use of javax.lang.model.element.ElementKind in project vertx-docgen by vert-x3.

the class Helper method resolveLink.

public Element resolveLink(String signature) {
    Matcher signatureMatcher = P.matcher(signature);
    if (signatureMatcher.find()) {
        String memberName = signatureMatcher.group(1);
        String typeName = signature.substring(0, signatureMatcher.start());
        TypeElement typeElt = elementUtils.getTypeElement(typeName);
        if (typeElt == null) {
            return null;
        }
        Predicate<? super Element> memberMatcher;
        if (signatureMatcher.group(2) != null) {
            String t = signatureMatcher.group(2).trim();
            Predicate<ExecutableElement> parametersMatcher;
            if (t.length() == 0) {
                parametersMatcher = exeElt -> exeElt.getParameters().isEmpty();
            } else {
                parametersMatcher = parametersMatcher(t.split("\\s*,\\s*"));
            }
            memberMatcher = elt -> matchesConstructor(elt, memberName, parametersMatcher) || matchesMethod(elt, memberName, parametersMatcher);
        } else {
            memberMatcher = elt -> matchesConstructor(elt, memberName, exeElt -> true) || matchesMethod(elt, memberName, exeElt -> true) || matchesFieldOrEnumConstant(elt, memberName);
        }
        // The order of kinds is important
        for (ElementKind kind : Arrays.asList(ElementKind.FIELD, ElementKind.ENUM_CONSTANT, ElementKind.CONSTRUCTOR, ElementKind.METHOD)) {
            for (Element memberElt : elementUtils.getAllMembers(typeElt)) {
                if (memberElt.getKind() == kind && memberMatcher.test(memberElt)) {
                    return memberElt;
                }
            }
        }
        return null;
    } else {
        Element elt = elementUtils.getTypeElement(signature);
        if (elt == null) {
            elt = elementUtils.getPackageElement(signature);
        }
        return elt;
    }
}
Also used : Arrays(java.util.Arrays) TypeElement(javax.lang.model.element.TypeElement) Elements(javax.lang.model.util.Elements) Matcher(java.util.regex.Matcher) DeclaredType(javax.lang.model.type.DeclaredType) ArrayType(javax.lang.model.type.ArrayType) ElementKind(javax.lang.model.element.ElementKind) ExecutableType(javax.lang.model.type.ExecutableType) Predicate(java.util.function.Predicate) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) IOException(java.io.IOException) Reader(java.io.Reader) Types(javax.lang.model.util.Types) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) TypeParameterElement(javax.lang.model.element.TypeParameterElement) TypeKind(javax.lang.model.type.TypeKind) TypeMirror(javax.lang.model.type.TypeMirror) List(java.util.List) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) PrimitiveType(javax.lang.model.type.PrimitiveType) TypeVariable(javax.lang.model.type.TypeVariable) Pattern(java.util.regex.Pattern) DocTrees(com.sun.source.util.DocTrees) ElementKind(javax.lang.model.element.ElementKind) Matcher(java.util.regex.Matcher) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) TypeParameterElement(javax.lang.model.element.TypeParameterElement)

Example 42 with ElementKind

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

the class JsonObjectProcessor method addAllNonPrivateAccessors.

private void addAllNonPrivateAccessors(Element element, Elements elements, Types types, JsonObjectHolder objectHolder) {
    List<? extends Element> enclosedElements = element.getEnclosedElements();
    for (Element enclosedElement : enclosedElements) {
        ElementKind enclosedElementKind = enclosedElement.getKind();
        if (enclosedElementKind == ElementKind.FIELD) {
            Set<Modifier> modifiers = enclosedElement.getModifiers();
            if (modifiers.contains(Modifier.PRIVATE) && !modifiers.contains(Modifier.TRANSIENT) && !modifiers.contains(Modifier.STATIC)) {
                String getter = JsonFieldHolder.getGetter(enclosedElement, elements);
                String setter = JsonFieldHolder.getSetter(enclosedElement, elements);
                if (!TextUtils.isEmpty(getter) && !TextUtils.isEmpty(setter)) {
                    createOrUpdateFieldHolder(enclosedElement, elements, types, objectHolder);
                }
            }
        }
    }
}
Also used : ElementKind(javax.lang.model.element.ElementKind) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) TypeParameterElement(javax.lang.model.element.TypeParameterElement) Modifier(javax.lang.model.element.Modifier)

Example 43 with ElementKind

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

the class JsonFieldProcessor method ensureTypeConverterClassValid.

private boolean ensureTypeConverterClassValid(TypeMirror typeConverterClassMirror, Elements elements, Types types) {
    TypeElement typeConverterElement = elements.getTypeElement(typeConverterClassMirror.toString());
    if (typeConverterElement != null) {
        boolean isTypeConverterType = false;
        TypeElement element = typeConverterElement;
        while (!isTypeConverterType && element != null) {
            for (TypeMirror iface : element.getInterfaces()) {
                if (types.erasure(iface).toString().equals(TypeConverter.class.getCanonicalName())) {
                    isTypeConverterType = true;
                }
            }
            TypeMirror superClassMirror = element.getSuperclass();
            if (superClassMirror != null) {
                superClassMirror = types.erasure(superClassMirror);
                element = elements.getTypeElement(superClassMirror.toString());
            } else {
                element = null;
            }
        }
        if (!isTypeConverterType) {
            error(element, "TypeConverter elements must implement the TypeConverter interface or extend from one of the convenience helpers (ie StringBasedTypeConverter or DateTypeConverter).");
            return false;
        }
        boolean constructorIsDeclared = false;
        boolean hasAccessibleConstructor = false;
        List<? extends Element> enclosedElements = typeConverterElement.getEnclosedElements();
        for (Element enclosedElement : enclosedElements) {
            ElementKind enclosedElementKind = enclosedElement.getKind();
            if (enclosedElementKind == ElementKind.CONSTRUCTOR) {
                constructorIsDeclared = true;
                if (!enclosedElement.getModifiers().contains(Modifier.PRIVATE)) {
                    ExecutableElement executableElement = (ExecutableElement) enclosedElement;
                    if (executableElement.getParameters().size() == 0) {
                        hasAccessibleConstructor = true;
                    }
                }
            }
        }
        if (constructorIsDeclared && !hasAccessibleConstructor) {
            error(element, "TypeConverter classes must have a non-private zero argument constructor.");
            return false;
        }
    }
    return true;
}
Also used : TypeConverter(com.bluelinelabs.logansquare.typeconverters.TypeConverter) ElementKind(javax.lang.model.element.ElementKind) TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) ExecutableElement(javax.lang.model.element.ExecutableElement)

Example 44 with ElementKind

use of javax.lang.model.element.ElementKind in project tiger by google.

the class DependencyInformationCollectorProcessor method process.

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
    utils = new Utils(processingEnv, env);
    if (annotations.isEmpty()) {
        return false;
    }
    boolean foundSomething = false;
    Element someElement = Iterables.getFirst(env.getElementsAnnotatedWith(Iterables.getFirst(annotations, null)), null);
    ElementKind elementKind = someElement.getKind();
    while (!(elementKind.equals(ElementKind.CLASS) || elementKind.equals(ElementKind.INTERFACE))) {
        someElement = someElement.getEnclosingElement();
        elementKind = someElement.getKind();
    }
    String suffix = ((TypeElement) someElement).getQualifiedName().toString().replace(".", "_");
    String uniqueSuffix = suffix + BaseEncoding.base64().encode(UUID.randomUUID().toString().getBytes());
    TypeSpec.Builder dependencyInfoCollectedBuilder = TypeSpec.classBuilder("DependencyInfo_" + uniqueSuffix).addModifiers(Modifier.PUBLIC, Modifier.FINAL);
    for (Element element : env.getElementsAnnotatedWith(Module.class)) {
        foundSomething = true;
        moduleStrings.add(element.toString());
    }
    String jsonString = gson.toJson(moduleStrings);
    dependencyInfoCollectedBuilder.addField(FieldSpec.builder(String.class, SharedNames.DEPENDENCY_INFORMATION_FIELD_NAME_MODULES, Modifier.PUBLIC, Modifier.FINAL).initializer("$S", jsonString).build());
    for (Element element : env.getElementsAnnotatedWith(MembersInjector.class)) {
        foundSomething = true;
        membersInjectors.add(element.toString());
    }
    jsonString = gson.toJson(membersInjectors);
    dependencyInfoCollectedBuilder.addField(FieldSpec.builder(String.class, SharedNames.DEPENDENCY_INFORMATION_FIELD_NAME_MEMBERS_INJECTORS, Modifier.PUBLIC, Modifier.FINAL).initializer("$S", jsonString).build());
    for (Element element : env.getElementsAnnotatedWith(ScopeDependency.class)) {
        foundSomething = true;
        scopeDependencies.add(element.toString());
    }
    if (!scopeDependencies.isEmpty()) {
        jsonString = gson.toJson(scopeDependencies);
        dependencyInfoCollectedBuilder.addField(FieldSpec.builder(String.class, SharedNames.DEPENDENCY_INFORMATION_FIELD_NAME_SCOPE_DEPENDENCIES, Modifier.PUBLIC, Modifier.FINAL).initializer("$S", jsonString).build());
    }
    for (Element element : env.getElementsAnnotatedWith(ScopedComponentNames.class)) {
        foundSomething = true;
        scopedComponentNames.add(element.toString());
    }
    if (!scopedComponentNames.isEmpty()) {
        jsonString = gson.toJson(scopedComponentNames);
        dependencyInfoCollectedBuilder.addField(FieldSpec.builder(String.class, SharedNames.DEPENDENCY_INFORMATION_FIELD_NAME_SCOPED_COMPONENT_NAMES, Modifier.PUBLIC, Modifier.FINAL).initializer("$S", jsonString).build());
    }
    for (Element element : env.getElementsAnnotatedWith(PackageForGenerated.class)) {
        foundSomething = true;
        jsonString = getPackageForGenerated((TypeElement) element);
        dependencyInfoCollectedBuilder.addField(FieldSpec.builder(String.class, SharedNames.DEPENDENCY_INFORMATION_FIELD_NAME_PACKAGE_FOR_GENERATED, Modifier.PUBLIC, Modifier.FINAL).initializer("$S", jsonString).build());
    }
    for (Element element : env.getElementsAnnotatedWith(Inject.class)) {
        if (element.getKind().equals(ElementKind.CONSTRUCTOR)) {
            Element classElement = element.getEnclosingElement();
            if (utils.getScopeType(classElement, null) != null) {
                foundSomething = true;
                ctorInjectedClassStrings.add(classElement.toString());
            }
        }
    }
    jsonString = gson.toJson(ctorInjectedClassStrings);
    dependencyInfoCollectedBuilder.addField(FieldSpec.builder(String.class, SharedNames.DEPENDENCY_INFORMATION_FIELD_NAME_CTOR_INJECTED_CLASSES, Modifier.PUBLIC, Modifier.FINAL).initializer("$S", jsonString).build());
    if (foundSomething) {
        writeJavaFile(SharedNames.DEPENDENCY_INFORMATION_PACKAGE_NAME, dependencyInfoCollectedBuilder.build());
    }
    return false;
}
Also used : ElementKind(javax.lang.model.element.ElementKind) TypeElement(javax.lang.model.element.TypeElement) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 45 with ElementKind

use of javax.lang.model.element.ElementKind in project tiger by google.

the class Tiger2InjectorGenerator method generateInjectorBuilder.

/**
 * Subcomponents has 1 ctor parameter, which is the parent (sub)component. Components has 0 ctor
 * parameter and 0 or more dependecies.
 */
protected void generateInjectorBuilder(@Nullable TypeElement expliciteBuilder) {
    messager.printMessage(Kind.NOTE, "generateInjectorBuilder, component: " + eitherComponent + " explicit: " + (expliciteBuilder != null));
    Preconditions.checkArgument(utils.isEitherComponent(eitherComponent), "Expect (sub)component, but found: " + eitherComponent);
    boolean explicit = expliciteBuilder != null;
    boolean isSubcomponent = utils.isSubcomponent(eitherComponent);
    messager.printMessage(Kind.NOTE, "generateInjectorBuilder, pos: 1");
    String packageString = utils.getPackageString(eitherComponent);
    String generatedComponentSimpleName = utils.getComponentImplementationSimpleNameFromInterface(eitherComponent);
    ClassName componentClassName = ClassName.get(packageString, generatedComponentSimpleName);
    messager.printMessage(Kind.NOTE, "generateInjectorBuilder, pos: 2");
    // Generate class header.
    String builderName = explicit ? expliciteBuilder.getSimpleName().toString() : "Builder";
    Builder builderBuilder = TypeSpec.classBuilder(builderName).addModifiers(Modifier.PUBLIC, Modifier.STATIC);
    messager.printMessage(Kind.NOTE, "generateInjectorBuilder, pos: 3");
    if (explicit) {
        ElementKind kind = expliciteBuilder.getKind();
        ClassName superName = ClassName.get(eitherComponent).nestedClass(builderName);
        if (kind.equals(ElementKind.INTERFACE)) {
            builderBuilder.addSuperinterface(superName);
        } else {
            Preconditions.checkState(kind.equals(ElementKind.CLASS), TAG + " unexpected kind for builder: " + expliciteBuilder);
            builderBuilder.superclass(superName);
        }
    }
    messager.printMessage(Kind.NOTE, "generateInjectorBuilder, pos: 4");
    // ctor for subcomponent.
    if (isSubcomponent) {
        TypeName parentComponentTypeName = TypeName.get(parentEitherComponent.asType());
        String parentComponentSourceCodeName = Utils.getSourceCodeName(parentComponentTypeName);
        builderBuilder.addField(FieldSpec.builder(parentComponentTypeName, parentComponentSourceCodeName, Modifier.PRIVATE).build());
        MethodSpec.Builder ctorBuilder = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC);
        ctorBuilder.addParameter(parentComponentTypeName, parentComponentSourceCodeName).addCode("this.$N = $N;", parentComponentSourceCodeName, parentComponentSourceCodeName);
        builderBuilder.addMethod(ctorBuilder.build());
    } else {
        // setter for parent component.
        ClassName dependencyClassName = null;
        if (explicit && parentEitherComponent != null) {
            dependencyClassName = (ClassName) ClassName.get(parentEitherComponent.asType());
            String methodName = explicit ? utils.getBuilderSetterName(types, elements, expliciteBuilder, parentEitherComponent) : null;
            if (methodName != null || !explicit) {
                utils.addSetMethod(types, elements, componentClassName, builderBuilder, dependencyClassName, methodName, builderName);
            }
        }
    }
    messager.printMessage(Kind.NOTE, "generateInjectorBuilder, pos: 5");
    /**
     * Set deps methods.
     */
    for (TypeElement m : componentDependencies) {
        String methodName = explicit ? Preconditions.checkNotNull(utils.getBuilderSetterName(types, elements, expliciteBuilder, m)) : null;
        logger.l(Kind.NOTE, "componentDependency: %s", m);
        utils.addSetMethod(types, elements, componentClassName, builderBuilder, ClassName.get(m.asType()), methodName, builderName);
    }
    messager.printMessage(Kind.NOTE, "generateInjectorBuilder, pos: 6");
    /**
     * Set @BindsInstance methods.
     */
    /**
     * TODO: refactor this. see {@link #collectComponentToBindsInstanceMap()}
     */
    // if (isSubcomponent) {
    // instanceDeps.remove(BindingKey.get(componentToParentMap.get(component)));
    // } else {
    // if (dependencyComponent != null) {
    // instanceDeps.remove(BindingKey.get(dependencyComponent));
    // }
    // }
    // for (TypeElement typeElement :componentToComponentDependencyMap.get(component)) {
    // instanceDeps.remove(BindingKey.get(typeElement));
    // }
    // for (TypeElement typeElement :sortedPassedModules) {
    // instanceDeps.remove(BindingKey.get(typeElement));
    // }
    messager.printMessage(Kind.NOTE, TAG + ".generateInjectorBuilder instanceDeps" + bindsInstances);
    for (BindingKey key : bindsInstances) {
        String methodName = explicit ? Preconditions.checkNotNull(utils.getBuilderSetterName(types, elements, expliciteBuilder, key)) : null;
        ClassName builderParentClassName = componentClassName;
        if (explicit) {
            ExecutableElement setter = utils.getBuilderSetter(types, elements, expliciteBuilder, key);
            if (setter.getReturnType().getKind() == TypeKind.VOID) {
                builderParentClassName = null;
            }
        }
        messager.printMessage(Kind.NOTE, TAG + " generateInjectorBuilder @BindsInstance " + key);
        utils.addSetMethod(types, elements, builderParentClassName, builderBuilder, key.getTypeName(), methodName, builderName);
    }
    messager.printMessage(Kind.NOTE, "generateInjectorBuilder, pos: 7");
    /**
     * Set module methods.
     */
    for (TypeElement m : nonNullaryCtorModules) {
        String methodName = explicit ? Preconditions.checkNotNull(utils.getBuilderSetterName(types, elements, expliciteBuilder, m)) : null;
        logger.l(Kind.NOTE, "nonNullaryCtorModules: %s", m);
        utils.addSetMethod(types, elements, componentClassName, builderBuilder, ClassName.get(m.asType()), methodName, builderName);
    }
    // build() method.
    String methodName = explicit ? utils.getBuildMethod(processingEnv.getTypeUtils(), elements, expliciteBuilder).getSimpleName().toString() : "build";
    MethodSpec.Builder buildMethodBuilder = MethodSpec.methodBuilder(methodName).addModifiers(Modifier.PUBLIC).returns(componentClassName);
    StringBuilder returnCodeBuilder = new StringBuilder("return new $T(");
    for (BindingKey key : utils.sortBindingKeys(getAllCtorParameters())) {
        returnCodeBuilder.append(Utils.getSourceCodeNameHandlingBox(key, dependencies)).append(", ");
    }
    if (returnCodeBuilder.charAt(returnCodeBuilder.length() - 1) != '(') {
        returnCodeBuilder.delete(returnCodeBuilder.length() - 2, returnCodeBuilder.length());
    }
    returnCodeBuilder.append(");");
    messager.printMessage(Kind.NOTE, "generateInjectorBuilder, return string: " + returnCodeBuilder.toString());
    buildMethodBuilder.addCode(returnCodeBuilder.toString(), componentClassName);
    builderBuilder.addMethod(buildMethodBuilder.build());
    injectorBuilder.addType(builderBuilder.build());
}
Also used : ElementKind(javax.lang.model.element.ElementKind) TypeName(com.squareup.javapoet.TypeName) MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) Builder(com.squareup.javapoet.TypeSpec.Builder) ExecutableElement(javax.lang.model.element.ExecutableElement) ClassName(com.squareup.javapoet.ClassName)

Aggregations

ElementKind (javax.lang.model.element.ElementKind)50 TypeElement (javax.lang.model.element.TypeElement)27 Element (javax.lang.model.element.Element)25 ExecutableElement (javax.lang.model.element.ExecutableElement)23 VariableElement (javax.lang.model.element.VariableElement)13 TypeMirror (javax.lang.model.type.TypeMirror)13 PackageElement (javax.lang.model.element.PackageElement)9 ArrayList (java.util.ArrayList)8 AnnotationMirror (javax.lang.model.element.AnnotationMirror)7 LinkedHashSet (java.util.LinkedHashSet)6 ClassName (com.squareup.javapoet.ClassName)5 MethodSpec (com.squareup.javapoet.MethodSpec)5 TypeName (com.squareup.javapoet.TypeName)5 HashSet (java.util.HashSet)5 Modifier (javax.lang.model.element.Modifier)5 CodeVariableElement (com.oracle.truffle.dsl.processor.java.model.CodeVariableElement)4 HashMap (java.util.HashMap)4 Set (java.util.Set)4 TypeParameterElement (javax.lang.model.element.TypeParameterElement)4 CodeTypeMirror (com.oracle.truffle.dsl.processor.java.model.CodeTypeMirror)3