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;
}
}
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;
}
};
}
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);
}
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;
}
}
};
}
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);
}
}
Aggregations