Search in sources :

Example 1 with ImportTree

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

the class WildcardImport method matchCompilationUnit.

@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
    ImmutableList<ImportTree> wildcardImports = getWildcardImports(tree.getImports());
    if (wildcardImports.isEmpty()) {
        return NO_MATCH;
    }
    // Find all of the types that need to be imported.
    Set<TypeToImport> typesToImport = ImportCollector.collect((JCCompilationUnit) tree);
    Fix fix = createFix(wildcardImports, typesToImport, state);
    if (fix.isEmpty()) {
        return NO_MATCH;
    }
    return describeMatch(wildcardImports.get(0), fix);
}
Also used : Fix(com.google.errorprone.fixes.Fix) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) ImportTree(com.sun.source.tree.ImportTree)

Example 2 with ImportTree

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

the class RemoveUnusedImports method matchCompilationUnit.

@Override
public Description matchCompilationUnit(CompilationUnitTree compilationUnitTree, VisitorState state) {
    final ImmutableSetMultimap<ImportTree, Symbol> importedSymbols = getImportedSymbols(compilationUnitTree, state);
    if (importedSymbols.isEmpty()) {
        return NO_MATCH;
    }
    final Set<ImportTree> unusedImports = new HashSet<>(importedSymbols.keySet());
    new TreeSymbolScanner(JavacTrees.instance(state.context), state.getTypes()).scan(compilationUnitTree, new SymbolSink() {

        @Override
        public boolean keepScanning() {
            return !unusedImports.isEmpty();
        }

        @Override
        public void accept(Symbol symbol) {
            unusedImports.removeAll(importedSymbols.inverse().get(symbol));
        }
    });
    if (unusedImports.isEmpty()) {
        return NO_MATCH;
    }
    SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
    for (ImportTree unusedImport : unusedImports) {
        fixBuilder.delete(unusedImport);
    }
    return describeMatch(unusedImports.iterator().next(), fixBuilder.build());
}
Also used : SuggestedFix(com.google.errorprone.fixes.SuggestedFix) ASTHelpers.getSymbol(com.google.errorprone.util.ASTHelpers.getSymbol) Symbol(com.sun.tools.javac.code.Symbol) ImportTree(com.sun.source.tree.ImportTree) HashSet(java.util.HashSet)

Example 3 with ImportTree

use of com.sun.source.tree.ImportTree in project meghanada-server by mopemope.

the class TreeAnalyzer method analyzeImports.

private static void analyzeImports(CompilationUnitTree cut, Source src, EndPosTable endPosTable) {
    CachedASMReflector cachedASMReflector = CachedASMReflector.getInstance();
    long firstLine = 0;
    for (ImportTree imp : cut.getImports()) {
        JCTree.JCImport jcImport = (JCTree.JCImport) imp;
        int startPos = jcImport.getPreferredPosition();
        int endPos = jcImport.getEndPosition(endPosTable);
        Range range = Range.create(src, startPos + 1, endPos);
        firstLine = range.begin.line;
        String importClass = imp.getQualifiedIdentifier().toString();
        String simpleName = ClassNameUtils.getSimpleName(importClass);
        if (imp.isStatic()) {
            // TODO static asterisk
            Tree tree = imp.getQualifiedIdentifier();
            if (tree instanceof JCTree.JCFieldAccess) {
                JCTree.JCFieldAccess fieldAccess = (JCTree.JCFieldAccess) tree;
                com.sun.tools.javac.util.Name name = fieldAccess.getIdentifier();
                JCTree.JCExpression expression = fieldAccess.getExpression();
                String methodName = name.toString();
                String decClazz = expression.toString();
                src.addStaticImport(methodName, decClazz);
            } else {
                log.warn("Not impl");
            }
        } else {
            if (simpleName.equals("*")) {
                // wild
                for (String s : cachedASMReflector.getPackageClasses(importClass).values()) {
                    src.addImport(s);
                }
            } else {
                src.addImport(importClass);
            }
        }
    }
    src.setClassStartLine(firstLine);
}
Also used : CachedASMReflector(meghanada.reflect.asm.CachedASMReflector) JCTree(com.sun.tools.javac.tree.JCTree) VariableTree(com.sun.source.tree.VariableTree) ImportTree(com.sun.source.tree.ImportTree) Tree(com.sun.source.tree.Tree) ExpressionTree(com.sun.source.tree.ExpressionTree) JCTree(com.sun.tools.javac.tree.JCTree) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) ImportTree(com.sun.source.tree.ImportTree)

Example 4 with ImportTree

use of com.sun.source.tree.ImportTree in project robolectric by robolectric.

the class ImplementsValidator method captureJavadoc.

private void captureJavadoc(TypeElement elem) {
    List<String> imports = new ArrayList<>();
    try {
        List<? extends ImportTree> importLines = Trees.instance(env).getPath(elem).getCompilationUnit().getImports();
        for (ImportTree importLine : importLines) {
            imports.add(importLine.getQualifiedIdentifier().toString());
        }
    } catch (IllegalArgumentException e) {
    // Trees relies on javac APIs and is not available in all annotation processing
    // implementations
    }
    List<TypeElement> enclosedTypes = ElementFilter.typesIn(elem.getEnclosedElements());
    for (TypeElement enclosedType : enclosedTypes) {
        imports.add(enclosedType.getQualifiedName().toString());
    }
    Elements elementUtils = env.getElementUtils();
    modelBuilder.documentType(elem, elementUtils.getDocComment(elem), imports);
    for (Element memberElement : ElementFilter.methodsIn(elem.getEnclosedElements())) {
        try {
            ExecutableElement methodElement = (ExecutableElement) memberElement;
            Implementation implementation = memberElement.getAnnotation(Implementation.class);
            DocumentedMethod documentedMethod = new DocumentedMethod(memberElement.toString());
            for (Modifier modifier : memberElement.getModifiers()) {
                documentedMethod.modifiers.add(modifier.toString());
            }
            documentedMethod.isImplementation = implementation != null;
            if (implementation != null) {
                documentedMethod.minSdk = sdkOrNull(implementation.minSdk());
                documentedMethod.maxSdk = sdkOrNull(implementation.maxSdk());
            }
            for (VariableElement variableElement : methodElement.getParameters()) {
                documentedMethod.params.add(variableElement.toString());
            }
            documentedMethod.returnType = methodElement.getReturnType().toString();
            for (TypeMirror typeMirror : methodElement.getThrownTypes()) {
                documentedMethod.exceptions.add(typeMirror.toString());
            }
            String docMd = elementUtils.getDocComment(methodElement);
            if (docMd != null) {
                documentedMethod.setDocumentation(docMd);
            }
            modelBuilder.documentMethod(elem, documentedMethod);
        } catch (Exception e) {
            throw new RuntimeException("failed to capture javadoc for " + elem + "." + memberElement, e);
        }
    }
}
Also used : TypeElement(javax.lang.model.element.TypeElement) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) TypeParameterElement(javax.lang.model.element.TypeParameterElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ArrayList(java.util.ArrayList) VariableElement(javax.lang.model.element.VariableElement) Elements(javax.lang.model.util.Elements) Implementation(org.robolectric.annotation.Implementation) DocumentedMethod(org.robolectric.annotation.processing.DocumentedMethod) TypeMirror(javax.lang.model.type.TypeMirror) ImportTree(com.sun.source.tree.ImportTree) Modifier(javax.lang.model.element.Modifier)

Example 5 with ImportTree

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

Aggregations

ImportTree (com.sun.source.tree.ImportTree)9 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)5 ImmutableList (com.google.common.collect.ImmutableList)3 SuggestedFix (com.google.errorprone.fixes.SuggestedFix)3 Tree (com.sun.source.tree.Tree)3 Symbol (com.sun.tools.javac.code.Symbol)3 IdentifierTree (com.sun.source.tree.IdentifierTree)2 MemberSelectTree (com.sun.source.tree.MemberSelectTree)2 VariableTree (com.sun.source.tree.VariableTree)2 JavacTask (com.sun.source.util.JavacTask)2 File (java.io.File)2 List (java.util.List)2 JavaCompiler (javax.tools.JavaCompiler)2 StandardJavaFileManager (javax.tools.StandardJavaFileManager)2 ImmutableSet (com.google.common.collect.ImmutableSet)1 Sets (com.google.common.collect.Sets)1 VisitorState (com.google.errorprone.VisitorState)1 Fix (com.google.errorprone.fixes.Fix)1 ASTHelpers.getSymbol (com.google.errorprone.util.ASTHelpers.getSymbol)1 BlockTree (com.sun.source.tree.BlockTree)1