Search in sources :

Example 21 with PackageElement

use of javax.lang.model.element.PackageElement in project graal by oracle.

the class GeneratorUtils method createClass.

static CodeTypeElement createClass(Template sourceModel, TemplateMethod sourceMethod, Set<Modifier> modifiers, String simpleName, TypeMirror superType) {
    TypeElement templateType = sourceModel.getTemplateType();
    ProcessorContext context = ProcessorContext.getInstance();
    PackageElement pack = context.getEnvironment().getElementUtils().getPackageOf(templateType);
    CodeTypeElement clazz = new CodeTypeElement(modifiers, ElementKind.CLASS, pack, simpleName);
    TypeMirror resolvedSuperType = superType;
    if (resolvedSuperType == null) {
        resolvedSuperType = context.getType(Object.class);
    }
    clazz.setSuperClass(resolvedSuperType);
    CodeAnnotationMirror generatedByAnnotation = new CodeAnnotationMirror((DeclaredType) context.getType(GeneratedBy.class));
    generatedByAnnotation.setElementValue(generatedByAnnotation.findExecutableElement("value"), new CodeAnnotationValue(templateType.asType()));
    if (sourceMethod != null && sourceMethod.getMethod() != null) {
        generatedByAnnotation.setElementValue(generatedByAnnotation.findExecutableElement("methodName"), new CodeAnnotationValue(sourceMethod.createReferenceName()));
    }
    clazz.addAnnotationMirror(generatedByAnnotation);
    return clazz;
}
Also used : CodeAnnotationMirror(com.oracle.truffle.dsl.processor.java.model.CodeAnnotationMirror) CodeTypeElement(com.oracle.truffle.dsl.processor.java.model.CodeTypeElement) ElementUtils.fromTypeMirror(com.oracle.truffle.dsl.processor.java.ElementUtils.fromTypeMirror) TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) CodeTypeElement(com.oracle.truffle.dsl.processor.java.model.CodeTypeElement) PackageElement(javax.lang.model.element.PackageElement) ProcessorContext(com.oracle.truffle.dsl.processor.ProcessorContext) CodeAnnotationValue(com.oracle.truffle.dsl.processor.java.model.CodeAnnotationValue)

Example 22 with PackageElement

use of javax.lang.model.element.PackageElement in project graal by oracle.

the class ElementUtils method isDeprecated.

public static boolean isDeprecated(TypeElement baseType) {
    DeclaredType deprecated = ProcessorContext.getInstance().getDeclaredType(Deprecated.class);
    List<TypeElement> superTypes = getSuperTypes(baseType);
    superTypes.add(baseType);
    for (TypeElement type : superTypes) {
        PackageElement pack = ElementUtils.findPackageElement(type);
        if ((pack != null && ElementUtils.findAnnotationMirror(pack.getAnnotationMirrors(), deprecated) != null)) {
            return true;
        }
    }
    return false;
}
Also used : TypeElement(javax.lang.model.element.TypeElement) PackageElement(javax.lang.model.element.PackageElement) DeclaredType(javax.lang.model.type.DeclaredType)

Example 23 with PackageElement

use of javax.lang.model.element.PackageElement in project graal by oracle.

the class OptionProcessor method createFiles.

private void createFiles(OptionsInfo info) {
    String pkg = ((PackageElement) info.topDeclaringType.getEnclosingElement()).getQualifiedName().toString();
    Name topDeclaringClass = info.topDeclaringType.getSimpleName();
    Element[] originatingElements = info.originatingElements.toArray(new Element[info.originatingElements.size()]);
    createOptionsDescriptorsFile(info, pkg, topDeclaringClass, originatingElements);
}
Also used : PackageElement(javax.lang.model.element.PackageElement) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) Name(javax.lang.model.element.Name)

Example 24 with PackageElement

use of javax.lang.model.element.PackageElement in project graal by oracle.

the class OptionProcessor method processElement.

private void processElement(Element element, OptionsInfo info) {
    if (!element.getModifiers().contains(Modifier.STATIC)) {
        processingEnv.getMessager().printMessage(Kind.ERROR, "Option field must be static", element);
        return;
    }
    if (element.getModifiers().contains(Modifier.PRIVATE)) {
        processingEnv.getMessager().printMessage(Kind.ERROR, "Option field cannot be private", element);
        return;
    }
    Option annotation = element.getAnnotation(Option.class);
    assert annotation != null;
    assert element instanceof VariableElement;
    assert element.getKind() == ElementKind.FIELD;
    VariableElement field = (VariableElement) element;
    String fieldName = field.getSimpleName().toString();
    Elements elements = processingEnv.getElementUtils();
    Types types = processingEnv.getTypeUtils();
    TypeMirror fieldType = field.asType();
    if (fieldType.getKind() != TypeKind.DECLARED) {
        processingEnv.getMessager().printMessage(Kind.ERROR, "Option field must be of type " + OptionKey.class.getName(), element);
        return;
    }
    DeclaredType declaredFieldType = (DeclaredType) fieldType;
    TypeMirror optionKeyType = elements.getTypeElement(OptionKey.class.getName()).asType();
    if (!types.isSubtype(fieldType, types.erasure(optionKeyType))) {
        String msg = String.format("Option field type %s is not a subclass of %s", fieldType, optionKeyType);
        processingEnv.getMessager().printMessage(Kind.ERROR, msg, element);
        return;
    }
    if (!field.getModifiers().contains(Modifier.STATIC)) {
        processingEnv.getMessager().printMessage(Kind.ERROR, "Option field must be static", element);
        return;
    }
    if (field.getModifiers().contains(Modifier.PRIVATE)) {
        processingEnv.getMessager().printMessage(Kind.ERROR, "Option field cannot be private", element);
        return;
    }
    String optionName = annotation.name();
    if (optionName.equals("")) {
        optionName = fieldName;
    }
    if (!Character.isUpperCase(optionName.charAt(0))) {
        processingEnv.getMessager().printMessage(Kind.ERROR, "Option name must start with an upper case letter", element);
        return;
    }
    DeclaredType declaredOptionKeyType = declaredFieldType;
    while (!types.isSameType(types.erasure(declaredOptionKeyType), types.erasure(optionKeyType))) {
        List<? extends TypeMirror> directSupertypes = types.directSupertypes(declaredFieldType);
        assert !directSupertypes.isEmpty();
        declaredOptionKeyType = (DeclaredType) directSupertypes.get(0);
    }
    assert !declaredOptionKeyType.getTypeArguments().isEmpty();
    String optionType = declaredOptionKeyType.getTypeArguments().get(0).toString();
    if (optionType.startsWith("java.lang.")) {
        optionType = optionType.substring("java.lang.".length());
    }
    Element enclosing = element.getEnclosingElement();
    String declaringClass = "";
    String separator = "";
    Set<Element> originatingElementsList = info.originatingElements;
    originatingElementsList.add(field);
    PackageElement enclosingPackage = null;
    while (enclosing != null) {
        if (enclosing.getKind() == ElementKind.CLASS || enclosing.getKind() == ElementKind.INTERFACE) {
            if (enclosing.getModifiers().contains(Modifier.PRIVATE)) {
                String msg = String.format("Option field cannot be declared in a private %s %s", enclosing.getKind().name().toLowerCase(), enclosing);
                processingEnv.getMessager().printMessage(Kind.ERROR, msg, element);
                return;
            }
            originatingElementsList.add(enclosing);
            declaringClass = enclosing.getSimpleName() + separator + declaringClass;
            separator = ".";
        } else if (enclosing.getKind() == ElementKind.PACKAGE) {
            enclosingPackage = (PackageElement) enclosing;
        }
        enclosing = enclosing.getEnclosingElement();
    }
    if (enclosingPackage == null) {
        processingEnv.getMessager().printMessage(Kind.ERROR, "Option field cannot be declared in the unnamed package", element);
        return;
    }
    String[] helpValue = annotation.help();
    String help = "";
    String[] extraHelp = {};
    if (helpValue.length == 1) {
        help = helpValue[0];
        if (help.startsWith("file:")) {
            String path = help.substring("file:".length());
            Filer filer = processingEnv.getFiler();
            try {
                FileObject file;
                try {
                    file = filer.getResource(StandardLocation.SOURCE_PATH, enclosingPackage.getQualifiedName(), path);
                } catch (IllegalArgumentException | IOException e) {
                    // Handle the case when a compiler doesn't support the SOURCE_PATH location
                    file = filer.getResource(StandardLocation.CLASS_OUTPUT, enclosingPackage.getQualifiedName(), path);
                }
                try (BufferedReader br = new BufferedReader(new InputStreamReader(file.openInputStream()))) {
                    help = br.readLine();
                    if (help == null) {
                        help = "";
                    }
                    String line = br.readLine();
                    List<String> lines = new ArrayList<>();
                    while (line != null) {
                        lines.add(line);
                        line = br.readLine();
                    }
                    extraHelp = lines.toArray(new String[lines.size()]);
                }
            } catch (IOException e) {
                String msg = String.format("Error reading %s containing the help text for option field: %s", path, e);
                processingEnv.getMessager().printMessage(Kind.ERROR, msg, element);
                return;
            }
        }
    } else if (helpValue.length > 1) {
        help = helpValue[0];
        extraHelp = Arrays.copyOfRange(helpValue, 1, helpValue.length);
    }
    if (help.length() != 0) {
        char firstChar = help.charAt(0);
        if (!Character.isUpperCase(firstChar)) {
            processingEnv.getMessager().printMessage(Kind.ERROR, "Option help text must start with an upper case letter", element);
            return;
        }
    }
    info.options.add(new OptionInfo(optionName, annotation.type(), help, extraHelp, optionType, declaringClass, field));
}
Also used : SupportedAnnotationTypes(javax.annotation.processing.SupportedAnnotationTypes) Types(javax.lang.model.util.Types) InputStreamReader(java.io.InputStreamReader) PackageElement(javax.lang.model.element.PackageElement) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) ArrayList(java.util.ArrayList) VariableElement(javax.lang.model.element.VariableElement) IOException(java.io.IOException) Elements(javax.lang.model.util.Elements) TypeMirror(javax.lang.model.type.TypeMirror) BufferedReader(java.io.BufferedReader) Option(org.graalvm.compiler.options.Option) PackageElement(javax.lang.model.element.PackageElement) FileObject(javax.tools.FileObject) JavaFileObject(javax.tools.JavaFileObject) Filer(javax.annotation.processing.Filer) DeclaredType(javax.lang.model.type.DeclaredType)

Example 25 with PackageElement

use of javax.lang.model.element.PackageElement in project graal by oracle.

the class ServiceProviderProcessor method processElement.

private void processElement(TypeElement serviceProvider) {
    if (processed.contains(serviceProvider)) {
        return;
    }
    processed.add(serviceProvider);
    ServiceProvider annotation = serviceProvider.getAnnotation(ServiceProvider.class);
    if (annotation != null) {
        try {
            annotation.value();
        } catch (MirroredTypeException ex) {
            TypeMirror service = ex.getTypeMirror();
            if (verifyAnnotation(service, serviceProvider)) {
                if (serviceProvider.getNestingKind().isNested()) {
                    /*
                         * This is a simplifying constraint that means we don't have to process the
                         * qualified name to insert '$' characters at the relevant positions.
                         */
                    String msg = String.format("Service provider class %s must be a top level class", serviceProvider.getSimpleName());
                    processingEnv.getMessager().printMessage(Kind.ERROR, msg, serviceProvider);
                } else {
                    /*
                         * Since the definition of the service class is not necessarily modifiable,
                         * we need to support a non-top-level service class and ensure its name is
                         * properly expressed with '$' separating nesting levels instead of '.'.
                         */
                    TypeElement serviceElement = (TypeElement) processingEnv.getTypeUtils().asElement(service);
                    String serviceName = serviceElement.getSimpleName().toString();
                    Element enclosing = serviceElement.getEnclosingElement();
                    while (enclosing != null) {
                        final ElementKind kind = enclosing.getKind();
                        if (kind == ElementKind.PACKAGE) {
                            serviceName = ((PackageElement) enclosing).getQualifiedName().toString() + "." + serviceName;
                            break;
                        } else if (kind == ElementKind.CLASS || kind == ElementKind.INTERFACE) {
                            serviceName = ((TypeElement) enclosing).getSimpleName().toString() + "$" + serviceName;
                            enclosing = enclosing.getEnclosingElement();
                        } else {
                            String msg = String.format("Cannot generate provider descriptor for service class %s as it is not nested in a package, class or interface", serviceElement.getQualifiedName());
                            processingEnv.getMessager().printMessage(Kind.ERROR, msg, serviceProvider);
                            return;
                        }
                    }
                    serviceProviders.put(serviceProvider, serviceName);
                }
            }
        }
    }
}
Also used : MirroredTypeException(javax.lang.model.type.MirroredTypeException) ElementKind(javax.lang.model.element.ElementKind) TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) ServiceProvider(org.graalvm.compiler.serviceprovider.ServiceProvider) PackageElement(javax.lang.model.element.PackageElement) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement)

Aggregations

PackageElement (javax.lang.model.element.PackageElement)133 TypeElement (javax.lang.model.element.TypeElement)92 Element (javax.lang.model.element.Element)51 ExecutableElement (javax.lang.model.element.ExecutableElement)34 VariableElement (javax.lang.model.element.VariableElement)32 TypeSpec (com.squareup.javapoet.TypeSpec)20 IOException (java.io.IOException)17 HashSet (java.util.HashSet)13 TypeMirror (javax.lang.model.type.TypeMirror)13 AnnotationMirror (javax.lang.model.element.AnnotationMirror)12 JavaFileObject (javax.tools.JavaFileObject)12 ClassName (com.squareup.javapoet.ClassName)11 ArrayList (java.util.ArrayList)11 Set (java.util.Set)10 Elements (javax.lang.model.util.Elements)10 PrintWriter (java.io.PrintWriter)9 HashMap (java.util.HashMap)9 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)8 Map (java.util.Map)8 Messager (javax.annotation.processing.Messager)8