Search in sources :

Example 36 with CompilationUnitTree

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

the class JavacParser method parse.

@Override
public CompilationUnit parse(String mainType, String path, String source) {
    try {
        JavacEnvironment parserEnv = createEnvironment(path, source);
        JavacTask task = parserEnv.task();
        CompilationUnitTree unit = task.parse().iterator().next();
        task.analyze();
        processDiagnostics(parserEnv.diagnostics());
        return TreeConverter.convertCompilationUnit(options, parserEnv, unit);
    } catch (IOException e) {
        ErrorUtil.fatalError(e, path);
    }
    return null;
}
Also used : CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) IOException(java.io.IOException) JavacTask(com.sun.source.util.JavacTask)

Example 37 with CompilationUnitTree

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

the class JavacParser method parseFiles.

@Override
public void parseFiles(Collection<String> paths, Handler handler, SourceVersion sourceVersion) {
    List<File> files = new ArrayList<>();
    for (String path : paths) {
        files.add(new File(path));
    }
    try {
        JavacEnvironment env = createEnvironment(files, null, false);
        List<CompilationUnitTree> units = new ArrayList<>();
        for (CompilationUnitTree unit : env.task().parse()) {
            units.add(unit);
        }
        env.task().analyze();
        processDiagnostics(env.diagnostics());
        if (ErrorUtil.errorCount() == 0) {
            for (CompilationUnitTree ast : units) {
                com.google.devtools.j2objc.ast.CompilationUnit unit = TreeConverter.convertCompilationUnit(options, env, ast);
                processDiagnostics(env.diagnostics());
                handler.handleParsedUnit(unit.getSourceFilePath(), unit);
            }
        }
    } catch (IOException e) {
        ErrorUtil.fatalError(e, "javac file manager error");
    }
}
Also used : CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) ArrayList(java.util.ArrayList) CompilationUnit(com.google.devtools.j2objc.ast.CompilationUnit) IOException(java.io.IOException) RegularInputFile(com.google.devtools.j2objc.file.RegularInputFile) InputFile(com.google.devtools.j2objc.file.InputFile) File(java.io.File)

Example 38 with CompilationUnitTree

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

the class JavaDocGenerator method renderSource.

public String renderSource(TreePath path, List<? extends Tree> trees, String source) {
    CompilationUnitTree unit = path.getCompilationUnit();
    int from = (int) docTrees.getSourcePositions().getStartPosition(unit, trees.get(0));
    int to = (int) docTrees.getSourcePositions().getEndPosition(unit, trees.get(trees.size() - 1));
    // Correct boundaries
    while (from > 1 && source.charAt(from - 1) != '\n') {
        from--;
    }
    while (to < source.length() && source.charAt(to) != '\n') {
        to++;
    }
    String block = source.substring(from, to);
    // Determine margin
    int blockMargin = Integer.MAX_VALUE;
    LineMap lineMap = unit.getLineMap();
    for (Tree statement : trees) {
        int statementStart = (int) docTrees.getSourcePositions().getStartPosition(unit, statement);
        int lineStart = statementStart;
        while (lineMap.getLineNumber(statementStart) == lineMap.getLineNumber(lineStart - 1)) {
            lineStart--;
        }
        blockMargin = Math.min(blockMargin, statementStart - lineStart);
    }
    // Crop the fragment
    StringBuilder fragment = new StringBuilder();
    for (Iterator<String> sc = new Scanner(block).useDelimiter("\n"); sc.hasNext(); ) {
        String line = sc.next();
        int margin = Math.min(blockMargin, line.length());
        line = line.substring(margin);
        fragment.append(line);
        if (sc.hasNext()) {
            fragment.append('\n');
        }
    }
    return fragment.toString();
}
Also used : Scanner(java.util.Scanner) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) MethodTree(com.sun.source.tree.MethodTree) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) BlockTree(com.sun.source.tree.BlockTree) StatementTree(com.sun.source.tree.StatementTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) LineMap(com.sun.source.tree.LineMap)

Example 39 with CompilationUnitTree

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

the class FindIdentifiers method findAllIdents.

/**
 * Finds the set of all bare variable identifiers in scope at the current location. Identifiers
 * are ordered by ascending distance/scope count from the current location to match shadowing
 * rules. That is, if two variables with the same simple names appear in the set, the one that
 * appears first in iteration order is the one you get if you use the bare name in the source
 * code.
 *
 * <p>We do not report variables that would require a qualfied access. We also do not handle
 * wildcard imports.
 */
public static LinkedHashSet<VarSymbol> findAllIdents(VisitorState state) {
    ImmutableSet.Builder<VarSymbol> result = new ImmutableSet.Builder<>();
    Tree prev = state.getPath().getLeaf();
    for (Tree curr : state.getPath().getParentPath()) {
        switch(curr.getKind()) {
            case BLOCK:
                for (StatementTree stmt : ((BlockTree) curr).getStatements()) {
                    if (stmt.equals(prev)) {
                        break;
                    }
                    addIfVariable(stmt, result);
                }
                break;
            case METHOD:
                for (VariableTree param : ((MethodTree) curr).getParameters()) {
                    result.add(ASTHelpers.getSymbol(param));
                }
                break;
            case CATCH:
                result.add(ASTHelpers.getSymbol(((CatchTree) curr).getParameter()));
                break;
            case CLASS:
            case INTERFACE:
            case ENUM:
            case ANNOTATION_TYPE:
                // field is referred to by qualified name, but we don't support that.
                for (Tree member : ((ClassTree) curr).getMembers()) {
                    if (member.equals(prev)) {
                        break;
                    }
                    addIfVariable(member, result);
                }
                // Collect inherited fields.
                Type classType = ASTHelpers.getType(curr);
                List<Type> classTypeClosure = state.getTypes().closure(classType);
                List<Type> superTypes = classTypeClosure.size() <= 1 ? Collections.emptyList() : classTypeClosure.subList(1, classTypeClosure.size());
                for (Type type : superTypes) {
                    Scope scope = type.tsym.members();
                    ImmutableList.Builder<VarSymbol> varsList = ImmutableList.builder();
                    for (Symbol var : scope.getSymbols(VarSymbol.class::isInstance)) {
                        varsList.add((VarSymbol) var);
                    }
                    result.addAll(varsList.build().reverse());
                }
                break;
            case FOR_LOOP:
                addAllIfVariable(((ForLoopTree) curr).getInitializer(), result);
                break;
            case ENHANCED_FOR_LOOP:
                result.add(ASTHelpers.getSymbol(((EnhancedForLoopTree) curr).getVariable()));
                break;
            case TRY:
                TryTree tryTree = (TryTree) curr;
                boolean inResources = false;
                for (Tree resource : tryTree.getResources()) {
                    if (resource.equals(prev)) {
                        inResources = true;
                        break;
                    }
                }
                if (inResources) {
                    // Case 1: we're in one of the resource declarations
                    for (Tree resource : tryTree.getResources()) {
                        if (resource.equals(prev)) {
                            break;
                        }
                        addIfVariable(resource, result);
                    }
                } else if (tryTree.getBlock().equals(prev)) {
                    // Case 2: We're in the block (not a catch or finally)
                    addAllIfVariable(tryTree.getResources(), result);
                }
                break;
            case COMPILATION_UNIT:
                for (ImportTree importTree : ((CompilationUnitTree) curr).getImports()) {
                    if (importTree.isStatic() && importTree.getQualifiedIdentifier().getKind() == Kind.MEMBER_SELECT) {
                        MemberSelectTree memberSelectTree = (MemberSelectTree) importTree.getQualifiedIdentifier();
                        Scope scope = state.getTypes().membersClosure(ASTHelpers.getType(memberSelectTree.getExpression()), /* skipInterface= */
                        false);
                        for (Symbol var : scope.getSymbols(sym -> sym instanceof VarSymbol && sym.getSimpleName().equals(memberSelectTree.getIdentifier()))) {
                            result.add((VarSymbol) var);
                        }
                    }
                }
                break;
            default:
                // other node types don't introduce variables
                break;
        }
        prev = curr;
    }
    // TODO(eaftan): switch out collector for ImmutableSet.toImmutableSet()
    return result.build().stream().filter(var -> isVisible(var, state.getPath())).collect(Collectors.toCollection(LinkedHashSet::new));
}
Also used : MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) ClassType(com.sun.tools.javac.code.Type.ClassType) Modifier(javax.lang.model.element.Modifier) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) IdentifierTree(com.sun.source.tree.IdentifierTree) CatchTree(com.sun.source.tree.CatchTree) ForLoopTree(com.sun.source.tree.ForLoopTree) Method(java.lang.reflect.Method) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) TreePath(com.sun.source.util.TreePath) ImmutableSet(com.google.common.collect.ImmutableSet) Symbol(com.sun.tools.javac.code.Symbol) Set(java.util.Set) MemberSelectTree(com.sun.source.tree.MemberSelectTree) Env(com.sun.tools.javac.comp.Env) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) TreeScanner(com.sun.source.util.TreeScanner) Objects(java.util.Objects) List(java.util.List) WriteableScope(com.sun.tools.javac.code.Scope.WriteableScope) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) PackageSymbol(com.sun.tools.javac.code.Symbol.PackageSymbol) BlockTree(com.sun.source.tree.BlockTree) StatementTree(com.sun.source.tree.StatementTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) Flags(com.sun.tools.javac.code.Flags) Name(com.sun.tools.javac.util.Name) Scope(com.sun.tools.javac.code.Scope) Type(com.sun.tools.javac.code.Type) MethodTree(com.sun.source.tree.MethodTree) MemberEnter(com.sun.tools.javac.comp.MemberEnter) VariableTree(com.sun.source.tree.VariableTree) AttrContext(com.sun.tools.javac.comp.AttrContext) ArrayList(java.util.ArrayList) VisitorState(com.google.errorprone.VisitorState) BiPredicate(java.util.function.BiPredicate) Kind(com.sun.source.tree.Tree.Kind) ImmutableList(com.google.common.collect.ImmutableList) NewClassTree(com.sun.source.tree.NewClassTree) StreamSupport(java.util.stream.StreamSupport) ImportTree(com.sun.source.tree.ImportTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) Enter(com.sun.tools.javac.comp.Enter) ElementKind(javax.lang.model.element.ElementKind) KindSelector(com.sun.tools.javac.code.Kinds.KindSelector) TryTree(com.sun.source.tree.TryTree) Collections(java.util.Collections) Resolve(com.sun.tools.javac.comp.Resolve) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) MethodTree(com.sun.source.tree.MethodTree) CatchTree(com.sun.source.tree.CatchTree) ImmutableList(com.google.common.collect.ImmutableList) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) Symbol(com.sun.tools.javac.code.Symbol) PackageSymbol(com.sun.tools.javac.code.Symbol.PackageSymbol) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) MemberSelectTree(com.sun.source.tree.MemberSelectTree) VariableTree(com.sun.source.tree.VariableTree) NewClassTree(com.sun.source.tree.NewClassTree) ClassTree(com.sun.source.tree.ClassTree) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) StatementTree(com.sun.source.tree.StatementTree) ClassType(com.sun.tools.javac.code.Type.ClassType) Type(com.sun.tools.javac.code.Type) ImmutableSet(com.google.common.collect.ImmutableSet) WriteableScope(com.sun.tools.javac.code.Scope.WriteableScope) Scope(com.sun.tools.javac.code.Scope) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) IdentifierTree(com.sun.source.tree.IdentifierTree) CatchTree(com.sun.source.tree.CatchTree) ForLoopTree(com.sun.source.tree.ForLoopTree) MemberSelectTree(com.sun.source.tree.MemberSelectTree) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) BlockTree(com.sun.source.tree.BlockTree) StatementTree(com.sun.source.tree.StatementTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) NewClassTree(com.sun.source.tree.NewClassTree) ImportTree(com.sun.source.tree.ImportTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) TryTree(com.sun.source.tree.TryTree) BlockTree(com.sun.source.tree.BlockTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) TryTree(com.sun.source.tree.TryTree) ImportTree(com.sun.source.tree.ImportTree)

Example 40 with CompilationUnitTree

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

the class BugCheckerRefactoringTestHelper method doCompile.

private JCCompilationUnit doCompile(final JavaFileObject input, Iterable<JavaFileObject> files, Context context) throws IOException {
    JavacTool tool = JavacTool.create();
    DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<>();
    context.put(ErrorProneOptions.class, ErrorProneOptions.empty());
    JavacTaskImpl task = (JavacTaskImpl) tool.getTask(CharStreams.nullWriter(), fileManager, diagnosticsCollector, options, /*classes=*/
    null, files, context);
    Iterable<? extends CompilationUnitTree> trees = task.parse();
    task.analyze();
    JCCompilationUnit tree = Iterables.getOnlyElement(Iterables.filter(Iterables.filter(trees, JCCompilationUnit.class), compilationUnit -> compilationUnit.getSourceFile() == input));
    Iterable<Diagnostic<? extends JavaFileObject>> errorDiagnostics = Iterables.filter(diagnosticsCollector.getDiagnostics(), d -> d.getKind() == Diagnostic.Kind.ERROR);
    if (!Iterables.isEmpty(errorDiagnostics)) {
        fail("compilation failed unexpectedly: " + errorDiagnostics);
    }
    return tree;
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) Iterables(com.google.common.collect.Iterables) JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) HashMap(java.util.HashMap) ImportOrganizer(com.google.errorprone.apply.ImportOrganizer) Iterators(com.google.common.collect.Iterators) DescriptionBasedDiff(com.google.errorprone.apply.DescriptionBasedDiff) ErrorProneScannerTransformer(com.google.errorprone.scanner.ErrorProneScannerTransformer) ErrorProneScanner(com.google.errorprone.scanner.ErrorProneScanner) ImmutableList(com.google.common.collect.ImmutableList) CharStreams(com.google.common.io.CharStreams) JavacTool(com.sun.tools.javac.api.JavacTool) Diagnostic(javax.tools.Diagnostic) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) Formatter(com.google.googlejavaformat.java.Formatter) FormatterException(com.google.googlejavaformat.java.FormatterException) Fix(com.google.errorprone.fixes.Fix) DiagnosticCollector(javax.tools.DiagnosticCollector) Truth.assertAbout(com.google.common.truth.Truth.assertAbout) JavaFileObjects(com.google.testing.compile.JavaFileObjects) TreePath(com.sun.source.util.TreePath) Iterator(java.util.Iterator) BugChecker(com.google.errorprone.bugpatterns.BugChecker) IOException(java.io.IOException) Truth.assertThat(com.google.common.truth.Truth.assertThat) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) JavaSourceSubjectFactory.javaSource(com.google.testing.compile.JavaSourceSubjectFactory.javaSource) JavaFileObject(javax.tools.JavaFileObject) SourceFile(com.google.errorprone.apply.SourceFile) List(java.util.List) Description(com.google.errorprone.matchers.Description) Context(com.sun.tools.javac.util.Context) JCClassDecl(com.sun.tools.javac.tree.JCTree.JCClassDecl) JavaFileObject(javax.tools.JavaFileObject) JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) JavacTool(com.sun.tools.javac.api.JavacTool) Diagnostic(javax.tools.Diagnostic) DiagnosticCollector(javax.tools.DiagnosticCollector)

Aggregations

CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)56 JavacTask (com.sun.source.util.JavacTask)24 JavaCompiler (javax.tools.JavaCompiler)21 JavaFileObject (javax.tools.JavaFileObject)16 Tree (com.sun.source.tree.Tree)15 ClassTree (com.sun.source.tree.ClassTree)14 VariableTree (com.sun.source.tree.VariableTree)10 JavacTool (com.sun.tools.javac.api.JavacTool)9 JCTree (com.sun.tools.javac.tree.JCTree)9 IOException (java.io.IOException)9 MethodTree (com.sun.source.tree.MethodTree)8 ArrayList (java.util.ArrayList)8 Trees (com.sun.source.util.Trees)7 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)6 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)6 StandardJavaFileManager (javax.tools.StandardJavaFileManager)6 BinaryTree (com.sun.source.tree.BinaryTree)5 ExpressionTree (com.sun.source.tree.ExpressionTree)5 IdentifierTree (com.sun.source.tree.IdentifierTree)5 TreePath (com.sun.source.util.TreePath)5