1 //===- InterpolatingCompilationDatabase.cpp ---------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // InterpolatingCompilationDatabase wraps another CompilationDatabase and 11 // attempts to heuristically determine appropriate compile commands for files 12 // that are not included, such as headers or newly created files. 13 // 14 // Motivating cases include: 15 // Header files that live next to their implementation files. These typically 16 // share a base filename. (libclang/CXString.h, libclang/CXString.cpp). 17 // Some projects separate headers from includes. Filenames still typically 18 // match, maybe other path segments too. (include/llvm/IR/Use.h, lib/IR/Use.cc). 19 // Matches are sometimes only approximate (Sema.h, SemaDecl.cpp). This goes 20 // for directories too (Support/Unix/Process.inc, lib/Support/Process.cpp). 21 // Even if we can't find a "right" compile command, even a random one from 22 // the project will tend to get important flags like -I and -x right. 23 // 24 // We "borrow" the compile command for the closest available file: 25 // - points are awarded if the filename matches (ignoring extension) 26 // - points are awarded if the directory structure matches 27 // - ties are broken by length of path prefix match 28 // 29 // The compile command is adjusted, replacing the filename and removing output 30 // file arguments. The -x and -std flags may be affected too. 31 // 32 // Source language is a tricky issue: is it OK to use a .c file's command 33 // for building a .cc file? What language is a .h file in? 34 // - We only consider compile commands for c-family languages as candidates. 35 // - For files whose language is implied by the filename (e.g. .m, .hpp) 36 // we prefer candidates from the same language. 37 // If we must cross languages, we drop any -x and -std flags. 38 // - For .h files, candidates from any c-family language are acceptable. 39 // We use the candidate's language, inserting e.g. -x c++-header. 40 // 41 // This class is only useful when wrapping databases that can enumerate all 42 // their compile commands. If getAllFilenames() is empty, no inference occurs. 43 // 44 //===----------------------------------------------------------------------===// 45 46 #include "clang/Driver/Options.h" 47 #include "clang/Driver/Types.h" 48 #include "clang/Frontend/LangStandard.h" 49 #include "clang/Tooling/CompilationDatabase.h" 50 #include "llvm/ADT/DenseMap.h" 51 #include "llvm/ADT/StringExtras.h" 52 #include "llvm/ADT/StringSwitch.h" 53 #include "llvm/Option/ArgList.h" 54 #include "llvm/Option/OptTable.h" 55 #include "llvm/Support/Debug.h" 56 #include "llvm/Support/Path.h" 57 #include "llvm/Support/StringSaver.h" 58 #include "llvm/Support/raw_ostream.h" 59 #include <memory> 60 61 namespace clang { 62 namespace tooling { 63 namespace { 64 using namespace llvm; 65 namespace types = clang::driver::types; 66 namespace path = llvm::sys::path; 67 68 // The length of the prefix these two strings have in common. 69 size_t matchingPrefix(StringRef L, StringRef R) { 70 size_t Limit = std::min(L.size(), R.size()); 71 for (size_t I = 0; I < Limit; ++I) 72 if (L[I] != R[I]) 73 return I; 74 return Limit; 75 } 76 77 // A comparator for searching SubstringWithIndexes with std::equal_range etc. 78 // Optionaly prefix semantics: compares equal if the key is a prefix. 79 template <bool Prefix> struct Less { 80 bool operator()(StringRef Key, std::pair<StringRef, size_t> Value) const { 81 StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first; 82 return Key < V; 83 } 84 bool operator()(std::pair<StringRef, size_t> Value, StringRef Key) const { 85 StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first; 86 return V < Key; 87 } 88 }; 89 90 // Infer type from filename. If we might have gotten it wrong, set *Certain. 91 // *.h will be inferred as a C header, but not certain. 92 types::ID guessType(StringRef Filename, bool *Certain = nullptr) { 93 // path::extension is ".cpp", lookupTypeForExtension wants "cpp". 94 auto Lang = 95 types::lookupTypeForExtension(path::extension(Filename).substr(1)); 96 if (Certain) 97 *Certain = Lang != types::TY_CHeader && Lang != types::TY_INVALID; 98 return Lang; 99 } 100 101 // Return Lang as one of the canonical supported types. 102 // e.g. c-header --> c; fortran --> TY_INVALID 103 static types::ID foldType(types::ID Lang) { 104 switch (Lang) { 105 case types::TY_C: 106 case types::TY_CHeader: 107 return types::TY_C; 108 case types::TY_ObjC: 109 case types::TY_ObjCHeader: 110 return types::TY_ObjC; 111 case types::TY_CXX: 112 case types::TY_CXXHeader: 113 return types::TY_CXX; 114 case types::TY_ObjCXX: 115 case types::TY_ObjCXXHeader: 116 return types::TY_ObjCXX; 117 default: 118 return types::TY_INVALID; 119 } 120 } 121 122 // A CompileCommand that can be applied to another file. 123 struct TransferableCommand { 124 // Flags that should not apply to all files are stripped from CommandLine. 125 CompileCommand Cmd; 126 // Language detected from -x or the filename. Never TY_INVALID. 127 Optional<types::ID> Type; 128 // Standard specified by -std. 129 LangStandard::Kind Std = LangStandard::lang_unspecified; 130 131 TransferableCommand(CompileCommand C) 132 : Cmd(std::move(C)), Type(guessType(Cmd.Filename)) { 133 std::vector<std::string> NewArgs = {Cmd.CommandLine.front()}; 134 // Parse the old args in order to strip out and record unwanted flags. 135 auto OptTable = clang::driver::createDriverOptTable(); 136 std::vector<const char *> Argv; 137 for (unsigned I = 1; I < Cmd.CommandLine.size(); ++I) 138 Argv.push_back(Cmd.CommandLine[I].c_str()); 139 unsigned MissingI, MissingC; 140 auto ArgList = OptTable->ParseArgs(Argv, MissingI, MissingC); 141 for (const auto *Arg : ArgList) { 142 const auto &option = Arg->getOption(); 143 // Strip input and output files. 144 if (option.matches(clang::driver::options::OPT_INPUT) || 145 option.matches(clang::driver::options::OPT_o)) { 146 continue; 147 } 148 // Strip -x, but record the overridden language. 149 if (option.matches(clang::driver::options::OPT_x)) { 150 for (const char *Value : Arg->getValues()) 151 Type = types::lookupTypeForTypeSpecifier(Value); 152 continue; 153 } 154 // Strip --std, but record the value. 155 if (option.matches(clang::driver::options::OPT_std_EQ)) { 156 for (const char *Value : Arg->getValues()) { 157 Std = llvm::StringSwitch<LangStandard::Kind>(Value) 158 #define LANGSTANDARD(id, name, lang, desc, features) \ 159 .Case(name, LangStandard::lang_##id) 160 #define LANGSTANDARD_ALIAS(id, alias) .Case(alias, LangStandard::lang_##id) 161 #include "clang/Frontend/LangStandards.def" 162 .Default(Std); 163 } 164 continue; 165 } 166 llvm::opt::ArgStringList ArgStrs; 167 Arg->render(ArgList, ArgStrs); 168 NewArgs.insert(NewArgs.end(), ArgStrs.begin(), ArgStrs.end()); 169 } 170 Cmd.CommandLine = std::move(NewArgs); 171 172 if (Std != LangStandard::lang_unspecified) // -std take precedence over -x 173 Type = toType(LangStandard::getLangStandardForKind(Std).getLanguage()); 174 Type = foldType(*Type); 175 // The contract is to store None instead of TY_INVALID. 176 if (Type == types::TY_INVALID) 177 Type = llvm::None; 178 } 179 180 // Produce a CompileCommand for \p filename, based on this one. 181 CompileCommand transferTo(StringRef Filename) const { 182 CompileCommand Result = Cmd; 183 Result.Filename = Filename; 184 bool TypeCertain; 185 auto TargetType = guessType(Filename, &TypeCertain); 186 // If the filename doesn't determine the language (.h), transfer with -x. 187 if (TargetType != types::TY_INVALID && !TypeCertain && Type) { 188 TargetType = types::onlyPrecompileType(TargetType) // header? 189 ? types::lookupHeaderTypeForSourceType(*Type) 190 : *Type; 191 Result.CommandLine.push_back("-x"); 192 Result.CommandLine.push_back(types::getTypeName(TargetType)); 193 } 194 // --std flag may only be transferred if the language is the same. 195 // We may consider "translating" these, e.g. c++11 -> c11. 196 if (Std != LangStandard::lang_unspecified && foldType(TargetType) == Type) { 197 Result.CommandLine.push_back( 198 "-std=" + 199 std::string(LangStandard::getLangStandardForKind(Std).getName())); 200 } 201 Result.CommandLine.push_back(Filename); 202 return Result; 203 } 204 205 private: 206 // Map the language from the --std flag to that of the -x flag. 207 static types::ID toType(InputKind::Language Lang) { 208 switch (Lang) { 209 case InputKind::C: 210 return types::TY_C; 211 case InputKind::CXX: 212 return types::TY_CXX; 213 case InputKind::ObjC: 214 return types::TY_ObjC; 215 case InputKind::ObjCXX: 216 return types::TY_ObjCXX; 217 default: 218 return types::TY_INVALID; 219 } 220 } 221 }; 222 223 // Given a filename, FileIndex picks the best matching file from the underlying 224 // DB. This is the proxy file whose CompileCommand will be reused. The 225 // heuristics incorporate file name, extension, and directory structure. 226 // Strategy: 227 // - Build indexes of each of the substrings we want to look up by. 228 // These indexes are just sorted lists of the substrings. 229 // - Each criterion corresponds to a range lookup into the index, so we only 230 // need O(log N) string comparisons to determine scores. 231 // 232 // Apart from path proximity signals, also takes file extensions into account 233 // when scoring the candidates. 234 class FileIndex { 235 public: 236 FileIndex(std::vector<std::string> Files) 237 : OriginalPaths(std::move(Files)), Strings(Arena) { 238 // Sort commands by filename for determinism (index is a tiebreaker later). 239 llvm::sort(OriginalPaths.begin(), OriginalPaths.end()); 240 Paths.reserve(OriginalPaths.size()); 241 Types.reserve(OriginalPaths.size()); 242 Stems.reserve(OriginalPaths.size()); 243 for (size_t I = 0; I < OriginalPaths.size(); ++I) { 244 StringRef Path = Strings.save(StringRef(OriginalPaths[I]).lower()); 245 246 Paths.emplace_back(Path, I); 247 Types.push_back(foldType(guessType(Path))); 248 Stems.emplace_back(sys::path::stem(Path), I); 249 auto Dir = ++sys::path::rbegin(Path), DirEnd = sys::path::rend(Path); 250 for (int J = 0; J < DirectorySegmentsIndexed && Dir != DirEnd; ++J, ++Dir) 251 if (Dir->size() > ShortDirectorySegment) // not trivial ones 252 Components.emplace_back(*Dir, I); 253 } 254 llvm::sort(Paths.begin(), Paths.end()); 255 llvm::sort(Stems.begin(), Stems.end()); 256 llvm::sort(Components.begin(), Components.end()); 257 } 258 259 bool empty() const { return Paths.empty(); } 260 261 // Returns the path for the file that best fits OriginalFilename. 262 // Candidates with extensions matching PreferLanguage will be chosen over 263 // others (unless it's TY_INVALID, or all candidates are bad). 264 StringRef chooseProxy(StringRef OriginalFilename, 265 types::ID PreferLanguage) const { 266 assert(!empty() && "need at least one candidate!"); 267 std::string Filename = OriginalFilename.lower(); 268 auto Candidates = scoreCandidates(Filename); 269 std::pair<size_t, int> Best = 270 pickWinner(Candidates, Filename, PreferLanguage); 271 272 DEBUG_WITH_TYPE( 273 "interpolate", 274 llvm::dbgs() << "interpolate: chose " << OriginalPaths[Best.first] 275 << " as proxy for " << OriginalFilename << " preferring " 276 << (PreferLanguage == types::TY_INVALID 277 ? "none" 278 : types::getTypeName(PreferLanguage)) 279 << " score=" << Best.second << "\n"); 280 return OriginalPaths[Best.first]; 281 } 282 283 private: 284 using SubstringAndIndex = std::pair<StringRef, size_t>; 285 // Directory matching parameters: we look at the last two segments of the 286 // parent directory (usually the semantically significant ones in practice). 287 // We search only the last four of each candidate (for efficiency). 288 constexpr static int DirectorySegmentsIndexed = 4; 289 constexpr static int DirectorySegmentsQueried = 2; 290 constexpr static int ShortDirectorySegment = 1; // Only look at longer names. 291 292 // Award points to candidate entries that should be considered for the file. 293 // Returned keys are indexes into paths, and the values are (nonzero) scores. 294 DenseMap<size_t, int> scoreCandidates(StringRef Filename) const { 295 // Decompose Filename into the parts we care about. 296 // /some/path/complicated/project/Interesting.h 297 // [-prefix--][---dir---] [-dir-] [--stem---] 298 StringRef Stem = sys::path::stem(Filename); 299 llvm::SmallVector<StringRef, DirectorySegmentsQueried> Dirs; 300 llvm::StringRef Prefix; 301 auto Dir = ++sys::path::rbegin(Filename), 302 DirEnd = sys::path::rend(Filename); 303 for (int I = 0; I < DirectorySegmentsQueried && Dir != DirEnd; ++I, ++Dir) { 304 if (Dir->size() > ShortDirectorySegment) 305 Dirs.push_back(*Dir); 306 Prefix = Filename.substr(0, Dir - DirEnd); 307 } 308 309 // Now award points based on lookups into our various indexes. 310 DenseMap<size_t, int> Candidates; // Index -> score. 311 auto Award = [&](int Points, ArrayRef<SubstringAndIndex> Range) { 312 for (const auto &Entry : Range) 313 Candidates[Entry.second] += Points; 314 }; 315 // Award one point if the file's basename is a prefix of the candidate, 316 // and another if it's an exact match (so exact matches get two points). 317 Award(1, indexLookup</*Prefix=*/true>(Stem, Stems)); 318 Award(1, indexLookup</*Prefix=*/false>(Stem, Stems)); 319 // For each of the last few directories in the Filename, award a point 320 // if it's present in the candidate. 321 for (StringRef Dir : Dirs) 322 Award(1, indexLookup</*Prefix=*/false>(Dir, Components)); 323 // Award one more point if the whole rest of the path matches. 324 if (sys::path::root_directory(Prefix) != Prefix) 325 Award(1, indexLookup</*Prefix=*/true>(Prefix, Paths)); 326 return Candidates; 327 } 328 329 // Pick a single winner from the set of scored candidates. 330 // Returns (index, score). 331 std::pair<size_t, int> pickWinner(const DenseMap<size_t, int> &Candidates, 332 StringRef Filename, 333 types::ID PreferredLanguage) const { 334 struct ScoredCandidate { 335 size_t Index; 336 bool Preferred; 337 int Points; 338 size_t PrefixLength; 339 }; 340 // Choose the best candidate by (preferred, points, prefix length, alpha). 341 ScoredCandidate Best = {size_t(-1), false, 0, 0}; 342 for (const auto &Candidate : Candidates) { 343 ScoredCandidate S; 344 S.Index = Candidate.first; 345 S.Preferred = PreferredLanguage == types::TY_INVALID || 346 PreferredLanguage == Types[S.Index]; 347 S.Points = Candidate.second; 348 if (!S.Preferred && Best.Preferred) 349 continue; 350 if (S.Preferred == Best.Preferred) { 351 if (S.Points < Best.Points) 352 continue; 353 if (S.Points == Best.Points) { 354 S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first); 355 if (S.PrefixLength < Best.PrefixLength) 356 continue; 357 // hidden heuristics should at least be deterministic! 358 if (S.PrefixLength == Best.PrefixLength) 359 if (S.Index > Best.Index) 360 continue; 361 } 362 } 363 // PrefixLength was only set above if actually needed for a tiebreak. 364 // But it definitely needs to be set to break ties in the future. 365 S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first); 366 Best = S; 367 } 368 // Edge case: no candidate got any points. 369 // We ignore PreferredLanguage at this point (not ideal). 370 if (Best.Index == size_t(-1)) 371 return {longestMatch(Filename, Paths).second, 0}; 372 return {Best.Index, Best.Points}; 373 } 374 375 // Returns the range within a sorted index that compares equal to Key. 376 // If Prefix is true, it's instead the range starting with Key. 377 template <bool Prefix> 378 ArrayRef<SubstringAndIndex> 379 indexLookup(StringRef Key, ArrayRef<SubstringAndIndex> Idx) const { 380 // Use pointers as iteratiors to ease conversion of result to ArrayRef. 381 auto Range = std::equal_range(Idx.data(), Idx.data() + Idx.size(), Key, 382 Less<Prefix>()); 383 return {Range.first, Range.second}; 384 } 385 386 // Performs a point lookup into a nonempty index, returning a longest match. 387 SubstringAndIndex longestMatch(StringRef Key, 388 ArrayRef<SubstringAndIndex> Idx) const { 389 assert(!Idx.empty()); 390 // Longest substring match will be adjacent to a direct lookup. 391 auto It = 392 std::lower_bound(Idx.begin(), Idx.end(), SubstringAndIndex{Key, 0}); 393 if (It == Idx.begin()) 394 return *It; 395 if (It == Idx.end()) 396 return *--It; 397 // Have to choose between It and It-1 398 size_t Prefix = matchingPrefix(Key, It->first); 399 size_t PrevPrefix = matchingPrefix(Key, (It - 1)->first); 400 return Prefix > PrevPrefix ? *It : *--It; 401 } 402 403 // Original paths, everything else is in lowercase. 404 std::vector<std::string> OriginalPaths; 405 BumpPtrAllocator Arena; 406 StringSaver Strings; 407 // Indexes of candidates by certain substrings. 408 // String is lowercase and sorted, index points into OriginalPaths. 409 std::vector<SubstringAndIndex> Paths; // Full path. 410 // Lang types obtained by guessing on the corresponding path. I-th element is 411 // a type for the I-th path. 412 std::vector<types::ID> Types; 413 std::vector<SubstringAndIndex> Stems; // Basename, without extension. 414 std::vector<SubstringAndIndex> Components; // Last path components. 415 }; 416 417 // The actual CompilationDatabase wrapper delegates to its inner database. 418 // If no match, looks up a proxy file in FileIndex and transfers its 419 // command to the requested file. 420 class InterpolatingCompilationDatabase : public CompilationDatabase { 421 public: 422 InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner) 423 : Inner(std::move(Inner)), Index(this->Inner->getAllFiles()) {} 424 425 std::vector<CompileCommand> 426 getCompileCommands(StringRef Filename) const override { 427 auto Known = Inner->getCompileCommands(Filename); 428 if (Index.empty() || !Known.empty()) 429 return Known; 430 bool TypeCertain; 431 auto Lang = guessType(Filename, &TypeCertain); 432 if (!TypeCertain) 433 Lang = types::TY_INVALID; 434 auto ProxyCommands = 435 Inner->getCompileCommands(Index.chooseProxy(Filename, foldType(Lang))); 436 if (ProxyCommands.empty()) 437 return {}; 438 return {TransferableCommand(ProxyCommands[0]).transferTo(Filename)}; 439 } 440 441 std::vector<std::string> getAllFiles() const override { 442 return Inner->getAllFiles(); 443 } 444 445 std::vector<CompileCommand> getAllCompileCommands() const override { 446 return Inner->getAllCompileCommands(); 447 } 448 449 private: 450 std::unique_ptr<CompilationDatabase> Inner; 451 FileIndex Index; 452 }; 453 454 } // namespace 455 456 std::unique_ptr<CompilationDatabase> 457 inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner) { 458 return llvm::make_unique<InterpolatingCompilationDatabase>(std::move(Inner)); 459 } 460 461 } // namespace tooling 462 } // namespace clang 463