Search in sources :

Example 96 with JavaFileObject

use of javax.tools.JavaFileObject in project lombok by rzwitserloot.

the class CompilerMessageSuppressor method removeAllBetween.

public void removeAllBetween(JavaFileObject sourcefile, int startPos, int endPos) {
    DiagnosticListener<?> listener = context.get(DiagnosticListener.class);
    if (listener instanceof CapturingDiagnosticListener) {
        ((CapturingDiagnosticListener) listener).suppress(startPos, endPos);
    }
    Field field = null;
    Object receiver = null;
    if (deferDiagnosticsField != null)
        try {
            if (Boolean.TRUE.equals(deferDiagnosticsField.get(log))) {
                field = deferredDiagnosticsField;
                receiver = log;
            }
        } catch (Exception e) {
        }
    if (diagnosticHandlerField != null)
        try {
            Object handler = diagnosticHandlerField.get(log);
            field = getDeferredField(handler);
            receiver = handler;
        } catch (Exception e) {
        }
    if (field == null || receiver == null)
        return;
    try {
        ListBuffer<?> deferredDiagnostics = (ListBuffer<?>) field.get(receiver);
        ListBuffer<Object> newDeferredDiagnostics = new ListBuffer<Object>();
        for (Object diag_ : deferredDiagnostics) {
            if (!(diag_ instanceof JCDiagnostic)) {
                newDeferredDiagnostics.add(diag_);
                continue;
            }
            JCDiagnostic diag = (JCDiagnostic) diag_;
            long here = diag.getStartPosition();
            if (here >= startPos && here < endPos && diag.getSource() == sourcefile) {
            // We eliminate it
            } else {
                newDeferredDiagnostics.add(diag);
            }
        }
        field.set(receiver, newDeferredDiagnostics);
    } catch (Exception e) {
    // We do not expect failure here; if failure does occur, the best course of action is to silently continue; the result will be that the error output of
    // javac will contain rather a lot of messages, but this is a lot better than just crashing during compilation!
    }
}
Also used : Field(java.lang.reflect.Field) JCDiagnostic(com.sun.tools.javac.util.JCDiagnostic) ListBuffer(com.sun.tools.javac.util.ListBuffer) JavaFileObject(javax.tools.JavaFileObject) IOException(java.io.IOException)

Example 97 with JavaFileObject

use of javax.tools.JavaFileObject in project lombok by rzwitserloot.

the class JavacAST method printMessage.

/** Supply either a position or a node (in that case, position of the node is used) */
void printMessage(Diagnostic.Kind kind, String message, JavacNode node, DiagnosticPosition pos, boolean attemptToRemoveErrorsInRange) {
    JavaFileObject oldSource = null;
    JavaFileObject newSource = null;
    JCTree astObject = node == null ? null : node.get();
    JCCompilationUnit top = (JCCompilationUnit) top().get();
    newSource = top.sourcefile;
    if (newSource != null) {
        oldSource = log.useSource(newSource);
        if (pos == null)
            pos = astObject.pos();
    }
    if (pos != null && attemptToRemoveErrorsInRange) {
        removeFromDeferredDiagnostics(pos.getStartPosition(), node.getEndPosition(pos));
    }
    try {
        switch(kind) {
            case ERROR:
                increaseErrorCount(messager);
                boolean prev = log.multipleErrors;
                log.multipleErrors = true;
                try {
                    log.error(pos, "proc.messager", message);
                } finally {
                    log.multipleErrors = prev;
                }
                break;
            default:
            case WARNING:
                log.warning(pos, "proc.messager", message);
                break;
        }
    } finally {
        if (oldSource != null)
            log.useSource(oldSource);
    }
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) JavaFileObject(javax.tools.JavaFileObject) JCTree(com.sun.tools.javac.tree.JCTree)

Example 98 with JavaFileObject

use of javax.tools.JavaFileObject in project androidannotations by androidannotations.

the class ProcessorTestHelper method assertCompilationDiagnostingOn.

private static void assertCompilationDiagnostingOn(Kind expectedDiagnosticKind, File expectedErrorClassFile, String expectedContentInError, CompileResult result) throws IOException {
    String expectedErrorPath;
    boolean fileNameOnly = expectedErrorClassFile.getPath().split(Pattern.quote(File.separator)).length == 1;
    if (fileNameOnly) {
        // this is just the filename
        expectedErrorPath = expectedErrorClassFile.getPath();
    } else {
        expectedErrorPath = expectedErrorClassFile.toURI().toString();
    }
    for (Diagnostic<? extends JavaFileObject> diagnostic : result.diagnostics) {
        if (diagnostic.getKind() == expectedDiagnosticKind) {
            JavaFileObject source = diagnostic.getSource();
            if (source != null) {
                if (expectedErrorPath.endsWith(source.toUri().toString()) || fileNameOnly && source.toUri().toString().endsWith(expectedErrorPath)) {
                    CharSequence sourceContent = source.getCharContent(true);
                    if (diagnostic.getPosition() != Diagnostic.NOPOS) {
                        CharSequence contentInError = sourceContent.subSequence((int) diagnostic.getStartPosition(), (int) diagnostic.getEndPosition());
                        if (contentInError.toString().contains(expectedContentInError)) {
                            return;
                        }
                    }
                }
            }
        }
    }
    fail("Expected a compilation " + expectedDiagnosticKind + " in " + expectedErrorClassFile.toString() + " on " + expectedContentInError + ", diagnostics: " + result.diagnostics);
}
Also used : JavaFileObject(javax.tools.JavaFileObject)

Example 99 with JavaFileObject

use of javax.tools.JavaFileObject in project otter by alibaba.

the class JdkCompileTask method compile.

public synchronized Map<String, Class> compile(final Map<String, CharSequence> classes, final DiagnosticCollector<JavaFileObject> diagnosticsList) throws JdkCompileException {
    Map<String, Class> compiled = new HashMap<String, Class>();
    List<JavaFileObject> sources = new ArrayList<JavaFileObject>();
    for (Entry<String, CharSequence> entry : classes.entrySet()) {
        String qualifiedClassName = entry.getKey();
        CharSequence javaSource = entry.getValue();
        if (javaSource != null) {
            final int dotPos = qualifiedClassName.lastIndexOf('.');
            final String className = dotPos == -1 ? qualifiedClassName : qualifiedClassName.substring(dotPos + 1);
            final String packageName = dotPos == -1 ? "" : qualifiedClassName.substring(0, dotPos);
            final JavaFileObjectImpl source = new JavaFileObjectImpl(className, javaSource);
            sources.add(source);
            javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH, packageName, className + JAVA_EXTENSION, source);
        }
    }
    // Get a CompliationTask from the compiler and compile the sources
    final CompilationTask task = compiler.getTask(null, javaFileManager, diagnostics, options, null, sources);
    final Boolean result = task.call();
    if (result == null || !result.booleanValue()) {
        throw new JdkCompileException("Compilation failed.", classes.keySet(), diagnostics);
    }
    try {
        // put it in the output map
        for (String qualifiedClassName : classes.keySet()) {
            final Class<T> newClass = loadClass(qualifiedClassName);
            compiled.put(qualifiedClassName, (Class<?>) newClass);
        }
        return compiled;
    } catch (ClassNotFoundException e) {
        throw new JdkCompileException(classes.keySet(), e, diagnostics);
    } catch (IllegalArgumentException e) {
        throw new JdkCompileException(classes.keySet(), e, diagnostics);
    } catch (SecurityException e) {
        throw new JdkCompileException(classes.keySet(), e, diagnostics);
    }
}
Also used : HashMap(java.util.HashMap) JavaFileObjectImpl(com.alibaba.otter.shared.common.utils.compile.model.JavaFileObjectImpl) ArrayList(java.util.ArrayList) CompilationTask(javax.tools.JavaCompiler.CompilationTask) JdkCompileException(com.alibaba.otter.shared.common.utils.compile.exception.JdkCompileException) JavaFileObject(javax.tools.JavaFileObject)

Example 100 with JavaFileObject

use of javax.tools.JavaFileObject in project dagger by square.

the class GenericInjectAdapterGenerationTest method basicInjectAdapter.

@Test
public void basicInjectAdapter() {
    JavaFileObject sourceFile = JavaFileObjects.forSourceString("Basic", "" + "import dagger.Module;\n" + "import javax.inject.Inject;\n" + "class Basic {\n" + "  static class Simple {\n" + "    @Inject Simple() { }\n" + "  }\n" + "  static class A<T> { }\n" + "  static class B<T extends CharSequence> extends A<T> {\n" + "    @Inject Simple simple;\n" + "  }\n" + "  static class C extends B<String> { \n" + "    @Inject C() { }\n" + "  }\n" + "  @Module(injects = { C.class })\n" + "  static class AModule { }\n" + "}\n");
    JavaFileObject expectedInjectAdapterC = JavaFileObjects.forSourceString("Basic$B$$InjectAdapter", "" + "import dagger.internal.Binding;\n" + "import dagger.internal.Linker;\n" + "import java.lang.Override;\n" + "import java.lang.SuppressWarnings;\n" + "import java.util.Set;\n" + "public final class Basic$B$$InjectAdapter extends Binding<Basic.B> {\n" + "  private Binding<Basic.Simple> simple;\n" + "  private Binding<Basic.A> supertype;\n" + "  public Basic$B$$InjectAdapter() {\n" + "    super(\"Basic$B<T>\", \"members/Basic$B\", NOT_SINGLETON, Basic.B.class);\n" + "  }\n" + "  @Override\n" + "  @SuppressWarnings(\"unchecked\")\n" + "  public void attach(Linker linker) {\n" + "    simple = (Binding<Basic.Simple>) linker.requestBinding(\"Basic$Simple\", Basic.B.class, getClass().getClassLoader());\n" + "    supertype = (Binding<Basic.A>) linker.requestBinding(\"members/Basic$A\", Basic.B.class, getClass().getClassLoader(), false, true);\n" + "  }\n" + "  @Override\n" + "  public void getDependencies(Set<Binding<?>> getBindings, Set<Binding<?>> injectMembersBindings) {\n" + "    injectMembersBindings.add(simple);\n" + "    injectMembersBindings.add(supertype);\n" + "  }\n" + "  @Override\n" + "  public Basic.B get() {\n" + "    Basic.B result = new Basic.B();\n" + "    injectMembers(result);\n" + "    return result;\n" + "  }\n" + "  @Override\n" + "  public void injectMembers(Basic.B object) {\n" + "    object.simple = simple.get();\n" + "    supertype.injectMembers(object);\n" + "  }\n" + "}");
    assertAbout(javaSource()).that(sourceFile).processedWith(daggerProcessors()).compilesWithoutError().and().generatesSources(expectedInjectAdapterC);
}
Also used : JavaFileObject(javax.tools.JavaFileObject) Test(org.junit.Test)

Aggregations

JavaFileObject (javax.tools.JavaFileObject)663 Test (org.junit.Test)473 ButterKnifeProcessor (butterknife.compiler.ButterKnifeProcessor)121 IOException (java.io.IOException)52 JavaCompiler (javax.tools.JavaCompiler)40 StorIOContentResolverProcessor (com.pushtorefresh.storio.contentresolver.annotations.processor.StorIOContentResolverProcessor)38 StorIOSQLiteProcessor (com.pushtorefresh.storio.sqlite.annotations.processor.StorIOSQLiteProcessor)35 File (java.io.File)32 Diagnostic (javax.tools.Diagnostic)30 DiagnosticCollector (javax.tools.DiagnosticCollector)28 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)25 StandardJavaFileManager (javax.tools.StandardJavaFileManager)25 ArrayList (java.util.ArrayList)24 TypeElement (javax.lang.model.element.TypeElement)21 Result (com.sun.tools.javac.main.Main.Result)20 Writer (java.io.Writer)17 PrintWriter (java.io.PrintWriter)16 CompilationTask (javax.tools.JavaCompiler.CompilationTask)14 JCTree (com.sun.tools.javac.tree.JCTree)10 StringWriter (java.io.StringWriter)10