Search in sources :

Example 66 with TypeElement

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

the class TreeBuilder method buildNextMethodAccess.

/**
     * Builds an AST Tree to access the next() method of an iterator.
     *
     * @param iteratorExpr  an expression whose type is a subtype of Iterator
     * @return  a MemberSelectTree that accesses the next() method of
     *    the expression
     */
public MemberSelectTree buildNextMethodAccess(ExpressionTree iteratorExpr) {
    DeclaredType exprType = (DeclaredType) InternalUtils.typeOf(iteratorExpr);
    assert exprType != null : "expression must be of declared type Iterator<>";
    TypeElement exprElement = (TypeElement) exprType.asElement();
    // Find the next() method of the iterator type
    Symbol.MethodSymbol nextMethod = null;
    for (ExecutableElement method : ElementFilter.methodsIn(elements.getAllMembers(exprElement))) {
        Name methodName = method.getSimpleName();
        if (method.getParameters().size() == 0) {
            if (methodName.contentEquals("next")) {
                nextMethod = (Symbol.MethodSymbol) method;
            }
        }
    }
    assert nextMethod != null : "no next method declared for expression type";
    Type.MethodType methodType = (Type.MethodType) nextMethod.asType();
    Symbol.TypeSymbol methodClass = methodType.asElement();
    Type elementType;
    if (exprType.getTypeArguments().size() > 0) {
        elementType = (Type) exprType.getTypeArguments().get(0);
    } else {
        elementType = symtab.objectType;
    }
    // Replace the next method's generic return type with
    // the actual element type of the expression.
    Type.MethodType updatedMethodType = new Type.MethodType(com.sun.tools.javac.util.List.<Type>nil(), elementType, com.sun.tools.javac.util.List.<Type>nil(), methodClass);
    JCTree.JCFieldAccess nextAccess = (JCTree.JCFieldAccess) maker.Select((JCTree.JCExpression) iteratorExpr, nextMethod);
    nextAccess.setType(updatedMethodType);
    return nextAccess;
}
Also used : TypeElement(javax.lang.model.element.TypeElement) Symbol(com.sun.tools.javac.code.Symbol) ExecutableElement(javax.lang.model.element.ExecutableElement) JCTree(com.sun.tools.javac.tree.JCTree) Name(javax.lang.model.element.Name) DeclaredType(javax.lang.model.type.DeclaredType) ArrayType(javax.lang.model.type.ArrayType) Type(com.sun.tools.javac.code.Type) DeclaredType(javax.lang.model.type.DeclaredType)

Example 67 with TypeElement

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

the class TreeBuilder method getValueOfMethod.

/**
     * Returns the valueOf method of a boxed type such as Short or Float.
     */
public static Symbol.MethodSymbol getValueOfMethod(ProcessingEnvironment env, TypeMirror boxedType) {
    Symbol.MethodSymbol valueOfMethod = null;
    TypeMirror unboxedType = env.getTypeUtils().unboxedType(boxedType);
    TypeElement boxedElement = (TypeElement) ((DeclaredType) boxedType).asElement();
    for (ExecutableElement method : ElementFilter.methodsIn(env.getElementUtils().getAllMembers(boxedElement))) {
        Name methodName = method.getSimpleName();
        if (methodName.contentEquals("valueOf")) {
            List<? extends VariableElement> params = method.getParameters();
            if (params.size() == 1 && env.getTypeUtils().isSameType(params.get(0).asType(), unboxedType)) {
                valueOfMethod = (Symbol.MethodSymbol) method;
            }
        }
    }
    assert valueOfMethod != null : "no valueOf method declared for boxed type";
    return valueOfMethod;
}
Also used : TypeMirror(javax.lang.model.type.TypeMirror) Symbol(com.sun.tools.javac.code.Symbol) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Name(javax.lang.model.element.Name)

Example 68 with TypeElement

use of javax.lang.model.element.TypeElement in project storio by pushtorefresh.

the class StorIOAnnotationsProcessor method process.

//endregion
/**
     * For those who don't familiar with Annotation Processing API — this is the main method of Annotation Processor lifecycle.
     * <p>
     * It will be called after Java Compiler will find lang elements annotated with annotations from {@link #getSupportedAnnotationTypes()}.
     *
     * @param annotations set of annotations
     * @param roundEnv    environment of current processing round
     * @return true if annotation processor should not be invoked in next rounds of annotation processing, false otherwise
     */
@Override
public boolean process(@Nullable final Set<? extends TypeElement> annotations, @NotNull final RoundEnvironment roundEnv) {
    try {
        final Map<TypeElement, TypeMeta> annotatedClasses = processAnnotatedClasses(roundEnv, elementUtils);
        processAnnotatedFieldsOrMethods(roundEnv, annotatedClasses);
        processAnnotatedExecutables(roundEnv, annotatedClasses);
        validateAnnotatedClassesAndColumns(annotatedClasses);
        final Generator<TypeMeta> putResolverGenerator = createPutResolver();
        final Generator<TypeMeta> getResolverGenerator = createGetResolver();
        final Generator<TypeMeta> deleteResolverGenerator = createDeleteResolver();
        final Generator<TypeMeta> mappingGenerator = createMapping();
        for (TypeMeta typeMeta : annotatedClasses.values()) {
            putResolverGenerator.generateJavaFile(typeMeta).writeTo(filer);
            getResolverGenerator.generateJavaFile(typeMeta).writeTo(filer);
            deleteResolverGenerator.generateJavaFile(typeMeta).writeTo(filer);
            mappingGenerator.generateJavaFile(typeMeta).writeTo(filer);
        }
    } catch (ProcessingException e) {
        messager.printMessage(ERROR, e.getMessage(), e.element());
    } catch (Exception e) {
        messager.printMessage(ERROR, "Problem occurred with StorIOProcessor: " + e.getMessage());
    }
    return true;
}
Also used : TypeElement(javax.lang.model.element.TypeElement) StorIOTypeMeta(com.pushtorefresh.storio.common.annotations.processor.introspection.StorIOTypeMeta)

Example 69 with TypeElement

use of javax.lang.model.element.TypeElement in project storio by pushtorefresh.

the class StorIOContentResolverProcessor method processAnnotatedExecutables.

/**
     * Processes factory methods or constructors annotated with {@link StorIOContentResolverCreator}.
     *
     * @param roundEnvironment current processing environment
     * @param annotatedClasses map of classes annotated with {@link StorIOContentResolverType}
     */
@Override
protected void processAnnotatedExecutables(@NotNull RoundEnvironment roundEnvironment, @NotNull Map<TypeElement, StorIOContentResolverTypeMeta> annotatedClasses) {
    final Set<? extends Element> elementsAnnotatedWithStorIOContentResolverCreator = roundEnvironment.getElementsAnnotatedWith(StorIOContentResolverCreator.class);
    for (final Element annotatedElement : elementsAnnotatedWithStorIOContentResolverCreator) {
        final ExecutableElement annotatedExecutableElement = (ExecutableElement) annotatedElement;
        validateAnnotatedExecutable(annotatedExecutableElement);
        final StorIOContentResolverCreatorMeta storIOContentResolverCreatorMeta = new StorIOContentResolverCreatorMeta(annotatedExecutableElement.getEnclosingElement(), annotatedExecutableElement, annotatedExecutableElement.getAnnotation(StorIOContentResolverCreator.class));
        final StorIOContentResolverTypeMeta storIOContentResolverTypeMeta = annotatedClasses.get(storIOContentResolverCreatorMeta.enclosingElement);
        // If class already contains another creator -> throw exception.
        if (storIOContentResolverTypeMeta.creator == null) {
            storIOContentResolverTypeMeta.creator = annotatedExecutableElement;
        } else {
            throw new ProcessingException(annotatedExecutableElement, "Only one creator method or constructor is allowed: " + annotatedExecutableElement.getEnclosingElement().getSimpleName());
        }
    }
}
Also used : StorIOContentResolverTypeMeta(com.pushtorefresh.storio.contentresolver.annotations.processor.introspection.StorIOContentResolverTypeMeta) StorIOContentResolverCreatorMeta(com.pushtorefresh.storio.contentresolver.annotations.processor.introspection.StorIOContentResolverCreatorMeta) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) ExecutableElement(javax.lang.model.element.ExecutableElement) StorIOContentResolverCreator(com.pushtorefresh.storio.contentresolver.annotations.StorIOContentResolverCreator) ProcessingException(com.pushtorefresh.storio.common.annotations.processor.ProcessingException)

Example 70 with TypeElement

use of javax.lang.model.element.TypeElement in project storio by pushtorefresh.

the class StorIOSQLiteProcessor method validateAnnotatedClassesAndColumns.

@Override
protected void validateAnnotatedClassesAndColumns(@NotNull Map<TypeElement, StorIOSQLiteTypeMeta> annotatedClasses) {
    // Check that each annotated class has columns with at least one key column.
    for (final Map.Entry<TypeElement, StorIOSQLiteTypeMeta> annotatedType : annotatedClasses.entrySet()) {
        final StorIOSQLiteTypeMeta storIOSQLiteTypeMeta = annotatedType.getValue();
        if (storIOSQLiteTypeMeta.columns.size() == 0) {
            throw new ProcessingException(annotatedType.getKey(), "Class marked with " + StorIOSQLiteType.class.getSimpleName() + " annotation should have at least one field or method marked with " + StorIOSQLiteColumn.class.getSimpleName() + " annotation: " + storIOSQLiteTypeMeta.simpleName);
        }
        boolean hasAtLeastOneKeyColumn = false;
        for (final StorIOSQLiteColumnMeta columnMeta : storIOSQLiteTypeMeta.columns.values()) {
            if (columnMeta.storIOColumn.key()) {
                hasAtLeastOneKeyColumn = true;
                break;
            }
        }
        if (!hasAtLeastOneKeyColumn) {
            throw new ProcessingException(annotatedType.getKey(), "Class marked with " + StorIOSQLiteType.class.getSimpleName() + " annotation should have at least one KEY field or method marked with " + StorIOSQLiteColumn.class.getSimpleName() + " annotation: " + storIOSQLiteTypeMeta.simpleName);
        }
        if (storIOSQLiteTypeMeta.needCreator && storIOSQLiteTypeMeta.creator == null) {
            throw new ProcessingException(annotatedType.getKey(), "Class marked with " + StorIOSQLiteType.class.getSimpleName() + " annotation needs factory method or constructor marked with " + StorIOSQLiteCreator.class.getSimpleName() + " annotation: " + storIOSQLiteTypeMeta.simpleName);
        }
        if (storIOSQLiteTypeMeta.needCreator && storIOSQLiteTypeMeta.creator.getParameters().size() != storIOSQLiteTypeMeta.columns.size()) {
            throw new ProcessingException(annotatedType.getKey(), "Class marked with " + StorIOSQLiteType.class.getSimpleName() + " annotation needs factory method or constructor marked with " + StorIOSQLiteCreator.class.getSimpleName() + " annotation with the same amount of parameters as the number of columns: " + storIOSQLiteTypeMeta.simpleName);
        }
    }
}
Also used : StorIOSQLiteColumnMeta(com.pushtorefresh.storio.sqlite.annotations.processor.introspection.StorIOSQLiteColumnMeta) StorIOSQLiteTypeMeta(com.pushtorefresh.storio.sqlite.annotations.processor.introspection.StorIOSQLiteTypeMeta) TypeElement(javax.lang.model.element.TypeElement) Map(java.util.Map) ProcessingException(com.pushtorefresh.storio.common.annotations.processor.ProcessingException)

Aggregations

TypeElement (javax.lang.model.element.TypeElement)1562 ExecutableElement (javax.lang.model.element.ExecutableElement)517 Element (javax.lang.model.element.Element)502 TypeMirror (javax.lang.model.type.TypeMirror)420 VariableElement (javax.lang.model.element.VariableElement)333 DeclaredType (javax.lang.model.type.DeclaredType)201 ArrayList (java.util.ArrayList)177 PackageElement (javax.lang.model.element.PackageElement)159 AnnotationMirror (javax.lang.model.element.AnnotationMirror)151 Test (org.junit.Test)136 HashMap (java.util.HashMap)118 HashSet (java.util.HashSet)109 Elements (javax.lang.model.util.Elements)101 Map (java.util.Map)98 IOException (java.io.IOException)97 List (java.util.List)97 ClassName (com.squareup.javapoet.ClassName)88 Test (org.junit.jupiter.api.Test)80 MethodSpec (com.squareup.javapoet.MethodSpec)72 TypeSpec (com.squareup.javapoet.TypeSpec)63