Search in sources :

Example 1 with Filer

use of javax.annotation.processing.Filer in project javaslang by javaslang.

the class PatternsProcessor method generate.

// Expands all @Patterns classes
private void generate(Set<ClassModel> classModels) {
    final Filer filer = processingEnv.getFiler();
    for (ClassModel classModel : classModels) {
        final String derivedClassName = deriveClassName(classModel);
        final String code = Generator.generate(derivedClassName, classModel);
        final String fqn = (classModel.hasDefaultPackage() ? "" : classModel.getPackageName() + ".") + derivedClassName;
        try (final Writer writer = filer.createSourceFile(fqn, classModel.typeElement()).openWriter()) {
            writer.write(code);
        } catch (IOException x) {
            throw new Error("Error writing " + fqn, x);
        }
    }
}
Also used : ClassModel(javaslang.match.model.ClassModel) IOException(java.io.IOException) Filer(javax.annotation.processing.Filer) Writer(java.io.Writer)

Example 2 with Filer

use of javax.annotation.processing.Filer in project camel by apache.

the class AnnotationProcessorHelper method loadResource.

public static String loadResource(ProcessingEnvironment processingEnv, String packageName, String fileName) {
    Filer filer = processingEnv.getFiler();
    FileObject resource;
    String relativeName = packageName + "/" + fileName;
    try {
        resource = filer.getResource(StandardLocation.CLASS_OUTPUT, "", relativeName);
    } catch (Throwable e) {
        return "Cannot load classpath resource: " + relativeName + " due: " + e.getMessage();
    }
    if (resource == null) {
        return null;
    }
    try {
        InputStream is = resource.openInputStream();
        return loadText(is, true);
    } catch (Exception e) {
        warning(processingEnv, "APT cannot load file: " + packageName + "/" + fileName);
    }
    return null;
}
Also used : InputStream(java.io.InputStream) FileObject(javax.tools.FileObject) Filer(javax.annotation.processing.Filer) IOException(java.io.IOException)

Example 3 with Filer

use of javax.annotation.processing.Filer 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 4 with Filer

use of javax.annotation.processing.Filer in project graal by oracle.

the class OptionProcessor method createOptionsDescriptorsFile.

private void createOptionsDescriptorsFile(OptionsInfo info, String pkg, Name topDeclaringClass, Element[] originatingElements) {
    String optionsClassName = topDeclaringClass + "_" + OptionDescriptors.class.getSimpleName();
    Filer filer = processingEnv.getFiler();
    try (PrintWriter out = createSourceFile(pkg, optionsClassName, filer, originatingElements)) {
        out.println("// CheckStyle: stop header check");
        out.println("// CheckStyle: stop line length check");
        out.println("// GENERATED CONTENT - DO NOT EDIT");
        out.println("// Source: " + topDeclaringClass + ".java");
        out.println("package " + pkg + ";");
        out.println("");
        out.println("import java.util.*;");
        out.println("import " + OptionDescriptors.class.getPackage().getName() + ".*;");
        out.println("import " + OptionType.class.getName() + ";");
        out.println("");
        out.println("public class " + optionsClassName + " implements " + OptionDescriptors.class.getSimpleName() + " {");
        String desc = OptionDescriptor.class.getSimpleName();
        Collections.sort(info.options);
        out.println("    @Override");
        out.println("    public OptionDescriptor get(String value) {");
        out.println("        switch (value) {");
        out.println("        // CheckStyle: stop line length check");
        for (OptionInfo option : info.options) {
            String name = option.name;
            String optionField;
            if (option.field.getModifiers().contains(Modifier.PRIVATE)) {
                throw new InternalError();
            } else {
                optionField = option.declaringClass + "." + option.field.getSimpleName();
            }
            out.println("        case \"" + name + "\": {");
            OptionType optionType = option.optionType;
            String type = option.type;
            String help = option.help;
            String[] extraHelp = option.extraHelp;
            String declaringClass = option.declaringClass;
            Name fieldName = option.field.getSimpleName();
            out.printf("            return " + desc + ".create(\n");
            out.printf("                /*name*/ \"%s\",\n", name);
            out.printf("                /*optionType*/ %s.%s,\n", optionType.getDeclaringClass().getSimpleName(), optionType.name());
            out.printf("                /*optionValueType*/ %s.class,\n", type);
            out.printf("                /*help*/ \"%s\",\n", help);
            if (extraHelp.length != 0) {
                out.printf("                /*extraHelp*/ new String[] {\n");
                for (String line : extraHelp) {
                    out.printf("                         \"%s\",\n", line.replace("\\", "\\\\").replace("\"", "\\\""));
                }
                out.printf("                              },\n");
            }
            out.printf("                /*declaringClass*/ %s.class,\n", declaringClass);
            out.printf("                /*fieldName*/ \"%s\",\n", fieldName);
            out.printf("                /*option*/ %s);\n", optionField);
            out.println("        }");
        }
        out.println("        // CheckStyle: resume line length check");
        out.println("        }");
        out.println("        return null;");
        out.println("    }");
        out.println();
        out.println("    @Override");
        out.println("    public Iterator<" + desc + "> iterator() {");
        out.println("        return new Iterator<OptionDescriptor>() {");
        out.println("            int i = 0;");
        out.println("            @Override");
        out.println("            public boolean hasNext() {");
        out.println("                return i < " + info.options.size() + ";");
        out.println("            }");
        out.println("            @Override");
        out.println("            public OptionDescriptor next() {");
        out.println("                switch (i++) {");
        for (int i = 0; i < info.options.size(); i++) {
            OptionInfo option = info.options.get(i);
            out.println("                    case " + i + ": return get(\"" + option.name + "\");");
        }
        out.println("                }");
        out.println("                throw new NoSuchElementException();");
        out.println("            }");
        out.println("        };");
        out.println("    }");
        out.println("}");
    }
}
Also used : OptionDescriptors(org.graalvm.compiler.options.OptionDescriptors) Filer(javax.annotation.processing.Filer) OptionType(org.graalvm.compiler.options.OptionType) PrintWriter(java.io.PrintWriter) Name(javax.lang.model.element.Name)

Example 5 with Filer

use of javax.annotation.processing.Filer in project ballerina by ballerina-lang.

the class BallerinaAnnotationProcessor method createServiceFile.

private void createServiceFile(String interfaceName, List<String> implClasses) {
    Filer filer = this.processingEnv.getFiler();
    Writer writer = null;
    try {
        writer = filer.createResource(StandardLocation.CLASS_OUTPUT, "", JAVA_SPI_SERVICES_BASE_PATH + interfaceName).openWriter();
        writer.write(String.join("\n", implClasses));
    } catch (IOException e) {
        throw new RuntimeException("Error creating Java SPI services file: " + e.getMessage(), e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException ignore) {
            }
        }
    }
}
Also used : IOException(java.io.IOException) Filer(javax.annotation.processing.Filer) Writer(java.io.Writer)

Aggregations

Filer (javax.annotation.processing.Filer)27 IOException (java.io.IOException)18 TypeElement (javax.lang.model.element.TypeElement)13 FileObject (javax.tools.FileObject)13 Writer (java.io.Writer)11 Element (javax.lang.model.element.Element)9 File (java.io.File)6 PackageElement (javax.lang.model.element.PackageElement)6 PrintWriter (java.io.PrintWriter)5 URI (java.net.URI)4 ExecutableElement (javax.lang.model.element.ExecutableElement)4 JavaFileObject (javax.tools.JavaFileObject)4 StringWriter (java.io.StringWriter)3 ArrayList (java.util.ArrayList)3 ProcessingEnvironment (javax.annotation.processing.ProcessingEnvironment)3 Name (javax.lang.model.element.Name)3 VariableElement (javax.lang.model.element.VariableElement)3 DeclaredType (javax.lang.model.type.DeclaredType)3 FileReader (java.io.FileReader)2 FileWriter (java.io.FileWriter)2