xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===- InterpolatingCompilationDatabase.cpp ---------------------*- C++ -*-===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // InterpolatingCompilationDatabase wraps another CompilationDatabase and
107330f729Sjoerg // attempts to heuristically determine appropriate compile commands for files
117330f729Sjoerg // that are not included, such as headers or newly created files.
127330f729Sjoerg //
137330f729Sjoerg // Motivating cases include:
147330f729Sjoerg //   Header files that live next to their implementation files. These typically
157330f729Sjoerg // share a base filename. (libclang/CXString.h, libclang/CXString.cpp).
167330f729Sjoerg //   Some projects separate headers from includes. Filenames still typically
177330f729Sjoerg // match, maybe other path segments too. (include/llvm/IR/Use.h, lib/IR/Use.cc).
187330f729Sjoerg //   Matches are sometimes only approximate (Sema.h, SemaDecl.cpp). This goes
197330f729Sjoerg // for directories too (Support/Unix/Process.inc, lib/Support/Process.cpp).
207330f729Sjoerg //   Even if we can't find a "right" compile command, even a random one from
217330f729Sjoerg // the project will tend to get important flags like -I and -x right.
227330f729Sjoerg //
237330f729Sjoerg // We "borrow" the compile command for the closest available file:
247330f729Sjoerg //   - points are awarded if the filename matches (ignoring extension)
257330f729Sjoerg //   - points are awarded if the directory structure matches
267330f729Sjoerg //   - ties are broken by length of path prefix match
277330f729Sjoerg //
287330f729Sjoerg // The compile command is adjusted, replacing the filename and removing output
297330f729Sjoerg // file arguments. The -x and -std flags may be affected too.
307330f729Sjoerg //
317330f729Sjoerg // Source language is a tricky issue: is it OK to use a .c file's command
327330f729Sjoerg // for building a .cc file? What language is a .h file in?
337330f729Sjoerg //   - We only consider compile commands for c-family languages as candidates.
347330f729Sjoerg //   - For files whose language is implied by the filename (e.g. .m, .hpp)
357330f729Sjoerg //     we prefer candidates from the same language.
367330f729Sjoerg //     If we must cross languages, we drop any -x and -std flags.
377330f729Sjoerg //   - For .h files, candidates from any c-family language are acceptable.
387330f729Sjoerg //     We use the candidate's language, inserting  e.g. -x c++-header.
397330f729Sjoerg //
407330f729Sjoerg // This class is only useful when wrapping databases that can enumerate all
417330f729Sjoerg // their compile commands. If getAllFilenames() is empty, no inference occurs.
427330f729Sjoerg //
437330f729Sjoerg //===----------------------------------------------------------------------===//
447330f729Sjoerg 
457330f729Sjoerg #include "clang/Basic/LangStandard.h"
467330f729Sjoerg #include "clang/Driver/Options.h"
477330f729Sjoerg #include "clang/Driver/Types.h"
487330f729Sjoerg #include "clang/Tooling/CompilationDatabase.h"
497330f729Sjoerg #include "llvm/ADT/DenseMap.h"
507330f729Sjoerg #include "llvm/ADT/Optional.h"
517330f729Sjoerg #include "llvm/ADT/StringExtras.h"
527330f729Sjoerg #include "llvm/ADT/StringSwitch.h"
537330f729Sjoerg #include "llvm/Option/ArgList.h"
547330f729Sjoerg #include "llvm/Option/OptTable.h"
557330f729Sjoerg #include "llvm/Support/Debug.h"
567330f729Sjoerg #include "llvm/Support/Path.h"
577330f729Sjoerg #include "llvm/Support/StringSaver.h"
587330f729Sjoerg #include "llvm/Support/raw_ostream.h"
597330f729Sjoerg #include <memory>
607330f729Sjoerg 
617330f729Sjoerg namespace clang {
627330f729Sjoerg namespace tooling {
637330f729Sjoerg namespace {
647330f729Sjoerg using namespace llvm;
657330f729Sjoerg namespace types = clang::driver::types;
667330f729Sjoerg namespace path = llvm::sys::path;
677330f729Sjoerg 
687330f729Sjoerg // The length of the prefix these two strings have in common.
matchingPrefix(StringRef L,StringRef R)697330f729Sjoerg size_t matchingPrefix(StringRef L, StringRef R) {
707330f729Sjoerg   size_t Limit = std::min(L.size(), R.size());
717330f729Sjoerg   for (size_t I = 0; I < Limit; ++I)
727330f729Sjoerg     if (L[I] != R[I])
737330f729Sjoerg       return I;
747330f729Sjoerg   return Limit;
757330f729Sjoerg }
767330f729Sjoerg 
777330f729Sjoerg // A comparator for searching SubstringWithIndexes with std::equal_range etc.
787330f729Sjoerg // Optionaly prefix semantics: compares equal if the key is a prefix.
797330f729Sjoerg template <bool Prefix> struct Less {
operator ()clang::tooling::__anon983895e40111::Less807330f729Sjoerg   bool operator()(StringRef Key, std::pair<StringRef, size_t> Value) const {
817330f729Sjoerg     StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
827330f729Sjoerg     return Key < V;
837330f729Sjoerg   }
operator ()clang::tooling::__anon983895e40111::Less847330f729Sjoerg   bool operator()(std::pair<StringRef, size_t> Value, StringRef Key) const {
857330f729Sjoerg     StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
867330f729Sjoerg     return V < Key;
877330f729Sjoerg   }
887330f729Sjoerg };
897330f729Sjoerg 
907330f729Sjoerg // Infer type from filename. If we might have gotten it wrong, set *Certain.
917330f729Sjoerg // *.h will be inferred as a C header, but not certain.
guessType(StringRef Filename,bool * Certain=nullptr)927330f729Sjoerg types::ID guessType(StringRef Filename, bool *Certain = nullptr) {
937330f729Sjoerg   // path::extension is ".cpp", lookupTypeForExtension wants "cpp".
947330f729Sjoerg   auto Lang =
957330f729Sjoerg       types::lookupTypeForExtension(path::extension(Filename).substr(1));
967330f729Sjoerg   if (Certain)
977330f729Sjoerg     *Certain = Lang != types::TY_CHeader && Lang != types::TY_INVALID;
987330f729Sjoerg   return Lang;
997330f729Sjoerg }
1007330f729Sjoerg 
1017330f729Sjoerg // Return Lang as one of the canonical supported types.
1027330f729Sjoerg // e.g. c-header --> c; fortran --> TY_INVALID
foldType(types::ID Lang)1037330f729Sjoerg static types::ID foldType(types::ID Lang) {
1047330f729Sjoerg   switch (Lang) {
1057330f729Sjoerg   case types::TY_C:
1067330f729Sjoerg   case types::TY_CHeader:
1077330f729Sjoerg     return types::TY_C;
1087330f729Sjoerg   case types::TY_ObjC:
1097330f729Sjoerg   case types::TY_ObjCHeader:
1107330f729Sjoerg     return types::TY_ObjC;
1117330f729Sjoerg   case types::TY_CXX:
1127330f729Sjoerg   case types::TY_CXXHeader:
1137330f729Sjoerg     return types::TY_CXX;
1147330f729Sjoerg   case types::TY_ObjCXX:
1157330f729Sjoerg   case types::TY_ObjCXXHeader:
1167330f729Sjoerg     return types::TY_ObjCXX;
117*e038c9c4Sjoerg   case types::TY_CUDA:
118*e038c9c4Sjoerg   case types::TY_CUDA_DEVICE:
119*e038c9c4Sjoerg     return types::TY_CUDA;
1207330f729Sjoerg   default:
1217330f729Sjoerg     return types::TY_INVALID;
1227330f729Sjoerg   }
1237330f729Sjoerg }
1247330f729Sjoerg 
1257330f729Sjoerg // A CompileCommand that can be applied to another file.
1267330f729Sjoerg struct TransferableCommand {
1277330f729Sjoerg   // Flags that should not apply to all files are stripped from CommandLine.
1287330f729Sjoerg   CompileCommand Cmd;
1297330f729Sjoerg   // Language detected from -x or the filename. Never TY_INVALID.
1307330f729Sjoerg   Optional<types::ID> Type;
1317330f729Sjoerg   // Standard specified by -std.
1327330f729Sjoerg   LangStandard::Kind Std = LangStandard::lang_unspecified;
1337330f729Sjoerg   // Whether the command line is for the cl-compatible driver.
1347330f729Sjoerg   bool ClangCLMode;
1357330f729Sjoerg 
TransferableCommandclang::tooling::__anon983895e40111::TransferableCommand1367330f729Sjoerg   TransferableCommand(CompileCommand C)
1377330f729Sjoerg       : Cmd(std::move(C)), Type(guessType(Cmd.Filename)),
1387330f729Sjoerg         ClangCLMode(checkIsCLMode(Cmd.CommandLine)) {
1397330f729Sjoerg     std::vector<std::string> OldArgs = std::move(Cmd.CommandLine);
1407330f729Sjoerg     Cmd.CommandLine.clear();
1417330f729Sjoerg 
1427330f729Sjoerg     // Wrap the old arguments in an InputArgList.
1437330f729Sjoerg     llvm::opt::InputArgList ArgList;
1447330f729Sjoerg     {
1457330f729Sjoerg       SmallVector<const char *, 16> TmpArgv;
1467330f729Sjoerg       for (const std::string &S : OldArgs)
1477330f729Sjoerg         TmpArgv.push_back(S.c_str());
1487330f729Sjoerg       ArgList = {TmpArgv.begin(), TmpArgv.end()};
1497330f729Sjoerg     }
1507330f729Sjoerg 
1517330f729Sjoerg     // Parse the old args in order to strip out and record unwanted flags.
1527330f729Sjoerg     // We parse each argument individually so that we can retain the exact
1537330f729Sjoerg     // spelling of each argument; re-rendering is lossy for aliased flags.
1547330f729Sjoerg     // E.g. in CL mode, /W4 maps to -Wall.
1557330f729Sjoerg     auto &OptTable = clang::driver::getDriverOptTable();
1567330f729Sjoerg     if (!OldArgs.empty())
1577330f729Sjoerg       Cmd.CommandLine.emplace_back(OldArgs.front());
1587330f729Sjoerg     for (unsigned Pos = 1; Pos < OldArgs.size();) {
1597330f729Sjoerg       using namespace driver::options;
1607330f729Sjoerg 
1617330f729Sjoerg       const unsigned OldPos = Pos;
1627330f729Sjoerg       std::unique_ptr<llvm::opt::Arg> Arg(OptTable.ParseOneArg(
1637330f729Sjoerg           ArgList, Pos,
1647330f729Sjoerg           /* Include */ ClangCLMode ? CoreOption | CLOption : 0,
1657330f729Sjoerg           /* Exclude */ ClangCLMode ? 0 : CLOption));
1667330f729Sjoerg 
1677330f729Sjoerg       if (!Arg)
1687330f729Sjoerg         continue;
1697330f729Sjoerg 
1707330f729Sjoerg       const llvm::opt::Option &Opt = Arg->getOption();
1717330f729Sjoerg 
1727330f729Sjoerg       // Strip input and output files.
1737330f729Sjoerg       if (Opt.matches(OPT_INPUT) || Opt.matches(OPT_o) ||
1747330f729Sjoerg           (ClangCLMode && (Opt.matches(OPT__SLASH_Fa) ||
1757330f729Sjoerg                            Opt.matches(OPT__SLASH_Fe) ||
1767330f729Sjoerg                            Opt.matches(OPT__SLASH_Fi) ||
1777330f729Sjoerg                            Opt.matches(OPT__SLASH_Fo))))
1787330f729Sjoerg         continue;
1797330f729Sjoerg 
180*e038c9c4Sjoerg       // ...including when the inputs are passed after --.
181*e038c9c4Sjoerg       if (Opt.matches(OPT__DASH_DASH))
182*e038c9c4Sjoerg         break;
183*e038c9c4Sjoerg 
1847330f729Sjoerg       // Strip -x, but record the overridden language.
1857330f729Sjoerg       if (const auto GivenType = tryParseTypeArg(*Arg)) {
1867330f729Sjoerg         Type = *GivenType;
1877330f729Sjoerg         continue;
1887330f729Sjoerg       }
1897330f729Sjoerg 
1907330f729Sjoerg       // Strip -std, but record the value.
1917330f729Sjoerg       if (const auto GivenStd = tryParseStdArg(*Arg)) {
1927330f729Sjoerg         if (*GivenStd != LangStandard::lang_unspecified)
1937330f729Sjoerg           Std = *GivenStd;
1947330f729Sjoerg         continue;
1957330f729Sjoerg       }
1967330f729Sjoerg 
1977330f729Sjoerg       Cmd.CommandLine.insert(Cmd.CommandLine.end(),
1987330f729Sjoerg                              OldArgs.data() + OldPos, OldArgs.data() + Pos);
1997330f729Sjoerg     }
2007330f729Sjoerg 
201*e038c9c4Sjoerg     // Make use of -std iff -x was missing.
202*e038c9c4Sjoerg     if (Type == types::TY_INVALID && Std != LangStandard::lang_unspecified)
2037330f729Sjoerg       Type = toType(LangStandard::getLangStandardForKind(Std).getLanguage());
2047330f729Sjoerg     Type = foldType(*Type);
2057330f729Sjoerg     // The contract is to store None instead of TY_INVALID.
2067330f729Sjoerg     if (Type == types::TY_INVALID)
2077330f729Sjoerg       Type = llvm::None;
2087330f729Sjoerg   }
2097330f729Sjoerg 
2107330f729Sjoerg   // Produce a CompileCommand for \p filename, based on this one.
211*e038c9c4Sjoerg   // (This consumes the TransferableCommand just to avoid copying Cmd).
transferToclang::tooling::__anon983895e40111::TransferableCommand212*e038c9c4Sjoerg   CompileCommand transferTo(StringRef Filename) && {
213*e038c9c4Sjoerg     CompileCommand Result = std::move(Cmd);
214*e038c9c4Sjoerg     Result.Heuristic = "inferred from " + Result.Filename;
215*e038c9c4Sjoerg     Result.Filename = std::string(Filename);
2167330f729Sjoerg     bool TypeCertain;
2177330f729Sjoerg     auto TargetType = guessType(Filename, &TypeCertain);
2187330f729Sjoerg     // If the filename doesn't determine the language (.h), transfer with -x.
2197330f729Sjoerg     if ((!TargetType || !TypeCertain) && Type) {
2207330f729Sjoerg       // Use *Type, or its header variant if the file is a header.
2217330f729Sjoerg       // Treat no/invalid extension as header (e.g. C++ standard library).
2227330f729Sjoerg       TargetType =
2237330f729Sjoerg           (!TargetType || types::onlyPrecompileType(TargetType)) // header?
2247330f729Sjoerg               ? types::lookupHeaderTypeForSourceType(*Type)
2257330f729Sjoerg               : *Type;
2267330f729Sjoerg       if (ClangCLMode) {
2277330f729Sjoerg         const StringRef Flag = toCLFlag(TargetType);
2287330f729Sjoerg         if (!Flag.empty())
229*e038c9c4Sjoerg           Result.CommandLine.push_back(std::string(Flag));
2307330f729Sjoerg       } else {
2317330f729Sjoerg         Result.CommandLine.push_back("-x");
2327330f729Sjoerg         Result.CommandLine.push_back(types::getTypeName(TargetType));
2337330f729Sjoerg       }
2347330f729Sjoerg     }
2357330f729Sjoerg     // --std flag may only be transferred if the language is the same.
2367330f729Sjoerg     // We may consider "translating" these, e.g. c++11 -> c11.
2377330f729Sjoerg     if (Std != LangStandard::lang_unspecified && foldType(TargetType) == Type) {
2387330f729Sjoerg       Result.CommandLine.emplace_back((
2397330f729Sjoerg           llvm::Twine(ClangCLMode ? "/std:" : "-std=") +
2407330f729Sjoerg           LangStandard::getLangStandardForKind(Std).getName()).str());
2417330f729Sjoerg     }
242*e038c9c4Sjoerg     if (Filename.startswith("-") || (ClangCLMode && Filename.startswith("/")))
243*e038c9c4Sjoerg       Result.CommandLine.push_back("--");
244*e038c9c4Sjoerg     Result.CommandLine.push_back(std::string(Filename));
2457330f729Sjoerg     return Result;
2467330f729Sjoerg   }
2477330f729Sjoerg 
2487330f729Sjoerg private:
2497330f729Sjoerg   // Determine whether the given command line is intended for the CL driver.
checkIsCLModeclang::tooling::__anon983895e40111::TransferableCommand2507330f729Sjoerg   static bool checkIsCLMode(ArrayRef<std::string> CmdLine) {
2517330f729Sjoerg     // First look for --driver-mode.
2527330f729Sjoerg     for (StringRef S : llvm::reverse(CmdLine)) {
2537330f729Sjoerg       if (S.consume_front("--driver-mode="))
2547330f729Sjoerg         return S == "cl";
2557330f729Sjoerg     }
2567330f729Sjoerg 
2577330f729Sjoerg     // Otherwise just check the clang executable file name.
2587330f729Sjoerg     return !CmdLine.empty() &&
2597330f729Sjoerg            llvm::sys::path::stem(CmdLine.front()).endswith_lower("cl");
2607330f729Sjoerg   }
2617330f729Sjoerg 
2627330f729Sjoerg   // Map the language from the --std flag to that of the -x flag.
toTypeclang::tooling::__anon983895e40111::TransferableCommand2637330f729Sjoerg   static types::ID toType(Language Lang) {
2647330f729Sjoerg     switch (Lang) {
2657330f729Sjoerg     case Language::C:
2667330f729Sjoerg       return types::TY_C;
2677330f729Sjoerg     case Language::CXX:
2687330f729Sjoerg       return types::TY_CXX;
2697330f729Sjoerg     case Language::ObjC:
2707330f729Sjoerg       return types::TY_ObjC;
2717330f729Sjoerg     case Language::ObjCXX:
2727330f729Sjoerg       return types::TY_ObjCXX;
2737330f729Sjoerg     default:
2747330f729Sjoerg       return types::TY_INVALID;
2757330f729Sjoerg     }
2767330f729Sjoerg   }
2777330f729Sjoerg 
2787330f729Sjoerg   // Convert a file type to the matching CL-style type flag.
toCLFlagclang::tooling::__anon983895e40111::TransferableCommand2797330f729Sjoerg   static StringRef toCLFlag(types::ID Type) {
2807330f729Sjoerg     switch (Type) {
2817330f729Sjoerg     case types::TY_C:
2827330f729Sjoerg     case types::TY_CHeader:
2837330f729Sjoerg       return "/TC";
2847330f729Sjoerg     case types::TY_CXX:
2857330f729Sjoerg     case types::TY_CXXHeader:
2867330f729Sjoerg       return "/TP";
2877330f729Sjoerg     default:
2887330f729Sjoerg       return StringRef();
2897330f729Sjoerg     }
2907330f729Sjoerg   }
2917330f729Sjoerg 
2927330f729Sjoerg   // Try to interpret the argument as a type specifier, e.g. '-x'.
tryParseTypeArgclang::tooling::__anon983895e40111::TransferableCommand2937330f729Sjoerg   Optional<types::ID> tryParseTypeArg(const llvm::opt::Arg &Arg) {
2947330f729Sjoerg     const llvm::opt::Option &Opt = Arg.getOption();
2957330f729Sjoerg     using namespace driver::options;
2967330f729Sjoerg     if (ClangCLMode) {
2977330f729Sjoerg       if (Opt.matches(OPT__SLASH_TC) || Opt.matches(OPT__SLASH_Tc))
2987330f729Sjoerg         return types::TY_C;
2997330f729Sjoerg       if (Opt.matches(OPT__SLASH_TP) || Opt.matches(OPT__SLASH_Tp))
3007330f729Sjoerg         return types::TY_CXX;
3017330f729Sjoerg     } else {
3027330f729Sjoerg       if (Opt.matches(driver::options::OPT_x))
3037330f729Sjoerg         return types::lookupTypeForTypeSpecifier(Arg.getValue());
3047330f729Sjoerg     }
3057330f729Sjoerg     return None;
3067330f729Sjoerg   }
3077330f729Sjoerg 
3087330f729Sjoerg   // Try to interpret the argument as '-std='.
tryParseStdArgclang::tooling::__anon983895e40111::TransferableCommand3097330f729Sjoerg   Optional<LangStandard::Kind> tryParseStdArg(const llvm::opt::Arg &Arg) {
3107330f729Sjoerg     using namespace driver::options;
3117330f729Sjoerg     if (Arg.getOption().matches(ClangCLMode ? OPT__SLASH_std : OPT_std_EQ))
3127330f729Sjoerg       return LangStandard::getLangKind(Arg.getValue());
3137330f729Sjoerg     return None;
3147330f729Sjoerg   }
3157330f729Sjoerg };
3167330f729Sjoerg 
3177330f729Sjoerg // Given a filename, FileIndex picks the best matching file from the underlying
3187330f729Sjoerg // DB. This is the proxy file whose CompileCommand will be reused. The
3197330f729Sjoerg // heuristics incorporate file name, extension, and directory structure.
3207330f729Sjoerg // Strategy:
3217330f729Sjoerg // - Build indexes of each of the substrings we want to look up by.
3227330f729Sjoerg //   These indexes are just sorted lists of the substrings.
3237330f729Sjoerg // - Each criterion corresponds to a range lookup into the index, so we only
3247330f729Sjoerg //   need O(log N) string comparisons to determine scores.
3257330f729Sjoerg //
3267330f729Sjoerg // Apart from path proximity signals, also takes file extensions into account
3277330f729Sjoerg // when scoring the candidates.
3287330f729Sjoerg class FileIndex {
3297330f729Sjoerg public:
FileIndex(std::vector<std::string> Files)3307330f729Sjoerg   FileIndex(std::vector<std::string> Files)
3317330f729Sjoerg       : OriginalPaths(std::move(Files)), Strings(Arena) {
3327330f729Sjoerg     // Sort commands by filename for determinism (index is a tiebreaker later).
3337330f729Sjoerg     llvm::sort(OriginalPaths);
3347330f729Sjoerg     Paths.reserve(OriginalPaths.size());
3357330f729Sjoerg     Types.reserve(OriginalPaths.size());
3367330f729Sjoerg     Stems.reserve(OriginalPaths.size());
3377330f729Sjoerg     for (size_t I = 0; I < OriginalPaths.size(); ++I) {
3387330f729Sjoerg       StringRef Path = Strings.save(StringRef(OriginalPaths[I]).lower());
3397330f729Sjoerg 
3407330f729Sjoerg       Paths.emplace_back(Path, I);
3417330f729Sjoerg       Types.push_back(foldType(guessType(Path)));
3427330f729Sjoerg       Stems.emplace_back(sys::path::stem(Path), I);
3437330f729Sjoerg       auto Dir = ++sys::path::rbegin(Path), DirEnd = sys::path::rend(Path);
3447330f729Sjoerg       for (int J = 0; J < DirectorySegmentsIndexed && Dir != DirEnd; ++J, ++Dir)
3457330f729Sjoerg         if (Dir->size() > ShortDirectorySegment) // not trivial ones
3467330f729Sjoerg           Components.emplace_back(*Dir, I);
3477330f729Sjoerg     }
3487330f729Sjoerg     llvm::sort(Paths);
3497330f729Sjoerg     llvm::sort(Stems);
3507330f729Sjoerg     llvm::sort(Components);
3517330f729Sjoerg   }
3527330f729Sjoerg 
empty() const3537330f729Sjoerg   bool empty() const { return Paths.empty(); }
3547330f729Sjoerg 
3557330f729Sjoerg   // Returns the path for the file that best fits OriginalFilename.
3567330f729Sjoerg   // Candidates with extensions matching PreferLanguage will be chosen over
3577330f729Sjoerg   // others (unless it's TY_INVALID, or all candidates are bad).
chooseProxy(StringRef OriginalFilename,types::ID PreferLanguage) const3587330f729Sjoerg   StringRef chooseProxy(StringRef OriginalFilename,
3597330f729Sjoerg                         types::ID PreferLanguage) const {
3607330f729Sjoerg     assert(!empty() && "need at least one candidate!");
3617330f729Sjoerg     std::string Filename = OriginalFilename.lower();
3627330f729Sjoerg     auto Candidates = scoreCandidates(Filename);
3637330f729Sjoerg     std::pair<size_t, int> Best =
3647330f729Sjoerg         pickWinner(Candidates, Filename, PreferLanguage);
3657330f729Sjoerg 
3667330f729Sjoerg     DEBUG_WITH_TYPE(
3677330f729Sjoerg         "interpolate",
3687330f729Sjoerg         llvm::dbgs() << "interpolate: chose " << OriginalPaths[Best.first]
3697330f729Sjoerg                      << " as proxy for " << OriginalFilename << " preferring "
3707330f729Sjoerg                      << (PreferLanguage == types::TY_INVALID
3717330f729Sjoerg                              ? "none"
3727330f729Sjoerg                              : types::getTypeName(PreferLanguage))
3737330f729Sjoerg                      << " score=" << Best.second << "\n");
3747330f729Sjoerg     return OriginalPaths[Best.first];
3757330f729Sjoerg   }
3767330f729Sjoerg 
3777330f729Sjoerg private:
3787330f729Sjoerg   using SubstringAndIndex = std::pair<StringRef, size_t>;
3797330f729Sjoerg   // Directory matching parameters: we look at the last two segments of the
3807330f729Sjoerg   // parent directory (usually the semantically significant ones in practice).
3817330f729Sjoerg   // We search only the last four of each candidate (for efficiency).
3827330f729Sjoerg   constexpr static int DirectorySegmentsIndexed = 4;
3837330f729Sjoerg   constexpr static int DirectorySegmentsQueried = 2;
3847330f729Sjoerg   constexpr static int ShortDirectorySegment = 1; // Only look at longer names.
3857330f729Sjoerg 
3867330f729Sjoerg   // Award points to candidate entries that should be considered for the file.
3877330f729Sjoerg   // Returned keys are indexes into paths, and the values are (nonzero) scores.
scoreCandidates(StringRef Filename) const3887330f729Sjoerg   DenseMap<size_t, int> scoreCandidates(StringRef Filename) const {
3897330f729Sjoerg     // Decompose Filename into the parts we care about.
3907330f729Sjoerg     // /some/path/complicated/project/Interesting.h
3917330f729Sjoerg     // [-prefix--][---dir---] [-dir-] [--stem---]
3927330f729Sjoerg     StringRef Stem = sys::path::stem(Filename);
3937330f729Sjoerg     llvm::SmallVector<StringRef, DirectorySegmentsQueried> Dirs;
3947330f729Sjoerg     llvm::StringRef Prefix;
3957330f729Sjoerg     auto Dir = ++sys::path::rbegin(Filename),
3967330f729Sjoerg          DirEnd = sys::path::rend(Filename);
3977330f729Sjoerg     for (int I = 0; I < DirectorySegmentsQueried && Dir != DirEnd; ++I, ++Dir) {
3987330f729Sjoerg       if (Dir->size() > ShortDirectorySegment)
3997330f729Sjoerg         Dirs.push_back(*Dir);
4007330f729Sjoerg       Prefix = Filename.substr(0, Dir - DirEnd);
4017330f729Sjoerg     }
4027330f729Sjoerg 
4037330f729Sjoerg     // Now award points based on lookups into our various indexes.
4047330f729Sjoerg     DenseMap<size_t, int> Candidates; // Index -> score.
4057330f729Sjoerg     auto Award = [&](int Points, ArrayRef<SubstringAndIndex> Range) {
4067330f729Sjoerg       for (const auto &Entry : Range)
4077330f729Sjoerg         Candidates[Entry.second] += Points;
4087330f729Sjoerg     };
4097330f729Sjoerg     // Award one point if the file's basename is a prefix of the candidate,
4107330f729Sjoerg     // and another if it's an exact match (so exact matches get two points).
4117330f729Sjoerg     Award(1, indexLookup</*Prefix=*/true>(Stem, Stems));
4127330f729Sjoerg     Award(1, indexLookup</*Prefix=*/false>(Stem, Stems));
4137330f729Sjoerg     // For each of the last few directories in the Filename, award a point
4147330f729Sjoerg     // if it's present in the candidate.
4157330f729Sjoerg     for (StringRef Dir : Dirs)
4167330f729Sjoerg       Award(1, indexLookup</*Prefix=*/false>(Dir, Components));
4177330f729Sjoerg     // Award one more point if the whole rest of the path matches.
4187330f729Sjoerg     if (sys::path::root_directory(Prefix) != Prefix)
4197330f729Sjoerg       Award(1, indexLookup</*Prefix=*/true>(Prefix, Paths));
4207330f729Sjoerg     return Candidates;
4217330f729Sjoerg   }
4227330f729Sjoerg 
4237330f729Sjoerg   // Pick a single winner from the set of scored candidates.
4247330f729Sjoerg   // Returns (index, score).
pickWinner(const DenseMap<size_t,int> & Candidates,StringRef Filename,types::ID PreferredLanguage) const4257330f729Sjoerg   std::pair<size_t, int> pickWinner(const DenseMap<size_t, int> &Candidates,
4267330f729Sjoerg                                     StringRef Filename,
4277330f729Sjoerg                                     types::ID PreferredLanguage) const {
4287330f729Sjoerg     struct ScoredCandidate {
4297330f729Sjoerg       size_t Index;
4307330f729Sjoerg       bool Preferred;
4317330f729Sjoerg       int Points;
4327330f729Sjoerg       size_t PrefixLength;
4337330f729Sjoerg     };
4347330f729Sjoerg     // Choose the best candidate by (preferred, points, prefix length, alpha).
4357330f729Sjoerg     ScoredCandidate Best = {size_t(-1), false, 0, 0};
4367330f729Sjoerg     for (const auto &Candidate : Candidates) {
4377330f729Sjoerg       ScoredCandidate S;
4387330f729Sjoerg       S.Index = Candidate.first;
4397330f729Sjoerg       S.Preferred = PreferredLanguage == types::TY_INVALID ||
4407330f729Sjoerg                     PreferredLanguage == Types[S.Index];
4417330f729Sjoerg       S.Points = Candidate.second;
4427330f729Sjoerg       if (!S.Preferred && Best.Preferred)
4437330f729Sjoerg         continue;
4447330f729Sjoerg       if (S.Preferred == Best.Preferred) {
4457330f729Sjoerg         if (S.Points < Best.Points)
4467330f729Sjoerg           continue;
4477330f729Sjoerg         if (S.Points == Best.Points) {
4487330f729Sjoerg           S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
4497330f729Sjoerg           if (S.PrefixLength < Best.PrefixLength)
4507330f729Sjoerg             continue;
4517330f729Sjoerg           // hidden heuristics should at least be deterministic!
4527330f729Sjoerg           if (S.PrefixLength == Best.PrefixLength)
4537330f729Sjoerg             if (S.Index > Best.Index)
4547330f729Sjoerg               continue;
4557330f729Sjoerg         }
4567330f729Sjoerg       }
4577330f729Sjoerg       // PrefixLength was only set above if actually needed for a tiebreak.
4587330f729Sjoerg       // But it definitely needs to be set to break ties in the future.
4597330f729Sjoerg       S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
4607330f729Sjoerg       Best = S;
4617330f729Sjoerg     }
4627330f729Sjoerg     // Edge case: no candidate got any points.
4637330f729Sjoerg     // We ignore PreferredLanguage at this point (not ideal).
4647330f729Sjoerg     if (Best.Index == size_t(-1))
4657330f729Sjoerg       return {longestMatch(Filename, Paths).second, 0};
4667330f729Sjoerg     return {Best.Index, Best.Points};
4677330f729Sjoerg   }
4687330f729Sjoerg 
4697330f729Sjoerg   // Returns the range within a sorted index that compares equal to Key.
4707330f729Sjoerg   // If Prefix is true, it's instead the range starting with Key.
4717330f729Sjoerg   template <bool Prefix>
4727330f729Sjoerg   ArrayRef<SubstringAndIndex>
indexLookup(StringRef Key,ArrayRef<SubstringAndIndex> Idx) const4737330f729Sjoerg   indexLookup(StringRef Key, ArrayRef<SubstringAndIndex> Idx) const {
4747330f729Sjoerg     // Use pointers as iteratiors to ease conversion of result to ArrayRef.
4757330f729Sjoerg     auto Range = std::equal_range(Idx.data(), Idx.data() + Idx.size(), Key,
4767330f729Sjoerg                                   Less<Prefix>());
4777330f729Sjoerg     return {Range.first, Range.second};
4787330f729Sjoerg   }
4797330f729Sjoerg 
4807330f729Sjoerg   // Performs a point lookup into a nonempty index, returning a longest match.
longestMatch(StringRef Key,ArrayRef<SubstringAndIndex> Idx) const4817330f729Sjoerg   SubstringAndIndex longestMatch(StringRef Key,
4827330f729Sjoerg                                  ArrayRef<SubstringAndIndex> Idx) const {
4837330f729Sjoerg     assert(!Idx.empty());
4847330f729Sjoerg     // Longest substring match will be adjacent to a direct lookup.
4857330f729Sjoerg     auto It = llvm::lower_bound(Idx, SubstringAndIndex{Key, 0});
4867330f729Sjoerg     if (It == Idx.begin())
4877330f729Sjoerg       return *It;
4887330f729Sjoerg     if (It == Idx.end())
4897330f729Sjoerg       return *--It;
4907330f729Sjoerg     // Have to choose between It and It-1
4917330f729Sjoerg     size_t Prefix = matchingPrefix(Key, It->first);
4927330f729Sjoerg     size_t PrevPrefix = matchingPrefix(Key, (It - 1)->first);
4937330f729Sjoerg     return Prefix > PrevPrefix ? *It : *--It;
4947330f729Sjoerg   }
4957330f729Sjoerg 
4967330f729Sjoerg   // Original paths, everything else is in lowercase.
4977330f729Sjoerg   std::vector<std::string> OriginalPaths;
4987330f729Sjoerg   BumpPtrAllocator Arena;
4997330f729Sjoerg   StringSaver Strings;
5007330f729Sjoerg   // Indexes of candidates by certain substrings.
5017330f729Sjoerg   // String is lowercase and sorted, index points into OriginalPaths.
5027330f729Sjoerg   std::vector<SubstringAndIndex> Paths;      // Full path.
5037330f729Sjoerg   // Lang types obtained by guessing on the corresponding path. I-th element is
5047330f729Sjoerg   // a type for the I-th path.
5057330f729Sjoerg   std::vector<types::ID> Types;
5067330f729Sjoerg   std::vector<SubstringAndIndex> Stems;      // Basename, without extension.
5077330f729Sjoerg   std::vector<SubstringAndIndex> Components; // Last path components.
5087330f729Sjoerg };
5097330f729Sjoerg 
5107330f729Sjoerg // The actual CompilationDatabase wrapper delegates to its inner database.
5117330f729Sjoerg // If no match, looks up a proxy file in FileIndex and transfers its
5127330f729Sjoerg // command to the requested file.
5137330f729Sjoerg class InterpolatingCompilationDatabase : public CompilationDatabase {
5147330f729Sjoerg public:
InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)5157330f729Sjoerg   InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)
5167330f729Sjoerg       : Inner(std::move(Inner)), Index(this->Inner->getAllFiles()) {}
5177330f729Sjoerg 
5187330f729Sjoerg   std::vector<CompileCommand>
getCompileCommands(StringRef Filename) const5197330f729Sjoerg   getCompileCommands(StringRef Filename) const override {
5207330f729Sjoerg     auto Known = Inner->getCompileCommands(Filename);
5217330f729Sjoerg     if (Index.empty() || !Known.empty())
5227330f729Sjoerg       return Known;
5237330f729Sjoerg     bool TypeCertain;
5247330f729Sjoerg     auto Lang = guessType(Filename, &TypeCertain);
5257330f729Sjoerg     if (!TypeCertain)
5267330f729Sjoerg       Lang = types::TY_INVALID;
5277330f729Sjoerg     auto ProxyCommands =
5287330f729Sjoerg         Inner->getCompileCommands(Index.chooseProxy(Filename, foldType(Lang)));
5297330f729Sjoerg     if (ProxyCommands.empty())
5307330f729Sjoerg       return {};
531*e038c9c4Sjoerg     return {transferCompileCommand(std::move(ProxyCommands.front()), Filename)};
5327330f729Sjoerg   }
5337330f729Sjoerg 
getAllFiles() const5347330f729Sjoerg   std::vector<std::string> getAllFiles() const override {
5357330f729Sjoerg     return Inner->getAllFiles();
5367330f729Sjoerg   }
5377330f729Sjoerg 
getAllCompileCommands() const5387330f729Sjoerg   std::vector<CompileCommand> getAllCompileCommands() const override {
5397330f729Sjoerg     return Inner->getAllCompileCommands();
5407330f729Sjoerg   }
5417330f729Sjoerg 
5427330f729Sjoerg private:
5437330f729Sjoerg   std::unique_ptr<CompilationDatabase> Inner;
5447330f729Sjoerg   FileIndex Index;
5457330f729Sjoerg };
5467330f729Sjoerg 
5477330f729Sjoerg } // namespace
5487330f729Sjoerg 
5497330f729Sjoerg std::unique_ptr<CompilationDatabase>
inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner)5507330f729Sjoerg inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner) {
5517330f729Sjoerg   return std::make_unique<InterpolatingCompilationDatabase>(std::move(Inner));
5527330f729Sjoerg }
5537330f729Sjoerg 
transferCompileCommand(CompileCommand Cmd,StringRef Filename)554*e038c9c4Sjoerg tooling::CompileCommand transferCompileCommand(CompileCommand Cmd,
555*e038c9c4Sjoerg                                                StringRef Filename) {
556*e038c9c4Sjoerg   return TransferableCommand(std::move(Cmd)).transferTo(Filename);
557*e038c9c4Sjoerg }
558*e038c9c4Sjoerg 
5597330f729Sjoerg } // namespace tooling
5607330f729Sjoerg } // namespace clang
561