10b57cec5SDimitry Andric //===- InterpolatingCompilationDatabase.cpp ---------------------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // InterpolatingCompilationDatabase wraps another CompilationDatabase and
100b57cec5SDimitry Andric // attempts to heuristically determine appropriate compile commands for files
110b57cec5SDimitry Andric // that are not included, such as headers or newly created files.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric // Motivating cases include:
140b57cec5SDimitry Andric // Header files that live next to their implementation files. These typically
150b57cec5SDimitry Andric // share a base filename. (libclang/CXString.h, libclang/CXString.cpp).
160b57cec5SDimitry Andric // Some projects separate headers from includes. Filenames still typically
170b57cec5SDimitry Andric // match, maybe other path segments too. (include/llvm/IR/Use.h, lib/IR/Use.cc).
180b57cec5SDimitry Andric // Matches are sometimes only approximate (Sema.h, SemaDecl.cpp). This goes
190b57cec5SDimitry Andric // for directories too (Support/Unix/Process.inc, lib/Support/Process.cpp).
200b57cec5SDimitry Andric // Even if we can't find a "right" compile command, even a random one from
210b57cec5SDimitry Andric // the project will tend to get important flags like -I and -x right.
220b57cec5SDimitry Andric //
230b57cec5SDimitry Andric // We "borrow" the compile command for the closest available file:
240b57cec5SDimitry Andric // - points are awarded if the filename matches (ignoring extension)
250b57cec5SDimitry Andric // - points are awarded if the directory structure matches
260b57cec5SDimitry Andric // - ties are broken by length of path prefix match
270b57cec5SDimitry Andric //
280b57cec5SDimitry Andric // The compile command is adjusted, replacing the filename and removing output
290b57cec5SDimitry Andric // file arguments. The -x and -std flags may be affected too.
300b57cec5SDimitry Andric //
310b57cec5SDimitry Andric // Source language is a tricky issue: is it OK to use a .c file's command
320b57cec5SDimitry Andric // for building a .cc file? What language is a .h file in?
330b57cec5SDimitry Andric // - We only consider compile commands for c-family languages as candidates.
340b57cec5SDimitry Andric // - For files whose language is implied by the filename (e.g. .m, .hpp)
350b57cec5SDimitry Andric // we prefer candidates from the same language.
360b57cec5SDimitry Andric // If we must cross languages, we drop any -x and -std flags.
370b57cec5SDimitry Andric // - For .h files, candidates from any c-family language are acceptable.
380b57cec5SDimitry Andric // We use the candidate's language, inserting e.g. -x c++-header.
390b57cec5SDimitry Andric //
400b57cec5SDimitry Andric // This class is only useful when wrapping databases that can enumerate all
410b57cec5SDimitry Andric // their compile commands. If getAllFilenames() is empty, no inference occurs.
420b57cec5SDimitry Andric //
430b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
440b57cec5SDimitry Andric
45a7dea167SDimitry Andric #include "clang/Basic/LangStandard.h"
46*5f7ddb14SDimitry Andric #include "clang/Driver/Driver.h"
470b57cec5SDimitry Andric #include "clang/Driver/Options.h"
480b57cec5SDimitry Andric #include "clang/Driver/Types.h"
490b57cec5SDimitry Andric #include "clang/Tooling/CompilationDatabase.h"
50*5f7ddb14SDimitry Andric #include "llvm/ADT/ArrayRef.h"
510b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
520b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
530b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
540b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
550b57cec5SDimitry Andric #include "llvm/Option/ArgList.h"
560b57cec5SDimitry Andric #include "llvm/Option/OptTable.h"
570b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
580b57cec5SDimitry Andric #include "llvm/Support/Path.h"
590b57cec5SDimitry Andric #include "llvm/Support/StringSaver.h"
600b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
610b57cec5SDimitry Andric #include <memory>
620b57cec5SDimitry Andric
630b57cec5SDimitry Andric namespace clang {
640b57cec5SDimitry Andric namespace tooling {
650b57cec5SDimitry Andric namespace {
660b57cec5SDimitry Andric using namespace llvm;
670b57cec5SDimitry Andric namespace types = clang::driver::types;
680b57cec5SDimitry Andric namespace path = llvm::sys::path;
690b57cec5SDimitry Andric
700b57cec5SDimitry Andric // The length of the prefix these two strings have in common.
matchingPrefix(StringRef L,StringRef R)710b57cec5SDimitry Andric size_t matchingPrefix(StringRef L, StringRef R) {
720b57cec5SDimitry Andric size_t Limit = std::min(L.size(), R.size());
730b57cec5SDimitry Andric for (size_t I = 0; I < Limit; ++I)
740b57cec5SDimitry Andric if (L[I] != R[I])
750b57cec5SDimitry Andric return I;
760b57cec5SDimitry Andric return Limit;
770b57cec5SDimitry Andric }
780b57cec5SDimitry Andric
790b57cec5SDimitry Andric // A comparator for searching SubstringWithIndexes with std::equal_range etc.
800b57cec5SDimitry Andric // Optionaly prefix semantics: compares equal if the key is a prefix.
810b57cec5SDimitry Andric template <bool Prefix> struct Less {
operator ()clang::tooling::__anon893e7f6d0111::Less820b57cec5SDimitry Andric bool operator()(StringRef Key, std::pair<StringRef, size_t> Value) const {
830b57cec5SDimitry Andric StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
840b57cec5SDimitry Andric return Key < V;
850b57cec5SDimitry Andric }
operator ()clang::tooling::__anon893e7f6d0111::Less860b57cec5SDimitry Andric bool operator()(std::pair<StringRef, size_t> Value, StringRef Key) const {
870b57cec5SDimitry Andric StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
880b57cec5SDimitry Andric return V < Key;
890b57cec5SDimitry Andric }
900b57cec5SDimitry Andric };
910b57cec5SDimitry Andric
920b57cec5SDimitry Andric // Infer type from filename. If we might have gotten it wrong, set *Certain.
930b57cec5SDimitry Andric // *.h will be inferred as a C header, but not certain.
guessType(StringRef Filename,bool * Certain=nullptr)940b57cec5SDimitry Andric types::ID guessType(StringRef Filename, bool *Certain = nullptr) {
950b57cec5SDimitry Andric // path::extension is ".cpp", lookupTypeForExtension wants "cpp".
960b57cec5SDimitry Andric auto Lang =
970b57cec5SDimitry Andric types::lookupTypeForExtension(path::extension(Filename).substr(1));
980b57cec5SDimitry Andric if (Certain)
990b57cec5SDimitry Andric *Certain = Lang != types::TY_CHeader && Lang != types::TY_INVALID;
1000b57cec5SDimitry Andric return Lang;
1010b57cec5SDimitry Andric }
1020b57cec5SDimitry Andric
1030b57cec5SDimitry Andric // Return Lang as one of the canonical supported types.
1040b57cec5SDimitry Andric // e.g. c-header --> c; fortran --> TY_INVALID
foldType(types::ID Lang)1050b57cec5SDimitry Andric static types::ID foldType(types::ID Lang) {
1060b57cec5SDimitry Andric switch (Lang) {
1070b57cec5SDimitry Andric case types::TY_C:
1080b57cec5SDimitry Andric case types::TY_CHeader:
1090b57cec5SDimitry Andric return types::TY_C;
1100b57cec5SDimitry Andric case types::TY_ObjC:
1110b57cec5SDimitry Andric case types::TY_ObjCHeader:
1120b57cec5SDimitry Andric return types::TY_ObjC;
1130b57cec5SDimitry Andric case types::TY_CXX:
1140b57cec5SDimitry Andric case types::TY_CXXHeader:
1150b57cec5SDimitry Andric return types::TY_CXX;
1160b57cec5SDimitry Andric case types::TY_ObjCXX:
1170b57cec5SDimitry Andric case types::TY_ObjCXXHeader:
1180b57cec5SDimitry Andric return types::TY_ObjCXX;
1195ffd83dbSDimitry Andric case types::TY_CUDA:
1205ffd83dbSDimitry Andric case types::TY_CUDA_DEVICE:
1215ffd83dbSDimitry Andric return types::TY_CUDA;
1220b57cec5SDimitry Andric default:
1230b57cec5SDimitry Andric return types::TY_INVALID;
1240b57cec5SDimitry Andric }
1250b57cec5SDimitry Andric }
1260b57cec5SDimitry Andric
1270b57cec5SDimitry Andric // A CompileCommand that can be applied to another file.
1280b57cec5SDimitry Andric struct TransferableCommand {
1290b57cec5SDimitry Andric // Flags that should not apply to all files are stripped from CommandLine.
1300b57cec5SDimitry Andric CompileCommand Cmd;
1310b57cec5SDimitry Andric // Language detected from -x or the filename. Never TY_INVALID.
1320b57cec5SDimitry Andric Optional<types::ID> Type;
1330b57cec5SDimitry Andric // Standard specified by -std.
1340b57cec5SDimitry Andric LangStandard::Kind Std = LangStandard::lang_unspecified;
1350b57cec5SDimitry Andric // Whether the command line is for the cl-compatible driver.
1360b57cec5SDimitry Andric bool ClangCLMode;
1370b57cec5SDimitry Andric
TransferableCommandclang::tooling::__anon893e7f6d0111::TransferableCommand1380b57cec5SDimitry Andric TransferableCommand(CompileCommand C)
139*5f7ddb14SDimitry Andric : Cmd(std::move(C)), Type(guessType(Cmd.Filename)) {
1400b57cec5SDimitry Andric std::vector<std::string> OldArgs = std::move(Cmd.CommandLine);
1410b57cec5SDimitry Andric Cmd.CommandLine.clear();
1420b57cec5SDimitry Andric
1430b57cec5SDimitry Andric // Wrap the old arguments in an InputArgList.
1440b57cec5SDimitry Andric llvm::opt::InputArgList ArgList;
1450b57cec5SDimitry Andric {
1460b57cec5SDimitry Andric SmallVector<const char *, 16> TmpArgv;
1470b57cec5SDimitry Andric for (const std::string &S : OldArgs)
1480b57cec5SDimitry Andric TmpArgv.push_back(S.c_str());
149*5f7ddb14SDimitry Andric ClangCLMode = !TmpArgv.empty() &&
150*5f7ddb14SDimitry Andric driver::IsClangCL(driver::getDriverMode(
151*5f7ddb14SDimitry Andric TmpArgv.front(), llvm::makeArrayRef(TmpArgv).slice(1)));
1520b57cec5SDimitry Andric ArgList = {TmpArgv.begin(), TmpArgv.end()};
1530b57cec5SDimitry Andric }
1540b57cec5SDimitry Andric
1550b57cec5SDimitry Andric // Parse the old args in order to strip out and record unwanted flags.
1560b57cec5SDimitry Andric // We parse each argument individually so that we can retain the exact
1570b57cec5SDimitry Andric // spelling of each argument; re-rendering is lossy for aliased flags.
1580b57cec5SDimitry Andric // E.g. in CL mode, /W4 maps to -Wall.
159a7dea167SDimitry Andric auto &OptTable = clang::driver::getDriverOptTable();
1600b57cec5SDimitry Andric if (!OldArgs.empty())
1610b57cec5SDimitry Andric Cmd.CommandLine.emplace_back(OldArgs.front());
1620b57cec5SDimitry Andric for (unsigned Pos = 1; Pos < OldArgs.size();) {
1630b57cec5SDimitry Andric using namespace driver::options;
1640b57cec5SDimitry Andric
1650b57cec5SDimitry Andric const unsigned OldPos = Pos;
166a7dea167SDimitry Andric std::unique_ptr<llvm::opt::Arg> Arg(OptTable.ParseOneArg(
1670b57cec5SDimitry Andric ArgList, Pos,
1680b57cec5SDimitry Andric /* Include */ ClangCLMode ? CoreOption | CLOption : 0,
1690b57cec5SDimitry Andric /* Exclude */ ClangCLMode ? 0 : CLOption));
1700b57cec5SDimitry Andric
1710b57cec5SDimitry Andric if (!Arg)
1720b57cec5SDimitry Andric continue;
1730b57cec5SDimitry Andric
1740b57cec5SDimitry Andric const llvm::opt::Option &Opt = Arg->getOption();
1750b57cec5SDimitry Andric
1760b57cec5SDimitry Andric // Strip input and output files.
1770b57cec5SDimitry Andric if (Opt.matches(OPT_INPUT) || Opt.matches(OPT_o) ||
1780b57cec5SDimitry Andric (ClangCLMode && (Opt.matches(OPT__SLASH_Fa) ||
1790b57cec5SDimitry Andric Opt.matches(OPT__SLASH_Fe) ||
1800b57cec5SDimitry Andric Opt.matches(OPT__SLASH_Fi) ||
1810b57cec5SDimitry Andric Opt.matches(OPT__SLASH_Fo))))
1820b57cec5SDimitry Andric continue;
1830b57cec5SDimitry Andric
184*5f7ddb14SDimitry Andric // ...including when the inputs are passed after --.
185*5f7ddb14SDimitry Andric if (Opt.matches(OPT__DASH_DASH))
186*5f7ddb14SDimitry Andric break;
187*5f7ddb14SDimitry Andric
1880b57cec5SDimitry Andric // Strip -x, but record the overridden language.
1890b57cec5SDimitry Andric if (const auto GivenType = tryParseTypeArg(*Arg)) {
1900b57cec5SDimitry Andric Type = *GivenType;
1910b57cec5SDimitry Andric continue;
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric
1940b57cec5SDimitry Andric // Strip -std, but record the value.
1950b57cec5SDimitry Andric if (const auto GivenStd = tryParseStdArg(*Arg)) {
1960b57cec5SDimitry Andric if (*GivenStd != LangStandard::lang_unspecified)
1970b57cec5SDimitry Andric Std = *GivenStd;
1980b57cec5SDimitry Andric continue;
1990b57cec5SDimitry Andric }
2000b57cec5SDimitry Andric
2010b57cec5SDimitry Andric Cmd.CommandLine.insert(Cmd.CommandLine.end(),
2020b57cec5SDimitry Andric OldArgs.data() + OldPos, OldArgs.data() + Pos);
2030b57cec5SDimitry Andric }
2040b57cec5SDimitry Andric
205480093f4SDimitry Andric // Make use of -std iff -x was missing.
206480093f4SDimitry Andric if (Type == types::TY_INVALID && Std != LangStandard::lang_unspecified)
2070b57cec5SDimitry Andric Type = toType(LangStandard::getLangStandardForKind(Std).getLanguage());
2080b57cec5SDimitry Andric Type = foldType(*Type);
2090b57cec5SDimitry Andric // The contract is to store None instead of TY_INVALID.
2100b57cec5SDimitry Andric if (Type == types::TY_INVALID)
2110b57cec5SDimitry Andric Type = llvm::None;
2120b57cec5SDimitry Andric }
2130b57cec5SDimitry Andric
2140b57cec5SDimitry Andric // Produce a CompileCommand for \p filename, based on this one.
215*5f7ddb14SDimitry Andric // (This consumes the TransferableCommand just to avoid copying Cmd).
transferToclang::tooling::__anon893e7f6d0111::TransferableCommand216*5f7ddb14SDimitry Andric CompileCommand transferTo(StringRef Filename) && {
217*5f7ddb14SDimitry Andric CompileCommand Result = std::move(Cmd);
218*5f7ddb14SDimitry Andric Result.Heuristic = "inferred from " + Result.Filename;
2195ffd83dbSDimitry Andric Result.Filename = std::string(Filename);
2200b57cec5SDimitry Andric bool TypeCertain;
2210b57cec5SDimitry Andric auto TargetType = guessType(Filename, &TypeCertain);
2220b57cec5SDimitry Andric // If the filename doesn't determine the language (.h), transfer with -x.
2230b57cec5SDimitry Andric if ((!TargetType || !TypeCertain) && Type) {
2240b57cec5SDimitry Andric // Use *Type, or its header variant if the file is a header.
2250b57cec5SDimitry Andric // Treat no/invalid extension as header (e.g. C++ standard library).
2260b57cec5SDimitry Andric TargetType =
2270b57cec5SDimitry Andric (!TargetType || types::onlyPrecompileType(TargetType)) // header?
2280b57cec5SDimitry Andric ? types::lookupHeaderTypeForSourceType(*Type)
2290b57cec5SDimitry Andric : *Type;
2300b57cec5SDimitry Andric if (ClangCLMode) {
2310b57cec5SDimitry Andric const StringRef Flag = toCLFlag(TargetType);
2320b57cec5SDimitry Andric if (!Flag.empty())
2335ffd83dbSDimitry Andric Result.CommandLine.push_back(std::string(Flag));
2340b57cec5SDimitry Andric } else {
2350b57cec5SDimitry Andric Result.CommandLine.push_back("-x");
2360b57cec5SDimitry Andric Result.CommandLine.push_back(types::getTypeName(TargetType));
2370b57cec5SDimitry Andric }
2380b57cec5SDimitry Andric }
2390b57cec5SDimitry Andric // --std flag may only be transferred if the language is the same.
2400b57cec5SDimitry Andric // We may consider "translating" these, e.g. c++11 -> c11.
2410b57cec5SDimitry Andric if (Std != LangStandard::lang_unspecified && foldType(TargetType) == Type) {
2420b57cec5SDimitry Andric Result.CommandLine.emplace_back((
2430b57cec5SDimitry Andric llvm::Twine(ClangCLMode ? "/std:" : "-std=") +
2440b57cec5SDimitry Andric LangStandard::getLangStandardForKind(Std).getName()).str());
2450b57cec5SDimitry Andric }
246*5f7ddb14SDimitry Andric if (Filename.startswith("-") || (ClangCLMode && Filename.startswith("/")))
247*5f7ddb14SDimitry Andric Result.CommandLine.push_back("--");
2485ffd83dbSDimitry Andric Result.CommandLine.push_back(std::string(Filename));
2490b57cec5SDimitry Andric return Result;
2500b57cec5SDimitry Andric }
2510b57cec5SDimitry Andric
2520b57cec5SDimitry Andric private:
2530b57cec5SDimitry Andric // Map the language from the --std flag to that of the -x flag.
toTypeclang::tooling::__anon893e7f6d0111::TransferableCommand254a7dea167SDimitry Andric static types::ID toType(Language Lang) {
2550b57cec5SDimitry Andric switch (Lang) {
256a7dea167SDimitry Andric case Language::C:
2570b57cec5SDimitry Andric return types::TY_C;
258a7dea167SDimitry Andric case Language::CXX:
2590b57cec5SDimitry Andric return types::TY_CXX;
260a7dea167SDimitry Andric case Language::ObjC:
2610b57cec5SDimitry Andric return types::TY_ObjC;
262a7dea167SDimitry Andric case Language::ObjCXX:
2630b57cec5SDimitry Andric return types::TY_ObjCXX;
2640b57cec5SDimitry Andric default:
2650b57cec5SDimitry Andric return types::TY_INVALID;
2660b57cec5SDimitry Andric }
2670b57cec5SDimitry Andric }
2680b57cec5SDimitry Andric
2690b57cec5SDimitry Andric // Convert a file type to the matching CL-style type flag.
toCLFlagclang::tooling::__anon893e7f6d0111::TransferableCommand2700b57cec5SDimitry Andric static StringRef toCLFlag(types::ID Type) {
2710b57cec5SDimitry Andric switch (Type) {
2720b57cec5SDimitry Andric case types::TY_C:
2730b57cec5SDimitry Andric case types::TY_CHeader:
2740b57cec5SDimitry Andric return "/TC";
2750b57cec5SDimitry Andric case types::TY_CXX:
2760b57cec5SDimitry Andric case types::TY_CXXHeader:
2770b57cec5SDimitry Andric return "/TP";
2780b57cec5SDimitry Andric default:
2790b57cec5SDimitry Andric return StringRef();
2800b57cec5SDimitry Andric }
2810b57cec5SDimitry Andric }
2820b57cec5SDimitry Andric
2830b57cec5SDimitry Andric // Try to interpret the argument as a type specifier, e.g. '-x'.
tryParseTypeArgclang::tooling::__anon893e7f6d0111::TransferableCommand2840b57cec5SDimitry Andric Optional<types::ID> tryParseTypeArg(const llvm::opt::Arg &Arg) {
2850b57cec5SDimitry Andric const llvm::opt::Option &Opt = Arg.getOption();
2860b57cec5SDimitry Andric using namespace driver::options;
2870b57cec5SDimitry Andric if (ClangCLMode) {
2880b57cec5SDimitry Andric if (Opt.matches(OPT__SLASH_TC) || Opt.matches(OPT__SLASH_Tc))
2890b57cec5SDimitry Andric return types::TY_C;
2900b57cec5SDimitry Andric if (Opt.matches(OPT__SLASH_TP) || Opt.matches(OPT__SLASH_Tp))
2910b57cec5SDimitry Andric return types::TY_CXX;
2920b57cec5SDimitry Andric } else {
2930b57cec5SDimitry Andric if (Opt.matches(driver::options::OPT_x))
2940b57cec5SDimitry Andric return types::lookupTypeForTypeSpecifier(Arg.getValue());
2950b57cec5SDimitry Andric }
2960b57cec5SDimitry Andric return None;
2970b57cec5SDimitry Andric }
2980b57cec5SDimitry Andric
2990b57cec5SDimitry Andric // Try to interpret the argument as '-std='.
tryParseStdArgclang::tooling::__anon893e7f6d0111::TransferableCommand3000b57cec5SDimitry Andric Optional<LangStandard::Kind> tryParseStdArg(const llvm::opt::Arg &Arg) {
3010b57cec5SDimitry Andric using namespace driver::options;
302a7dea167SDimitry Andric if (Arg.getOption().matches(ClangCLMode ? OPT__SLASH_std : OPT_std_EQ))
303a7dea167SDimitry Andric return LangStandard::getLangKind(Arg.getValue());
3040b57cec5SDimitry Andric return None;
3050b57cec5SDimitry Andric }
3060b57cec5SDimitry Andric };
3070b57cec5SDimitry Andric
3080b57cec5SDimitry Andric // Given a filename, FileIndex picks the best matching file from the underlying
3090b57cec5SDimitry Andric // DB. This is the proxy file whose CompileCommand will be reused. The
3100b57cec5SDimitry Andric // heuristics incorporate file name, extension, and directory structure.
3110b57cec5SDimitry Andric // Strategy:
3120b57cec5SDimitry Andric // - Build indexes of each of the substrings we want to look up by.
3130b57cec5SDimitry Andric // These indexes are just sorted lists of the substrings.
3140b57cec5SDimitry Andric // - Each criterion corresponds to a range lookup into the index, so we only
3150b57cec5SDimitry Andric // need O(log N) string comparisons to determine scores.
3160b57cec5SDimitry Andric //
3170b57cec5SDimitry Andric // Apart from path proximity signals, also takes file extensions into account
3180b57cec5SDimitry Andric // when scoring the candidates.
3190b57cec5SDimitry Andric class FileIndex {
3200b57cec5SDimitry Andric public:
FileIndex(std::vector<std::string> Files)3210b57cec5SDimitry Andric FileIndex(std::vector<std::string> Files)
3220b57cec5SDimitry Andric : OriginalPaths(std::move(Files)), Strings(Arena) {
3230b57cec5SDimitry Andric // Sort commands by filename for determinism (index is a tiebreaker later).
3240b57cec5SDimitry Andric llvm::sort(OriginalPaths);
3250b57cec5SDimitry Andric Paths.reserve(OriginalPaths.size());
3260b57cec5SDimitry Andric Types.reserve(OriginalPaths.size());
3270b57cec5SDimitry Andric Stems.reserve(OriginalPaths.size());
3280b57cec5SDimitry Andric for (size_t I = 0; I < OriginalPaths.size(); ++I) {
3290b57cec5SDimitry Andric StringRef Path = Strings.save(StringRef(OriginalPaths[I]).lower());
3300b57cec5SDimitry Andric
3310b57cec5SDimitry Andric Paths.emplace_back(Path, I);
3320b57cec5SDimitry Andric Types.push_back(foldType(guessType(Path)));
3330b57cec5SDimitry Andric Stems.emplace_back(sys::path::stem(Path), I);
3340b57cec5SDimitry Andric auto Dir = ++sys::path::rbegin(Path), DirEnd = sys::path::rend(Path);
3350b57cec5SDimitry Andric for (int J = 0; J < DirectorySegmentsIndexed && Dir != DirEnd; ++J, ++Dir)
3360b57cec5SDimitry Andric if (Dir->size() > ShortDirectorySegment) // not trivial ones
3370b57cec5SDimitry Andric Components.emplace_back(*Dir, I);
3380b57cec5SDimitry Andric }
3390b57cec5SDimitry Andric llvm::sort(Paths);
3400b57cec5SDimitry Andric llvm::sort(Stems);
3410b57cec5SDimitry Andric llvm::sort(Components);
3420b57cec5SDimitry Andric }
3430b57cec5SDimitry Andric
empty() const3440b57cec5SDimitry Andric bool empty() const { return Paths.empty(); }
3450b57cec5SDimitry Andric
3460b57cec5SDimitry Andric // Returns the path for the file that best fits OriginalFilename.
3470b57cec5SDimitry Andric // Candidates with extensions matching PreferLanguage will be chosen over
3480b57cec5SDimitry Andric // others (unless it's TY_INVALID, or all candidates are bad).
chooseProxy(StringRef OriginalFilename,types::ID PreferLanguage) const3490b57cec5SDimitry Andric StringRef chooseProxy(StringRef OriginalFilename,
3500b57cec5SDimitry Andric types::ID PreferLanguage) const {
3510b57cec5SDimitry Andric assert(!empty() && "need at least one candidate!");
3520b57cec5SDimitry Andric std::string Filename = OriginalFilename.lower();
3530b57cec5SDimitry Andric auto Candidates = scoreCandidates(Filename);
3540b57cec5SDimitry Andric std::pair<size_t, int> Best =
3550b57cec5SDimitry Andric pickWinner(Candidates, Filename, PreferLanguage);
3560b57cec5SDimitry Andric
3570b57cec5SDimitry Andric DEBUG_WITH_TYPE(
3580b57cec5SDimitry Andric "interpolate",
3590b57cec5SDimitry Andric llvm::dbgs() << "interpolate: chose " << OriginalPaths[Best.first]
3600b57cec5SDimitry Andric << " as proxy for " << OriginalFilename << " preferring "
3610b57cec5SDimitry Andric << (PreferLanguage == types::TY_INVALID
3620b57cec5SDimitry Andric ? "none"
3630b57cec5SDimitry Andric : types::getTypeName(PreferLanguage))
3640b57cec5SDimitry Andric << " score=" << Best.second << "\n");
3650b57cec5SDimitry Andric return OriginalPaths[Best.first];
3660b57cec5SDimitry Andric }
3670b57cec5SDimitry Andric
3680b57cec5SDimitry Andric private:
3690b57cec5SDimitry Andric using SubstringAndIndex = std::pair<StringRef, size_t>;
3700b57cec5SDimitry Andric // Directory matching parameters: we look at the last two segments of the
3710b57cec5SDimitry Andric // parent directory (usually the semantically significant ones in practice).
3720b57cec5SDimitry Andric // We search only the last four of each candidate (for efficiency).
3730b57cec5SDimitry Andric constexpr static int DirectorySegmentsIndexed = 4;
3740b57cec5SDimitry Andric constexpr static int DirectorySegmentsQueried = 2;
3750b57cec5SDimitry Andric constexpr static int ShortDirectorySegment = 1; // Only look at longer names.
3760b57cec5SDimitry Andric
3770b57cec5SDimitry Andric // Award points to candidate entries that should be considered for the file.
3780b57cec5SDimitry Andric // Returned keys are indexes into paths, and the values are (nonzero) scores.
scoreCandidates(StringRef Filename) const3790b57cec5SDimitry Andric DenseMap<size_t, int> scoreCandidates(StringRef Filename) const {
3800b57cec5SDimitry Andric // Decompose Filename into the parts we care about.
3810b57cec5SDimitry Andric // /some/path/complicated/project/Interesting.h
3820b57cec5SDimitry Andric // [-prefix--][---dir---] [-dir-] [--stem---]
3830b57cec5SDimitry Andric StringRef Stem = sys::path::stem(Filename);
3840b57cec5SDimitry Andric llvm::SmallVector<StringRef, DirectorySegmentsQueried> Dirs;
3850b57cec5SDimitry Andric llvm::StringRef Prefix;
3860b57cec5SDimitry Andric auto Dir = ++sys::path::rbegin(Filename),
3870b57cec5SDimitry Andric DirEnd = sys::path::rend(Filename);
3880b57cec5SDimitry Andric for (int I = 0; I < DirectorySegmentsQueried && Dir != DirEnd; ++I, ++Dir) {
3890b57cec5SDimitry Andric if (Dir->size() > ShortDirectorySegment)
3900b57cec5SDimitry Andric Dirs.push_back(*Dir);
3910b57cec5SDimitry Andric Prefix = Filename.substr(0, Dir - DirEnd);
3920b57cec5SDimitry Andric }
3930b57cec5SDimitry Andric
3940b57cec5SDimitry Andric // Now award points based on lookups into our various indexes.
3950b57cec5SDimitry Andric DenseMap<size_t, int> Candidates; // Index -> score.
3960b57cec5SDimitry Andric auto Award = [&](int Points, ArrayRef<SubstringAndIndex> Range) {
3970b57cec5SDimitry Andric for (const auto &Entry : Range)
3980b57cec5SDimitry Andric Candidates[Entry.second] += Points;
3990b57cec5SDimitry Andric };
4000b57cec5SDimitry Andric // Award one point if the file's basename is a prefix of the candidate,
4010b57cec5SDimitry Andric // and another if it's an exact match (so exact matches get two points).
4020b57cec5SDimitry Andric Award(1, indexLookup</*Prefix=*/true>(Stem, Stems));
4030b57cec5SDimitry Andric Award(1, indexLookup</*Prefix=*/false>(Stem, Stems));
4040b57cec5SDimitry Andric // For each of the last few directories in the Filename, award a point
4050b57cec5SDimitry Andric // if it's present in the candidate.
4060b57cec5SDimitry Andric for (StringRef Dir : Dirs)
4070b57cec5SDimitry Andric Award(1, indexLookup</*Prefix=*/false>(Dir, Components));
4080b57cec5SDimitry Andric // Award one more point if the whole rest of the path matches.
4090b57cec5SDimitry Andric if (sys::path::root_directory(Prefix) != Prefix)
4100b57cec5SDimitry Andric Award(1, indexLookup</*Prefix=*/true>(Prefix, Paths));
4110b57cec5SDimitry Andric return Candidates;
4120b57cec5SDimitry Andric }
4130b57cec5SDimitry Andric
4140b57cec5SDimitry Andric // Pick a single winner from the set of scored candidates.
4150b57cec5SDimitry Andric // Returns (index, score).
pickWinner(const DenseMap<size_t,int> & Candidates,StringRef Filename,types::ID PreferredLanguage) const4160b57cec5SDimitry Andric std::pair<size_t, int> pickWinner(const DenseMap<size_t, int> &Candidates,
4170b57cec5SDimitry Andric StringRef Filename,
4180b57cec5SDimitry Andric types::ID PreferredLanguage) const {
4190b57cec5SDimitry Andric struct ScoredCandidate {
4200b57cec5SDimitry Andric size_t Index;
4210b57cec5SDimitry Andric bool Preferred;
4220b57cec5SDimitry Andric int Points;
4230b57cec5SDimitry Andric size_t PrefixLength;
4240b57cec5SDimitry Andric };
4250b57cec5SDimitry Andric // Choose the best candidate by (preferred, points, prefix length, alpha).
4260b57cec5SDimitry Andric ScoredCandidate Best = {size_t(-1), false, 0, 0};
4270b57cec5SDimitry Andric for (const auto &Candidate : Candidates) {
4280b57cec5SDimitry Andric ScoredCandidate S;
4290b57cec5SDimitry Andric S.Index = Candidate.first;
4300b57cec5SDimitry Andric S.Preferred = PreferredLanguage == types::TY_INVALID ||
4310b57cec5SDimitry Andric PreferredLanguage == Types[S.Index];
4320b57cec5SDimitry Andric S.Points = Candidate.second;
4330b57cec5SDimitry Andric if (!S.Preferred && Best.Preferred)
4340b57cec5SDimitry Andric continue;
4350b57cec5SDimitry Andric if (S.Preferred == Best.Preferred) {
4360b57cec5SDimitry Andric if (S.Points < Best.Points)
4370b57cec5SDimitry Andric continue;
4380b57cec5SDimitry Andric if (S.Points == Best.Points) {
4390b57cec5SDimitry Andric S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
4400b57cec5SDimitry Andric if (S.PrefixLength < Best.PrefixLength)
4410b57cec5SDimitry Andric continue;
4420b57cec5SDimitry Andric // hidden heuristics should at least be deterministic!
4430b57cec5SDimitry Andric if (S.PrefixLength == Best.PrefixLength)
4440b57cec5SDimitry Andric if (S.Index > Best.Index)
4450b57cec5SDimitry Andric continue;
4460b57cec5SDimitry Andric }
4470b57cec5SDimitry Andric }
4480b57cec5SDimitry Andric // PrefixLength was only set above if actually needed for a tiebreak.
4490b57cec5SDimitry Andric // But it definitely needs to be set to break ties in the future.
4500b57cec5SDimitry Andric S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
4510b57cec5SDimitry Andric Best = S;
4520b57cec5SDimitry Andric }
4530b57cec5SDimitry Andric // Edge case: no candidate got any points.
4540b57cec5SDimitry Andric // We ignore PreferredLanguage at this point (not ideal).
4550b57cec5SDimitry Andric if (Best.Index == size_t(-1))
4560b57cec5SDimitry Andric return {longestMatch(Filename, Paths).second, 0};
4570b57cec5SDimitry Andric return {Best.Index, Best.Points};
4580b57cec5SDimitry Andric }
4590b57cec5SDimitry Andric
4600b57cec5SDimitry Andric // Returns the range within a sorted index that compares equal to Key.
4610b57cec5SDimitry Andric // If Prefix is true, it's instead the range starting with Key.
4620b57cec5SDimitry Andric template <bool Prefix>
4630b57cec5SDimitry Andric ArrayRef<SubstringAndIndex>
indexLookup(StringRef Key,ArrayRef<SubstringAndIndex> Idx) const4640b57cec5SDimitry Andric indexLookup(StringRef Key, ArrayRef<SubstringAndIndex> Idx) const {
4650b57cec5SDimitry Andric // Use pointers as iteratiors to ease conversion of result to ArrayRef.
4660b57cec5SDimitry Andric auto Range = std::equal_range(Idx.data(), Idx.data() + Idx.size(), Key,
4670b57cec5SDimitry Andric Less<Prefix>());
4680b57cec5SDimitry Andric return {Range.first, Range.second};
4690b57cec5SDimitry Andric }
4700b57cec5SDimitry Andric
4710b57cec5SDimitry Andric // Performs a point lookup into a nonempty index, returning a longest match.
longestMatch(StringRef Key,ArrayRef<SubstringAndIndex> Idx) const4720b57cec5SDimitry Andric SubstringAndIndex longestMatch(StringRef Key,
4730b57cec5SDimitry Andric ArrayRef<SubstringAndIndex> Idx) const {
4740b57cec5SDimitry Andric assert(!Idx.empty());
4750b57cec5SDimitry Andric // Longest substring match will be adjacent to a direct lookup.
4760b57cec5SDimitry Andric auto It = llvm::lower_bound(Idx, SubstringAndIndex{Key, 0});
4770b57cec5SDimitry Andric if (It == Idx.begin())
4780b57cec5SDimitry Andric return *It;
4790b57cec5SDimitry Andric if (It == Idx.end())
4800b57cec5SDimitry Andric return *--It;
4810b57cec5SDimitry Andric // Have to choose between It and It-1
4820b57cec5SDimitry Andric size_t Prefix = matchingPrefix(Key, It->first);
4830b57cec5SDimitry Andric size_t PrevPrefix = matchingPrefix(Key, (It - 1)->first);
4840b57cec5SDimitry Andric return Prefix > PrevPrefix ? *It : *--It;
4850b57cec5SDimitry Andric }
4860b57cec5SDimitry Andric
4870b57cec5SDimitry Andric // Original paths, everything else is in lowercase.
4880b57cec5SDimitry Andric std::vector<std::string> OriginalPaths;
4890b57cec5SDimitry Andric BumpPtrAllocator Arena;
4900b57cec5SDimitry Andric StringSaver Strings;
4910b57cec5SDimitry Andric // Indexes of candidates by certain substrings.
4920b57cec5SDimitry Andric // String is lowercase and sorted, index points into OriginalPaths.
4930b57cec5SDimitry Andric std::vector<SubstringAndIndex> Paths; // Full path.
4940b57cec5SDimitry Andric // Lang types obtained by guessing on the corresponding path. I-th element is
4950b57cec5SDimitry Andric // a type for the I-th path.
4960b57cec5SDimitry Andric std::vector<types::ID> Types;
4970b57cec5SDimitry Andric std::vector<SubstringAndIndex> Stems; // Basename, without extension.
4980b57cec5SDimitry Andric std::vector<SubstringAndIndex> Components; // Last path components.
4990b57cec5SDimitry Andric };
5000b57cec5SDimitry Andric
5010b57cec5SDimitry Andric // The actual CompilationDatabase wrapper delegates to its inner database.
5020b57cec5SDimitry Andric // If no match, looks up a proxy file in FileIndex and transfers its
5030b57cec5SDimitry Andric // command to the requested file.
5040b57cec5SDimitry Andric class InterpolatingCompilationDatabase : public CompilationDatabase {
5050b57cec5SDimitry Andric public:
InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)5060b57cec5SDimitry Andric InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)
5070b57cec5SDimitry Andric : Inner(std::move(Inner)), Index(this->Inner->getAllFiles()) {}
5080b57cec5SDimitry Andric
5090b57cec5SDimitry Andric std::vector<CompileCommand>
getCompileCommands(StringRef Filename) const5100b57cec5SDimitry Andric getCompileCommands(StringRef Filename) const override {
5110b57cec5SDimitry Andric auto Known = Inner->getCompileCommands(Filename);
5120b57cec5SDimitry Andric if (Index.empty() || !Known.empty())
5130b57cec5SDimitry Andric return Known;
5140b57cec5SDimitry Andric bool TypeCertain;
5150b57cec5SDimitry Andric auto Lang = guessType(Filename, &TypeCertain);
5160b57cec5SDimitry Andric if (!TypeCertain)
5170b57cec5SDimitry Andric Lang = types::TY_INVALID;
5180b57cec5SDimitry Andric auto ProxyCommands =
5190b57cec5SDimitry Andric Inner->getCompileCommands(Index.chooseProxy(Filename, foldType(Lang)));
5200b57cec5SDimitry Andric if (ProxyCommands.empty())
5210b57cec5SDimitry Andric return {};
522*5f7ddb14SDimitry Andric return {transferCompileCommand(std::move(ProxyCommands.front()), Filename)};
5230b57cec5SDimitry Andric }
5240b57cec5SDimitry Andric
getAllFiles() const5250b57cec5SDimitry Andric std::vector<std::string> getAllFiles() const override {
5260b57cec5SDimitry Andric return Inner->getAllFiles();
5270b57cec5SDimitry Andric }
5280b57cec5SDimitry Andric
getAllCompileCommands() const5290b57cec5SDimitry Andric std::vector<CompileCommand> getAllCompileCommands() const override {
5300b57cec5SDimitry Andric return Inner->getAllCompileCommands();
5310b57cec5SDimitry Andric }
5320b57cec5SDimitry Andric
5330b57cec5SDimitry Andric private:
5340b57cec5SDimitry Andric std::unique_ptr<CompilationDatabase> Inner;
5350b57cec5SDimitry Andric FileIndex Index;
5360b57cec5SDimitry Andric };
5370b57cec5SDimitry Andric
5380b57cec5SDimitry Andric } // namespace
5390b57cec5SDimitry Andric
5400b57cec5SDimitry Andric std::unique_ptr<CompilationDatabase>
inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner)5410b57cec5SDimitry Andric inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner) {
542a7dea167SDimitry Andric return std::make_unique<InterpolatingCompilationDatabase>(std::move(Inner));
5430b57cec5SDimitry Andric }
5440b57cec5SDimitry Andric
transferCompileCommand(CompileCommand Cmd,StringRef Filename)545*5f7ddb14SDimitry Andric tooling::CompileCommand transferCompileCommand(CompileCommand Cmd,
546*5f7ddb14SDimitry Andric StringRef Filename) {
547*5f7ddb14SDimitry Andric return TransferableCommand(std::move(Cmd)).transferTo(Filename);
548*5f7ddb14SDimitry Andric }
549*5f7ddb14SDimitry Andric
5500b57cec5SDimitry Andric } // namespace tooling
5510b57cec5SDimitry Andric } // namespace clang
552