[include-fixer] Rank symbols based on the number of occurrences we found while merging.
This sorts based on the popularity of the header, not the symbol. If
there are mutliple matching symbols in one header we take the maximum
popularity for that header and deduplicate. If we know nothing we sort
lexicographically based on the header path.
Differential Revision: http://reviews.llvm.org/D20814
llvm-svn: 271283
diff --git a/clang-tools-extra/include-fixer/SymbolIndexManager.cpp b/clang-tools-extra/include-fixer/SymbolIndexManager.cpp
index 2a0547a..1800fab 100644
--- a/clang-tools-extra/include-fixer/SymbolIndexManager.cpp
+++ b/clang-tools-extra/include-fixer/SymbolIndexManager.cpp
@@ -17,6 +17,37 @@
namespace clang {
namespace include_fixer {
+using clang::find_all_symbols::SymbolInfo;
+
+/// Sorts and uniques SymbolInfos based on the popularity info in SymbolInfo.
+static void rankByPopularity(std::vector<SymbolInfo> &Symbols) {
+ // First collect occurrences per header file.
+ std::map<llvm::StringRef, unsigned> HeaderPopularity;
+ for (const SymbolInfo &Symbol : Symbols) {
+ unsigned &Popularity = HeaderPopularity[Symbol.getFilePath()];
+ Popularity = std::max(Popularity, Symbol.getNumOccurrences());
+ }
+
+ // Sort by the gathered popularities. Use file name as a tie breaker so we can
+ // deduplicate.
+ std::sort(Symbols.begin(), Symbols.end(),
+ [&](const SymbolInfo &A, const SymbolInfo &B) {
+ auto APop = HeaderPopularity[A.getFilePath()];
+ auto BPop = HeaderPopularity[B.getFilePath()];
+ if (APop != BPop)
+ return APop > BPop;
+ return A.getFilePath() < B.getFilePath();
+ });
+
+ // Deduplicate based on the file name. They will have the same popularity and
+ // we don't want to suggest the same header twice.
+ Symbols.erase(std::unique(Symbols.begin(), Symbols.end(),
+ [](const SymbolInfo &A, const SymbolInfo &B) {
+ return A.getFilePath() == B.getFilePath();
+ }),
+ Symbols.end());
+}
+
std::vector<std::string>
SymbolIndexManager::search(llvm::StringRef Identifier) const {
// The identifier may be fully qualified, so split it and get all the context
@@ -45,6 +76,8 @@
DEBUG(llvm::dbgs() << "Searching " << Names.back() << "... got "
<< Symbols.size() << " results...\n");
+ rankByPopularity(Symbols);
+
for (const auto &Symbol : Symbols) {
// Match the identifier name without qualifier.
if (Symbol.getName() == Names.back()) {