Search in sources :

Example 1 with CompilationUnitTree

use of com.sun.source.tree.CompilationUnitTree 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 CompilationUnitTree

use of com.sun.source.tree.CompilationUnitTree in project j2objc by google.

the class JavacParser method processAnnotations.

@Override
public ProcessingResult processAnnotations(Iterable<String> fileArgs, List<ProcessingContext> inputs) {
    final List<ProcessingContext> generatedInputs = Lists.newArrayList();
    PathClassLoader loader = new PathClassLoader(options.fileUtil().getClassPathEntries());
    loader.addPaths(options.getProcessorPathEntries());
    Iterator<Processor> serviceIterator = ServiceLoader.load(Processor.class, loader).iterator();
    if (serviceIterator.hasNext()) {
        List<File> inputFiles = new ArrayList<>();
        for (ProcessingContext input : inputs) {
            inputFiles.add(new File(input.getFile().getAbsolutePath()));
        }
        try {
            JavacEnvironment env = createEnvironment(inputFiles, null, true);
            List<CompilationUnitTree> units = new ArrayList<>();
            for (CompilationUnitTree unit : env.task().parse()) {
                units.add(unit);
            }
            // JavacTaskImpl.enter() parses and runs annotation processing, but
            // not type checking and attribution (that's done by analyze()).
            env.task().enter();
            processDiagnostics(env.diagnostics());
            // The source output directory is created and set in createEnvironment().
            File sourceOutputDirectory = env.fileManager().getLocation(StandardLocation.SOURCE_OUTPUT).iterator().next();
            collectGeneratedInputs(sourceOutputDirectory, "", generatedInputs);
            return new JavacProcessingResult(generatedInputs, sourceOutputDirectory);
        } catch (IOException e) {
            ErrorUtil.fatalError(e, "javac file manager error");
        }
    }
    // No annotation processors on classpath, or processing errors reported.
    return new JavacProcessingResult(generatedInputs, null);
}
Also used : ProcessingContext(com.google.devtools.j2objc.pipeline.ProcessingContext) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) Processor(javax.annotation.processing.Processor) ArrayList(java.util.ArrayList) IOException(java.io.IOException) PathClassLoader(com.google.devtools.j2objc.util.PathClassLoader) RegularInputFile(com.google.devtools.j2objc.file.RegularInputFile) InputFile(com.google.devtools.j2objc.file.InputFile) File(java.io.File)

Example 3 with CompilationUnitTree

use of com.sun.source.tree.CompilationUnitTree in project error-prone by google.

the class TemplateIntegrationTest method extractRefasterRule.

private CodeTransformer extractRefasterRule(JavaFileObject object) {
    compile(object);
    ClassTree classTree = Iterables.getOnlyElement(FluentIterable.from(compilationUnits).transformAndConcat(new Function<CompilationUnitTree, Iterable<? extends Tree>>() {

        @Override
        public Iterable<? extends Tree> apply(CompilationUnitTree input) {
            return input.getTypeDecls();
        }
    }).filter(ClassTree.class));
    return Iterables.getOnlyElement(RefasterRuleBuilderScanner.extractRules(classTree, context));
}
Also used : CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) FluentIterable(com.google.common.collect.FluentIterable) ClassTree(com.sun.source.tree.ClassTree) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree)

Example 4 with CompilationUnitTree

use of com.sun.source.tree.CompilationUnitTree in project error-prone by google.

the class EmptyTopLevelDeclaration method matchCompilationUnit.

@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
    List<Tree> toDelete = new ArrayList<>();
    for (Tree member : tree.getTypeDecls()) {
        if (member.getKind() == Tree.Kind.EMPTY_STATEMENT) {
            toDelete.add(member);
        }
    }
    if (toDelete.isEmpty()) {
        return Description.NO_MATCH;
    }
    SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
    for (Tree member : toDelete) {
        fixBuilder.delete(member);
    }
    return describeMatch(toDelete.get(0), fixBuilder.build());
}
Also used : SuggestedFix(com.google.errorprone.fixes.SuggestedFix) ArrayList(java.util.ArrayList) Tree(com.sun.source.tree.Tree) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree)

Example 5 with CompilationUnitTree

use of com.sun.source.tree.CompilationUnitTree in project vertx-docgen by vert-x3.

the class Helper method readSource.

/**
 * Read the source code of the provided element, this returns the source of the entire related compilation unit.
 *
 * @param elt the element to load
 * @return the source
 */
String readSource(Element elt) {
    CompilationUnitTree unit = docTrees.getPath(elt).getCompilationUnit();
    StringBuilder source = new StringBuilder();
    try (Reader reader = unit.getSourceFile().openReader(true)) {
        char[] buffer = new char[256];
        while (true) {
            int len = reader.read(buffer);
            if (len == -1) {
                break;
            }
            source.append(buffer, 0, len);
        }
        return source.toString();
    } catch (IOException e) {
        throw new DocGenException(elt, "Could not read source code of element " + elt);
    }
}
Also used : CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) Reader(java.io.Reader) IOException(java.io.IOException)

Aggregations

CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)53 JavacTask (com.sun.source.util.JavacTask)22 JavaCompiler (javax.tools.JavaCompiler)21 JavaFileObject (javax.tools.JavaFileObject)15 Tree (com.sun.source.tree.Tree)13 ClassTree (com.sun.source.tree.ClassTree)12 JavacTool (com.sun.tools.javac.api.JavacTool)9 JCTree (com.sun.tools.javac.tree.JCTree)9 ArrayList (java.util.ArrayList)9 VariableTree (com.sun.source.tree.VariableTree)8 IOException (java.io.IOException)8 Trees (com.sun.source.util.Trees)7 File (java.io.File)7 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)6 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)6 StandardJavaFileManager (javax.tools.StandardJavaFileManager)6 ImportTree (com.sun.source.tree.ImportTree)5 MethodTree (com.sun.source.tree.MethodTree)5 Element (javax.lang.model.element.Element)5 IdentifierTree (com.sun.source.tree.IdentifierTree)4