Search in sources :

Example 1 with Diagnostic

use of javax.tools.Diagnostic 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 Diagnostic

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

the class DiagnosticPrettyPrinterTest method createDiagnostic.

/**
   * Create a {@link Diagnostic} for use in tests.
   *
   * @param message The compilation error message.
   * @param row The row within the source, 1-indexed because the compiler does that.
   * @param column The column within {@code row}, also 1-indexed.
   */
private Diagnostic<? extends JavaFileObject> createDiagnostic(final String message, String pathToSource, String sourceContents, final long row, final long column) throws Exception {
    final JavaFileObject fileObject = new StringJavaFileObject(pathToSource, sourceContents);
    // Calculate the position, because we're all bad at counting things
    int pos = -1;
    if (row != -1) {
        pos = -1;
        int rowCount = 1;
        while (rowCount <= row) {
            pos++;
            if (sourceContents.charAt(pos) == '\n') {
                rowCount++;
            }
        }
        // And now just add the row, which is 1 indexed, so we then subtract 1.
        pos += row - 1;
    }
    final int position = pos;
    return new Diagnostic<JavaFileObject>() {

        @Override
        public Kind getKind() {
            return Kind.ERROR;
        }

        @Override
        public JavaFileObject getSource() {
            return fileObject;
        }

        @Override
        public long getPosition() {
            return position;
        }

        @Override
        public long getStartPosition() {
            return position;
        }

        @Override
        public long getEndPosition() {
            return position;
        }

        @Override
        public long getLineNumber() {
            return row;
        }

        @Override
        public long getColumnNumber() {
            return column;
        }

        @Override
        @Nullable
        public String getCode() {
            return null;
        }

        @Override
        public String getMessage(Locale locale) {
            return message;
        }
    };
}
Also used : Locale(java.util.Locale) JavaFileObject(javax.tools.JavaFileObject) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) Diagnostic(javax.tools.Diagnostic)

Example 3 with Diagnostic

use of javax.tools.Diagnostic in project jsonschema2pojo by joelittlejohn.

the class CompilerWarningIT method checkWarnings.

@Test
public void checkWarnings() {
    schemaRule.generate(schema, "com.example", config);
    schemaRule.compile(compiler, new NullWriter(), new ArrayList<File>(), config);
    List<Diagnostic<? extends JavaFileObject>> warnings = warnings(schemaRule.getDiagnostics());
    assertThat(warnings, matcher);
}
Also used : JavaFileObject(javax.tools.JavaFileObject) Diagnostic(javax.tools.Diagnostic) File(java.io.File) NullWriter(org.apache.commons.io.output.NullWriter) Test(org.junit.Test)

Example 4 with Diagnostic

use of javax.tools.Diagnostic in project jsonschema2pojo by joelittlejohn.

the class Jsonschema2PojoRule method apply.

@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            active = true;
            diagnostics = new ArrayList<Diagnostic<? extends JavaFileObject>>();
            boolean captureDiagnosticsStart = captureDiagnostics;
            try {
                File testRoot = methodNameDir(classNameDir(rootDirectory(), description.getClassName()), description.getMethodName());
                generateDir = new File(testRoot, "generate");
                compileDir = new File(testRoot, "compile");
                base.evaluate();
            } finally {
                generateDir = null;
                compileDir = null;
                classLoader = null;
                sourceDirInitialized = false;
                classesDirInitialized = false;
                captureDiagnostics = captureDiagnosticsStart;
                diagnostics = null;
                active = false;
            }
        }
    };
}
Also used : JavaFileObject(javax.tools.JavaFileObject) Statement(org.junit.runners.model.Statement) Diagnostic(javax.tools.Diagnostic) File(java.io.File)

Example 5 with Diagnostic

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

the class TestClassFileMetaData method compile.

static byte[] compile(File file) {
    try {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        File tempDir = getTempDir();
        tempDir.mkdirs();
        List<String> options = Arrays.asList("-proc:none", "-d", tempDir.getAbsolutePath());
        StringWriter captureWarnings = new StringWriter();
        final StringBuilder compilerErrors = new StringBuilder();
        DiagnosticListener<JavaFileObject> diagnostics = new DiagnosticListener<JavaFileObject>() {

            @Override
            public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
                compilerErrors.append(diagnostic.toString()).append("\n");
            }
        };
        CompilationTask task = compiler.getTask(captureWarnings, null, diagnostics, options, null, Collections.singleton(new ContentBasedJavaFileObject(file.getPath(), readFileAsString(file))));
        Boolean taskResult = task.call();
        assertTrue("Compilation task didn't succeed: \n<Warnings and Errors>\n" + compilerErrors.toString() + "\n</Warnings and Errors>", taskResult);
        return PostCompilerApp.readFile(new File(tempDir, file.getName().replaceAll("\\.java$", ".class")));
    } catch (Exception e) {
        throw Lombok.sneakyThrow(e);
    }
}
Also used : JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) DiagnosticListener(javax.tools.DiagnosticListener) CompilationTask(javax.tools.JavaCompiler.CompilationTask) IOException(java.io.IOException) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) StringWriter(java.io.StringWriter) File(java.io.File)

Aggregations

Diagnostic (javax.tools.Diagnostic)31 JavaFileObject (javax.tools.JavaFileObject)30 Test (org.junit.Test)13 JavaCompiler (javax.tools.JavaCompiler)11 Result (com.sun.tools.javac.main.Main.Result)10 DiagnosticCollector (javax.tools.DiagnosticCollector)9 File (java.io.File)7 IOException (java.io.IOException)7 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)7 PrintWriter (java.io.PrintWriter)6 Matchers.containsString (org.hamcrest.Matchers.containsString)6 ArrayList (java.util.ArrayList)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 DiagnosticListener (javax.tools.DiagnosticListener)4 ImmutableList (com.google.common.collect.ImmutableList)3 Truth.assertThat (com.google.common.truth.Truth.assertThat)2 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)2 JavacTask (com.sun.source.util.JavacTask)2 OutputStreamWriter (java.io.OutputStreamWriter)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2