Java Code Examples for com.sun.source.util.Trees#getElement()

The following examples show how to use com.sun.source.util.Trees#getElement() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConvertToARM.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Collection<? extends TreePath> findResourceUsages(
        final VariableElement resource,
        final Collection<? extends TreePath> statements,
        final Trees trees) {
    final List<TreePath> usages = new LinkedList<>();
    if (statements != null) {
        final ErrorAwareTreePathScanner<List<TreePath>,List<TreePath>> scanner = new ErrorAwareTreePathScanner<List<TreePath>, List<TreePath>>() {
            @Override
            public List<TreePath> visitIdentifier(IdentifierTree node, List<TreePath> p) {
                final TreePath path = getCurrentPath();
                final Element element = trees.getElement(path);
                if (element == resource) {
                    usages.add(path);
                }
                return super.visitIdentifier(node, p);
            }
        };
        for (TreePath st : statements) {
            scanner.scan(st, usages);
        }
    }
    return usages;
}
 
Example 2
Source File: TopClassFinder.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @return  list of {@code Element}s representing top classes,
 *          or an empty list of none were found
 */
private static List<TypeElement> findTopClassElems(
                                    CompilationInfo compInfo,
                                    CompilationUnitTree compilationUnit,
                                    Filter filter) {
    List<? extends Tree> typeDecls = compilationUnit.getTypeDecls();
    if ((typeDecls == null) || typeDecls.isEmpty()) {
        return Collections.<TypeElement>emptyList();
    }
    
    List<TypeElement> result = new ArrayList<TypeElement>(typeDecls.size());

    Trees trees = compInfo.getTrees();
    for (Tree typeDecl : typeDecls) {
        if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
            Element element = trees.getElement(
                    new TreePath(new TreePath(compilationUnit), typeDecl));
            TypeElement typeElement = (TypeElement) element;
            if (filter.passes(typeElement, compInfo)) {
                result.add(typeElement);
            }
        }
    }

    return result;
}
 
Example 3
Source File: ChangeParamsTransformer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Tree visitNewClass(NewClassTree tree, Element p) {
    if (constructorRefactoring && !compatible && !workingCopy.getTreeUtilities().isSynthetic(getCurrentPath())) {
        ExecutableElement constructor = (ExecutableElement) p;
        final Trees trees = workingCopy.getTrees();
        Element el = trees.getElement(getCurrentPath());
        el = resolveAnonymousClassConstructor(el, tree, trees);
        if (isMethodMatch(el, p)) {
            List<ExpressionTree> arguments = getNewArguments(tree.getArguments(), false, constructor);
            NewClassTree nju = make.NewClass(tree.getEnclosingExpression(),
                    (List<ExpressionTree>)tree.getTypeArguments(),
                    tree.getIdentifier(),
                    arguments,
                    tree.getClassBody());
            rewrite(tree, nju);
        }
    }
    return super.visitNewClass(tree, p);
}
 
Example 4
Source File: ConvertToARM.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean isAssigned(
        final Element what,
        final Iterable<? extends TreePath> where,
        final Trees trees) {
    ErrorAwareTreePathScanner<Boolean, Void> scanner = new ErrorAwareTreePathScanner<Boolean, Void>() {
        @Override public Boolean visitAssignment(AssignmentTree node, Void p) {
            if (trees.getElement(new TreePath(getCurrentPath(), node.getVariable())) == what) {
                return true;
            }
            return super.visitAssignment(node, p);
        }
        @Override
        public Boolean reduce(Boolean r1, Boolean r2) {
            return r1 == Boolean.TRUE || r2 == Boolean.TRUE;
        }
    };
    
    for (TreePath usage : where) {
        if (scanner.scan(usage, null) == Boolean.TRUE) {
            return true;
        }
    }
    return false;
}
 
Example 5
Source File: FindUsagesVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Tree visitNewClass(NewClassTree node, Element p) {
    if(isCancelled.get()) {
        return null;
    }
    Trees trees = workingCopy.getTrees();
    ClassTree classTree = ((NewClassTree) node).getClassBody();
    if (classTree != null && p.getKind() == ElementKind.CONSTRUCTOR) {
        for (Tree t : classTree.getMembers()) {
            Element elem = workingCopy.getTrees().getElement(TreePath.getPath(workingCopy.getCompilationUnit(), t));
            if ((elem != null) && (elem.getKind() == ElementKind.CONSTRUCTOR)) {
                TreePath superCall = trees.getPath(workingCopy.getCompilationUnit(), ((ExpressionStatementTree) ((MethodTree) t).getBody().getStatements().get(0)).getExpression());
                Element superCallElement = trees.getElement(superCall);
                if (superCallElement != null && superCallElement.equals(p) && !workingCopy.getTreeUtilities().isSynthetic(superCall)) {
                    addUsage(superCall);
                }
            }
        }
    } else {
        addIfMatch(getCurrentPath(), node, p);
    }
    return super.visitNewClass(node, p);
}
 
Example 6
Source File: AssignmentIssues.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.AssignmentIssues.assignmentToCatchBlockParameter", description = "#DESC_org.netbeans.modules.java.hints.AssignmentIssues.assignmentToCatchBlockParameter", category = "assignment_issues", enabled = false, suppressWarnings = "AssignmentToCatchBlockParameter", options=Options.QUERY) //NOI18N
@TriggerTreeKind(Kind.CATCH)
public static List<ErrorDescription> assignmentToCatchBlockParameter(HintContext context) {
    final Trees trees = context.getInfo().getTrees();
    final TreePath catchPath = context.getPath();
    final Element param = trees.getElement(TreePath.getPath(catchPath, ((CatchTree) catchPath.getLeaf()).getParameter()));
    if (param == null || param.getKind() != ElementKind.EXCEPTION_PARAMETER) {
        return null;
    }
    final TreePath block = TreePath.getPath(catchPath, ((CatchTree) catchPath.getLeaf()).getBlock());
    final List<TreePath> paths = new LinkedList<TreePath>();
    new AssignmentFinder(trees, param).scan(block, paths);
    final List<ErrorDescription> ret = new ArrayList<ErrorDescription>(paths.size());
    for (TreePath path : paths) {
        ret.add(ErrorDescriptionFactory.forTree(context, path, NbBundle.getMessage(AssignmentIssues.class, "MSG_AssignmentToCatchBlockParameter", param.getSimpleName()))); //NOI18N
    }
    return ret;
}
 
Example 7
Source File: PullUpTransformer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private BlockTree updateSuperThisReferences(BlockTree body, final TreePath mpath) {
    final Map<ExpressionTree, ExpressionTree> original2Translated = new HashMap<ExpressionTree, ExpressionTree>();
    final Trees trees = workingCopy.getTrees();
    ErrorAwareTreeScanner<Boolean, Void> idScan = new ErrorAwareTreeScanner<Boolean, Void>() {
        @Override
        public Boolean visitMemberSelect(MemberSelectTree node, Void nothing) {
            String isThis = node.getExpression().toString();
            if (isThis.equals("super") || isThis.endsWith(".super")) { //NOI18N
                TreePath currentPath = new TreePath(mpath, node);
                Element el = trees.getElement(currentPath);
                if (el != null && el.getEnclosingElement().equals(targetType)) {
                    original2Translated.put(node, make.Identifier(node.getIdentifier()));
                    return Boolean.TRUE;
                }
            }
            return super.visitMemberSelect(node, nothing);
        }

        @Override
        public Boolean reduce(Boolean r1, Boolean r2) {
            return (r1 == Boolean.TRUE || r2 == Boolean.TRUE);
        }
    };
    boolean update = idScan.scan(body, null) == Boolean.TRUE;

    if (update) {
        body = (BlockTree) workingCopy.getTreeUtilities().translate(body, original2Translated);
    }
    return body;
}
 
Example 8
Source File: RADComponentRenameRefactoringSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitClass(ClassTree t, Void v) {
    if (variableElement == null) {
        // try to find the component's field variable in the class
        List<? extends Tree> members = (List<? extends Tree>) t.getMembers();
        Iterator<? extends Tree> it = members.iterator();
        while(it.hasNext()){
            Tree tr = it.next();
            if (tr.getKind() == Tree.Kind.VARIABLE) {
                Trees trees = info.getTrees();
                TreePath path = new TreePath(getCurrentPath(), tr);
                Element el = trees.getElement(path);
                if (el != null) { // Issue 185420
                    String sname = el.getSimpleName().toString();
                    if(sname.equals(this.member)){
                        this.handle = TreePathHandle.create(path, info);
                        variableElement = el;
                        if (findUsages) {
                            usagesPositions = new ArrayList<Integer>();
                        }
                    }
                }
            }
        }
    }
    if (findUsages) {
        super.visitClass(t, v);
    }
    return null;
}
 
Example 9
Source File: BIGuardedBlockHandlerFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean checkChange(CompilationController javac, PositionBounds span) throws IOException, BadLocationException {
    final int begin = span.getBegin().getOffset();
    final Trees trees = javac.getTrees();
    TreePath path = javac.getTreeUtilities().pathFor(begin + 1);
    if (path == null) {
        return false;
    }
    
    Element element = trees.getElement(path);
    if (element == null) {
        return false;
    }

    TreePath decl = trees.getPath(element);
    if (decl != null) {
        SourcePositions sourcePositions = trees.getSourcePositions();
        long declBegin = sourcePositions.getStartPosition(decl.getCompilationUnit(), decl.getLeaf());
        FileObject fo = SourceUtils.getFile(element, javac.getClasspathInfo());
        Document doc = javac.getDocument();
        GuardedSectionManager guards = GuardedSectionManager.getInstance((StyledDocument) doc);
        
        if (fo != javac.getFileObject() || guards != null && !isGuarded(guards, doc.createPosition((int) declBegin))) {
            // tree being refactored is declared outside of this file
            // or out of guarded sections. It should be safe to make change
            return true;
        }
    } else {
        // e.g. package; change is OK
            return true;
    }
    return false;
}
 
Example 10
Source File: ImportsTrackerTestHelper.java    From buck with Apache License 2.0 5 votes vote down vote up
public static ImportsTracker loadImports(
    Elements elements, Types types, Trees trees, CompilationUnitTree compilationUnit) {
  TreePath compilationUnitPath = new TreePath(compilationUnit);
  ImportsTracker result =
      new ImportsTracker(elements, types, (PackageElement) trees.getElement(compilationUnitPath));
  for (ImportTree importTree : compilationUnit.getImports()) {
    handleImport(trees, result, new TreePath(compilationUnitPath, importTree));
  }
  return result;
}
 
Example 11
Source File: SrcFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TypeElement findClass(CompilationController ctrl, String className) {
    CompilationUnitTree cunit = ctrl.getCompilationUnit();
    for (Tree declTree : cunit.getTypeDecls()) {
        ClassTree classTree = (ClassTree) declTree;
        if (className.equals(classTree.getSimpleName().toString())) {
            Trees trees = ctrl.getTrees();
            TypeElement classElm = (TypeElement) trees.getElement(trees.getPath(cunit, classTree));
            return classElm;
        }
    }
    return null;
}
 
Example 12
Source File: PreconditionsChecker.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isLocalVariable(IdentifierTree id, Trees trees) {
    Element el = trees.getElement(TreePath.getPath(treePath, id));
    if (el != null) {
        return el.getKind() == ElementKind.LOCAL_VARIABLE || el.getKind() == ElementKind.PARAMETER;
    }
    return false;
}
 
Example 13
Source File: FieldEncapsulation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TypeElement getEnclosingClass (TreePath path, final Trees trees) {
    while (path != null && path.getLeaf().getKind() != Tree.Kind.COMPILATION_UNIT) {
        if (TreeUtilities.CLASS_TREE_KINDS.contains(path.getLeaf().getKind())) {
            return (TypeElement) trees.getElement(path);
        }
        path = path.getParentPath();
    }
    return null;
}
 
Example 14
Source File: InlineRefactoringPlugin.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Element asElement(TreePath treePath) {
    Trees treeUtil = workingCopy.getTrees();
    return treeUtil.getElement(treePath);
}
 
Example 15
Source File: FindUsagesVisitor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void addIfMatch(TreePath path, Tree tree, Element elementToFind) {
    if(isCancelled.get()) {
        return;
    }
    if (JavaPluginUtils.isSyntheticPath(workingCopy, path)) {
        if (ElementKind.CONSTRUCTOR != elementToFind.getKind()
                || tree.getKind() != Tree.Kind.IDENTIFIER
                || !"super".contentEquals(((IdentifierTree) tree).getName())) { // NOI18N
            // do not skip synthetic usages of constructor
            return;
        }
    }
    Trees trees = workingCopy.getTrees();
    Element el = trees.getElement(path);
    if (el == null) {
        path = path.getParentPath();
        if (path != null && path.getLeaf().getKind() == Kind.IMPORT) {
            ImportTree impTree = (ImportTree) path.getLeaf();
            if (!impTree.isStatic()) {
                return;
            }
            Tree idTree = impTree.getQualifiedIdentifier();
            if (idTree.getKind() != Kind.MEMBER_SELECT) {
                return;
            }
            final Name id = ((MemberSelectTree) idTree).getIdentifier();
            if (id.contentEquals("*")) {
                return;
            }
            Tree classTree = ((MemberSelectTree) idTree).getExpression();
            path = trees.getPath(workingCopy.getCompilationUnit(), classTree);
            el = trees.getElement(path);
            if (el == null) {
                return;
            }
            Iterator iter = workingCopy.getElementUtilities().getMembers(el.asType(), new ElementUtilities.ElementAcceptor() {
                @Override
                public boolean accept(Element e, TypeMirror type) {
                    return id.equals(e.getSimpleName());
                }
            }).iterator();
            if (iter.hasNext()) {
                el = (Element) iter.next();
            }
            if (iter.hasNext()) {
                return;
            }
        } else {
            return;
        }
    }
    if (elementToFind != null && elementToFind.getKind() == ElementKind.METHOD && el.getKind() == ElementKind.METHOD) {
        for (ExecutableElement executableElement : methods) {
            if (el.equals(executableElement) 
                    || workingCopy.getElements().overrides((ExecutableElement) el,
                    executableElement, (TypeElement) elementToFind.getEnclosingElement())) {
                addUsage(path);
            }
        }
    } else if (el.equals(elementToFind)) {
        final ElementKind kind = elementToFind.getKind();
        if(kind.isField() || kind == ElementKind.LOCAL_VARIABLE || kind == ElementKind.RESOURCE_VARIABLE || kind == ElementKind.PARAMETER) {
            JavaWhereUsedFilters.ReadWrite access;
            Element collectionElement = workingCopy.getElementUtilities().findElement("java.util.Collection"); //NOI18N
            Element mapElement = workingCopy.getElementUtilities().findElement("java.util.Map"); //NOI18N
            if(collectionElement != null &&
                    workingCopy.getTypes().isSubtype(
                            workingCopy.getTypes().erasure(el.asType()),
                            workingCopy.getTypes().erasure(collectionElement.asType()))) {
                access = analyzeCollectionAccess(path);
            } else if(mapElement != null &&
                    workingCopy.getTypes().isSubtype(
                            workingCopy.getTypes().erasure(el.asType()),
                            workingCopy.getTypes().erasure(mapElement.asType()))) {
                access = analyzeCollectionAccess(path);
            } else {
                access = analyzeVarAccess(path, elementToFind, tree);
            }
            addUsage(path, access);
        } else {
            addUsage(path);
        }
    }
}
 
Example 16
Source File: VarUsageVisitor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Element asElement(Tree tree) {
    Trees treeUtil = workingCopy.getTrees();
    TreePath treePath = treeUtil.getPath(workingCopy.getCompilationUnit(), tree);
    Element element = treeUtil.getElement(treePath);
    return element;
}
 
Example 17
Source File: ExtractSuperclassRefactoringPlugin.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Tree visitMethod(final MethodTree methodTree, Element p) {
    final Trees trees = workingCopy.getTrees();
    Element current = trees.getElement(getCurrentPath());
    if (current != null) {
        for (MemberInfo<ElementHandle<? extends Element>> memberInfo : refactoring.getMembers()) {
            if (memberInfo.getGroup() == MemberInfo.Group.METHOD
                    && memberInfo.getElementHandle().resolve(workingCopy) == current) {
                if(!memberInfo.isMakeAbstract()) {
                    members2Remove.add(methodTree);
                }
                GeneratorUtilities genUtils = GeneratorUtilities.get(workingCopy);
                MethodTree newMethod = genUtils.importComments(methodTree, workingCopy.getCompilationUnit());
                ModifiersTree modifiers = methodTree.getModifiers();
                if (modifiers.getFlags().contains(Modifier.PRIVATE)) {
                    modifiers = make.removeModifiersModifier(modifiers, Modifier.PRIVATE);
                    modifiers = make.addModifiersModifier(modifiers, Modifier.PROTECTED);
                }
                newMethod = genUtils.importFQNs(newMethod);
                modifiers = genUtils.importFQNs(modifiers);
                final List<? extends TypeMirror> thrownTypes = ((ExecutableElement)current).getThrownTypes();
                List<ExpressionTree> newThrownTypes = new ArrayList<ExpressionTree>(thrownTypes.size());
                for (TypeMirror typeMirror : thrownTypes) {
                    newThrownTypes.add((ExpressionTree) make.Type(typeMirror)); // Necessary as this is not covered by importFQNs
                }
                if (memberInfo.isMakeAbstract() && !current.getModifiers().contains(Modifier.ABSTRACT)) {
                    newMethod = make.Method(
                            RefactoringUtils.makeAbstract(make, modifiers),
                            newMethod.getName(),
                            newMethod.getReturnType(),
                            newMethod.getTypeParameters(),
                            newMethod.getParameters(),
                            newThrownTypes,
                            (BlockTree) null,
                            null);
                } else {
                    newMethod = make.Method(modifiers,
                            newMethod.getName(),
                            newMethod.getReturnType(),
                            newMethod.getTypeParameters(),
                            newMethod.getParameters(),
                            newThrownTypes,
                            newMethod.getBody(),
                            (ExpressionTree) newMethod.getDefaultValue());
                }
                genUtils.copyComments(methodTree, newMethod, false);
                genUtils.copyComments(methodTree, newMethod, true);
                makeAbstract |= newMethod.getModifiers().getFlags().contains(Modifier.ABSTRACT);
                members.add(newMethod);
                break;
            }
        }
    }
    return methodTree;
}
 
Example 18
Source File: UseSuperTypeRefactoringPlugin.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Element asElement(Tree tree) {
    Trees treeUtil = workingCopy.getTrees();
    TreePath treePath = treeUtil.getPath(workingCopy.getCompilationUnit(), tree);
    Element element = treeUtil.getElement(treePath);
    return element;
}
 
Example 19
Source File: UseSuperTypeRefactoringPlugin.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Tree visitVariable(VariableTree varTree, Element elementToMatch) {
    TreePath treePath = getCurrentPath();
    VariableElement varElement = (VariableElement) workingCopy.
            getTrees().getElement(treePath);


    //This check shouldn't be needed (ideally).
    if (varElement == null) {
        return super.visitVariable(varTree, elementToMatch);
    }
    TreePath parentPath = treePath.getParentPath();
    if(parentPath != null && parentPath.getLeaf().getKind() == Tree.Kind.CATCH) {
        // Do not change in catch statement
        return super.visitVariable(varTree, elementToMatch);
    }

    Types types = workingCopy.getTypes();
    TypeMirror varTypeErasure = types.erasure(varElement.asType());
    TypeMirror elToMatchErasure = types.erasure(subTypeElement.asType());

    if (types.isSameType(varTypeErasure, elToMatchErasure)) {
        
        //Check for overloaded methods
        boolean clashWithOverload = false;
        if(parentPath != null && parentPath.getLeaf().getKind() == Tree.Kind.METHOD) {
            Trees trees = workingCopy.getTrees();
            ExecutableElement parent = (ExecutableElement) trees.getElement(parentPath);
            TreePath enclosing = JavaRefactoringUtils.findEnclosingClass(workingCopy, parentPath, true, true, true, true, true);
            TypeElement typeEl = (TypeElement) (enclosing == null? null : trees.getElement(enclosing));
            if(parent != null && typeEl != null) {
                Name simpleName = parent.getSimpleName();
                int size = parent.getParameters().size();
                OUTER: for (ExecutableElement method : ElementFilter.methodsIn(workingCopy.getElements().getAllMembers(typeEl))) {
                    if (method != parent &&
                        method.getKind() == parent.getKind() &&
                        size == method.getParameters().size() &&
                        simpleName.contentEquals(method.getSimpleName())) {
                        for (int i = 0; i < parent.getParameters().size(); i++) {
                            VariableElement par = parent.getParameters().get(i);
                            TypeMirror parErasure = types.erasure(par.asType());
                            TypeMirror par2Erasure = types.erasure(method.getParameters().get(i).asType());
                            if(!types.isSameType(parErasure, par2Erasure)) {
                                if(types.isAssignable(types.erasure(superTypeElement.asType()), par2Erasure)) {
                                    clashWithOverload = true;
                                    break OUTER;
                                }
                                if(types.isSubtype(parErasure, par2Erasure)) {
                                    clashWithOverload = true;
                                    break OUTER;
                                }
                            }
                        }
                    }
                }
            }
        }
        if (!clashWithOverload && isReplaceCandidate(varElement)) {
            replaceWithSuperType(treePath, varTree, varElement, superTypeElement);
        }
    }
    return super.visitVariable(varTree, elementToMatch);
}
 
Example 20
Source File: OrganizeImports.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Performs 'organize imports' in two modes. If 'addImports' is null, it optimizes imports according to coding style.
 * However if addImports is not null && not empty, it will add the elements in addImports, and reorder the set
 * of import statements, but will not remove unused imports.
 * Combination of bulk + addImports is not tested.
 * 
 * @param copy working copy to change
 * @param addImports if not null, just adds and reorders imports. If null, performs optimization
 * @param isBulkMode called from batch processing
 * @throws IllegalStateException 
 */
public static void doOrganizeImports(WorkingCopy copy, Set<Element> addImports, boolean isBulkMode) throws IllegalStateException {
    CompilationUnitTree cu = copy.getCompilationUnit();
    List<? extends ImportTree> imports = cu.getImports();
    if (imports.isEmpty()) {
        if (addImports == null) {
            return;
        }
    } else if (addImports == null) {
        // check diag code only if in the 'optimize all' mode.
        List<Diagnostic> diags = copy.getDiagnostics();
        if (!diags.isEmpty()) {
            SourcePositions sp = copy.getTrees().getSourcePositions();
            long startPos = sp.getStartPosition(cu, imports.get(0));
            long endPos = sp.getEndPosition(cu, imports.get(imports.size() - 1));
            for (Diagnostic d : diags) {
                if (startPos <= d.getPosition() && d.getPosition() <= endPos) {
                    if (ERROR_CODE.contentEquals(d.getCode()))
                        return;
                }
            }
        }
    }
    final CodeStyle cs = CodeStyle.getDefault(copy.getFileObject());
    Set<Element> starImports = new HashSet<Element>();
    Set<Element> staticStarImports = new HashSet<Element>();
    Set<Element> toImport = getUsedElements(copy, cu, starImports, staticStarImports);
    List<ImportTree> imps = new LinkedList<ImportTree>();  
    TreeMaker maker = copy.getTreeMaker();
    
    if (addImports != null) {
        // copy over all imports to be added + existing imports.
        toImport.addAll(addImports);
        imps.addAll(cu.getImports());
    } else if (!toImport.isEmpty() || isBulkMode) {
        // track import star import scopes, so only one star import/scope appears in imps - #251977
        Set<Element> starImportScopes = new HashSet<>();
        Trees trees = copy.getTrees();
        for (ImportTree importTree : cu.getImports()) {
            Tree qualIdent = importTree.getQualifiedIdentifier();
            if (qualIdent.getKind() == Tree.Kind.MEMBER_SELECT && "*".contentEquals(((MemberSelectTree)qualIdent).getIdentifier())) {
                ImportTree imp = null;
                Element importedScope = trees.getElement(TreePath.getPath(cu, ((MemberSelectTree)qualIdent).getExpression()));
                
                if (importTree.isStatic()) {
                    if (staticStarImports != null && 
                        staticStarImports.contains(importedScope) &&
                        !starImportScopes.contains(importedScope)) {
                        imp = maker.Import(qualIdent, true);
                    }
                } else {
                    if (starImports != null && 
                        starImports.contains(importedScope) &&
                        !starImportScopes.contains(importedScope)) {
                        imp = maker.Import(qualIdent, false);
                    }
                }
                if (imp != null) {
                    starImportScopes.add(importedScope);
                    imps.add(imp);
                }
            }
        }
    } else {
        return;
    }
    if (!imps.isEmpty()) {
        Collections.sort(imps, new Comparator<ImportTree>() {

            private CodeStyle.ImportGroups groups = cs.getImportGroups();

            @Override
            public int compare(ImportTree o1, ImportTree o2) {
                if (o1 == o2)
                    return 0;
                String s1 = o1.getQualifiedIdentifier().toString();
                String s2 = o2.getQualifiedIdentifier().toString();
                int bal = groups.getGroupId(s1, o1.isStatic()) - groups.getGroupId(s2, o2.isStatic());
                return bal == 0 ? s1.compareTo(s2) : bal;
            }
        });
    }
    CompilationUnitTree cut = maker.CompilationUnit(cu.getPackageAnnotations(), cu.getPackageName(), imps, cu.getTypeDecls(), cu.getSourceFile());
    ((JCCompilationUnit)cut).packge = ((JCCompilationUnit)cu).packge;
    if (starImports != null || staticStarImports != null) {
        ((JCCompilationUnit)cut).starImportScope = ((JCCompilationUnit)cu).starImportScope;
    }
    CompilationUnitTree ncu = toImport.isEmpty() ? cut : GeneratorUtilities.get(copy).addImports(cut, toImport);
    copy.rewrite(cu, ncu);
}