Search in sources :

Example 1 with JavacTask

use of com.sun.source.util.JavacTask in project buck by facebook.

the class TracingTaskListener method setupTracing.

public static void setupTracing(JavaCompiler.CompilationTask task, JavacPhaseTracer tracing, Object next) {
    if (!(task instanceof JavacTask)) {
        return;
    }
    final JavacTask javacTask = (JavacTask) task;
    // The main part of Buck doesn't have access to `TaskListener`, since that's defined in the
    // compiler jar. So we had to pass it as an object and downcast.
    final TaskListener nextListener = (TaskListener) next;
    javacTask.setTaskListener(new TracingTaskListener(tracing, nextListener));
}
Also used : TaskListener(com.sun.source.util.TaskListener) JavacTask(com.sun.source.util.JavacTask)

Example 2 with JavacTask

use of com.sun.source.util.JavacTask in project jdk8u_jdk by JetBrains.

the class Compiler method compileOne.

private File compileOne(Type type) {
    if (this.flags.contains(Flags.USECACHE)) {
        File dir = cache.get(type.getName());
        if (dir != null) {
            return dir;
        }
    }
    List<JavaFileObject> files = new ArrayList<>();
    SourceProcessor accum = (name, src) -> files.add(new SourceFile(name, src));
    for (Type dep : type.typeDependencies()) {
        dep.generateAsDependency(accum, type.methodDependencies());
    }
    type.generate(accum);
    JavacTask ct = (JavacTask) this.systemJavaCompiler.getTask(null, this.fm, null, null, null, files);
    File destDir = null;
    do {
        int value = counter.incrementAndGet();
        destDir = new File(root, Integer.toString(value));
    } while (destDir.exists());
    if (this.flags.contains(Flags.VERBOSE)) {
        System.out.println("Compilation unit for " + type.getName() + " : compiled into " + destDir);
        for (JavaFileObject jfo : files) {
            System.out.println(jfo.toString());
        }
    }
    try {
        destDir.mkdirs();
        this.fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
    } catch (IOException e) {
        throw new RuntimeException("IOException encountered during compilation");
    }
    Boolean result = ct.call();
    if (result == Boolean.FALSE) {
        throw new RuntimeException("Compilation failure in " + type.getName() + " unit");
    }
    if (this.flags.contains(Flags.USECACHE)) {
        File existing = cache.putIfAbsent(type.getName(), destDir);
        if (existing != null) {
            deleteDir(destDir);
            return existing;
        }
    } else {
        this.tempDirs.add(destDir);
    }
    return destDir;
}
Also used : java.util(java.util) Type(separate.SourceModel.Type) JavacTask(com.sun.source.util.JavacTask) Files(java.nio.file.Files) javax.tools(javax.tools) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Class(separate.SourceModel.Class) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) FileVisitResult(java.nio.file.FileVisitResult) java.io(java.io) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SourceProcessor(separate.SourceModel.SourceProcessor) URI(java.net.URI) Path(java.nio.file.Path) Extends(separate.SourceModel.Extends) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) SourceProcessor(separate.SourceModel.SourceProcessor) Type(separate.SourceModel.Type) JavacTask(com.sun.source.util.JavacTask)

Example 3 with JavacTask

use of com.sun.source.util.JavacTask in project st-js by st-js.

the class Generator method parseAndResolve.

// JavaCompiler throws an Error, so catching Throwable is intentional
@SuppressWarnings("PMD.AvoidCatchingThrowable")
private <JS> CompilationUnitTree parseAndResolve(File inputFile, GenerationContext<JS> context, ClassLoader builtProjectClassLoader, String sourceEncoding) {
    JavaCompiler.CompilationTask task = null;
    JavacTask javacTask = null;
    try {
        JavaCompiler compiler = getCompiler(builtProjectClassLoader, sourceEncoding);
        Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjectsFromFiles(Collections.singleton(inputFile));
        List<String> options = Arrays.asList("-proc:none");
        task = compiler.getTask(null, classLoaderFileManager, null, options, null, fileObjects);
        javacTask = (JavacTask) task;
        context.setTrees(Trees.instance(javacTask));
        context.setElements(javacTask.getElements());
        context.setTypes(javacTask.getTypes());
        Timers.start("parse-java");
        CompilationUnitTree cu = javacTask.parse().iterator().next();
        Timers.end("parse-java");
        Timers.start("analyze-java");
        javacTask.analyze();
        Timers.end("analyze-java");
        context.setCompilationUnit(cu);
        return cu;
    } catch (Throwable e) {
        throw new JavascriptFileGenerationException(new SourcePosition(context.getInputFile(), 0, 0), "Cannot parse the Java file", e);
    }
}
Also used : CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) JavaCompiler(javax.tools.JavaCompiler) JavacTask(com.sun.source.util.JavacTask)

Example 4 with JavacTask

use of com.sun.source.util.JavacTask in project error-prone by google.

the class ErrorProneJavacPluginTest method applyFixes.

@Test
public void applyFixes() throws IOException {
    // TODO(b/63064865): Test is broken on Windows.  Disable for now.
    Assume.assumeFalse(StandardSystemProperty.OS_NAME.value().startsWith("Windows"));
    Path tmp = temporaryFolder.newFolder().toPath();
    Path fileA = tmp.resolve("A.java");
    Path fileB = tmp.resolve("B.java");
    Files.write(fileA, ImmutableList.of(// 
    "class A implements Runnable {", "  public void run() {}", "}"), UTF_8);
    Files.write(fileB, ImmutableList.of(// 
    "class B implements Runnable {", "  public void run() {}", "}"), UTF_8);
    JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
    JavacTask task = JavacTool.create().getTask(null, fileManager, diagnosticCollector, ImmutableList.of("-Xplugin:ErrorProne" + " -XepPatchChecks:MissingOverride -XepPatchLocation:IN_PLACE", "-XDcompilePolicy=byfile"), ImmutableList.of(), fileManager.getJavaFileObjects(fileA, fileB));
    assertThat(task.call()).named(Joiner.on('\n').join(diagnosticCollector.getDiagnostics())).isTrue();
    assertThat(Files.readAllLines(fileA, UTF_8)).containsExactly(// 
    "class A implements Runnable {", "  @Override public void run() {}", "}").inOrder();
    assertThat(Files.readAllLines(fileB, UTF_8)).containsExactly(// 
    "class B implements Runnable {", "  @Override public void run() {}", "}").inOrder();
}
Also used : Path(java.nio.file.Path) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) Context(com.sun.tools.javac.util.Context) JavaFileObject(javax.tools.JavaFileObject) DiagnosticCollector(javax.tools.DiagnosticCollector) JavacTask(com.sun.source.util.JavacTask) Test(org.junit.Test)

Example 5 with JavacTask

use of com.sun.source.util.JavacTask in project error-prone by google.

the class ErrorProneJavacPluginTest method hello.

@Test
public void hello() throws IOException {
    FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
    Path source = fileSystem.getPath("Test.java");
    Files.write(source, ImmutableList.of("import java.util.HashSet;", "import java.util.Set;", "class Test {", "  public static void main(String[] args) {", "    Set<Short> s = new HashSet<>();", "    for (short i = 0; i < 100; i++) {", "      s.add(i);", "      s.remove(i - 1);", "    }", "    System.out.println(s.size());", "  }", "}"), UTF_8);
    JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
    JavacTask task = JavacTool.create().getTask(null, fileManager, diagnosticCollector, ImmutableList.of("-Xplugin:ErrorProne", "-XDcompilePolicy=byfile"), ImmutableList.of(), fileManager.getJavaFileObjects(source));
    assertThat(task.call()).isFalse();
    Diagnostic<? extends JavaFileObject> diagnostic = diagnosticCollector.getDiagnostics().stream().filter(d -> d.getKind() == Diagnostic.Kind.ERROR).collect(onlyElement());
    assertThat(diagnostic.getMessage(ENGLISH)).contains("[CollectionIncompatibleType]");
}
Also used : Path(java.nio.file.Path) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) Context(com.sun.tools.javac.util.Context) RunWith(org.junit.runner.RunWith) MoreCollectors.onlyElement(com.google.common.collect.MoreCollectors.onlyElement) StandardSystemProperty(com.google.common.base.StandardSystemProperty) ImmutableList(com.google.common.collect.ImmutableList) JavacTool(com.sun.tools.javac.api.JavacTool) Jimfs(com.google.common.jimfs.Jimfs) Diagnostic(javax.tools.Diagnostic) Assert.fail(org.junit.Assert.fail) Assume(org.junit.Assume) ENGLISH(java.util.Locale.ENGLISH) Path(java.nio.file.Path) DiagnosticCollector(javax.tools.DiagnosticCollector) PrintWriter(java.io.PrintWriter) Configuration(com.google.common.jimfs.Configuration) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) JavacTask(com.sun.source.util.JavacTask) Files(java.nio.file.Files) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) StringWriter(java.io.StringWriter) IOException(java.io.IOException) Test(org.junit.Test) JUnit4(org.junit.runners.JUnit4) Truth.assertThat(com.google.common.truth.Truth.assertThat) FileSystem(java.nio.file.FileSystem) JavaFileObject(javax.tools.JavaFileObject) Rule(org.junit.Rule) Paths(java.nio.file.Paths) Context(com.sun.tools.javac.util.Context) TemporaryFolder(org.junit.rules.TemporaryFolder) Joiner(com.google.common.base.Joiner) JavaFileObject(javax.tools.JavaFileObject) FileSystem(java.nio.file.FileSystem) DiagnosticCollector(javax.tools.DiagnosticCollector) JavacTask(com.sun.source.util.JavacTask) Test(org.junit.Test)

Aggregations

JavacTask (com.sun.source.util.JavacTask)97 JavaCompiler (javax.tools.JavaCompiler)45 JavaFileObject (javax.tools.JavaFileObject)27 JavacTool (com.sun.tools.javac.api.JavacTool)24 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)23 StandardJavaFileManager (javax.tools.StandardJavaFileManager)17 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)16 IOException (java.io.IOException)14 DiagnosticCollector (javax.tools.DiagnosticCollector)13 File (java.io.File)12 StringWriter (java.io.StringWriter)12 Context (com.sun.tools.javac.util.Context)11 PrintWriter (java.io.PrintWriter)11 JavacFileManager (com.sun.tools.javac.file.JavacFileManager)9 Path (java.nio.file.Path)8 ArrayList (java.util.ArrayList)8 JCCompilationUnit (com.sun.tools.javac.tree.JCTree.JCCompilationUnit)7 Diagnostic (javax.tools.Diagnostic)7 ClassTree (com.sun.source.tree.ClassTree)6 Trees (com.sun.source.util.Trees)6