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