1ea9773acSSam McCall //===- InterpolatingCompilationDatabase.cpp ---------------------*- C++ -*-===// 2ea9773acSSam McCall // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6ea9773acSSam McCall // 7ea9773acSSam McCall //===----------------------------------------------------------------------===// 8ea9773acSSam McCall // 9ea9773acSSam McCall // InterpolatingCompilationDatabase wraps another CompilationDatabase and 10ea9773acSSam McCall // attempts to heuristically determine appropriate compile commands for files 11ea9773acSSam McCall // that are not included, such as headers or newly created files. 12ea9773acSSam McCall // 13ea9773acSSam McCall // Motivating cases include: 14ea9773acSSam McCall // Header files that live next to their implementation files. These typically 15ea9773acSSam McCall // share a base filename. (libclang/CXString.h, libclang/CXString.cpp). 16ea9773acSSam McCall // Some projects separate headers from includes. Filenames still typically 17ea9773acSSam McCall // match, maybe other path segments too. (include/llvm/IR/Use.h, lib/IR/Use.cc). 18ea9773acSSam McCall // Matches are sometimes only approximate (Sema.h, SemaDecl.cpp). This goes 19ea9773acSSam McCall // for directories too (Support/Unix/Process.inc, lib/Support/Process.cpp). 20ea9773acSSam McCall // Even if we can't find a "right" compile command, even a random one from 21ea9773acSSam McCall // the project will tend to get important flags like -I and -x right. 22ea9773acSSam McCall // 23ea9773acSSam McCall // We "borrow" the compile command for the closest available file: 24ea9773acSSam McCall // - points are awarded if the filename matches (ignoring extension) 25ea9773acSSam McCall // - points are awarded if the directory structure matches 26ea9773acSSam McCall // - ties are broken by length of path prefix match 27ea9773acSSam McCall // 28ea9773acSSam McCall // The compile command is adjusted, replacing the filename and removing output 29ea9773acSSam McCall // file arguments. The -x and -std flags may be affected too. 30ea9773acSSam McCall // 31ea9773acSSam McCall // Source language is a tricky issue: is it OK to use a .c file's command 32ea9773acSSam McCall // for building a .cc file? What language is a .h file in? 33ea9773acSSam McCall // - We only consider compile commands for c-family languages as candidates. 34ea9773acSSam McCall // - For files whose language is implied by the filename (e.g. .m, .hpp) 35ea9773acSSam McCall // we prefer candidates from the same language. 36ea9773acSSam McCall // If we must cross languages, we drop any -x and -std flags. 37ea9773acSSam McCall // - For .h files, candidates from any c-family language are acceptable. 38ea9773acSSam McCall // We use the candidate's language, inserting e.g. -x c++-header. 39ea9773acSSam McCall // 40ea9773acSSam McCall // This class is only useful when wrapping databases that can enumerate all 41ea9773acSSam McCall // their compile commands. If getAllFilenames() is empty, no inference occurs. 42ea9773acSSam McCall // 43ea9773acSSam McCall //===----------------------------------------------------------------------===// 44ea9773acSSam McCall 4509d890d7SRainer Orth #include "clang/Basic/LangStandard.h" 46*ce90b60bSKadir Cetinkaya #include "clang/Driver/Driver.h" 47ea9773acSSam McCall #include "clang/Driver/Options.h" 48ea9773acSSam McCall #include "clang/Driver/Types.h" 49ea9773acSSam McCall #include "clang/Tooling/CompilationDatabase.h" 50*ce90b60bSKadir Cetinkaya #include "llvm/ADT/ArrayRef.h" 51ea9773acSSam McCall #include "llvm/ADT/DenseMap.h" 52e05bf606SHamza Sood #include "llvm/ADT/Optional.h" 53ea9773acSSam McCall #include "llvm/ADT/StringExtras.h" 54ea9773acSSam McCall #include "llvm/ADT/StringSwitch.h" 55ea9773acSSam McCall #include "llvm/Option/ArgList.h" 56ea9773acSSam McCall #include "llvm/Option/OptTable.h" 57ea9773acSSam McCall #include "llvm/Support/Debug.h" 58ea9773acSSam McCall #include "llvm/Support/Path.h" 59ea9773acSSam McCall #include "llvm/Support/StringSaver.h" 60ea9773acSSam McCall #include "llvm/Support/raw_ostream.h" 61ea9773acSSam McCall #include <memory> 62ea9773acSSam McCall 63ea9773acSSam McCall namespace clang { 64ea9773acSSam McCall namespace tooling { 65ea9773acSSam McCall namespace { 66ea9773acSSam McCall using namespace llvm; 67ea9773acSSam McCall namespace types = clang::driver::types; 68ea9773acSSam McCall namespace path = llvm::sys::path; 69ea9773acSSam McCall 70ea9773acSSam McCall // The length of the prefix these two strings have in common. 71ea9773acSSam McCall size_t matchingPrefix(StringRef L, StringRef R) { 72ea9773acSSam McCall size_t Limit = std::min(L.size(), R.size()); 73ea9773acSSam McCall for (size_t I = 0; I < Limit; ++I) 74ea9773acSSam McCall if (L[I] != R[I]) 75ea9773acSSam McCall return I; 76ea9773acSSam McCall return Limit; 77ea9773acSSam McCall } 78ea9773acSSam McCall 79ea9773acSSam McCall // A comparator for searching SubstringWithIndexes with std::equal_range etc. 80ea9773acSSam McCall // Optionaly prefix semantics: compares equal if the key is a prefix. 81ea9773acSSam McCall template <bool Prefix> struct Less { 82ea9773acSSam McCall bool operator()(StringRef Key, std::pair<StringRef, size_t> Value) const { 83ea9773acSSam McCall StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first; 84ea9773acSSam McCall return Key < V; 85ea9773acSSam McCall } 86ea9773acSSam McCall bool operator()(std::pair<StringRef, size_t> Value, StringRef Key) const { 87ea9773acSSam McCall StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first; 88ea9773acSSam McCall return V < Key; 89ea9773acSSam McCall } 90ea9773acSSam McCall }; 91ea9773acSSam McCall 92ea9773acSSam McCall // Infer type from filename. If we might have gotten it wrong, set *Certain. 93ea9773acSSam McCall // *.h will be inferred as a C header, but not certain. 94ea9773acSSam McCall types::ID guessType(StringRef Filename, bool *Certain = nullptr) { 95ea9773acSSam McCall // path::extension is ".cpp", lookupTypeForExtension wants "cpp". 96ea9773acSSam McCall auto Lang = 97ea9773acSSam McCall types::lookupTypeForExtension(path::extension(Filename).substr(1)); 98ea9773acSSam McCall if (Certain) 99ea9773acSSam McCall *Certain = Lang != types::TY_CHeader && Lang != types::TY_INVALID; 100ea9773acSSam McCall return Lang; 101ea9773acSSam McCall } 102ea9773acSSam McCall 103ea9773acSSam McCall // Return Lang as one of the canonical supported types. 104ea9773acSSam McCall // e.g. c-header --> c; fortran --> TY_INVALID 105ea9773acSSam McCall static types::ID foldType(types::ID Lang) { 106ea9773acSSam McCall switch (Lang) { 107ea9773acSSam McCall case types::TY_C: 108ea9773acSSam McCall case types::TY_CHeader: 109ea9773acSSam McCall return types::TY_C; 110ea9773acSSam McCall case types::TY_ObjC: 111ea9773acSSam McCall case types::TY_ObjCHeader: 112ea9773acSSam McCall return types::TY_ObjC; 113ea9773acSSam McCall case types::TY_CXX: 114ea9773acSSam McCall case types::TY_CXXHeader: 115ea9773acSSam McCall return types::TY_CXX; 116ea9773acSSam McCall case types::TY_ObjCXX: 117ea9773acSSam McCall case types::TY_ObjCXXHeader: 118ea9773acSSam McCall return types::TY_ObjCXX; 1196ed88afdSADRA case types::TY_CUDA: 1206ed88afdSADRA case types::TY_CUDA_DEVICE: 1212a1418f2SChristopher Tetreault return types::TY_CUDA; 122ea9773acSSam McCall default: 123ea9773acSSam McCall return types::TY_INVALID; 124ea9773acSSam McCall } 125ea9773acSSam McCall } 126ea9773acSSam McCall 127ea9773acSSam McCall // A CompileCommand that can be applied to another file. 128ea9773acSSam McCall struct TransferableCommand { 129ea9773acSSam McCall // Flags that should not apply to all files are stripped from CommandLine. 130ea9773acSSam McCall CompileCommand Cmd; 1315167e2d1SIlya Biryukov // Language detected from -x or the filename. Never TY_INVALID. 1325167e2d1SIlya Biryukov Optional<types::ID> Type; 133ea9773acSSam McCall // Standard specified by -std. 134ea9773acSSam McCall LangStandard::Kind Std = LangStandard::lang_unspecified; 135e05bf606SHamza Sood // Whether the command line is for the cl-compatible driver. 136e05bf606SHamza Sood bool ClangCLMode; 137ea9773acSSam McCall 138ea9773acSSam McCall TransferableCommand(CompileCommand C) 139*ce90b60bSKadir Cetinkaya : Cmd(std::move(C)), Type(guessType(Cmd.Filename)) { 140e05bf606SHamza Sood std::vector<std::string> OldArgs = std::move(Cmd.CommandLine); 141e05bf606SHamza Sood Cmd.CommandLine.clear(); 142e05bf606SHamza Sood 143e05bf606SHamza Sood // Wrap the old arguments in an InputArgList. 144e05bf606SHamza Sood llvm::opt::InputArgList ArgList; 145e05bf606SHamza Sood { 146e05bf606SHamza Sood SmallVector<const char *, 16> TmpArgv; 147e05bf606SHamza Sood for (const std::string &S : OldArgs) 148e05bf606SHamza Sood TmpArgv.push_back(S.c_str()); 149*ce90b60bSKadir Cetinkaya ClangCLMode = !TmpArgv.empty() && 150*ce90b60bSKadir Cetinkaya driver::IsClangCL(driver::getDriverMode( 151*ce90b60bSKadir Cetinkaya TmpArgv.front(), llvm::makeArrayRef(TmpArgv).slice(1))); 152e05bf606SHamza Sood ArgList = {TmpArgv.begin(), TmpArgv.end()}; 153e05bf606SHamza Sood } 154e05bf606SHamza Sood 155ea9773acSSam McCall // Parse the old args in order to strip out and record unwanted flags. 156e05bf606SHamza Sood // We parse each argument individually so that we can retain the exact 157e05bf606SHamza Sood // spelling of each argument; re-rendering is lossy for aliased flags. 158e05bf606SHamza Sood // E.g. in CL mode, /W4 maps to -Wall. 15943392759SIlya Biryukov auto &OptTable = clang::driver::getDriverOptTable(); 16060ca31a7SSerge Guelton if (!OldArgs.empty()) 161e05bf606SHamza Sood Cmd.CommandLine.emplace_back(OldArgs.front()); 162e05bf606SHamza Sood for (unsigned Pos = 1; Pos < OldArgs.size();) { 163e05bf606SHamza Sood using namespace driver::options; 164e05bf606SHamza Sood 165e05bf606SHamza Sood const unsigned OldPos = Pos; 16643392759SIlya Biryukov std::unique_ptr<llvm::opt::Arg> Arg(OptTable.ParseOneArg( 167e05bf606SHamza Sood ArgList, Pos, 168e05bf606SHamza Sood /* Include */ ClangCLMode ? CoreOption | CLOption : 0, 169e05bf606SHamza Sood /* Exclude */ ClangCLMode ? 0 : CLOption)); 170e05bf606SHamza Sood 171e05bf606SHamza Sood if (!Arg) 172e05bf606SHamza Sood continue; 173e05bf606SHamza Sood 174e05bf606SHamza Sood const llvm::opt::Option &Opt = Arg->getOption(); 175e05bf606SHamza Sood 176ea9773acSSam McCall // Strip input and output files. 177e05bf606SHamza Sood if (Opt.matches(OPT_INPUT) || Opt.matches(OPT_o) || 178e05bf606SHamza Sood (ClangCLMode && (Opt.matches(OPT__SLASH_Fa) || 179e05bf606SHamza Sood Opt.matches(OPT__SLASH_Fe) || 180e05bf606SHamza Sood Opt.matches(OPT__SLASH_Fi) || 181e05bf606SHamza Sood Opt.matches(OPT__SLASH_Fo)))) 182ea9773acSSam McCall continue; 183e05bf606SHamza Sood 184e030ce3eSJanusz Nykiel // ...including when the inputs are passed after --. 185e030ce3eSJanusz Nykiel if (Opt.matches(OPT__DASH_DASH)) 186e030ce3eSJanusz Nykiel break; 187e030ce3eSJanusz Nykiel 188ea9773acSSam McCall // Strip -x, but record the overridden language. 189e05bf606SHamza Sood if (const auto GivenType = tryParseTypeArg(*Arg)) { 190e05bf606SHamza Sood Type = *GivenType; 191ea9773acSSam McCall continue; 192ea9773acSSam McCall } 193e05bf606SHamza Sood 194e05bf606SHamza Sood // Strip -std, but record the value. 195e05bf606SHamza Sood if (const auto GivenStd = tryParseStdArg(*Arg)) { 196e05bf606SHamza Sood if (*GivenStd != LangStandard::lang_unspecified) 197e05bf606SHamza Sood Std = *GivenStd; 198ea9773acSSam McCall continue; 199ea9773acSSam McCall } 200e05bf606SHamza Sood 201e05bf606SHamza Sood Cmd.CommandLine.insert(Cmd.CommandLine.end(), 202fd1dc75bSHamza Sood OldArgs.data() + OldPos, OldArgs.data() + Pos); 203ea9773acSSam McCall } 204ea9773acSSam McCall 205c2377eaeSKadir Cetinkaya // Make use of -std iff -x was missing. 206c2377eaeSKadir Cetinkaya if (Type == types::TY_INVALID && Std != LangStandard::lang_unspecified) 207ea9773acSSam McCall Type = toType(LangStandard::getLangStandardForKind(Std).getLanguage()); 2085167e2d1SIlya Biryukov Type = foldType(*Type); 2095167e2d1SIlya Biryukov // The contract is to store None instead of TY_INVALID. 2105167e2d1SIlya Biryukov if (Type == types::TY_INVALID) 2115167e2d1SIlya Biryukov Type = llvm::None; 212ea9773acSSam McCall } 213ea9773acSSam McCall 214ea9773acSSam McCall // Produce a CompileCommand for \p filename, based on this one. 215588db1ccSSam McCall // (This consumes the TransferableCommand just to avoid copying Cmd). 216588db1ccSSam McCall CompileCommand transferTo(StringRef Filename) && { 217588db1ccSSam McCall CompileCommand Result = std::move(Cmd); 218588db1ccSSam McCall Result.Heuristic = "inferred from " + Result.Filename; 219adcd0268SBenjamin Kramer Result.Filename = std::string(Filename); 220ea9773acSSam McCall bool TypeCertain; 221ea9773acSSam McCall auto TargetType = guessType(Filename, &TypeCertain); 222ea9773acSSam McCall // If the filename doesn't determine the language (.h), transfer with -x. 22387ad30beSSam McCall if ((!TargetType || !TypeCertain) && Type) { 22487ad30beSSam McCall // Use *Type, or its header variant if the file is a header. 22587ad30beSSam McCall // Treat no/invalid extension as header (e.g. C++ standard library). 22687ad30beSSam McCall TargetType = 22787ad30beSSam McCall (!TargetType || types::onlyPrecompileType(TargetType)) // header? 2285167e2d1SIlya Biryukov ? types::lookupHeaderTypeForSourceType(*Type) 2295167e2d1SIlya Biryukov : *Type; 230e05bf606SHamza Sood if (ClangCLMode) { 231e05bf606SHamza Sood const StringRef Flag = toCLFlag(TargetType); 232e05bf606SHamza Sood if (!Flag.empty()) 233adcd0268SBenjamin Kramer Result.CommandLine.push_back(std::string(Flag)); 234e05bf606SHamza Sood } else { 235ea9773acSSam McCall Result.CommandLine.push_back("-x"); 236ea9773acSSam McCall Result.CommandLine.push_back(types::getTypeName(TargetType)); 237ea9773acSSam McCall } 238e05bf606SHamza Sood } 239ea9773acSSam McCall // --std flag may only be transferred if the language is the same. 240ea9773acSSam McCall // We may consider "translating" these, e.g. c++11 -> c11. 241ea9773acSSam McCall if (Std != LangStandard::lang_unspecified && foldType(TargetType) == Type) { 242e05bf606SHamza Sood Result.CommandLine.emplace_back(( 243e05bf606SHamza Sood llvm::Twine(ClangCLMode ? "/std:" : "-std=") + 244e05bf606SHamza Sood LangStandard::getLangStandardForKind(Std).getName()).str()); 245ea9773acSSam McCall } 246e030ce3eSJanusz Nykiel if (Filename.startswith("-") || (ClangCLMode && Filename.startswith("/"))) 247e030ce3eSJanusz Nykiel Result.CommandLine.push_back("--"); 248adcd0268SBenjamin Kramer Result.CommandLine.push_back(std::string(Filename)); 249ea9773acSSam McCall return Result; 250ea9773acSSam McCall } 251ea9773acSSam McCall 252ea9773acSSam McCall private: 253ea9773acSSam McCall // Map the language from the --std flag to that of the -x flag. 25409d890d7SRainer Orth static types::ID toType(Language Lang) { 255ea9773acSSam McCall switch (Lang) { 25609d890d7SRainer Orth case Language::C: 257ea9773acSSam McCall return types::TY_C; 25809d890d7SRainer Orth case Language::CXX: 259ea9773acSSam McCall return types::TY_CXX; 26009d890d7SRainer Orth case Language::ObjC: 261ea9773acSSam McCall return types::TY_ObjC; 26209d890d7SRainer Orth case Language::ObjCXX: 263ea9773acSSam McCall return types::TY_ObjCXX; 264ea9773acSSam McCall default: 265ea9773acSSam McCall return types::TY_INVALID; 266ea9773acSSam McCall } 267ea9773acSSam McCall } 268e05bf606SHamza Sood 269e05bf606SHamza Sood // Convert a file type to the matching CL-style type flag. 270e05bf606SHamza Sood static StringRef toCLFlag(types::ID Type) { 271e05bf606SHamza Sood switch (Type) { 272e05bf606SHamza Sood case types::TY_C: 273e05bf606SHamza Sood case types::TY_CHeader: 274e05bf606SHamza Sood return "/TC"; 275e05bf606SHamza Sood case types::TY_CXX: 276e05bf606SHamza Sood case types::TY_CXXHeader: 277e05bf606SHamza Sood return "/TP"; 278e05bf606SHamza Sood default: 279e05bf606SHamza Sood return StringRef(); 280e05bf606SHamza Sood } 281e05bf606SHamza Sood } 282e05bf606SHamza Sood 283e05bf606SHamza Sood // Try to interpret the argument as a type specifier, e.g. '-x'. 284e05bf606SHamza Sood Optional<types::ID> tryParseTypeArg(const llvm::opt::Arg &Arg) { 285e05bf606SHamza Sood const llvm::opt::Option &Opt = Arg.getOption(); 286e05bf606SHamza Sood using namespace driver::options; 287e05bf606SHamza Sood if (ClangCLMode) { 288e05bf606SHamza Sood if (Opt.matches(OPT__SLASH_TC) || Opt.matches(OPT__SLASH_Tc)) 289e05bf606SHamza Sood return types::TY_C; 290e05bf606SHamza Sood if (Opt.matches(OPT__SLASH_TP) || Opt.matches(OPT__SLASH_Tp)) 291e05bf606SHamza Sood return types::TY_CXX; 292e05bf606SHamza Sood } else { 293e05bf606SHamza Sood if (Opt.matches(driver::options::OPT_x)) 294e05bf606SHamza Sood return types::lookupTypeForTypeSpecifier(Arg.getValue()); 295e05bf606SHamza Sood } 296e05bf606SHamza Sood return None; 297e05bf606SHamza Sood } 298e05bf606SHamza Sood 299e05bf606SHamza Sood // Try to interpret the argument as '-std='. 300e05bf606SHamza Sood Optional<LangStandard::Kind> tryParseStdArg(const llvm::opt::Arg &Arg) { 301e05bf606SHamza Sood using namespace driver::options; 30209d890d7SRainer Orth if (Arg.getOption().matches(ClangCLMode ? OPT__SLASH_std : OPT_std_EQ)) 30309d890d7SRainer Orth return LangStandard::getLangKind(Arg.getValue()); 304e05bf606SHamza Sood return None; 305e05bf606SHamza Sood } 306ea9773acSSam McCall }; 307ea9773acSSam McCall 3085167e2d1SIlya Biryukov // Given a filename, FileIndex picks the best matching file from the underlying 3095167e2d1SIlya Biryukov // DB. This is the proxy file whose CompileCommand will be reused. The 3105167e2d1SIlya Biryukov // heuristics incorporate file name, extension, and directory structure. 3115167e2d1SIlya Biryukov // Strategy: 312ea9773acSSam McCall // - Build indexes of each of the substrings we want to look up by. 313ea9773acSSam McCall // These indexes are just sorted lists of the substrings. 314ea9773acSSam McCall // - Each criterion corresponds to a range lookup into the index, so we only 315ea9773acSSam McCall // need O(log N) string comparisons to determine scores. 3165167e2d1SIlya Biryukov // 3175167e2d1SIlya Biryukov // Apart from path proximity signals, also takes file extensions into account 3185167e2d1SIlya Biryukov // when scoring the candidates. 3195167e2d1SIlya Biryukov class FileIndex { 320ea9773acSSam McCall public: 3215167e2d1SIlya Biryukov FileIndex(std::vector<std::string> Files) 3225167e2d1SIlya Biryukov : OriginalPaths(std::move(Files)), Strings(Arena) { 323ea9773acSSam McCall // Sort commands by filename for determinism (index is a tiebreaker later). 32455fab260SFangrui Song llvm::sort(OriginalPaths); 3255167e2d1SIlya Biryukov Paths.reserve(OriginalPaths.size()); 3265167e2d1SIlya Biryukov Types.reserve(OriginalPaths.size()); 3275167e2d1SIlya Biryukov Stems.reserve(OriginalPaths.size()); 3285167e2d1SIlya Biryukov for (size_t I = 0; I < OriginalPaths.size(); ++I) { 3295167e2d1SIlya Biryukov StringRef Path = Strings.save(StringRef(OriginalPaths[I]).lower()); 3305167e2d1SIlya Biryukov 3315167e2d1SIlya Biryukov Paths.emplace_back(Path, I); 3325167e2d1SIlya Biryukov Types.push_back(foldType(guessType(Path))); 333ea9773acSSam McCall Stems.emplace_back(sys::path::stem(Path), I); 334ea9773acSSam McCall auto Dir = ++sys::path::rbegin(Path), DirEnd = sys::path::rend(Path); 335ea9773acSSam McCall for (int J = 0; J < DirectorySegmentsIndexed && Dir != DirEnd; ++J, ++Dir) 336ea9773acSSam McCall if (Dir->size() > ShortDirectorySegment) // not trivial ones 337ea9773acSSam McCall Components.emplace_back(*Dir, I); 338ea9773acSSam McCall } 33955fab260SFangrui Song llvm::sort(Paths); 34055fab260SFangrui Song llvm::sort(Stems); 34155fab260SFangrui Song llvm::sort(Components); 342ea9773acSSam McCall } 343ea9773acSSam McCall 3445167e2d1SIlya Biryukov bool empty() const { return Paths.empty(); } 345ea9773acSSam McCall 3465167e2d1SIlya Biryukov // Returns the path for the file that best fits OriginalFilename. 3475167e2d1SIlya Biryukov // Candidates with extensions matching PreferLanguage will be chosen over 3485167e2d1SIlya Biryukov // others (unless it's TY_INVALID, or all candidates are bad). 3495167e2d1SIlya Biryukov StringRef chooseProxy(StringRef OriginalFilename, 350ea9773acSSam McCall types::ID PreferLanguage) const { 351ea9773acSSam McCall assert(!empty() && "need at least one candidate!"); 352ea9773acSSam McCall std::string Filename = OriginalFilename.lower(); 353ea9773acSSam McCall auto Candidates = scoreCandidates(Filename); 354ea9773acSSam McCall std::pair<size_t, int> Best = 355ea9773acSSam McCall pickWinner(Candidates, Filename, PreferLanguage); 356ea9773acSSam McCall 3575167e2d1SIlya Biryukov DEBUG_WITH_TYPE( 3585167e2d1SIlya Biryukov "interpolate", 3595167e2d1SIlya Biryukov llvm::dbgs() << "interpolate: chose " << OriginalPaths[Best.first] 3605167e2d1SIlya Biryukov << " as proxy for " << OriginalFilename << " preferring " 361ea9773acSSam McCall << (PreferLanguage == types::TY_INVALID 362ea9773acSSam McCall ? "none" 363ea9773acSSam McCall : types::getTypeName(PreferLanguage)) 364ea9773acSSam McCall << " score=" << Best.second << "\n"); 3655167e2d1SIlya Biryukov return OriginalPaths[Best.first]; 366ea9773acSSam McCall } 367ea9773acSSam McCall 368ea9773acSSam McCall private: 369ea9773acSSam McCall using SubstringAndIndex = std::pair<StringRef, size_t>; 370ea9773acSSam McCall // Directory matching parameters: we look at the last two segments of the 371ea9773acSSam McCall // parent directory (usually the semantically significant ones in practice). 372ea9773acSSam McCall // We search only the last four of each candidate (for efficiency). 373ea9773acSSam McCall constexpr static int DirectorySegmentsIndexed = 4; 374ea9773acSSam McCall constexpr static int DirectorySegmentsQueried = 2; 375ea9773acSSam McCall constexpr static int ShortDirectorySegment = 1; // Only look at longer names. 376ea9773acSSam McCall 377ea9773acSSam McCall // Award points to candidate entries that should be considered for the file. 378ea9773acSSam McCall // Returned keys are indexes into paths, and the values are (nonzero) scores. 379ea9773acSSam McCall DenseMap<size_t, int> scoreCandidates(StringRef Filename) const { 380ea9773acSSam McCall // Decompose Filename into the parts we care about. 381ea9773acSSam McCall // /some/path/complicated/project/Interesting.h 382ea9773acSSam McCall // [-prefix--][---dir---] [-dir-] [--stem---] 383ea9773acSSam McCall StringRef Stem = sys::path::stem(Filename); 384ea9773acSSam McCall llvm::SmallVector<StringRef, DirectorySegmentsQueried> Dirs; 385ea9773acSSam McCall llvm::StringRef Prefix; 386ea9773acSSam McCall auto Dir = ++sys::path::rbegin(Filename), 387ea9773acSSam McCall DirEnd = sys::path::rend(Filename); 388ea9773acSSam McCall for (int I = 0; I < DirectorySegmentsQueried && Dir != DirEnd; ++I, ++Dir) { 389ea9773acSSam McCall if (Dir->size() > ShortDirectorySegment) 390ea9773acSSam McCall Dirs.push_back(*Dir); 391ea9773acSSam McCall Prefix = Filename.substr(0, Dir - DirEnd); 392ea9773acSSam McCall } 393ea9773acSSam McCall 394ea9773acSSam McCall // Now award points based on lookups into our various indexes. 395ea9773acSSam McCall DenseMap<size_t, int> Candidates; // Index -> score. 396ea9773acSSam McCall auto Award = [&](int Points, ArrayRef<SubstringAndIndex> Range) { 397ea9773acSSam McCall for (const auto &Entry : Range) 398ea9773acSSam McCall Candidates[Entry.second] += Points; 399ea9773acSSam McCall }; 400ea9773acSSam McCall // Award one point if the file's basename is a prefix of the candidate, 401ea9773acSSam McCall // and another if it's an exact match (so exact matches get two points). 402ea9773acSSam McCall Award(1, indexLookup</*Prefix=*/true>(Stem, Stems)); 403ea9773acSSam McCall Award(1, indexLookup</*Prefix=*/false>(Stem, Stems)); 404ea9773acSSam McCall // For each of the last few directories in the Filename, award a point 405ea9773acSSam McCall // if it's present in the candidate. 406ea9773acSSam McCall for (StringRef Dir : Dirs) 407ea9773acSSam McCall Award(1, indexLookup</*Prefix=*/false>(Dir, Components)); 408ea9773acSSam McCall // Award one more point if the whole rest of the path matches. 409ea9773acSSam McCall if (sys::path::root_directory(Prefix) != Prefix) 410ea9773acSSam McCall Award(1, indexLookup</*Prefix=*/true>(Prefix, Paths)); 411ea9773acSSam McCall return Candidates; 412ea9773acSSam McCall } 413ea9773acSSam McCall 414ea9773acSSam McCall // Pick a single winner from the set of scored candidates. 415ea9773acSSam McCall // Returns (index, score). 416ea9773acSSam McCall std::pair<size_t, int> pickWinner(const DenseMap<size_t, int> &Candidates, 417ea9773acSSam McCall StringRef Filename, 418ea9773acSSam McCall types::ID PreferredLanguage) const { 419ea9773acSSam McCall struct ScoredCandidate { 420ea9773acSSam McCall size_t Index; 421ea9773acSSam McCall bool Preferred; 422ea9773acSSam McCall int Points; 423ea9773acSSam McCall size_t PrefixLength; 424ea9773acSSam McCall }; 425ea9773acSSam McCall // Choose the best candidate by (preferred, points, prefix length, alpha). 426ea9773acSSam McCall ScoredCandidate Best = {size_t(-1), false, 0, 0}; 427ea9773acSSam McCall for (const auto &Candidate : Candidates) { 428ea9773acSSam McCall ScoredCandidate S; 429ea9773acSSam McCall S.Index = Candidate.first; 430ea9773acSSam McCall S.Preferred = PreferredLanguage == types::TY_INVALID || 4315167e2d1SIlya Biryukov PreferredLanguage == Types[S.Index]; 432ea9773acSSam McCall S.Points = Candidate.second; 433ea9773acSSam McCall if (!S.Preferred && Best.Preferred) 434ea9773acSSam McCall continue; 435ea9773acSSam McCall if (S.Preferred == Best.Preferred) { 436ea9773acSSam McCall if (S.Points < Best.Points) 437ea9773acSSam McCall continue; 438ea9773acSSam McCall if (S.Points == Best.Points) { 439ea9773acSSam McCall S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first); 440ea9773acSSam McCall if (S.PrefixLength < Best.PrefixLength) 441ea9773acSSam McCall continue; 442ea9773acSSam McCall // hidden heuristics should at least be deterministic! 443ea9773acSSam McCall if (S.PrefixLength == Best.PrefixLength) 444ea9773acSSam McCall if (S.Index > Best.Index) 445ea9773acSSam McCall continue; 446ea9773acSSam McCall } 447ea9773acSSam McCall } 448ea9773acSSam McCall // PrefixLength was only set above if actually needed for a tiebreak. 449ea9773acSSam McCall // But it definitely needs to be set to break ties in the future. 450ea9773acSSam McCall S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first); 451ea9773acSSam McCall Best = S; 452ea9773acSSam McCall } 453ea9773acSSam McCall // Edge case: no candidate got any points. 454ea9773acSSam McCall // We ignore PreferredLanguage at this point (not ideal). 455ea9773acSSam McCall if (Best.Index == size_t(-1)) 456ea9773acSSam McCall return {longestMatch(Filename, Paths).second, 0}; 457ea9773acSSam McCall return {Best.Index, Best.Points}; 458ea9773acSSam McCall } 459ea9773acSSam McCall 460ea9773acSSam McCall // Returns the range within a sorted index that compares equal to Key. 461ea9773acSSam McCall // If Prefix is true, it's instead the range starting with Key. 462ea9773acSSam McCall template <bool Prefix> 463ea9773acSSam McCall ArrayRef<SubstringAndIndex> 4645167e2d1SIlya Biryukov indexLookup(StringRef Key, ArrayRef<SubstringAndIndex> Idx) const { 465ea9773acSSam McCall // Use pointers as iteratiors to ease conversion of result to ArrayRef. 46644f2f4ecSSam McCall auto Range = std::equal_range(Idx.data(), Idx.data() + Idx.size(), Key, 46744f2f4ecSSam McCall Less<Prefix>()); 468ea9773acSSam McCall return {Range.first, Range.second}; 469ea9773acSSam McCall } 470ea9773acSSam McCall 471ea9773acSSam McCall // Performs a point lookup into a nonempty index, returning a longest match. 4725167e2d1SIlya Biryukov SubstringAndIndex longestMatch(StringRef Key, 4735167e2d1SIlya Biryukov ArrayRef<SubstringAndIndex> Idx) const { 474ea9773acSSam McCall assert(!Idx.empty()); 475ea9773acSSam McCall // Longest substring match will be adjacent to a direct lookup. 4767264a474SFangrui Song auto It = llvm::lower_bound(Idx, SubstringAndIndex{Key, 0}); 477ea9773acSSam McCall if (It == Idx.begin()) 478ea9773acSSam McCall return *It; 479ea9773acSSam McCall if (It == Idx.end()) 480ea9773acSSam McCall return *--It; 481ea9773acSSam McCall // Have to choose between It and It-1 482ea9773acSSam McCall size_t Prefix = matchingPrefix(Key, It->first); 483ea9773acSSam McCall size_t PrevPrefix = matchingPrefix(Key, (It - 1)->first); 484ea9773acSSam McCall return Prefix > PrevPrefix ? *It : *--It; 485ea9773acSSam McCall } 486ea9773acSSam McCall 4875167e2d1SIlya Biryukov // Original paths, everything else is in lowercase. 4885167e2d1SIlya Biryukov std::vector<std::string> OriginalPaths; 489ea9773acSSam McCall BumpPtrAllocator Arena; 490ea9773acSSam McCall StringSaver Strings; 491ea9773acSSam McCall // Indexes of candidates by certain substrings. 492ea9773acSSam McCall // String is lowercase and sorted, index points into OriginalPaths. 493ea9773acSSam McCall std::vector<SubstringAndIndex> Paths; // Full path. 4945167e2d1SIlya Biryukov // Lang types obtained by guessing on the corresponding path. I-th element is 4955167e2d1SIlya Biryukov // a type for the I-th path. 4965167e2d1SIlya Biryukov std::vector<types::ID> Types; 497ea9773acSSam McCall std::vector<SubstringAndIndex> Stems; // Basename, without extension. 498ea9773acSSam McCall std::vector<SubstringAndIndex> Components; // Last path components. 499ea9773acSSam McCall }; 500ea9773acSSam McCall 501ea9773acSSam McCall // The actual CompilationDatabase wrapper delegates to its inner database. 5025167e2d1SIlya Biryukov // If no match, looks up a proxy file in FileIndex and transfers its 5035167e2d1SIlya Biryukov // command to the requested file. 504ea9773acSSam McCall class InterpolatingCompilationDatabase : public CompilationDatabase { 505ea9773acSSam McCall public: 506ea9773acSSam McCall InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner) 5075167e2d1SIlya Biryukov : Inner(std::move(Inner)), Index(this->Inner->getAllFiles()) {} 508ea9773acSSam McCall 509ea9773acSSam McCall std::vector<CompileCommand> 510ea9773acSSam McCall getCompileCommands(StringRef Filename) const override { 511ea9773acSSam McCall auto Known = Inner->getCompileCommands(Filename); 512ea9773acSSam McCall if (Index.empty() || !Known.empty()) 513ea9773acSSam McCall return Known; 514ea9773acSSam McCall bool TypeCertain; 515ea9773acSSam McCall auto Lang = guessType(Filename, &TypeCertain); 516ea9773acSSam McCall if (!TypeCertain) 517ea9773acSSam McCall Lang = types::TY_INVALID; 5185167e2d1SIlya Biryukov auto ProxyCommands = 5195167e2d1SIlya Biryukov Inner->getCompileCommands(Index.chooseProxy(Filename, foldType(Lang))); 5205167e2d1SIlya Biryukov if (ProxyCommands.empty()) 5215167e2d1SIlya Biryukov return {}; 522588db1ccSSam McCall return {transferCompileCommand(std::move(ProxyCommands.front()), Filename)}; 523ea9773acSSam McCall } 524ea9773acSSam McCall 525ea9773acSSam McCall std::vector<std::string> getAllFiles() const override { 526ea9773acSSam McCall return Inner->getAllFiles(); 527ea9773acSSam McCall } 528ea9773acSSam McCall 529ea9773acSSam McCall std::vector<CompileCommand> getAllCompileCommands() const override { 530ea9773acSSam McCall return Inner->getAllCompileCommands(); 531ea9773acSSam McCall } 532ea9773acSSam McCall 533ea9773acSSam McCall private: 534ea9773acSSam McCall std::unique_ptr<CompilationDatabase> Inner; 5355167e2d1SIlya Biryukov FileIndex Index; 536ea9773acSSam McCall }; 537ea9773acSSam McCall 538ea9773acSSam McCall } // namespace 539ea9773acSSam McCall 540ea9773acSSam McCall std::unique_ptr<CompilationDatabase> 541ea9773acSSam McCall inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner) { 5422b3d49b6SJonas Devlieghere return std::make_unique<InterpolatingCompilationDatabase>(std::move(Inner)); 543ea9773acSSam McCall } 544ea9773acSSam McCall 545588db1ccSSam McCall tooling::CompileCommand transferCompileCommand(CompileCommand Cmd, 546588db1ccSSam McCall StringRef Filename) { 547588db1ccSSam McCall return TransferableCommand(std::move(Cmd)).transferTo(Filename); 548588db1ccSSam McCall } 549588db1ccSSam McCall 550ea9773acSSam McCall } // namespace tooling 551ea9773acSSam McCall } // namespace clang 552