Search in sources :

Example 1 with JavacFileManager

use of com.sun.tools.javac.file.JavacFileManager in project bazel by bazelbuild.

the class JavaSource2CFGDOT method getMethodTreeAndCompilationUnit.

/**
     * @return The AST of a specific method in a specific class as well as the
     *         {@link CompilationUnitTree} in a specific file (or null they do
     *         not exist).
     */
public static Entry</*@Nullable*/
MethodTree, /*@Nullable*/
CompilationUnitTree> getMethodTreeAndCompilationUnit(String file, final String method, String clas) {
    final Holder<MethodTree> m = new Holder<>();
    final Holder<CompilationUnitTree> c = new Holder<>();
    BasicTypeProcessor typeProcessor = new BasicTypeProcessor() {

        @Override
        protected TreePathScanner<?, ?> createTreePathScanner(CompilationUnitTree root) {
            c.value = root;
            return new TreePathScanner<Void, Void>() {

                @Override
                public Void visitMethod(MethodTree node, Void p) {
                    ExecutableElement el = TreeUtils.elementFromDeclaration(node);
                    if (el.getSimpleName().contentEquals(method)) {
                        m.value = node;
                        // compilation).
                        throw new RuntimeException();
                    }
                    return null;
                }
            };
        }
    };
    Context context = new Context();
    JavaCompiler javac = new JavaCompiler(context);
    javac.attrParseOnly = true;
    JavacFileManager fileManager = (JavacFileManager) context.get(JavaFileManager.class);
    JavaFileObject l = fileManager.getJavaFileObjectsFromStrings(List.of(file)).iterator().next();
    PrintStream err = System.err;
    try {
        // redirect syserr to nothing (and prevent the compiler from issuing
        // warnings about our exception.
        System.setErr(new PrintStream(new OutputStream() {

            @Override
            public void write(int b) throws IOException {
            }
        }));
        javac.compile(List.of(l), List.of(clas), List.of(typeProcessor));
    } catch (Throwable e) {
    // ok
    } finally {
        System.setErr(err);
    }
    return new Entry<MethodTree, CompilationUnitTree>() {

        @Override
        public CompilationUnitTree setValue(CompilationUnitTree value) {
            return null;
        }

        @Override
        public CompilationUnitTree getValue() {
            return c.value;
        }

        @Override
        public MethodTree getKey() {
            return m.value;
        }
    };
}
Also used : Context(com.sun.tools.javac.util.Context) PrintStream(java.io.PrintStream) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) MethodTree(com.sun.source.tree.MethodTree) JavaFileManager(javax.tools.JavaFileManager) Holder(javax.xml.ws.Holder) ExecutableElement(javax.lang.model.element.ExecutableElement) OutputStream(java.io.OutputStream) TreePathScanner(com.sun.source.util.TreePathScanner) JavaCompiler(com.sun.tools.javac.main.JavaCompiler) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) JavaFileObject(javax.tools.JavaFileObject) Entry(java.util.Map.Entry) BasicTypeProcessor(org.checkerframework.javacutil.BasicTypeProcessor)

Example 2 with JavacFileManager

use of com.sun.tools.javac.file.JavacFileManager in project bazel by bazelbuild.

the class JavacTurbineTest method reducedClasspath.

@Test
public void reducedClasspath() throws Exception {
    Path libD = temp.newFile("libd.jar").toPath();
    compileLib(libD, Collections.<Path>emptyList(), Arrays.asList(new StringJavaFileObject("D.java", "public class D {}")));
    Path libC = temp.newFile("libc.jar").toPath();
    compileLib(libC, Collections.singleton(libD), Arrays.asList(new StringJavaFileObject("C.java", "class C { static D d; }")));
    Path libB = temp.newFile("libb.jar").toPath();
    compileLib(libB, Arrays.asList(libC, libD), Arrays.asList(new StringJavaFileObject("B.java", "class B { static C c; }")));
    Path libA = temp.newFile("liba.jar").toPath();
    compileLib(libA, Arrays.asList(libB, libC, libD), Arrays.asList(new StringJavaFileObject("A.java", "class A { static B b; }")));
    Path depsA = writedeps("liba.jdeps", Deps.Dependencies.newBuilder().setSuccess(true).setRuleLabel("//lib:a").addDependency(Deps.Dependency.newBuilder().setPath(libB.toString()).setKind(Deps.Dependency.Kind.EXPLICIT)).build());
    optionsBuilder.addClassPathEntries(ImmutableList.of(libA.toString(), libB.toString(), libC.toString(), libD.toString()));
    optionsBuilder.addAllDepsArtifacts(ImmutableList.of(depsA.toString()));
    optionsBuilder.addDirectJarToTarget(libA.toString(), "//lib:a");
    optionsBuilder.addIndirectJarToTarget(libB.toString(), "//lib:b");
    optionsBuilder.addIndirectJarToTarget(libC.toString(), "//lib:c");
    optionsBuilder.addIndirectJarToTarget(libD.toString(), "//lib:d");
    optionsBuilder.setTargetLabel("//my:target");
    addSourceLines("Hello.java", "class Hello {", "  public static A a = new A();", "  public static void main(String[] args) {", "    A a = null;", "    B b = null;", "    C c = null;", "    D d = null;", "  }", "}");
    optionsBuilder.addSources(ImmutableList.copyOf(Iterables.transform(sources, TO_STRING)));
    try (JavacTurbine turbine = new JavacTurbine(new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.err, UTF_8))), optionsBuilder.build())) {
        assertThat(turbine.compile()).isEqualTo(Result.OK_WITH_REDUCED_CLASSPATH);
        Context context = turbine.context;
        JavacFileManager fm = (JavacFileManager) context.get(JavaFileManager.class);
        assertThat(fm.getLocationAsPaths(StandardLocation.CLASS_PATH)).containsExactly(libA, libB);
        Deps.Dependencies depsProto = getDeps();
        assertThat(depsProto.getSuccess()).isTrue();
        assertThat(depsProto.getRuleLabel()).isEqualTo("//my:target");
        assertThat(getEntries(depsProto)).containsExactlyEntriesIn(ImmutableMap.of(libA.toString(), Deps.Dependency.Kind.EXPLICIT, libB.toString(), Deps.Dependency.Kind.INCOMPLETE));
    }
}
Also used : Path(java.nio.file.Path) Context(com.sun.tools.javac.util.Context) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) Deps(com.google.devtools.build.lib.view.proto.Deps) JavaFileManager(javax.tools.JavaFileManager) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter) BufferedWriter(java.io.BufferedWriter) Test(org.junit.Test)

Example 3 with JavacFileManager

use of com.sun.tools.javac.file.JavacFileManager in project bazel by bazelbuild.

the class TreePrunerTest method setUp.

@Before
public void setUp() {
    this.context = new Context();
    // registers itself in the context as a side effect
    new JavacFileManager(context, true, UTF_8);
}
Also used : Context(com.sun.tools.javac.util.Context) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) Before(org.junit.Before)

Example 4 with JavacFileManager

use of com.sun.tools.javac.file.JavacFileManager 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"), 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) 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) RunWith(org.junit.runner.RunWith) 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) MoreCollectors.onlyElement(com.google.common.collect.MoreCollectors.onlyElement) JavaFileObject(javax.tools.JavaFileObject) ImmutableList(com.google.common.collect.ImmutableList) JavacTool(com.sun.tools.javac.api.JavacTool) Jimfs(com.google.common.jimfs.Jimfs) Diagnostic(javax.tools.Diagnostic) Context(com.sun.tools.javac.util.Context) ENGLISH(java.util.Locale.ENGLISH) Path(java.nio.file.Path) DiagnosticCollector(javax.tools.DiagnosticCollector) JavaFileObject(javax.tools.JavaFileObject) FileSystem(java.nio.file.FileSystem) DiagnosticCollector(javax.tools.DiagnosticCollector) JavacTask(com.sun.source.util.JavacTask) Test(org.junit.Test)

Example 5 with JavacFileManager

use of com.sun.tools.javac.file.JavacFileManager in project j2objc by google.

the class JavacParser method createEnvironment.

// Creates a javac environment from a collection of files and/or file objects.
private JavacEnvironment createEnvironment(List<File> files, List<JavaFileObject> fileObjects, boolean processAnnotations) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    JavacFileManager fileManager = getFileManager(compiler, diagnostics);
    List<String> javacOptions = getJavacOptions(processAnnotations);
    if (fileObjects == null) {
        fileObjects = new ArrayList<>();
    }
    for (JavaFileObject jfo : fileManager.getJavaFileObjectsFromFiles(files)) {
        fileObjects.add(jfo);
    }
    JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, fileManager, diagnostics, javacOptions, null, fileObjects);
    return new JavacEnvironment(task, fileManager, diagnostics);
}
Also used : JavacFileManager(com.sun.tools.javac.file.JavacFileManager) JavaFileObject(javax.tools.JavaFileObject) JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) JavaCompiler(javax.tools.JavaCompiler) DiagnosticCollector(javax.tools.DiagnosticCollector)

Aggregations

JavacFileManager (com.sun.tools.javac.file.JavacFileManager)35 Context (com.sun.tools.javac.util.Context)19 JavaFileObject (javax.tools.JavaFileObject)10 File (java.io.File)9 IOException (java.io.IOException)7 PrintWriter (java.io.PrintWriter)7 JavaFileManager (javax.tools.JavaFileManager)7 VirtualFile (com.redhat.ceylon.compiler.typechecker.io.VirtualFile)5 Path (java.nio.file.Path)5 JavacTask (com.sun.source.util.JavacTask)4 Options (com.sun.tools.javac.util.Options)4 OutputStreamWriter (java.io.OutputStreamWriter)4 BufferedWriter (java.io.BufferedWriter)3 Deps (com.google.devtools.build.lib.view.proto.Deps)2 JavacTool (com.sun.tools.javac.api.JavacTool)2 JavaCompiler (com.sun.tools.javac.main.JavaCompiler)2 AnnotationProcessingError (com.sun.tools.javac.processing.AnnotationProcessingError)2 PropagatedException (com.sun.tools.javac.util.PropagatedException)2 DiagnosticCollector (javax.tools.DiagnosticCollector)2 Test (org.junit.Test)2