Search in sources :

Example 6 with Filer

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

the class MatchProcessor method createFiles.

private void createFiles(MatchRuleDescriptor info) {
    String pkg = ((PackageElement) info.topDeclaringType.getEnclosingElement()).getQualifiedName().toString();
    Name topDeclaringClass = info.topDeclaringType.getSimpleName();
    String matchStatementClassName = topDeclaringClass + "_" + MatchStatementSet.class.getSimpleName();
    Element[] originatingElements = info.originatingElements.toArray(new Element[info.originatingElements.size()]);
    Types typeUtils = typeUtils();
    Filer filer = processingEnv.getFiler();
    try (PrintWriter out = createSourceFile(pkg, matchStatementClassName, 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 " + MatchStatementSet.class.getPackage().getName() + ".*;");
        out.println("import " + NodeMatchRules.class.getName() + ";");
        out.println("import " + Position.class.getName() + ";");
        out.println("import " + ServiceProvider.class.getName() + ";");
        for (String p : info.requiredPackages) {
            out.println("import " + p + ".*;");
        }
        out.println("");
        out.println("@" + ServiceProvider.class.getSimpleName() + "(" + MatchStatementSet.class.getSimpleName() + ".class)");
        out.println("public class " + matchStatementClassName + " implements " + MatchStatementSet.class.getSimpleName() + " {");
        out.println();
        // Generate declarations for the wrapper class to invoke the code generation methods.
        for (MethodInvokerItem invoker : info.invokers.getValues()) {
            StringBuilder args = new StringBuilder();
            StringBuilder types = new StringBuilder();
            int count = invoker.fields.size();
            int index = 0;
            for (VariableElement arg : invoker.fields) {
                args.append('"');
                args.append(arg.getSimpleName());
                args.append('"');
                types.append(String.format("(%s) args[%s]", fullClassName(typeUtils.asElement(arg.asType())), index++));
                if (count-- > 1) {
                    args.append(", ");
                    types.append(", ");
                }
            }
            out.printf("    private static final String[] %s = new String[] {%s};\n", invoker.argumentsListName(), args);
            out.printf("    private static final class %s implements MatchGenerator {\n", invoker.wrapperClass());
            out.printf("        static MatchGenerator instance = new %s();\n", invoker.wrapperClass());
            out.printf("        @Override\n");
            out.printf("        public ComplexMatchResult match(NodeMatchRules nodeMatchRules, Object...args) {\n");
            out.printf("            return ((%s) nodeMatchRules).%s(%s);\n", invoker.nodeLIRBuilderClass, invoker.methodName, types);
            out.printf("        }\n");
            out.printf("        @Override\n");
            out.printf("        public String getName() {\n");
            out.printf("             return \"%s\";\n", invoker.methodName);
            out.printf("        }\n");
            out.printf("    }\n");
            out.println();
        }
        String desc = MatchStatement.class.getSimpleName();
        out.println("    @Override");
        out.println("    public Class<? extends NodeMatchRules> forClass() {");
        out.println("        return " + topDeclaringClass + ".class;");
        out.println("    }");
        out.println();
        out.println("    @Override");
        out.println("    public List<" + desc + "> statements() {");
        out.println("        // Checkstyle: stop ");
        for (String positionDeclaration : info.positionDeclarations) {
            out.println("        " + positionDeclaration);
        }
        out.println();
        out.println("        List<" + desc + "> statements = Collections.unmodifiableList(Arrays.asList(");
        int i = 0;
        for (MatchRuleItem matchRule : info.matchRules) {
            String comma = i == info.matchRules.size() - 1 ? "" : ",";
            out.printf("            %s%s\n", matchRule.ruleBuilder(), comma);
            i++;
        }
        out.println("        ));");
        out.println("        // Checkstyle: resume");
        out.println("        return statements;");
        out.println("    }");
        out.println();
        out.println("}");
    }
}
Also used : SupportedAnnotationTypes(javax.annotation.processing.SupportedAnnotationTypes) Types(javax.lang.model.util.Types) Position(org.graalvm.compiler.graph.Position) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) PackageElement(javax.lang.model.element.PackageElement) VariableElement(javax.lang.model.element.VariableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) MatchStatementSet(org.graalvm.compiler.core.match.MatchStatementSet) VariableElement(javax.lang.model.element.VariableElement) Name(javax.lang.model.element.Name) ServiceProvider(org.graalvm.compiler.serviceprovider.ServiceProvider) Filer(javax.annotation.processing.Filer) PrintWriter(java.io.PrintWriter) NodeMatchRules(org.graalvm.compiler.core.gen.NodeMatchRules)

Example 7 with Filer

use of javax.annotation.processing.Filer in project tikxml by Tickaroo.

the class TikXmlAutoValueExtension method applicable.

@Override
public boolean applicable(Context context) {
    ProcessingEnvironment environment = context.processingEnvironment();
    try {
        Xml xmlAnnotation = context.autoValueClass().getAnnotation(Xml.class);
        if (xmlAnnotation == null) {
            // Auto value class not annotated with @Xml annotation
            return false;
        }
        if (!xmlAnnotation.inheritance()) {
            throw new ProcessingException(context.autoValueClass(), "Inheritance in TikXml can't be disabled via @" + Xml.class.getSimpleName() + "(inheritance = false) in class " + context.autoValueClass().getQualifiedName());
        }
        List<AnnotatedMethod<?>> annotatedMethods = AutoValueScannerKt.extractAutoValueProperties(context.autoValueClass(), context.properties(), context.processingEnvironment().getTypeUtils(), context.processingEnvironment().getElementUtils());
        // generate code
        AutoValueAnnotatedClass annotatedClass = new AutoValueAnnotatedClass(context.packageName(), context.autoValueClass(), xmlAnnotation, annotatedMethods);
        try {
            Filer filer = context.processingEnvironment().getFiler();
            JavaFile.builder(context.packageName(), AutoValueTypeAdapterCodeGeneratorKt.generateValueHolder(annotatedClass, context.processingEnvironment().getElementUtils())).build().writeTo(filer);
            JavaFile.builder(context.packageName(), AutoValueTypeAdapterCodeGeneratorKt.generateTypeAdapter(annotatedClass)).build().writeTo(filer);
        } catch (IOException e) {
            throw new ProcessingException(annotatedClass.getAutoValueClass(), "Error while generating code for " + annotatedClass.getAutoValueClass().getQualifiedName() + ": " + e.getMessage());
        }
    } catch (ProcessingException exception) {
        environment.getMessager().printMessage(Diagnostic.Kind.ERROR, exception.getMessage(), exception.getElement());
    }
    // We don't generate code as an autovalue extension
    return false;
}
Also used : Xml(com.tickaroo.tikxml.annotation.Xml) IOException(java.io.IOException) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) Filer(javax.annotation.processing.Filer) ProcessingException(com.tickaroo.tikxml.processor.ProcessingException)

Example 8 with Filer

use of javax.annotation.processing.Filer in project ecf by eclipse.

the class AsyncAnnotationProcessor method process.

public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    ProcessingEnvironment env = super.processingEnv;
    Filer filer = env.getFiler();
    Set<TypeElement> annotatedDecls = (Set<TypeElement>) roundEnv.getElementsAnnotatedWith(AsyncService.class);
    for (Iterator<TypeElement> i = annotatedDecls.iterator(); i.hasNext(); ) {
        writeAsyncType(filer, i.next());
    }
    return true;
}
Also used : Set(java.util.Set) TypeElement(javax.lang.model.element.TypeElement) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) Filer(javax.annotation.processing.Filer) AsyncService(org.eclipse.ecf.remoteservice.AsyncService)

Example 9 with Filer

use of javax.annotation.processing.Filer in project syndesis by syndesisio.

the class ActionProcessor method obtainResourceFile.

// *****************************************
// Helpers
// *****************************************
/**
 * Helper method to produce class output text file using the given handler
 */
@SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
private File obtainResourceFile(Element element) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    TypeElement classElement;
    if (element instanceof TypeElement) {
        classElement = (TypeElement) element;
    } else if (element instanceof ExecutableElement) {
        classElement = (TypeElement) element.getEnclosingElement();
    } else {
        warning("Unsupported element kind: " + element.getKind());
        return null;
    }
    final String javaTypeName = canonicalClassName(classElement.getQualifiedName().toString());
    final String packageName = javaTypeName.substring(0, javaTypeName.lastIndexOf('.'));
    final Annotation annotation = element.getAnnotation(annotationClass);
    if (annotation == null) {
        error("Annotation SyndesisExtensionAction not found processing element " + element);
    }
    final String actionId = (String) annotationClass.getMethod("id").invoke(annotation);
    final String fileName = new StringBuilder().append(classElement.getSimpleName().toString()).append('-').append(Names.sanitize(actionId)).append(".json").toString();
    File result = null;
    Filer filer = processingEnv.getFiler();
    FileObject resource;
    try {
        resource = filer.getResource(StandardLocation.SOURCE_OUTPUT, packageName, fileName);
    } catch (Exception e) {
        resource = filer.createResource(StandardLocation.SOURCE_OUTPUT, packageName, fileName);
    }
    URI uri = resource.toUri();
    if (uri != null) {
        try {
            result = new File(uri.getPath());
        } catch (Exception e) {
            warning("Cannot convert output directory resource URI to a file " + e);
        }
    }
    if (result == null) {
        warning("No class output directory could be found!");
    } else {
        result.getParentFile().mkdirs();
    }
    return result;
}
Also used : TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) FileObject(javax.tools.FileObject) File(java.io.File) Filer(javax.annotation.processing.Filer) URI(java.net.URI) Annotation(java.lang.annotation.Annotation) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 10 with Filer

use of javax.annotation.processing.Filer in project fabric8 by fabric8io.

the class CompilationTaskFactory method createFileManager.

/**
 * Obtains the {@link javax.tools.JavaFileManager} from the {@link javax.annotation.processing.ProcessingEnvironment}/
 * @param processingEnvironment The processing environment.
 * @return                      The file manager.
 */
static JavaFileManager createFileManager(ProcessingEnvironment processingEnvironment) {
    Filer filer = processingEnvironment.getFiler();
    try {
        Field field = filer.getClass().getDeclaredField(FILE_MANAGER_FIELD_NAME);
        field.setAccessible(true);
        return (JavaFileManager) field.get(filer);
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}
Also used : Field(java.lang.reflect.Field) JavaFileManager(javax.tools.JavaFileManager) Filer(javax.annotation.processing.Filer)

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