Search in sources :

Example 16 with Modifier

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

the class DeepLinkProcessor method process.

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    Set<Element> customAnnotations = new HashSet<>();
    for (Element annotation : annotations) {
        if (annotation.getAnnotation(DEEP_LINK_SPEC_CLASS) != null) {
            customAnnotations.add(annotation);
        }
    }
    Map<Element, String[]> prefixes = new HashMap<>();
    Set<Element> customAnnotatedElements = new HashSet<>();
    for (Element customAnnotation : customAnnotations) {
        ElementKind kind = customAnnotation.getKind();
        if (kind != ElementKind.ANNOTATION_TYPE) {
            error(customAnnotation, "Only annotation types can be annotated with @%s", DEEP_LINK_SPEC_CLASS.getSimpleName());
        }
        String[] prefix = customAnnotation.getAnnotation(DEEP_LINK_SPEC_CLASS).prefix();
        if (Utils.hasEmptyOrNullString(prefix)) {
            error(customAnnotation, "Prefix property cannot have null or empty strings");
        }
        if (prefix.length == 0) {
            error(customAnnotation, "Prefix property cannot be empty");
        }
        prefixes.put(customAnnotation, prefix);
        for (Element customAnnotatedElement : roundEnv.getElementsAnnotatedWith(MoreElements.asType(customAnnotation))) {
            customAnnotatedElements.add(customAnnotatedElement);
        }
    }
    Set<Element> elementsToProcess = new HashSet<>(customAnnotatedElements);
    elementsToProcess.addAll(roundEnv.getElementsAnnotatedWith(DEEP_LINK_CLASS));
    List<DeepLinkAnnotatedElement> deepLinkElements = new ArrayList<>();
    for (Element element : elementsToProcess) {
        ElementKind kind = element.getKind();
        if (kind != ElementKind.METHOD && kind != ElementKind.CLASS) {
            error(element, "Only classes and methods can be annotated with @%s", DEEP_LINK_CLASS.getSimpleName());
        }
        if (kind == ElementKind.METHOD) {
            Set<Modifier> methodModifiers = element.getModifiers();
            if (!methodModifiers.contains(Modifier.STATIC)) {
                error(element, "Only static methods can be annotated with @%s", DEEP_LINK_CLASS.getSimpleName());
            }
        }
        DeepLink deepLinkAnnotation = element.getAnnotation(DEEP_LINK_CLASS);
        List<String> deepLinks = new ArrayList<>();
        if (deepLinkAnnotation != null) {
            deepLinks.addAll(Arrays.asList(deepLinkAnnotation.value()));
        }
        if (customAnnotatedElements.contains(element)) {
            deepLinks.addAll(enumerateCustomDeepLinks(element, prefixes));
        }
        DeepLinkEntry.Type type = kind == ElementKind.CLASS ? DeepLinkEntry.Type.CLASS : DeepLinkEntry.Type.METHOD;
        for (String deepLink : deepLinks) {
            try {
                deepLinkElements.add(new DeepLinkAnnotatedElement(deepLink, element, type));
            } catch (MalformedURLException e) {
                messager.printMessage(Diagnostic.Kind.ERROR, "Malformed Deep Link URL " + deepLink);
            }
        }
    }
    Set<? extends Element> deepLinkHandlerElements = roundEnv.getElementsAnnotatedWith(DeepLinkHandler.class);
    for (Element deepLinkHandlerElement : deepLinkHandlerElements) {
        Optional<AnnotationMirror> annotationMirror = getAnnotationMirror(deepLinkHandlerElement, DeepLinkHandler.class);
        if (annotationMirror.isPresent()) {
            Iterable<TypeMirror> klasses = getTypeValue(annotationMirror.get(), "value");
            List<TypeElement> typeElements = FluentIterable.from(klasses).transform(new Function<TypeMirror, TypeElement>() {

                @Override
                public TypeElement apply(TypeMirror klass) {
                    return MoreTypes.asTypeElement(klass);
                }
            }).toList();
            String packageName = processingEnv.getElementUtils().getPackageOf(deepLinkHandlerElement).getQualifiedName().toString();
            try {
                generateDeepLinkDelegate(packageName, typeElements);
            } catch (IOException e) {
                messager.printMessage(Diagnostic.Kind.ERROR, "Error creating file");
            } catch (RuntimeException e) {
                messager.printMessage(Diagnostic.Kind.ERROR, "Internal error during annotation processing: " + e.getClass().getSimpleName());
            }
        }
    }
    Set<? extends Element> deepLinkModuleElements = roundEnv.getElementsAnnotatedWith(DeepLinkModule.class);
    for (Element deepLinkModuleElement : deepLinkModuleElements) {
        String packageName = processingEnv.getElementUtils().getPackageOf(deepLinkModuleElement).getQualifiedName().toString();
        try {
            generateDeepLinkLoader(packageName, deepLinkModuleElement.getSimpleName().toString(), deepLinkElements);
        } catch (IOException e) {
            messager.printMessage(Diagnostic.Kind.ERROR, "Error creating file");
        } catch (RuntimeException e) {
            messager.printMessage(Diagnostic.Kind.ERROR, "Internal error during annotation processing: " + e.getClass().getSimpleName());
        }
    }
    return false;
}
Also used : ElementKind(javax.lang.model.element.ElementKind) MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) PackageElement(javax.lang.model.element.PackageElement) ArrayList(java.util.ArrayList) Function(com.google.common.base.Function) TypeMirror(javax.lang.model.type.TypeMirror) Modifier(javax.lang.model.element.Modifier) HashSet(java.util.HashSet) TypeElement(javax.lang.model.element.TypeElement) IOException(java.io.IOException) MoreElements.getAnnotationMirror(com.google.auto.common.MoreElements.getAnnotationMirror) AnnotationMirror(javax.lang.model.element.AnnotationMirror)

Example 17 with Modifier

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

the class ClassToGenerateInfo method collectMethodsReturningClassType.

/**
   * Get information about methods returning class type of the original class so we can duplicate
   * them in the generated class for chaining purposes
   */
private void collectMethodsReturningClassType(TypeElement originalClass) {
    TypeElement clazz = originalClass;
    while (clazz.getSuperclass().getKind() != TypeKind.NONE) {
        for (Element subElement : clazz.getEnclosedElements()) {
            Set<Modifier> modifiers = subElement.getModifiers();
            if (subElement.getKind() == ElementKind.METHOD && !modifiers.contains(Modifier.PRIVATE) && !modifiers.contains(Modifier.FINAL) && !modifiers.contains(Modifier.STATIC)) {
                TypeMirror methodReturnType = ((ExecutableType) subElement.asType()).getReturnType();
                if (methodReturnType.equals(clazz.asType()) || typeUtils.isSubtype(clazz.asType(), methodReturnType)) {
                    ExecutableElement castedSubElement = ((ExecutableElement) subElement);
                    List<? extends VariableElement> params = castedSubElement.getParameters();
                    String methodName = subElement.getSimpleName().toString();
                    if (methodName.equals(RESET_METHOD) && params.isEmpty()) {
                        continue;
                    }
                    methodsReturningClassType.add(new MethodInfo(methodName, modifiers, buildParamList(params), castedSubElement.isVarArgs()));
                }
            }
        }
        clazz = (TypeElement) typeUtils.asElement(clazz.getSuperclass());
    }
}
Also used : ExecutableType(javax.lang.model.type.ExecutableType) TypeMirror(javax.lang.model.type.TypeMirror) 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) TypeParameterElement(javax.lang.model.element.TypeParameterElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Modifier(javax.lang.model.element.Modifier)

Example 18 with Modifier

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

the class CodeWriter method emitModifiers.

/**
   * Emits {@code modifiers} in the standard order. Modifiers in {@code implicitModifiers} will not
   * be emitted.
   */
public void emitModifiers(Set<Modifier> modifiers, Set<Modifier> implicitModifiers) throws IOException {
    if (modifiers.isEmpty())
        return;
    for (Modifier modifier : EnumSet.copyOf(modifiers)) {
        if (implicitModifiers.contains(modifier))
            continue;
        emitAndIndent(modifier.name().toLowerCase(Locale.US));
        emitAndIndent(" ");
    }
}
Also used : Modifier(javax.lang.model.element.Modifier)

Example 19 with Modifier

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

the class Util method requireExactlyOneOf.

static void requireExactlyOneOf(Set<Modifier> modifiers, Modifier... mutuallyExclusive) {
    int count = 0;
    for (Modifier modifier : mutuallyExclusive) {
        // Skip 'DEFAULT' if it doesn't exist!
        if (modifier == null && Util.DEFAULT == null)
            continue;
        if (modifiers.contains(modifier))
            count++;
    }
    checkArgument(count == 1, "modifiers %s must contain one of %s", modifiers, Arrays.toString(mutuallyExclusive));
}
Also used : Modifier(javax.lang.model.element.Modifier)

Example 20 with Modifier

use of javax.lang.model.element.Modifier in project lwjgl by LWJGL.

the class FieldsGenerator method validateField.

private static void validateField(VariableElement field) {
    // Check if field is "public static final"
    Set<Modifier> modifiers = field.getModifiers();
    if (modifiers.size() != 3 || !modifiers.contains(Modifier.PUBLIC) || !modifiers.contains(Modifier.STATIC) || !modifiers.contains(Modifier.FINAL)) {
        throw new RuntimeException("Field " + field.getSimpleName() + " is not declared public static final");
    }
    // Check suported types (int, long, float, String)
    TypeMirror field_type = field.asType();
    if ("java.lang.String".equals(field_type.toString())) {
    } else if (field_type instanceof PrimitiveType) {
        PrimitiveType field_type_prim = (PrimitiveType) field_type;
        TypeKind field_kind = field_type_prim.getKind();
        if (field_kind != TypeKind.INT && field_kind != TypeKind.LONG && field_kind != TypeKind.FLOAT && field_kind != TypeKind.BYTE) {
            throw new RuntimeException("Field " + field.getSimpleName() + " is not of type 'int', 'long', 'float' or 'byte' " + field_kind.toString());
        }
    } else {
        throw new RuntimeException("Field " + field.getSimpleName() + " is not a primitive type or String");
    }
    Object field_value = field.getConstantValue();
    if (field_value == null) {
        throw new RuntimeException("Field " + field.getSimpleName() + " has no initial value");
    }
}
Also used : TypeMirror(javax.lang.model.type.TypeMirror) TypeKind(javax.lang.model.type.TypeKind) PrimitiveType(javax.lang.model.type.PrimitiveType) 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