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"
46fe6060f1SDimitry 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"
50fe6060f1SDimitry Andric #include "llvm/ADT/ArrayRef.h"
510b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
520b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
530b57cec5SDimitry Andric #include "llvm/Option/ArgList.h"
540b57cec5SDimitry Andric #include "llvm/Option/OptTable.h"
550b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
560b57cec5SDimitry Andric #include "llvm/Support/Path.h"
570b57cec5SDimitry Andric #include "llvm/Support/StringSaver.h"
580b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
590b57cec5SDimitry Andric #include <memory>
60bdd1243dSDimitry Andric #include <optional>
610b57cec5SDimitry Andric
620b57cec5SDimitry Andric namespace clang {
630b57cec5SDimitry Andric namespace tooling {
640b57cec5SDimitry Andric namespace {
650b57cec5SDimitry Andric using namespace llvm;
660b57cec5SDimitry Andric namespace types = clang::driver::types;
670b57cec5SDimitry Andric namespace path = llvm::sys::path;
680b57cec5SDimitry Andric
690b57cec5SDimitry Andric // The length of the prefix these two strings have in common.
matchingPrefix(StringRef L,StringRef R)700b57cec5SDimitry Andric size_t matchingPrefix(StringRef L, StringRef R) {
710b57cec5SDimitry Andric size_t Limit = std::min(L.size(), R.size());
720b57cec5SDimitry Andric for (size_t I = 0; I < Limit; ++I)
730b57cec5SDimitry Andric if (L[I] != R[I])
740b57cec5SDimitry Andric return I;
750b57cec5SDimitry Andric return Limit;
760b57cec5SDimitry Andric }
770b57cec5SDimitry Andric
780b57cec5SDimitry Andric // A comparator for searching SubstringWithIndexes with std::equal_range etc.
790b57cec5SDimitry Andric // Optionaly prefix semantics: compares equal if the key is a prefix.
800b57cec5SDimitry Andric template <bool Prefix> struct Less {
operator ()clang::tooling::__anon8a9af54b0111::Less810b57cec5SDimitry Andric bool operator()(StringRef Key, std::pair<StringRef, size_t> Value) const {
820b57cec5SDimitry Andric StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
830b57cec5SDimitry Andric return Key < V;
840b57cec5SDimitry Andric }
operator ()clang::tooling::__anon8a9af54b0111::Less850b57cec5SDimitry Andric bool operator()(std::pair<StringRef, size_t> Value, StringRef Key) const {
860b57cec5SDimitry Andric StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
870b57cec5SDimitry Andric return V < Key;
880b57cec5SDimitry Andric }
890b57cec5SDimitry Andric };
900b57cec5SDimitry Andric
910b57cec5SDimitry Andric // Infer type from filename. If we might have gotten it wrong, set *Certain.
920b57cec5SDimitry Andric // *.h will be inferred as a C header, but not certain.
guessType(StringRef Filename,bool * Certain=nullptr)930b57cec5SDimitry Andric types::ID guessType(StringRef Filename, bool *Certain = nullptr) {
940b57cec5SDimitry Andric // path::extension is ".cpp", lookupTypeForExtension wants "cpp".
950b57cec5SDimitry Andric auto Lang =
960b57cec5SDimitry Andric types::lookupTypeForExtension(path::extension(Filename).substr(1));
970b57cec5SDimitry Andric if (Certain)
980b57cec5SDimitry Andric *Certain = Lang != types::TY_CHeader && Lang != types::TY_INVALID;
990b57cec5SDimitry Andric return Lang;
1000b57cec5SDimitry Andric }
1010b57cec5SDimitry Andric
1020b57cec5SDimitry Andric // Return Lang as one of the canonical supported types.
1030b57cec5SDimitry Andric // e.g. c-header --> c; fortran --> TY_INVALID
foldType(types::ID Lang)1040b57cec5SDimitry Andric static types::ID foldType(types::ID Lang) {
1050b57cec5SDimitry Andric switch (Lang) {
1060b57cec5SDimitry Andric case types::TY_C:
1070b57cec5SDimitry Andric case types::TY_CHeader:
1080b57cec5SDimitry Andric return types::TY_C;
1090b57cec5SDimitry Andric case types::TY_ObjC:
1100b57cec5SDimitry Andric case types::TY_ObjCHeader:
1110b57cec5SDimitry Andric return types::TY_ObjC;
1120b57cec5SDimitry Andric case types::TY_CXX:
1130b57cec5SDimitry Andric case types::TY_CXXHeader:
1140b57cec5SDimitry Andric return types::TY_CXX;
1150b57cec5SDimitry Andric case types::TY_ObjCXX:
1160b57cec5SDimitry Andric case types::TY_ObjCXXHeader:
1170b57cec5SDimitry Andric return types::TY_ObjCXX;
1185ffd83dbSDimitry Andric case types::TY_CUDA:
1195ffd83dbSDimitry Andric case types::TY_CUDA_DEVICE:
1205ffd83dbSDimitry Andric return types::TY_CUDA;
1210b57cec5SDimitry Andric default:
1220b57cec5SDimitry Andric return types::TY_INVALID;
1230b57cec5SDimitry Andric }
1240b57cec5SDimitry Andric }
1250b57cec5SDimitry Andric
1260b57cec5SDimitry Andric // A CompileCommand that can be applied to another file.
1270b57cec5SDimitry Andric struct TransferableCommand {
1280b57cec5SDimitry Andric // Flags that should not apply to all files are stripped from CommandLine.
1290b57cec5SDimitry Andric CompileCommand Cmd;
1300b57cec5SDimitry Andric // Language detected from -x or the filename. Never TY_INVALID.
131bdd1243dSDimitry Andric std::optional<types::ID> Type;
1320b57cec5SDimitry Andric // Standard specified by -std.
1330b57cec5SDimitry Andric LangStandard::Kind Std = LangStandard::lang_unspecified;
1340b57cec5SDimitry Andric // Whether the command line is for the cl-compatible driver.
1350b57cec5SDimitry Andric bool ClangCLMode;
1360b57cec5SDimitry Andric
TransferableCommandclang::tooling::__anon8a9af54b0111::TransferableCommand1370b57cec5SDimitry Andric TransferableCommand(CompileCommand C)
138fe6060f1SDimitry Andric : Cmd(std::move(C)), Type(guessType(Cmd.Filename)) {
1390b57cec5SDimitry Andric std::vector<std::string> OldArgs = std::move(Cmd.CommandLine);
1400b57cec5SDimitry Andric Cmd.CommandLine.clear();
1410b57cec5SDimitry Andric
1420b57cec5SDimitry Andric // Wrap the old arguments in an InputArgList.
1430b57cec5SDimitry Andric llvm::opt::InputArgList ArgList;
1440b57cec5SDimitry Andric {
1450b57cec5SDimitry Andric SmallVector<const char *, 16> TmpArgv;
1460b57cec5SDimitry Andric for (const std::string &S : OldArgs)
1470b57cec5SDimitry Andric TmpArgv.push_back(S.c_str());
148fe6060f1SDimitry Andric ClangCLMode = !TmpArgv.empty() &&
149fe6060f1SDimitry Andric driver::IsClangCL(driver::getDriverMode(
150bdd1243dSDimitry Andric TmpArgv.front(), llvm::ArrayRef(TmpArgv).slice(1)));
1510b57cec5SDimitry Andric ArgList = {TmpArgv.begin(), TmpArgv.end()};
1520b57cec5SDimitry Andric }
1530b57cec5SDimitry Andric
1540b57cec5SDimitry Andric // Parse the old args in order to strip out and record unwanted flags.
1550b57cec5SDimitry Andric // We parse each argument individually so that we can retain the exact
1560b57cec5SDimitry Andric // spelling of each argument; re-rendering is lossy for aliased flags.
1570b57cec5SDimitry Andric // E.g. in CL mode, /W4 maps to -Wall.
158a7dea167SDimitry Andric auto &OptTable = clang::driver::getDriverOptTable();
1590b57cec5SDimitry Andric if (!OldArgs.empty())
1600b57cec5SDimitry Andric Cmd.CommandLine.emplace_back(OldArgs.front());
1610b57cec5SDimitry Andric for (unsigned Pos = 1; Pos < OldArgs.size();) {
1620b57cec5SDimitry Andric using namespace driver::options;
1630b57cec5SDimitry Andric
1640b57cec5SDimitry Andric const unsigned OldPos = Pos;
165a7dea167SDimitry Andric std::unique_ptr<llvm::opt::Arg> Arg(OptTable.ParseOneArg(
1660b57cec5SDimitry Andric ArgList, Pos,
167*5f757f3fSDimitry Andric llvm::opt::Visibility(ClangCLMode ? CLOption : ClangOption)));
1680b57cec5SDimitry Andric
1690b57cec5SDimitry Andric if (!Arg)
1700b57cec5SDimitry Andric continue;
1710b57cec5SDimitry Andric
1720b57cec5SDimitry Andric const llvm::opt::Option &Opt = Arg->getOption();
1730b57cec5SDimitry Andric
1740b57cec5SDimitry Andric // Strip input and output files.
1750b57cec5SDimitry Andric if (Opt.matches(OPT_INPUT) || Opt.matches(OPT_o) ||
1760b57cec5SDimitry Andric (ClangCLMode && (Opt.matches(OPT__SLASH_Fa) ||
1770b57cec5SDimitry Andric Opt.matches(OPT__SLASH_Fe) ||
1780b57cec5SDimitry Andric Opt.matches(OPT__SLASH_Fi) ||
1790b57cec5SDimitry Andric Opt.matches(OPT__SLASH_Fo))))
1800b57cec5SDimitry Andric continue;
1810b57cec5SDimitry Andric
182fe6060f1SDimitry Andric // ...including when the inputs are passed after --.
183fe6060f1SDimitry Andric if (Opt.matches(OPT__DASH_DASH))
184fe6060f1SDimitry Andric break;
185fe6060f1SDimitry Andric
1860b57cec5SDimitry Andric // Strip -x, but record the overridden language.
1870b57cec5SDimitry Andric if (const auto GivenType = tryParseTypeArg(*Arg)) {
1880b57cec5SDimitry Andric Type = *GivenType;
1890b57cec5SDimitry Andric continue;
1900b57cec5SDimitry Andric }
1910b57cec5SDimitry Andric
1920b57cec5SDimitry Andric // Strip -std, but record the value.
1930b57cec5SDimitry Andric if (const auto GivenStd = tryParseStdArg(*Arg)) {
1940b57cec5SDimitry Andric if (*GivenStd != LangStandard::lang_unspecified)
1950b57cec5SDimitry Andric Std = *GivenStd;
1960b57cec5SDimitry Andric continue;
1970b57cec5SDimitry Andric }
1980b57cec5SDimitry Andric
1990b57cec5SDimitry Andric Cmd.CommandLine.insert(Cmd.CommandLine.end(),
2000b57cec5SDimitry Andric OldArgs.data() + OldPos, OldArgs.data() + Pos);
2010b57cec5SDimitry Andric }
2020b57cec5SDimitry Andric
203480093f4SDimitry Andric // Make use of -std iff -x was missing.
204480093f4SDimitry Andric if (Type == types::TY_INVALID && Std != LangStandard::lang_unspecified)
2050b57cec5SDimitry Andric Type = toType(LangStandard::getLangStandardForKind(Std).getLanguage());
2060b57cec5SDimitry Andric Type = foldType(*Type);
2070b57cec5SDimitry Andric // The contract is to store None instead of TY_INVALID.
2080b57cec5SDimitry Andric if (Type == types::TY_INVALID)
209bdd1243dSDimitry Andric Type = std::nullopt;
2100b57cec5SDimitry Andric }
2110b57cec5SDimitry Andric
2120b57cec5SDimitry Andric // Produce a CompileCommand for \p filename, based on this one.
213fe6060f1SDimitry Andric // (This consumes the TransferableCommand just to avoid copying Cmd).
transferToclang::tooling::__anon8a9af54b0111::TransferableCommand214fe6060f1SDimitry Andric CompileCommand transferTo(StringRef Filename) && {
215fe6060f1SDimitry Andric CompileCommand Result = std::move(Cmd);
216fe6060f1SDimitry Andric Result.Heuristic = "inferred from " + Result.Filename;
2175ffd83dbSDimitry Andric Result.Filename = std::string(Filename);
2180b57cec5SDimitry Andric bool TypeCertain;
2190b57cec5SDimitry Andric auto TargetType = guessType(Filename, &TypeCertain);
2200b57cec5SDimitry Andric // If the filename doesn't determine the language (.h), transfer with -x.
2210b57cec5SDimitry Andric if ((!TargetType || !TypeCertain) && Type) {
2220b57cec5SDimitry Andric // Use *Type, or its header variant if the file is a header.
2230b57cec5SDimitry Andric // Treat no/invalid extension as header (e.g. C++ standard library).
2240b57cec5SDimitry Andric TargetType =
2250b57cec5SDimitry Andric (!TargetType || types::onlyPrecompileType(TargetType)) // header?
2260b57cec5SDimitry Andric ? types::lookupHeaderTypeForSourceType(*Type)
2270b57cec5SDimitry Andric : *Type;
2280b57cec5SDimitry Andric if (ClangCLMode) {
2290b57cec5SDimitry Andric const StringRef Flag = toCLFlag(TargetType);
2300b57cec5SDimitry Andric if (!Flag.empty())
2315ffd83dbSDimitry Andric Result.CommandLine.push_back(std::string(Flag));
2320b57cec5SDimitry Andric } else {
2330b57cec5SDimitry Andric Result.CommandLine.push_back("-x");
2340b57cec5SDimitry Andric Result.CommandLine.push_back(types::getTypeName(TargetType));
2350b57cec5SDimitry Andric }
2360b57cec5SDimitry Andric }
2370b57cec5SDimitry Andric // --std flag may only be transferred if the language is the same.
2380b57cec5SDimitry Andric // We may consider "translating" these, e.g. c++11 -> c11.
2390b57cec5SDimitry Andric if (Std != LangStandard::lang_unspecified && foldType(TargetType) == Type) {
2400b57cec5SDimitry Andric Result.CommandLine.emplace_back((
2410b57cec5SDimitry Andric llvm::Twine(ClangCLMode ? "/std:" : "-std=") +
2420b57cec5SDimitry Andric LangStandard::getLangStandardForKind(Std).getName()).str());
2430b57cec5SDimitry Andric }
244fe6060f1SDimitry Andric Result.CommandLine.push_back("--");
2455ffd83dbSDimitry Andric Result.CommandLine.push_back(std::string(Filename));
2460b57cec5SDimitry Andric return Result;
2470b57cec5SDimitry Andric }
2480b57cec5SDimitry Andric
2490b57cec5SDimitry Andric private:
2500b57cec5SDimitry Andric // Map the language from the --std flag to that of the -x flag.
toTypeclang::tooling::__anon8a9af54b0111::TransferableCommand251a7dea167SDimitry Andric static types::ID toType(Language Lang) {
2520b57cec5SDimitry Andric switch (Lang) {
253a7dea167SDimitry Andric case Language::C:
2540b57cec5SDimitry Andric return types::TY_C;
255a7dea167SDimitry Andric case Language::CXX:
2560b57cec5SDimitry Andric return types::TY_CXX;
257a7dea167SDimitry Andric case Language::ObjC:
2580b57cec5SDimitry Andric return types::TY_ObjC;
259a7dea167SDimitry Andric case Language::ObjCXX:
2600b57cec5SDimitry Andric return types::TY_ObjCXX;
2610b57cec5SDimitry Andric default:
2620b57cec5SDimitry Andric return types::TY_INVALID;
2630b57cec5SDimitry Andric }
2640b57cec5SDimitry Andric }
2650b57cec5SDimitry Andric
2660b57cec5SDimitry Andric // Convert a file type to the matching CL-style type flag.
toCLFlagclang::tooling::__anon8a9af54b0111::TransferableCommand2670b57cec5SDimitry Andric static StringRef toCLFlag(types::ID Type) {
2680b57cec5SDimitry Andric switch (Type) {
2690b57cec5SDimitry Andric case types::TY_C:
2700b57cec5SDimitry Andric case types::TY_CHeader:
2710b57cec5SDimitry Andric return "/TC";
2720b57cec5SDimitry Andric case types::TY_CXX:
2730b57cec5SDimitry Andric case types::TY_CXXHeader:
2740b57cec5SDimitry Andric return "/TP";
2750b57cec5SDimitry Andric default:
2760b57cec5SDimitry Andric return StringRef();
2770b57cec5SDimitry Andric }
2780b57cec5SDimitry Andric }
2790b57cec5SDimitry Andric
2800b57cec5SDimitry Andric // Try to interpret the argument as a type specifier, e.g. '-x'.
tryParseTypeArgclang::tooling::__anon8a9af54b0111::TransferableCommand281bdd1243dSDimitry Andric std::optional<types::ID> tryParseTypeArg(const llvm::opt::Arg &Arg) {
2820b57cec5SDimitry Andric const llvm::opt::Option &Opt = Arg.getOption();
2830b57cec5SDimitry Andric using namespace driver::options;
2840b57cec5SDimitry Andric if (ClangCLMode) {
2850b57cec5SDimitry Andric if (Opt.matches(OPT__SLASH_TC) || Opt.matches(OPT__SLASH_Tc))
2860b57cec5SDimitry Andric return types::TY_C;
2870b57cec5SDimitry Andric if (Opt.matches(OPT__SLASH_TP) || Opt.matches(OPT__SLASH_Tp))
2880b57cec5SDimitry Andric return types::TY_CXX;
2890b57cec5SDimitry Andric } else {
2900b57cec5SDimitry Andric if (Opt.matches(driver::options::OPT_x))
2910b57cec5SDimitry Andric return types::lookupTypeForTypeSpecifier(Arg.getValue());
2920b57cec5SDimitry Andric }
293bdd1243dSDimitry Andric return std::nullopt;
2940b57cec5SDimitry Andric }
2950b57cec5SDimitry Andric
2960b57cec5SDimitry Andric // Try to interpret the argument as '-std='.
tryParseStdArgclang::tooling::__anon8a9af54b0111::TransferableCommand297bdd1243dSDimitry Andric std::optional<LangStandard::Kind> tryParseStdArg(const llvm::opt::Arg &Arg) {
2980b57cec5SDimitry Andric using namespace driver::options;
299a7dea167SDimitry Andric if (Arg.getOption().matches(ClangCLMode ? OPT__SLASH_std : OPT_std_EQ))
300a7dea167SDimitry Andric return LangStandard::getLangKind(Arg.getValue());
301bdd1243dSDimitry Andric return std::nullopt;
3020b57cec5SDimitry Andric }
3030b57cec5SDimitry Andric };
3040b57cec5SDimitry Andric
3050b57cec5SDimitry Andric // Given a filename, FileIndex picks the best matching file from the underlying
3060b57cec5SDimitry Andric // DB. This is the proxy file whose CompileCommand will be reused. The
3070b57cec5SDimitry Andric // heuristics incorporate file name, extension, and directory structure.
3080b57cec5SDimitry Andric // Strategy:
3090b57cec5SDimitry Andric // - Build indexes of each of the substrings we want to look up by.
3100b57cec5SDimitry Andric // These indexes are just sorted lists of the substrings.
3110b57cec5SDimitry Andric // - Each criterion corresponds to a range lookup into the index, so we only
3120b57cec5SDimitry Andric // need O(log N) string comparisons to determine scores.
3130b57cec5SDimitry Andric //
3140b57cec5SDimitry Andric // Apart from path proximity signals, also takes file extensions into account
3150b57cec5SDimitry Andric // when scoring the candidates.
3160b57cec5SDimitry Andric class FileIndex {
3170b57cec5SDimitry Andric public:
FileIndex(std::vector<std::string> Files)3180b57cec5SDimitry Andric FileIndex(std::vector<std::string> Files)
3190b57cec5SDimitry Andric : OriginalPaths(std::move(Files)), Strings(Arena) {
3200b57cec5SDimitry Andric // Sort commands by filename for determinism (index is a tiebreaker later).
3210b57cec5SDimitry Andric llvm::sort(OriginalPaths);
3220b57cec5SDimitry Andric Paths.reserve(OriginalPaths.size());
3230b57cec5SDimitry Andric Types.reserve(OriginalPaths.size());
3240b57cec5SDimitry Andric Stems.reserve(OriginalPaths.size());
3250b57cec5SDimitry Andric for (size_t I = 0; I < OriginalPaths.size(); ++I) {
3260b57cec5SDimitry Andric StringRef Path = Strings.save(StringRef(OriginalPaths[I]).lower());
3270b57cec5SDimitry Andric
3280b57cec5SDimitry Andric Paths.emplace_back(Path, I);
32981ad6265SDimitry Andric Types.push_back(foldType(guessType(OriginalPaths[I])));
3300b57cec5SDimitry Andric Stems.emplace_back(sys::path::stem(Path), I);
3310b57cec5SDimitry Andric auto Dir = ++sys::path::rbegin(Path), DirEnd = sys::path::rend(Path);
3320b57cec5SDimitry Andric for (int J = 0; J < DirectorySegmentsIndexed && Dir != DirEnd; ++J, ++Dir)
3330b57cec5SDimitry Andric if (Dir->size() > ShortDirectorySegment) // not trivial ones
3340b57cec5SDimitry Andric Components.emplace_back(*Dir, I);
3350b57cec5SDimitry Andric }
3360b57cec5SDimitry Andric llvm::sort(Paths);
3370b57cec5SDimitry Andric llvm::sort(Stems);
3380b57cec5SDimitry Andric llvm::sort(Components);
3390b57cec5SDimitry Andric }
3400b57cec5SDimitry Andric
empty() const3410b57cec5SDimitry Andric bool empty() const { return Paths.empty(); }
3420b57cec5SDimitry Andric
3430b57cec5SDimitry Andric // Returns the path for the file that best fits OriginalFilename.
3440b57cec5SDimitry Andric // Candidates with extensions matching PreferLanguage will be chosen over
3450b57cec5SDimitry Andric // others (unless it's TY_INVALID, or all candidates are bad).
chooseProxy(StringRef OriginalFilename,types::ID PreferLanguage) const3460b57cec5SDimitry Andric StringRef chooseProxy(StringRef OriginalFilename,
3470b57cec5SDimitry Andric types::ID PreferLanguage) const {
3480b57cec5SDimitry Andric assert(!empty() && "need at least one candidate!");
3490b57cec5SDimitry Andric std::string Filename = OriginalFilename.lower();
3500b57cec5SDimitry Andric auto Candidates = scoreCandidates(Filename);
3510b57cec5SDimitry Andric std::pair<size_t, int> Best =
3520b57cec5SDimitry Andric pickWinner(Candidates, Filename, PreferLanguage);
3530b57cec5SDimitry Andric
3540b57cec5SDimitry Andric DEBUG_WITH_TYPE(
3550b57cec5SDimitry Andric "interpolate",
3560b57cec5SDimitry Andric llvm::dbgs() << "interpolate: chose " << OriginalPaths[Best.first]
3570b57cec5SDimitry Andric << " as proxy for " << OriginalFilename << " preferring "
3580b57cec5SDimitry Andric << (PreferLanguage == types::TY_INVALID
3590b57cec5SDimitry Andric ? "none"
3600b57cec5SDimitry Andric : types::getTypeName(PreferLanguage))
3610b57cec5SDimitry Andric << " score=" << Best.second << "\n");
3620b57cec5SDimitry Andric return OriginalPaths[Best.first];
3630b57cec5SDimitry Andric }
3640b57cec5SDimitry Andric
3650b57cec5SDimitry Andric private:
3660b57cec5SDimitry Andric using SubstringAndIndex = std::pair<StringRef, size_t>;
3670b57cec5SDimitry Andric // Directory matching parameters: we look at the last two segments of the
3680b57cec5SDimitry Andric // parent directory (usually the semantically significant ones in practice).
3690b57cec5SDimitry Andric // We search only the last four of each candidate (for efficiency).
3700b57cec5SDimitry Andric constexpr static int DirectorySegmentsIndexed = 4;
3710b57cec5SDimitry Andric constexpr static int DirectorySegmentsQueried = 2;
3720b57cec5SDimitry Andric constexpr static int ShortDirectorySegment = 1; // Only look at longer names.
3730b57cec5SDimitry Andric
3740b57cec5SDimitry Andric // Award points to candidate entries that should be considered for the file.
3750b57cec5SDimitry Andric // Returned keys are indexes into paths, and the values are (nonzero) scores.
scoreCandidates(StringRef Filename) const3760b57cec5SDimitry Andric DenseMap<size_t, int> scoreCandidates(StringRef Filename) const {
3770b57cec5SDimitry Andric // Decompose Filename into the parts we care about.
3780b57cec5SDimitry Andric // /some/path/complicated/project/Interesting.h
3790b57cec5SDimitry Andric // [-prefix--][---dir---] [-dir-] [--stem---]
3800b57cec5SDimitry Andric StringRef Stem = sys::path::stem(Filename);
3810b57cec5SDimitry Andric llvm::SmallVector<StringRef, DirectorySegmentsQueried> Dirs;
3820b57cec5SDimitry Andric llvm::StringRef Prefix;
3830b57cec5SDimitry Andric auto Dir = ++sys::path::rbegin(Filename),
3840b57cec5SDimitry Andric DirEnd = sys::path::rend(Filename);
3850b57cec5SDimitry Andric for (int I = 0; I < DirectorySegmentsQueried && Dir != DirEnd; ++I, ++Dir) {
3860b57cec5SDimitry Andric if (Dir->size() > ShortDirectorySegment)
3870b57cec5SDimitry Andric Dirs.push_back(*Dir);
3880b57cec5SDimitry Andric Prefix = Filename.substr(0, Dir - DirEnd);
3890b57cec5SDimitry Andric }
3900b57cec5SDimitry Andric
3910b57cec5SDimitry Andric // Now award points based on lookups into our various indexes.
3920b57cec5SDimitry Andric DenseMap<size_t, int> Candidates; // Index -> score.
3930b57cec5SDimitry Andric auto Award = [&](int Points, ArrayRef<SubstringAndIndex> Range) {
3940b57cec5SDimitry Andric for (const auto &Entry : Range)
3950b57cec5SDimitry Andric Candidates[Entry.second] += Points;
3960b57cec5SDimitry Andric };
3970b57cec5SDimitry Andric // Award one point if the file's basename is a prefix of the candidate,
3980b57cec5SDimitry Andric // and another if it's an exact match (so exact matches get two points).
3990b57cec5SDimitry Andric Award(1, indexLookup</*Prefix=*/true>(Stem, Stems));
4000b57cec5SDimitry Andric Award(1, indexLookup</*Prefix=*/false>(Stem, Stems));
4010b57cec5SDimitry Andric // For each of the last few directories in the Filename, award a point
4020b57cec5SDimitry Andric // if it's present in the candidate.
4030b57cec5SDimitry Andric for (StringRef Dir : Dirs)
4040b57cec5SDimitry Andric Award(1, indexLookup</*Prefix=*/false>(Dir, Components));
4050b57cec5SDimitry Andric // Award one more point if the whole rest of the path matches.
4060b57cec5SDimitry Andric if (sys::path::root_directory(Prefix) != Prefix)
4070b57cec5SDimitry Andric Award(1, indexLookup</*Prefix=*/true>(Prefix, Paths));
4080b57cec5SDimitry Andric return Candidates;
4090b57cec5SDimitry Andric }
4100b57cec5SDimitry Andric
4110b57cec5SDimitry Andric // Pick a single winner from the set of scored candidates.
4120b57cec5SDimitry Andric // Returns (index, score).
pickWinner(const DenseMap<size_t,int> & Candidates,StringRef Filename,types::ID PreferredLanguage) const4130b57cec5SDimitry Andric std::pair<size_t, int> pickWinner(const DenseMap<size_t, int> &Candidates,
4140b57cec5SDimitry Andric StringRef Filename,
4150b57cec5SDimitry Andric types::ID PreferredLanguage) const {
4160b57cec5SDimitry Andric struct ScoredCandidate {
4170b57cec5SDimitry Andric size_t Index;
4180b57cec5SDimitry Andric bool Preferred;
4190b57cec5SDimitry Andric int Points;
4200b57cec5SDimitry Andric size_t PrefixLength;
4210b57cec5SDimitry Andric };
4220b57cec5SDimitry Andric // Choose the best candidate by (preferred, points, prefix length, alpha).
4230b57cec5SDimitry Andric ScoredCandidate Best = {size_t(-1), false, 0, 0};
4240b57cec5SDimitry Andric for (const auto &Candidate : Candidates) {
4250b57cec5SDimitry Andric ScoredCandidate S;
4260b57cec5SDimitry Andric S.Index = Candidate.first;
4270b57cec5SDimitry Andric S.Preferred = PreferredLanguage == types::TY_INVALID ||
4280b57cec5SDimitry Andric PreferredLanguage == Types[S.Index];
4290b57cec5SDimitry Andric S.Points = Candidate.second;
4300b57cec5SDimitry Andric if (!S.Preferred && Best.Preferred)
4310b57cec5SDimitry Andric continue;
4320b57cec5SDimitry Andric if (S.Preferred == Best.Preferred) {
4330b57cec5SDimitry Andric if (S.Points < Best.Points)
4340b57cec5SDimitry Andric continue;
4350b57cec5SDimitry Andric if (S.Points == Best.Points) {
4360b57cec5SDimitry Andric S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
4370b57cec5SDimitry Andric if (S.PrefixLength < Best.PrefixLength)
4380b57cec5SDimitry Andric continue;
4390b57cec5SDimitry Andric // hidden heuristics should at least be deterministic!
4400b57cec5SDimitry Andric if (S.PrefixLength == Best.PrefixLength)
4410b57cec5SDimitry Andric if (S.Index > Best.Index)
4420b57cec5SDimitry Andric continue;
4430b57cec5SDimitry Andric }
4440b57cec5SDimitry Andric }
4450b57cec5SDimitry Andric // PrefixLength was only set above if actually needed for a tiebreak.
4460b57cec5SDimitry Andric // But it definitely needs to be set to break ties in the future.
4470b57cec5SDimitry Andric S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
4480b57cec5SDimitry Andric Best = S;
4490b57cec5SDimitry Andric }
4500b57cec5SDimitry Andric // Edge case: no candidate got any points.
4510b57cec5SDimitry Andric // We ignore PreferredLanguage at this point (not ideal).
4520b57cec5SDimitry Andric if (Best.Index == size_t(-1))
4530b57cec5SDimitry Andric return {longestMatch(Filename, Paths).second, 0};
4540b57cec5SDimitry Andric return {Best.Index, Best.Points};
4550b57cec5SDimitry Andric }
4560b57cec5SDimitry Andric
4570b57cec5SDimitry Andric // Returns the range within a sorted index that compares equal to Key.
4580b57cec5SDimitry Andric // If Prefix is true, it's instead the range starting with Key.
4590b57cec5SDimitry Andric template <bool Prefix>
4600b57cec5SDimitry Andric ArrayRef<SubstringAndIndex>
indexLookup(StringRef Key,ArrayRef<SubstringAndIndex> Idx) const4610b57cec5SDimitry Andric indexLookup(StringRef Key, ArrayRef<SubstringAndIndex> Idx) const {
4620b57cec5SDimitry Andric // Use pointers as iteratiors to ease conversion of result to ArrayRef.
4630b57cec5SDimitry Andric auto Range = std::equal_range(Idx.data(), Idx.data() + Idx.size(), Key,
4640b57cec5SDimitry Andric Less<Prefix>());
4650b57cec5SDimitry Andric return {Range.first, Range.second};
4660b57cec5SDimitry Andric }
4670b57cec5SDimitry Andric
4680b57cec5SDimitry Andric // Performs a point lookup into a nonempty index, returning a longest match.
longestMatch(StringRef Key,ArrayRef<SubstringAndIndex> Idx) const4690b57cec5SDimitry Andric SubstringAndIndex longestMatch(StringRef Key,
4700b57cec5SDimitry Andric ArrayRef<SubstringAndIndex> Idx) const {
4710b57cec5SDimitry Andric assert(!Idx.empty());
4720b57cec5SDimitry Andric // Longest substring match will be adjacent to a direct lookup.
4730b57cec5SDimitry Andric auto It = llvm::lower_bound(Idx, SubstringAndIndex{Key, 0});
4740b57cec5SDimitry Andric if (It == Idx.begin())
4750b57cec5SDimitry Andric return *It;
4760b57cec5SDimitry Andric if (It == Idx.end())
4770b57cec5SDimitry Andric return *--It;
4780b57cec5SDimitry Andric // Have to choose between It and It-1
4790b57cec5SDimitry Andric size_t Prefix = matchingPrefix(Key, It->first);
4800b57cec5SDimitry Andric size_t PrevPrefix = matchingPrefix(Key, (It - 1)->first);
4810b57cec5SDimitry Andric return Prefix > PrevPrefix ? *It : *--It;
4820b57cec5SDimitry Andric }
4830b57cec5SDimitry Andric
4840b57cec5SDimitry Andric // Original paths, everything else is in lowercase.
4850b57cec5SDimitry Andric std::vector<std::string> OriginalPaths;
4860b57cec5SDimitry Andric BumpPtrAllocator Arena;
4870b57cec5SDimitry Andric StringSaver Strings;
4880b57cec5SDimitry Andric // Indexes of candidates by certain substrings.
4890b57cec5SDimitry Andric // String is lowercase and sorted, index points into OriginalPaths.
4900b57cec5SDimitry Andric std::vector<SubstringAndIndex> Paths; // Full path.
4910b57cec5SDimitry Andric // Lang types obtained by guessing on the corresponding path. I-th element is
4920b57cec5SDimitry Andric // a type for the I-th path.
4930b57cec5SDimitry Andric std::vector<types::ID> Types;
4940b57cec5SDimitry Andric std::vector<SubstringAndIndex> Stems; // Basename, without extension.
4950b57cec5SDimitry Andric std::vector<SubstringAndIndex> Components; // Last path components.
4960b57cec5SDimitry Andric };
4970b57cec5SDimitry Andric
4980b57cec5SDimitry Andric // The actual CompilationDatabase wrapper delegates to its inner database.
4990b57cec5SDimitry Andric // If no match, looks up a proxy file in FileIndex and transfers its
5000b57cec5SDimitry Andric // command to the requested file.
5010b57cec5SDimitry Andric class InterpolatingCompilationDatabase : public CompilationDatabase {
5020b57cec5SDimitry Andric public:
InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)5030b57cec5SDimitry Andric InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)
5040b57cec5SDimitry Andric : Inner(std::move(Inner)), Index(this->Inner->getAllFiles()) {}
5050b57cec5SDimitry Andric
5060b57cec5SDimitry Andric std::vector<CompileCommand>
getCompileCommands(StringRef Filename) const5070b57cec5SDimitry Andric getCompileCommands(StringRef Filename) const override {
5080b57cec5SDimitry Andric auto Known = Inner->getCompileCommands(Filename);
5090b57cec5SDimitry Andric if (Index.empty() || !Known.empty())
5100b57cec5SDimitry Andric return Known;
5110b57cec5SDimitry Andric bool TypeCertain;
5120b57cec5SDimitry Andric auto Lang = guessType(Filename, &TypeCertain);
5130b57cec5SDimitry Andric if (!TypeCertain)
5140b57cec5SDimitry Andric Lang = types::TY_INVALID;
5150b57cec5SDimitry Andric auto ProxyCommands =
5160b57cec5SDimitry Andric Inner->getCompileCommands(Index.chooseProxy(Filename, foldType(Lang)));
5170b57cec5SDimitry Andric if (ProxyCommands.empty())
5180b57cec5SDimitry Andric return {};
519fe6060f1SDimitry Andric return {transferCompileCommand(std::move(ProxyCommands.front()), Filename)};
5200b57cec5SDimitry Andric }
5210b57cec5SDimitry Andric
getAllFiles() const5220b57cec5SDimitry Andric std::vector<std::string> getAllFiles() const override {
5230b57cec5SDimitry Andric return Inner->getAllFiles();
5240b57cec5SDimitry Andric }
5250b57cec5SDimitry Andric
getAllCompileCommands() const5260b57cec5SDimitry Andric std::vector<CompileCommand> getAllCompileCommands() const override {
5270b57cec5SDimitry Andric return Inner->getAllCompileCommands();
5280b57cec5SDimitry Andric }
5290b57cec5SDimitry Andric
5300b57cec5SDimitry Andric private:
5310b57cec5SDimitry Andric std::unique_ptr<CompilationDatabase> Inner;
5320b57cec5SDimitry Andric FileIndex Index;
5330b57cec5SDimitry Andric };
5340b57cec5SDimitry Andric
5350b57cec5SDimitry Andric } // namespace
5360b57cec5SDimitry Andric
5370b57cec5SDimitry Andric std::unique_ptr<CompilationDatabase>
inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner)5380b57cec5SDimitry Andric inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner) {
539a7dea167SDimitry Andric return std::make_unique<InterpolatingCompilationDatabase>(std::move(Inner));
5400b57cec5SDimitry Andric }
5410b57cec5SDimitry Andric
transferCompileCommand(CompileCommand Cmd,StringRef Filename)542fe6060f1SDimitry Andric tooling::CompileCommand transferCompileCommand(CompileCommand Cmd,
543fe6060f1SDimitry Andric StringRef Filename) {
544fe6060f1SDimitry Andric return TransferableCommand(std::move(Cmd)).transferTo(Filename);
545fe6060f1SDimitry Andric }
546fe6060f1SDimitry Andric
5470b57cec5SDimitry Andric } // namespace tooling
5480b57cec5SDimitry Andric } // namespace clang
549