Search in sources :

Example 51 with Elements

use of javax.lang.model.util.Elements in project auto by google.

the class ExtensionTest method testCantConsumeNonExistentMethod.

@Test
public void testCantConsumeNonExistentMethod() {
    class ConsumeBogusMethod extends NonFinalExtension {

        @Override
        public Set<ExecutableElement> consumeMethods(Context context) {
            // Find Integer.intValue() and try to consume that.
            Elements elementUtils = context.processingEnvironment().getElementUtils();
            TypeElement javaLangInteger = elementUtils.getTypeElement(Integer.class.getName());
            for (ExecutableElement method : ElementFilter.methodsIn(javaLangInteger.getEnclosedElements())) {
                if (method.getSimpleName().contentEquals("intValue")) {
                    return ImmutableSet.of(method);
                }
            }
            throw new AssertionError("Could not find Integer.intValue()");
        }
    }
    JavaFileObject impl = JavaFileObjects.forSourceLines("foo.bar.Baz", "package foo.bar;", "import com.google.auto.value.AutoValue;", "@AutoValue public abstract class Baz {", "  abstract String foo();", "}");
    Compilation compilation = javac().withProcessors(new AutoValueProcessor(ImmutableList.of(new ConsumeBogusMethod()))).compile(impl);
    assertThat(compilation).hadErrorContainingMatch("wants to consume a method that is not one of the abstract methods in this class" + ".*intValue\\(\\)").inFile(impl).onLineContaining("@AutoValue public abstract class Baz");
}
Also used : BuilderContext(com.google.auto.value.extension.AutoValueExtension.BuilderContext) JavaFileObject(javax.tools.JavaFileObject) Compilation(com.google.testing.compile.Compilation) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Elements(javax.lang.model.util.Elements) Test(org.junit.Test)

Example 52 with Elements

use of javax.lang.model.util.Elements in project dubbo by alibaba.

the class AbstractServiceRestMetadataResolver method resolve.

@Override
public final ServiceRestMetadata resolve(ProcessingEnvironment processingEnv, TypeElement serviceType, Set<? extends TypeElement> annotations) {
    info("%s is processing the service type[%s] with annotations[%s]", processorName, serviceType, annotations.stream().map(t -> "@" + t.toString()).collect(Collectors.joining(",")));
    ServiceRestMetadata serviceRestMetadata = new ServiceRestMetadata();
    Elements elements = processingEnv.getElementUtils();
    try {
        AnnotationMirror serviceAnnotation = getAnnotation(serviceType);
        String serviceInterfaceName = resolveServiceInterfaceName(serviceType, serviceAnnotation);
        serviceRestMetadata.setServiceInterface(serviceInterfaceName);
        serviceRestMetadata.setGroup(getGroup(serviceAnnotation));
        serviceRestMetadata.setVersion(getVersion(serviceAnnotation));
        TypeElement serviceInterfaceType = elements.getTypeElement(serviceInterfaceName);
        List<? extends ExecutableElement> serviceMethods = new LinkedList<>(getPublicNonStaticMethods(serviceInterfaceType, Object.class));
        // Sorts
        sort(serviceMethods, ExecutableElementComparator.INSTANCE);
        serviceMethods.forEach(serviceMethod -> {
            resolveRestMethodMetadata(processingEnv, serviceType, serviceInterfaceType, serviceMethod).ifPresent(serviceRestMetadata.getMeta()::add);
        });
    } finally {
        clearCache();
    }
    info("The %s's process result : %s", processorName, serviceRestMetadata);
    return serviceRestMetadata;
}
Also used : AnnotationMirror(javax.lang.model.element.AnnotationMirror) ServiceRestMetadata(org.apache.dubbo.metadata.rest.ServiceRestMetadata) TypeElement(javax.lang.model.element.TypeElement) Elements(javax.lang.model.util.Elements) LinkedList(java.util.LinkedList)

Example 53 with Elements

use of javax.lang.model.util.Elements in project dubbo by alibaba.

the class CollectionTypeDefinitionBuilder method accept.

@Override
public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) {
    Elements elements = processingEnv.getElementUtils();
    TypeElement collectionTypeElement = elements.getTypeElement(Collection.class.getTypeName());
    TypeMirror collectionType = collectionTypeElement.asType();
    Types types = processingEnv.getTypeUtils();
    TypeMirror erasedType = types.erasure(type);
    return types.isAssignable(erasedType, collectionType);
}
Also used : Types(javax.lang.model.util.Types) TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) Collection(java.util.Collection) Elements(javax.lang.model.util.Elements)

Example 54 with Elements

use of javax.lang.model.util.Elements in project dagger by square.

the class ModuleAdapterProcessor method providerMethodsByClass.

/**
 * Returns a map containing all {@code @Provides} methods, indexed by class.
 */
private Map<String, List<ExecutableElement>> providerMethodsByClass(RoundEnvironment env) {
    Elements elementUtils = processingEnv.getElementUtils();
    Types types = processingEnv.getTypeUtils();
    Map<String, List<ExecutableElement>> result = new HashMap<String, List<ExecutableElement>>();
    provides: for (Element providerMethod : findProvidesMethods(env)) {
        switch(providerMethod.getEnclosingElement().getKind()) {
            case CLASS:
                // valid, move along
                break;
            default:
                // TODO(tbroyer): pass annotation information
                error("Unexpected @Provides on " + elementToString(providerMethod), providerMethod);
                continue;
        }
        TypeElement type = (TypeElement) providerMethod.getEnclosingElement();
        Set<Modifier> typeModifiers = type.getModifiers();
        if (typeModifiers.contains(PRIVATE) || typeModifiers.contains(ABSTRACT)) {
            error("Classes declaring @Provides methods must not be private or abstract: " + type.getQualifiedName(), type);
            continue;
        }
        Set<Modifier> methodModifiers = providerMethod.getModifiers();
        if (methodModifiers.contains(PRIVATE) || methodModifiers.contains(ABSTRACT) || methodModifiers.contains(STATIC)) {
            error("@Provides methods must not be private, abstract or static: " + type.getQualifiedName() + "." + providerMethod, providerMethod);
            continue;
        }
        ExecutableElement providerMethodAsExecutable = (ExecutableElement) providerMethod;
        if (!providerMethodAsExecutable.getThrownTypes().isEmpty()) {
            error("@Provides methods must not have a throws clause: " + type.getQualifiedName() + "." + providerMethod, providerMethod);
            continue;
        }
        // Invalidate return types.
        TypeMirror returnType = types.erasure(providerMethodAsExecutable.getReturnType());
        if (!returnType.getKind().equals(TypeKind.ERROR)) {
            // processors is not "invalid" in this way, so ignore).
            for (String invalidTypeName : INVALID_RETURN_TYPES) {
                TypeElement invalidTypeElement = elementUtils.getTypeElement(invalidTypeName);
                if (invalidTypeElement != null && types.isSameType(returnType, types.erasure(invalidTypeElement.asType()))) {
                    error(String.format("@Provides method must not return %s directly: %s.%s", invalidTypeElement, type.getQualifiedName(), providerMethod), providerMethod);
                    // Skip to next provides method.
                    continue provides;
                }
            }
        }
        List<ExecutableElement> methods = result.get(type.getQualifiedName().toString());
        if (methods == null) {
            methods = new ArrayList<ExecutableElement>();
            result.put(type.getQualifiedName().toString(), methods);
        }
        methods.add(providerMethodAsExecutable);
    }
    TypeMirror objectType = elementUtils.getTypeElement("java.lang.Object").asType();
    // should still be registered and a ModuleAdapter should still be written.
    for (Element module : env.getElementsAnnotatedWith(Module.class)) {
        if (!module.getKind().equals(ElementKind.CLASS)) {
            error("Modules must be classes: " + elementToString(module), module);
            continue;
        }
        TypeElement moduleType = (TypeElement) module;
        // Verify that all modules do not extend from non-Object types.
        if (!types.isSameType(moduleType.getSuperclass(), objectType)) {
            error("Modules must not extend from other classes: " + elementToString(module), module);
        }
        String moduleName = moduleType.getQualifiedName().toString();
        if (result.containsKey(moduleName))
            continue;
        result.put(moduleName, new ArrayList<ExecutableElement>());
    }
    return result;
}
Also used : SupportedAnnotationTypes(javax.annotation.processing.SupportedAnnotationTypes) Types(javax.lang.model.util.Types) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) VariableElement(javax.lang.model.element.VariableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ArrayList(java.util.ArrayList) Util.typeToString(dagger.internal.codegen.Util.typeToString) Util.elementToString(dagger.internal.codegen.Util.elementToString) Elements(javax.lang.model.util.Elements) TypeMirror(javax.lang.model.type.TypeMirror) List(java.util.List) ArrayList(java.util.ArrayList)

Example 55 with Elements

use of javax.lang.model.util.Elements in project ceylon-compiler by ceylon.

the class T6358786 method main.

public static void main(String... args) throws IOException {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    String srcdir = System.getProperty("test.src");
    File file = new File(srcdir, args[0]);
    JavacTaskImpl task = (JavacTaskImpl) tool.getTask(null, fm, null, null, null, fm.getJavaFileObjectsFromFiles(Arrays.asList(file)));
    Elements elements = task.getElements();
    for (TypeElement clazz : task.enter(task.parse())) {
        String doc = elements.getDocComment(clazz);
        if (doc == null)
            throw new AssertionError(clazz.getSimpleName() + ": no doc comment");
        System.out.format("%s: %s%n", clazz.getSimpleName(), doc);
    }
}
Also used : JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) TypeElement(javax.lang.model.element.TypeElement) Elements(javax.lang.model.util.Elements)

Aggregations

Elements (javax.lang.model.util.Elements)146 TypeElement (javax.lang.model.element.TypeElement)90 TypeMirror (javax.lang.model.type.TypeMirror)52 Element (javax.lang.model.element.Element)46 Types (javax.lang.model.util.Types)40 VariableElement (javax.lang.model.element.VariableElement)35 ExecutableElement (javax.lang.model.element.ExecutableElement)32 Map (java.util.Map)18 ArrayList (java.util.ArrayList)17 SupportedAnnotationTypes (javax.annotation.processing.SupportedAnnotationTypes)17 PackageElement (javax.lang.model.element.PackageElement)17 LinkedHashSet (java.util.LinkedHashSet)15 AnnotationMirror (javax.lang.model.element.AnnotationMirror)15 Test (org.junit.Test)15 List (java.util.List)14 XmlElements (javax.xml.bind.annotation.XmlElements)14 Metadata (org.apache.camel.spi.Metadata)14 Set (java.util.Set)12 DeclaredType (javax.lang.model.type.DeclaredType)12 AnnotationProcessorHelper.findTypeElement (org.apache.camel.tools.apt.AnnotationProcessorHelper.findTypeElement)12