Search in sources :

Example 16 with JavaCompiler

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

Example 17 with JavaCompiler

use of javax.tools.JavaCompiler in project error-prone by google.

the class CodeTransformerTestHelper method transform.

public JavaFileObject transform(JavaFileObject original) {
    JavaCompiler compiler = JavacTool.create();
    DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticsCollector, Locale.ENGLISH, UTF_8);
    JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(CharStreams.nullWriter(), fileManager, diagnosticsCollector, ImmutableList.<String>of(), null, ImmutableList.of(original));
    try {
        SourceFile sourceFile = SourceFile.create(original);
        Iterable<? extends CompilationUnitTree> trees = task.parse();
        task.analyze();
        JCCompilationUnit tree = Iterables.getOnlyElement(Iterables.filter(trees, JCCompilationUnit.class));
        DescriptionBasedDiff diff = DescriptionBasedDiff.create(tree);
        transformer().apply(new TreePath(tree), task.getContext(), diff);
        diff.applyDifferences(sourceFile);
        return JavaFileObjects.forSourceString(Iterables.getOnlyElement(Iterables.filter(tree.getTypeDecls(), JCClassDecl.class)).sym.getQualifiedName().toString(), sourceFile.getSourceText());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) DescriptionBasedDiff(com.google.errorprone.apply.DescriptionBasedDiff) JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) JCClassDecl(com.sun.tools.javac.tree.JCTree.JCClassDecl) JavaCompiler(javax.tools.JavaCompiler) IOException(java.io.IOException) JavaFileObject(javax.tools.JavaFileObject) TreePath(com.sun.source.util.TreePath) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) SourceFile(com.google.errorprone.apply.SourceFile)

Example 18 with JavaCompiler

use of javax.tools.JavaCompiler in project error-prone by google.

the class GuardedByBinderTest method bind.

private String bind(String className, String exprString, JavaFileObject fileObject) {
    JavaCompiler javaCompiler = JavacTool.create();
    JavacTaskImpl task = (JavacTaskImpl) javaCompiler.getTask(new PrintWriter(System.err, true), fileManager, null, Collections.<String>emptyList(), null, Arrays.asList(fileObject));
    Iterable<? extends CompilationUnitTree> compilationUnits = task.parse();
    task.analyze();
    for (CompilationUnitTree compilationUnit : compilationUnits) {
        FindClass finder = new FindClass();
        finder.visitTopLevel((JCTree.JCCompilationUnit) compilationUnit);
        for (JCTree.JCClassDecl classDecl : finder.decls) {
            if (classDecl.getSimpleName().contentEquals(className)) {
                Optional<GuardedByExpression> guardExpression = GuardedByBinder.bindString(exprString, GuardedBySymbolResolver.from(ASTHelpers.getSymbol(classDecl), compilationUnit, task.getContext(), null));
                if (!guardExpression.isPresent()) {
                    throw new IllegalGuardedBy(exprString);
                }
                return guardExpression.get().debugPrint();
            }
        }
    }
    throw new AssertionError("Couldn't find a class with the given name: " + className);
}
Also used : JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) JavaCompiler(javax.tools.JavaCompiler) JCTree(com.sun.tools.javac.tree.JCTree) PrintWriter(java.io.PrintWriter)

Example 19 with JavaCompiler

use of javax.tools.JavaCompiler in project error-prone by google.

the class ErrorProneJavaCompilerTest method testGetStandardJavaFileManager.

@Test
public void testGetStandardJavaFileManager() {
    JavaCompiler mockCompiler = mock(JavaCompiler.class);
    ErrorProneJavaCompiler compiler = new ErrorProneJavaCompiler(mockCompiler);
    JavaFileObjectDiagnosticListener listener = mock(JavaFileObjectDiagnosticListener.class);
    Locale locale = Locale.CANADA;
    compiler.getStandardFileManager(listener, locale, null);
    verify(mockCompiler).getStandardFileManager(listener, locale, null);
}
Also used : Locale(java.util.Locale) JavaCompiler(javax.tools.JavaCompiler) Test(org.junit.Test)

Example 20 with JavaCompiler

use of javax.tools.JavaCompiler in project error-prone by google.

the class ErrorProneJavaCompilerTest method doCompile.

private CompilationResult doCompile(List<String> fileNames, List<String> extraArgs, List<Class<? extends BugChecker>> customCheckers) {
    DiagnosticTestHelper diagnosticHelper = new DiagnosticTestHelper();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream, UTF_8), true);
    ErrorProneInMemoryFileManager fileManager = new ErrorProneInMemoryFileManager();
    List<String> args = Lists.newArrayList("-d", tempDir.getRoot().getAbsolutePath(), "-proc:none");
    args.addAll(extraArgs);
    JavaCompiler errorProneJavaCompiler = (customCheckers.isEmpty()) ? new ErrorProneJavaCompiler() : new ErrorProneJavaCompiler(ScannerSupplier.fromBugCheckerClasses(customCheckers));
    JavaCompiler.CompilationTask task = errorProneJavaCompiler.getTask(printWriter, fileManager, diagnosticHelper.collector, args, null, fileManager.forResources(getClass(), fileNames.toArray(new String[0])));
    try {
        fileManager.close();
    } catch (IOException e) {
        throw new IOError(e);
    }
    return new CompilationResult(task.call(), diagnosticHelper);
}
Also used : JavaCompiler(javax.tools.JavaCompiler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Matchers.containsString(org.hamcrest.Matchers.containsString) IOException(java.io.IOException) IOError(java.io.IOError) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter)

Aggregations

JavaCompiler (javax.tools.JavaCompiler)101 StandardJavaFileManager (javax.tools.StandardJavaFileManager)43 JavaFileObject (javax.tools.JavaFileObject)39 File (java.io.File)31 DiagnosticCollector (javax.tools.DiagnosticCollector)24 ArrayList (java.util.ArrayList)22 JavacTask (com.sun.source.util.JavacTask)20 IOException (java.io.IOException)17 CompilationTask (javax.tools.JavaCompiler.CompilationTask)16 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)15 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)11 Diagnostic (javax.tools.Diagnostic)11 PrintWriter (java.io.PrintWriter)9 Test (org.junit.Test)9 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 FileOutputStream (java.io.FileOutputStream)5 StringWriter (java.io.StringWriter)5 JavaFileManager (javax.tools.JavaFileManager)5 OutputStream (java.io.OutputStream)4