public Void visitCompilationUnit(CompilationUnit node) {
if (inDefiningCompilationUnit) {
NodeList<Directive> directives = node.getDirectives();
for (Directive directive : directives) {
if (directive instanceof ImportDirective) {
ImportDirective importDirective = (ImportDirective) directive;
LibraryElement libraryElement = importDirective.getUriElement();
if (libraryElement != null) {
unusedImports.add(importDirective);
//
// Initialize prefixElementMap
//
if (importDirective.getAsToken() != null) {
SimpleIdentifier prefixIdentifier = importDirective.getPrefix();
if (prefixIdentifier != null) {
Element element = prefixIdentifier.getStaticElement();
if (element instanceof PrefixElement) {
PrefixElement prefixElementKey = (PrefixElement) element;
ArrayList<ImportDirective> list = prefixElementMap.get(prefixElementKey);
if (list == null) {
list = new ArrayList<ImportDirective>(1);
prefixElementMap.put(prefixElementKey, list);
}
list.add(importDirective);
}
// TODO (jwren) Can the element ever not be a PrefixElement?
}
}
//
// Initialize libraryMap: libraryElement -> importDirective
//
putIntoLibraryMap(libraryElement, importDirective);
//
// For this new addition to the libraryMap, also recursively add any exports from the
// libraryElement
//
addAdditionalLibrariesForExports(
libraryElement,
importDirective,
new ArrayList<LibraryElement>());
}
}
}
}
// If there are no imports in this library, don't visit the identifiers in the library- there
// can be no unused imports.
if (unusedImports.isEmpty()) {
return null;
}
if (unusedImports.size() > 1) {
// order the list of unusedImports to find duplicates in faster than O(n^2) time
ImportDirective[] importDirectiveArray = unusedImports.toArray(new ImportDirective[unusedImports.size()]);
Arrays.sort(importDirectiveArray, ImportDirective.COMPARATOR);
ImportDirective currentDirective = importDirectiveArray[0];
for (int i = 1; i < importDirectiveArray.length; i++) {
ImportDirective nextDirective = importDirectiveArray[i];
if (ImportDirective.COMPARATOR.compare(currentDirective, nextDirective) == 0) {
// Add either the currentDirective or nextDirective depending on which comes second, this
// guarantees that the first of the duplicates won't be highlighted.
if (currentDirective.getOffset() < nextDirective.getOffset()) {
duplicateImports.add(nextDirective);
} else {
duplicateImports.add(currentDirective);
}
}