Search in sources :

Example 1 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project buck by facebook.

the class Jsr199Javac method buildWithClasspath.

private int buildWithClasspath(JavacExecutionContext context, BuildTarget invokingRule, ImmutableList<String> options, ImmutableList<ResolvedJavacPluginProperties> annotationProcessors, ImmutableSortedSet<Path> javaSourceFilePaths, Path pathToSrcsList, JavaCompiler compiler, StandardJavaFileManager fileManager, Iterable<? extends JavaFileObject> compilationUnits, JavacOptions.AbiGenerationMode abiGenerationMode) {
    // since we do not print them out to console in case of error
    try {
        context.getProjectFilesystem().writeLinesToPath(FluentIterable.from(javaSourceFilePaths).transform(Object::toString).transform(ARGFILES_ESCAPER), pathToSrcsList);
    } catch (IOException e) {
        context.getEventSink().reportThrowable(e, "Cannot write list of .java files to compile to %s file! Terminating compilation.", pathToSrcsList);
        return 1;
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    List<String> classNamesForAnnotationProcessing = ImmutableList.of();
    Writer compilerOutputWriter = new PrintWriter(context.getStdErr());
    JavaCompiler.CompilationTask compilationTask = compiler.getTask(compilerOutputWriter, context.getUsedClassesFileWriter().wrapFileManager(fileManager), diagnostics, options, classNamesForAnnotationProcessing, compilationUnits);
    boolean isSuccess = false;
    BuckTracing.setCurrentThreadTracingInterfaceFromJsr199Javac(new Jsr199TracingBridge(context.getEventSink(), invokingRule));
    Object abiValidatingTaskListener = null;
    if (abiGenerationMode != JavacOptions.AbiGenerationMode.CLASS) {
        abiValidatingTaskListener = SourceBasedAbiStubber.newValidatingTaskListener(context.getClassLoaderCache(), compilationTask, new FileManagerBootClasspathOracle(fileManager), abiGenerationMode == JavacOptions.AbiGenerationMode.SOURCE ? Diagnostic.Kind.ERROR : Diagnostic.Kind.WARNING);
    }
    try {
        try (// in some unusual situations
        TranslatingJavacPhaseTracer tracer = TranslatingJavacPhaseTracer.setupTracing(invokingRule, context.getClassLoaderCache(), context.getEventSink(), compilationTask, abiValidatingTaskListener);
            // may choke with novel errors that don't occur on the command line.
            AnnotationProcessorFactory processorFactory = new AnnotationProcessorFactory(context.getEventSink(), compiler.getClass().getClassLoader(), context.getClassLoaderCache(), invokingRule)) {
            compilationTask.setProcessors(processorFactory.createProcessors(annotationProcessors));
            // Invoke the compilation and inspect the result.
            isSuccess = compilationTask.call();
        } catch (IOException e) {
            LOG.warn(e, "Unable to close annotation processor class loader. We may be leaking memory.");
        }
    } finally {
        // Clear the tracing interface so we have no chance of leaking it to code that shouldn't
        // be using it.
        BuckTracing.clearCurrentThreadTracingInterfaceFromJsr199Javac();
    }
    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
        LOG.debug("javac: %s", DiagnosticPrettyPrinter.format(diagnostic));
    }
    List<Diagnostic<? extends JavaFileObject>> cleanDiagnostics = DiagnosticCleaner.clean(diagnostics.getDiagnostics());
    if (isSuccess) {
        context.getUsedClassesFileWriter().writeFile(context.getProjectFilesystem(), context.getObjectMapper());
        return 0;
    } else {
        if (context.getVerbosity().shouldPrintStandardInformation()) {
            int numErrors = 0;
            int numWarnings = 0;
            for (Diagnostic<? extends JavaFileObject> diagnostic : cleanDiagnostics) {
                Diagnostic.Kind kind = diagnostic.getKind();
                if (kind == Diagnostic.Kind.ERROR) {
                    ++numErrors;
                    handleMissingSymbolError(invokingRule, diagnostic, context);
                } else if (kind == Diagnostic.Kind.WARNING || kind == Diagnostic.Kind.MANDATORY_WARNING) {
                    ++numWarnings;
                }
                context.getStdErr().println(DiagnosticPrettyPrinter.format(diagnostic));
            }
            if (numErrors > 0 || numWarnings > 0) {
                context.getStdErr().printf("Errors: %d. Warnings: %d.\n", numErrors, numWarnings);
            }
        }
        return 1;
    }
}
Also used : JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) IOException(java.io.IOException) JavaFileObject(javax.tools.JavaFileObject) TranslatingJavacPhaseTracer(com.facebook.buck.jvm.java.tracing.TranslatingJavacPhaseTracer) JavaFileObject(javax.tools.JavaFileObject) DiagnosticCollector(javax.tools.DiagnosticCollector) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) PrintWriter(java.io.PrintWriter)

Example 2 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project buck by facebook.

the class JavaInMemoryFileManagerTest method setUp.

@Before
public void setUp() {
    outputStream = new TestCustomZipOutputStream();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    inMemoryFileManager = new JavaInMemoryFileManager(ToolProvider.getSystemJavaCompiler().getStandardFileManager(diagnostics, null, null), Paths.get(URI.create("file:///tmp/test.jar!/")), outputStream, /*classesToBeRemovedFromJar */
    ImmutableSet.of());
}
Also used : JavaFileObject(javax.tools.JavaFileObject) DiagnosticCollector(javax.tools.DiagnosticCollector) TestCustomZipOutputStream(com.facebook.buck.testutil.TestCustomZipOutputStream) Before(org.junit.Before)

Example 3 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project javapoet by square.

the class FileReadingTest method compileJavaFile.

@Test
public void compileJavaFile() throws Exception {
    final String value = "Hello World!";
    TypeSpec type = TypeSpec.classBuilder("Test").addModifiers(Modifier.PUBLIC).addSuperinterface(ParameterizedTypeName.get(Callable.class, String.class)).addMethod(MethodSpec.methodBuilder("call").returns(String.class).addModifiers(Modifier.PUBLIC).addStatement("return $S", value).build()).build();
    JavaFile javaFile = JavaFile.builder("foo", type).build();
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, Locale.getDefault(), UTF_8);
    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(temporaryFolder.newFolder()));
    CompilationTask task = compiler.getTask(null, fileManager, diagnosticCollector, Collections.<String>emptySet(), Collections.<String>emptySet(), Collections.singleton(javaFile.toJavaFileObject()));
    assertThat(task.call()).isTrue();
    assertThat(diagnosticCollector.getDiagnostics()).isEmpty();
    ClassLoader loader = fileManager.getClassLoader(StandardLocation.CLASS_OUTPUT);
    Callable<?> test = Class.forName("foo.Test", true, loader).asSubclass(Callable.class).newInstance();
    assertThat(Callable.class.getMethod("call").invoke(test)).isEqualTo(value);
}
Also used : JavaFileObject(javax.tools.JavaFileObject) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) Callable(java.util.concurrent.Callable) CompilationTask(javax.tools.JavaCompiler.CompilationTask) Test(org.junit.Test)

Example 4 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project bazel by bazelbuild.

the class BazelJavaCompilerTest method assertCompileSucceeds.

private void assertCompileSucceeds(final String uri, final String content) throws Exception {
    JavaCompiler javac = BazelJavaCompiler.newInstance();
    JavaFileObject source = new SimpleJavaFileObject(URI.create(uri), JavaFileObject.Kind.SOURCE) {

        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return content;
        }
    };
    StandardJavaFileManager fileManager = javac.getStandardFileManager(null, null, null);
    // setting the output path by passing a flag to getTask is not reliable
    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(getTmpDir()));
    DiagnosticCollector<JavaFileObject> messages = new DiagnosticCollector<>();
    JavaCompiler.CompilationTask task = javac.getTask(null, fileManager, messages, null, null, Collections.singletonList(source));
    assertTrue(task.call());
    assertTrue(messages.getDiagnostics().isEmpty());
}
Also used : SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 5 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project auto by google.

the class AutoAnnotationCompilationTest method doTestMissingClass.

private void doTestMissingClass(File tempDir) {
    // Test that referring to an undefined annotation does not trigger @AutoAnnotation processing.
    // The class Erroneous references an undefined annotation @NotAutoAnnotation. If we didn't have
    // any special treatment of undefined types then we could run into a compiler bug where
    // AutoAnnotationProcessor would think that a method annotated with @NotAutoAnnotation was in
    // fact annotated with @AutoAnnotation. As it is, we do get an error about @NotAutoAnnotation
    // being undefined, and we do not get an error complaining that this supposed @AutoAnnotation
    // method is not static. We do need to have @AutoAnnotation appear somewhere so that the
    // processor will run.
    JavaFileObject erroneousJavaFileObject = JavaFileObjects.forSourceLines("com.example.annotations.Erroneous", "package com.example.annotations;", "", "import com.google.auto.value.AutoAnnotation;", "", "public class Erroneous {", "  @interface Empty {}", "  @AutoAnnotation static Empty newEmpty() {}", "  @NotAutoAnnotation Empty notNewEmpty() {}", "}");
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
    JavaCompiler.CompilationTask compilationTask = javaCompiler.getTask((Writer) null, (JavaFileManager) null, diagnosticCollector, ImmutableList.of("-d", tempDir.toString()), (Iterable<String>) null, ImmutableList.of(erroneousJavaFileObject));
    compilationTask.setProcessors(ImmutableList.of(new AutoAnnotationProcessor()));
    boolean result = compilationTask.call();
    assertThat(result).isFalse();
    List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticCollector.getDiagnostics();
    assertThat(diagnostics).isNotEmpty();
    assertThat(diagnostics.get(0).getMessage(null)).contains("NotAutoAnnotation");
    assertThat(diagnostics.get(0).getMessage(null)).doesNotContain("static");
}
Also used : JavaFileObject(javax.tools.JavaFileObject) JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) DiagnosticCollector(javax.tools.DiagnosticCollector)

Aggregations

DiagnosticCollector (javax.tools.DiagnosticCollector)28 JavaFileObject (javax.tools.JavaFileObject)28 JavaCompiler (javax.tools.JavaCompiler)24 StandardJavaFileManager (javax.tools.StandardJavaFileManager)16 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)9 Diagnostic (javax.tools.Diagnostic)9 CompilationTask (javax.tools.JavaCompiler.CompilationTask)9 File (java.io.File)8 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)8 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)4 Test (org.junit.Test)4 FileOutputStream (java.io.FileOutputStream)3 PrintWriter (java.io.PrintWriter)3 StringWriter (java.io.StringWriter)3 ImmutableList (com.google.common.collect.ImmutableList)2 Truth.assertThat (com.google.common.truth.Truth.assertThat)2 DescriptionBasedDiff (com.google.errorprone.apply.DescriptionBasedDiff)2 SourceFile (com.google.errorprone.apply.SourceFile)2 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)2