14ba319b5SDimitry Andric //===- InterpolatingCompilationDatabase.cpp ---------------------*- C++ -*-===//
24ba319b5SDimitry Andric //
34ba319b5SDimitry Andric // The LLVM Compiler Infrastructure
44ba319b5SDimitry Andric //
54ba319b5SDimitry Andric // This file is distributed under the University of Illinois Open Source
64ba319b5SDimitry Andric // License. See LICENSE.TXT for details.
74ba319b5SDimitry Andric //
84ba319b5SDimitry Andric //===----------------------------------------------------------------------===//
94ba319b5SDimitry Andric //
104ba319b5SDimitry Andric // InterpolatingCompilationDatabase wraps another CompilationDatabase and
114ba319b5SDimitry Andric // attempts to heuristically determine appropriate compile commands for files
124ba319b5SDimitry Andric // that are not included, such as headers or newly created files.
134ba319b5SDimitry Andric //
144ba319b5SDimitry Andric // Motivating cases include:
154ba319b5SDimitry Andric // Header files that live next to their implementation files. These typically
164ba319b5SDimitry Andric // share a base filename. (libclang/CXString.h, libclang/CXString.cpp).
174ba319b5SDimitry Andric // Some projects separate headers from includes. Filenames still typically
184ba319b5SDimitry Andric // match, maybe other path segments too. (include/llvm/IR/Use.h, lib/IR/Use.cc).
194ba319b5SDimitry Andric // Matches are sometimes only approximate (Sema.h, SemaDecl.cpp). This goes
204ba319b5SDimitry Andric // for directories too (Support/Unix/Process.inc, lib/Support/Process.cpp).
214ba319b5SDimitry Andric // Even if we can't find a "right" compile command, even a random one from
224ba319b5SDimitry Andric // the project will tend to get important flags like -I and -x right.
234ba319b5SDimitry Andric //
244ba319b5SDimitry Andric // We "borrow" the compile command for the closest available file:
254ba319b5SDimitry Andric // - points are awarded if the filename matches (ignoring extension)
264ba319b5SDimitry Andric // - points are awarded if the directory structure matches
274ba319b5SDimitry Andric // - ties are broken by length of path prefix match
284ba319b5SDimitry Andric //
294ba319b5SDimitry Andric // The compile command is adjusted, replacing the filename and removing output
304ba319b5SDimitry Andric // file arguments. The -x and -std flags may be affected too.
314ba319b5SDimitry Andric //
324ba319b5SDimitry Andric // Source language is a tricky issue: is it OK to use a .c file's command
334ba319b5SDimitry Andric // for building a .cc file? What language is a .h file in?
344ba319b5SDimitry Andric // - We only consider compile commands for c-family languages as candidates.
354ba319b5SDimitry Andric // - For files whose language is implied by the filename (e.g. .m, .hpp)
364ba319b5SDimitry Andric // we prefer candidates from the same language.
374ba319b5SDimitry Andric // If we must cross languages, we drop any -x and -std flags.
384ba319b5SDimitry Andric // - For .h files, candidates from any c-family language are acceptable.
394ba319b5SDimitry Andric // We use the candidate's language, inserting e.g. -x c++-header.
404ba319b5SDimitry Andric //
414ba319b5SDimitry Andric // This class is only useful when wrapping databases that can enumerate all
424ba319b5SDimitry Andric // their compile commands. If getAllFilenames() is empty, no inference occurs.
434ba319b5SDimitry Andric //
444ba319b5SDimitry Andric //===----------------------------------------------------------------------===//
454ba319b5SDimitry Andric
464ba319b5SDimitry Andric #include "clang/Driver/Options.h"
474ba319b5SDimitry Andric #include "clang/Driver/Types.h"
484ba319b5SDimitry Andric #include "clang/Frontend/LangStandard.h"
494ba319b5SDimitry Andric #include "clang/Tooling/CompilationDatabase.h"
504ba319b5SDimitry Andric #include "llvm/ADT/DenseMap.h"
51*b5893f02SDimitry Andric #include "llvm/ADT/Optional.h"
524ba319b5SDimitry Andric #include "llvm/ADT/StringExtras.h"
534ba319b5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
544ba319b5SDimitry Andric #include "llvm/Option/ArgList.h"
554ba319b5SDimitry Andric #include "llvm/Option/OptTable.h"
564ba319b5SDimitry Andric #include "llvm/Support/Debug.h"
574ba319b5SDimitry Andric #include "llvm/Support/Path.h"
584ba319b5SDimitry Andric #include "llvm/Support/StringSaver.h"
594ba319b5SDimitry Andric #include "llvm/Support/raw_ostream.h"
604ba319b5SDimitry Andric #include <memory>
614ba319b5SDimitry Andric
624ba319b5SDimitry Andric namespace clang {
634ba319b5SDimitry Andric namespace tooling {
644ba319b5SDimitry Andric namespace {
654ba319b5SDimitry Andric using namespace llvm;
664ba319b5SDimitry Andric namespace types = clang::driver::types;
674ba319b5SDimitry Andric namespace path = llvm::sys::path;
684ba319b5SDimitry Andric
694ba319b5SDimitry Andric // The length of the prefix these two strings have in common.
matchingPrefix(StringRef L,StringRef R)704ba319b5SDimitry Andric size_t matchingPrefix(StringRef L, StringRef R) {
714ba319b5SDimitry Andric size_t Limit = std::min(L.size(), R.size());
724ba319b5SDimitry Andric for (size_t I = 0; I < Limit; ++I)
734ba319b5SDimitry Andric if (L[I] != R[I])
744ba319b5SDimitry Andric return I;
754ba319b5SDimitry Andric return Limit;
764ba319b5SDimitry Andric }
774ba319b5SDimitry Andric
784ba319b5SDimitry Andric // A comparator for searching SubstringWithIndexes with std::equal_range etc.
794ba319b5SDimitry Andric // Optionaly prefix semantics: compares equal if the key is a prefix.
804ba319b5SDimitry Andric template <bool Prefix> struct Less {
operator ()clang::tooling::__anonad4080680111::Less814ba319b5SDimitry Andric bool operator()(StringRef Key, std::pair<StringRef, size_t> Value) const {
824ba319b5SDimitry Andric StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
834ba319b5SDimitry Andric return Key < V;
844ba319b5SDimitry Andric }
operator ()clang::tooling::__anonad4080680111::Less854ba319b5SDimitry Andric bool operator()(std::pair<StringRef, size_t> Value, StringRef Key) const {
864ba319b5SDimitry Andric StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
874ba319b5SDimitry Andric return V < Key;
884ba319b5SDimitry Andric }
894ba319b5SDimitry Andric };
904ba319b5SDimitry Andric
914ba319b5SDimitry Andric // Infer type from filename. If we might have gotten it wrong, set *Certain.
924ba319b5SDimitry Andric // *.h will be inferred as a C header, but not certain.
guessType(StringRef Filename,bool * Certain=nullptr)934ba319b5SDimitry Andric types::ID guessType(StringRef Filename, bool *Certain = nullptr) {
944ba319b5SDimitry Andric // path::extension is ".cpp", lookupTypeForExtension wants "cpp".
954ba319b5SDimitry Andric auto Lang =
964ba319b5SDimitry Andric types::lookupTypeForExtension(path::extension(Filename).substr(1));
974ba319b5SDimitry Andric if (Certain)
984ba319b5SDimitry Andric *Certain = Lang != types::TY_CHeader && Lang != types::TY_INVALID;
994ba319b5SDimitry Andric return Lang;
1004ba319b5SDimitry Andric }
1014ba319b5SDimitry Andric
1024ba319b5SDimitry Andric // Return Lang as one of the canonical supported types.
1034ba319b5SDimitry Andric // e.g. c-header --> c; fortran --> TY_INVALID
foldType(types::ID Lang)1044ba319b5SDimitry Andric static types::ID foldType(types::ID Lang) {
1054ba319b5SDimitry Andric switch (Lang) {
1064ba319b5SDimitry Andric case types::TY_C:
1074ba319b5SDimitry Andric case types::TY_CHeader:
1084ba319b5SDimitry Andric return types::TY_C;
1094ba319b5SDimitry Andric case types::TY_ObjC:
1104ba319b5SDimitry Andric case types::TY_ObjCHeader:
1114ba319b5SDimitry Andric return types::TY_ObjC;
1124ba319b5SDimitry Andric case types::TY_CXX:
1134ba319b5SDimitry Andric case types::TY_CXXHeader:
1144ba319b5SDimitry Andric return types::TY_CXX;
1154ba319b5SDimitry Andric case types::TY_ObjCXX:
1164ba319b5SDimitry Andric case types::TY_ObjCXXHeader:
1174ba319b5SDimitry Andric return types::TY_ObjCXX;
1184ba319b5SDimitry Andric default:
1194ba319b5SDimitry Andric return types::TY_INVALID;
1204ba319b5SDimitry Andric }
1214ba319b5SDimitry Andric }
1224ba319b5SDimitry Andric
1234ba319b5SDimitry Andric // A CompileCommand that can be applied to another file.
1244ba319b5SDimitry Andric struct TransferableCommand {
1254ba319b5SDimitry Andric // Flags that should not apply to all files are stripped from CommandLine.
1264ba319b5SDimitry Andric CompileCommand Cmd;
127*b5893f02SDimitry Andric // Language detected from -x or the filename. Never TY_INVALID.
128*b5893f02SDimitry Andric Optional<types::ID> Type;
1294ba319b5SDimitry Andric // Standard specified by -std.
1304ba319b5SDimitry Andric LangStandard::Kind Std = LangStandard::lang_unspecified;
131*b5893f02SDimitry Andric // Whether the command line is for the cl-compatible driver.
132*b5893f02SDimitry Andric bool ClangCLMode;
1334ba319b5SDimitry Andric
TransferableCommandclang::tooling::__anonad4080680111::TransferableCommand1344ba319b5SDimitry Andric TransferableCommand(CompileCommand C)
135*b5893f02SDimitry Andric : Cmd(std::move(C)), Type(guessType(Cmd.Filename)),
136*b5893f02SDimitry Andric ClangCLMode(checkIsCLMode(Cmd.CommandLine)) {
137*b5893f02SDimitry Andric std::vector<std::string> OldArgs = std::move(Cmd.CommandLine);
138*b5893f02SDimitry Andric Cmd.CommandLine.clear();
139*b5893f02SDimitry Andric
140*b5893f02SDimitry Andric // Wrap the old arguments in an InputArgList.
141*b5893f02SDimitry Andric llvm::opt::InputArgList ArgList;
142*b5893f02SDimitry Andric {
143*b5893f02SDimitry Andric SmallVector<const char *, 16> TmpArgv;
144*b5893f02SDimitry Andric for (const std::string &S : OldArgs)
145*b5893f02SDimitry Andric TmpArgv.push_back(S.c_str());
146*b5893f02SDimitry Andric ArgList = {TmpArgv.begin(), TmpArgv.end()};
147*b5893f02SDimitry Andric }
148*b5893f02SDimitry Andric
1494ba319b5SDimitry Andric // Parse the old args in order to strip out and record unwanted flags.
150*b5893f02SDimitry Andric // We parse each argument individually so that we can retain the exact
151*b5893f02SDimitry Andric // spelling of each argument; re-rendering is lossy for aliased flags.
152*b5893f02SDimitry Andric // E.g. in CL mode, /W4 maps to -Wall.
1534ba319b5SDimitry Andric auto OptTable = clang::driver::createDriverOptTable();
154*b5893f02SDimitry Andric Cmd.CommandLine.emplace_back(OldArgs.front());
155*b5893f02SDimitry Andric for (unsigned Pos = 1; Pos < OldArgs.size();) {
156*b5893f02SDimitry Andric using namespace driver::options;
157*b5893f02SDimitry Andric
158*b5893f02SDimitry Andric const unsigned OldPos = Pos;
159*b5893f02SDimitry Andric std::unique_ptr<llvm::opt::Arg> Arg(OptTable->ParseOneArg(
160*b5893f02SDimitry Andric ArgList, Pos,
161*b5893f02SDimitry Andric /* Include */ClangCLMode ? CoreOption | CLOption : 0,
162*b5893f02SDimitry Andric /* Exclude */ClangCLMode ? 0 : CLOption));
163*b5893f02SDimitry Andric
164*b5893f02SDimitry Andric if (!Arg)
165*b5893f02SDimitry Andric continue;
166*b5893f02SDimitry Andric
167*b5893f02SDimitry Andric const llvm::opt::Option &Opt = Arg->getOption();
168*b5893f02SDimitry Andric
1694ba319b5SDimitry Andric // Strip input and output files.
170*b5893f02SDimitry Andric if (Opt.matches(OPT_INPUT) || Opt.matches(OPT_o) ||
171*b5893f02SDimitry Andric (ClangCLMode && (Opt.matches(OPT__SLASH_Fa) ||
172*b5893f02SDimitry Andric Opt.matches(OPT__SLASH_Fe) ||
173*b5893f02SDimitry Andric Opt.matches(OPT__SLASH_Fi) ||
174*b5893f02SDimitry Andric Opt.matches(OPT__SLASH_Fo))))
1754ba319b5SDimitry Andric continue;
176*b5893f02SDimitry Andric
1774ba319b5SDimitry Andric // Strip -x, but record the overridden language.
178*b5893f02SDimitry Andric if (const auto GivenType = tryParseTypeArg(*Arg)) {
179*b5893f02SDimitry Andric Type = *GivenType;
1804ba319b5SDimitry Andric continue;
1814ba319b5SDimitry Andric }
182*b5893f02SDimitry Andric
183*b5893f02SDimitry Andric // Strip -std, but record the value.
184*b5893f02SDimitry Andric if (const auto GivenStd = tryParseStdArg(*Arg)) {
185*b5893f02SDimitry Andric if (*GivenStd != LangStandard::lang_unspecified)
186*b5893f02SDimitry Andric Std = *GivenStd;
1874ba319b5SDimitry Andric continue;
1884ba319b5SDimitry Andric }
189*b5893f02SDimitry Andric
190*b5893f02SDimitry Andric Cmd.CommandLine.insert(Cmd.CommandLine.end(),
191*b5893f02SDimitry Andric OldArgs.data() + OldPos, OldArgs.data() + Pos);
1924ba319b5SDimitry Andric }
1934ba319b5SDimitry Andric
1944ba319b5SDimitry Andric if (Std != LangStandard::lang_unspecified) // -std take precedence over -x
1954ba319b5SDimitry Andric Type = toType(LangStandard::getLangStandardForKind(Std).getLanguage());
196*b5893f02SDimitry Andric Type = foldType(*Type);
197*b5893f02SDimitry Andric // The contract is to store None instead of TY_INVALID.
198*b5893f02SDimitry Andric if (Type == types::TY_INVALID)
199*b5893f02SDimitry Andric Type = llvm::None;
2004ba319b5SDimitry Andric }
2014ba319b5SDimitry Andric
2024ba319b5SDimitry Andric // Produce a CompileCommand for \p filename, based on this one.
transferToclang::tooling::__anonad4080680111::TransferableCommand2034ba319b5SDimitry Andric CompileCommand transferTo(StringRef Filename) const {
2044ba319b5SDimitry Andric CompileCommand Result = Cmd;
2054ba319b5SDimitry Andric Result.Filename = Filename;
2064ba319b5SDimitry Andric bool TypeCertain;
2074ba319b5SDimitry Andric auto TargetType = guessType(Filename, &TypeCertain);
2084ba319b5SDimitry Andric // If the filename doesn't determine the language (.h), transfer with -x.
209*b5893f02SDimitry Andric if (TargetType != types::TY_INVALID && !TypeCertain && Type) {
2104ba319b5SDimitry Andric TargetType = types::onlyPrecompileType(TargetType) // header?
211*b5893f02SDimitry Andric ? types::lookupHeaderTypeForSourceType(*Type)
212*b5893f02SDimitry Andric : *Type;
213*b5893f02SDimitry Andric if (ClangCLMode) {
214*b5893f02SDimitry Andric const StringRef Flag = toCLFlag(TargetType);
215*b5893f02SDimitry Andric if (!Flag.empty())
216*b5893f02SDimitry Andric Result.CommandLine.push_back(Flag);
217*b5893f02SDimitry Andric } else {
2184ba319b5SDimitry Andric Result.CommandLine.push_back("-x");
2194ba319b5SDimitry Andric Result.CommandLine.push_back(types::getTypeName(TargetType));
2204ba319b5SDimitry Andric }
221*b5893f02SDimitry Andric }
2224ba319b5SDimitry Andric // --std flag may only be transferred if the language is the same.
2234ba319b5SDimitry Andric // We may consider "translating" these, e.g. c++11 -> c11.
2244ba319b5SDimitry Andric if (Std != LangStandard::lang_unspecified && foldType(TargetType) == Type) {
225*b5893f02SDimitry Andric Result.CommandLine.emplace_back((
226*b5893f02SDimitry Andric llvm::Twine(ClangCLMode ? "/std:" : "-std=") +
227*b5893f02SDimitry Andric LangStandard::getLangStandardForKind(Std).getName()).str());
2284ba319b5SDimitry Andric }
2294ba319b5SDimitry Andric Result.CommandLine.push_back(Filename);
2304ba319b5SDimitry Andric return Result;
2314ba319b5SDimitry Andric }
2324ba319b5SDimitry Andric
2334ba319b5SDimitry Andric private:
234*b5893f02SDimitry Andric // Determine whether the given command line is intended for the CL driver.
checkIsCLModeclang::tooling::__anonad4080680111::TransferableCommand235*b5893f02SDimitry Andric static bool checkIsCLMode(ArrayRef<std::string> CmdLine) {
236*b5893f02SDimitry Andric // First look for --driver-mode.
237*b5893f02SDimitry Andric for (StringRef S : llvm::reverse(CmdLine)) {
238*b5893f02SDimitry Andric if (S.consume_front("--driver-mode="))
239*b5893f02SDimitry Andric return S == "cl";
240*b5893f02SDimitry Andric }
241*b5893f02SDimitry Andric
242*b5893f02SDimitry Andric // Otherwise just check the clang executable file name.
243*b5893f02SDimitry Andric return llvm::sys::path::stem(CmdLine.front()).endswith_lower("cl");
244*b5893f02SDimitry Andric }
245*b5893f02SDimitry Andric
2464ba319b5SDimitry Andric // Map the language from the --std flag to that of the -x flag.
toTypeclang::tooling::__anonad4080680111::TransferableCommand2474ba319b5SDimitry Andric static types::ID toType(InputKind::Language Lang) {
2484ba319b5SDimitry Andric switch (Lang) {
2494ba319b5SDimitry Andric case InputKind::C:
2504ba319b5SDimitry Andric return types::TY_C;
2514ba319b5SDimitry Andric case InputKind::CXX:
2524ba319b5SDimitry Andric return types::TY_CXX;
2534ba319b5SDimitry Andric case InputKind::ObjC:
2544ba319b5SDimitry Andric return types::TY_ObjC;
2554ba319b5SDimitry Andric case InputKind::ObjCXX:
2564ba319b5SDimitry Andric return types::TY_ObjCXX;
2574ba319b5SDimitry Andric default:
2584ba319b5SDimitry Andric return types::TY_INVALID;
2594ba319b5SDimitry Andric }
2604ba319b5SDimitry Andric }
261*b5893f02SDimitry Andric
262*b5893f02SDimitry Andric // Convert a file type to the matching CL-style type flag.
toCLFlagclang::tooling::__anonad4080680111::TransferableCommand263*b5893f02SDimitry Andric static StringRef toCLFlag(types::ID Type) {
264*b5893f02SDimitry Andric switch (Type) {
265*b5893f02SDimitry Andric case types::TY_C:
266*b5893f02SDimitry Andric case types::TY_CHeader:
267*b5893f02SDimitry Andric return "/TC";
268*b5893f02SDimitry Andric case types::TY_CXX:
269*b5893f02SDimitry Andric case types::TY_CXXHeader:
270*b5893f02SDimitry Andric return "/TP";
271*b5893f02SDimitry Andric default:
272*b5893f02SDimitry Andric return StringRef();
273*b5893f02SDimitry Andric }
274*b5893f02SDimitry Andric }
275*b5893f02SDimitry Andric
276*b5893f02SDimitry Andric // Try to interpret the argument as a type specifier, e.g. '-x'.
tryParseTypeArgclang::tooling::__anonad4080680111::TransferableCommand277*b5893f02SDimitry Andric Optional<types::ID> tryParseTypeArg(const llvm::opt::Arg &Arg) {
278*b5893f02SDimitry Andric const llvm::opt::Option &Opt = Arg.getOption();
279*b5893f02SDimitry Andric using namespace driver::options;
280*b5893f02SDimitry Andric if (ClangCLMode) {
281*b5893f02SDimitry Andric if (Opt.matches(OPT__SLASH_TC) || Opt.matches(OPT__SLASH_Tc))
282*b5893f02SDimitry Andric return types::TY_C;
283*b5893f02SDimitry Andric if (Opt.matches(OPT__SLASH_TP) || Opt.matches(OPT__SLASH_Tp))
284*b5893f02SDimitry Andric return types::TY_CXX;
285*b5893f02SDimitry Andric } else {
286*b5893f02SDimitry Andric if (Opt.matches(driver::options::OPT_x))
287*b5893f02SDimitry Andric return types::lookupTypeForTypeSpecifier(Arg.getValue());
288*b5893f02SDimitry Andric }
289*b5893f02SDimitry Andric return None;
290*b5893f02SDimitry Andric }
291*b5893f02SDimitry Andric
292*b5893f02SDimitry Andric // Try to interpret the argument as '-std='.
tryParseStdArgclang::tooling::__anonad4080680111::TransferableCommand293*b5893f02SDimitry Andric Optional<LangStandard::Kind> tryParseStdArg(const llvm::opt::Arg &Arg) {
294*b5893f02SDimitry Andric using namespace driver::options;
295*b5893f02SDimitry Andric if (Arg.getOption().matches(ClangCLMode ? OPT__SLASH_std : OPT_std_EQ)) {
296*b5893f02SDimitry Andric return llvm::StringSwitch<LangStandard::Kind>(Arg.getValue())
297*b5893f02SDimitry Andric #define LANGSTANDARD(id, name, lang, ...) .Case(name, LangStandard::lang_##id)
298*b5893f02SDimitry Andric #define LANGSTANDARD_ALIAS(id, alias) .Case(alias, LangStandard::lang_##id)
299*b5893f02SDimitry Andric #include "clang/Frontend/LangStandards.def"
300*b5893f02SDimitry Andric #undef LANGSTANDARD_ALIAS
301*b5893f02SDimitry Andric #undef LANGSTANDARD
302*b5893f02SDimitry Andric .Default(LangStandard::lang_unspecified);
303*b5893f02SDimitry Andric }
304*b5893f02SDimitry Andric return None;
305*b5893f02SDimitry Andric }
3064ba319b5SDimitry Andric };
3074ba319b5SDimitry Andric
308*b5893f02SDimitry Andric // Given a filename, FileIndex picks the best matching file from the underlying
309*b5893f02SDimitry Andric // DB. This is the proxy file whose CompileCommand will be reused. The
310*b5893f02SDimitry Andric // heuristics incorporate file name, extension, and directory structure.
311*b5893f02SDimitry Andric // Strategy:
3124ba319b5SDimitry Andric // - Build indexes of each of the substrings we want to look up by.
3134ba319b5SDimitry Andric // These indexes are just sorted lists of the substrings.
3144ba319b5SDimitry Andric // - Each criterion corresponds to a range lookup into the index, so we only
3154ba319b5SDimitry Andric // need O(log N) string comparisons to determine scores.
316*b5893f02SDimitry Andric //
317*b5893f02SDimitry Andric // Apart from path proximity signals, also takes file extensions into account
318*b5893f02SDimitry Andric // when scoring the candidates.
319*b5893f02SDimitry Andric class FileIndex {
3204ba319b5SDimitry Andric public:
FileIndex(std::vector<std::string> Files)321*b5893f02SDimitry Andric FileIndex(std::vector<std::string> Files)
322*b5893f02SDimitry Andric : OriginalPaths(std::move(Files)), Strings(Arena) {
3234ba319b5SDimitry Andric // Sort commands by filename for determinism (index is a tiebreaker later).
324*b5893f02SDimitry Andric llvm::sort(OriginalPaths);
325*b5893f02SDimitry Andric Paths.reserve(OriginalPaths.size());
326*b5893f02SDimitry Andric Types.reserve(OriginalPaths.size());
327*b5893f02SDimitry Andric Stems.reserve(OriginalPaths.size());
328*b5893f02SDimitry Andric for (size_t I = 0; I < OriginalPaths.size(); ++I) {
329*b5893f02SDimitry Andric StringRef Path = Strings.save(StringRef(OriginalPaths[I]).lower());
330*b5893f02SDimitry Andric
331*b5893f02SDimitry Andric Paths.emplace_back(Path, I);
332*b5893f02SDimitry Andric Types.push_back(foldType(guessType(Path)));
3334ba319b5SDimitry Andric Stems.emplace_back(sys::path::stem(Path), I);
3344ba319b5SDimitry Andric auto Dir = ++sys::path::rbegin(Path), DirEnd = sys::path::rend(Path);
3354ba319b5SDimitry Andric for (int J = 0; J < DirectorySegmentsIndexed && Dir != DirEnd; ++J, ++Dir)
3364ba319b5SDimitry Andric if (Dir->size() > ShortDirectorySegment) // not trivial ones
3374ba319b5SDimitry Andric Components.emplace_back(*Dir, I);
3384ba319b5SDimitry Andric }
339*b5893f02SDimitry Andric llvm::sort(Paths);
340*b5893f02SDimitry Andric llvm::sort(Stems);
341*b5893f02SDimitry Andric llvm::sort(Components);
3424ba319b5SDimitry Andric }
3434ba319b5SDimitry Andric
empty() const344*b5893f02SDimitry Andric bool empty() const { return Paths.empty(); }
3454ba319b5SDimitry Andric
346*b5893f02SDimitry Andric // Returns the path for the file that best fits OriginalFilename.
347*b5893f02SDimitry Andric // Candidates with extensions matching PreferLanguage will be chosen over
348*b5893f02SDimitry Andric // others (unless it's TY_INVALID, or all candidates are bad).
chooseProxy(StringRef OriginalFilename,types::ID PreferLanguage) const349*b5893f02SDimitry Andric StringRef chooseProxy(StringRef OriginalFilename,
3504ba319b5SDimitry Andric types::ID PreferLanguage) const {
3514ba319b5SDimitry Andric assert(!empty() && "need at least one candidate!");
3524ba319b5SDimitry Andric std::string Filename = OriginalFilename.lower();
3534ba319b5SDimitry Andric auto Candidates = scoreCandidates(Filename);
3544ba319b5SDimitry Andric std::pair<size_t, int> Best =
3554ba319b5SDimitry Andric pickWinner(Candidates, Filename, PreferLanguage);
3564ba319b5SDimitry Andric
357*b5893f02SDimitry Andric DEBUG_WITH_TYPE(
358*b5893f02SDimitry Andric "interpolate",
359*b5893f02SDimitry Andric llvm::dbgs() << "interpolate: chose " << OriginalPaths[Best.first]
360*b5893f02SDimitry Andric << " as proxy for " << OriginalFilename << " preferring "
3614ba319b5SDimitry Andric << (PreferLanguage == types::TY_INVALID
3624ba319b5SDimitry Andric ? "none"
3634ba319b5SDimitry Andric : types::getTypeName(PreferLanguage))
3644ba319b5SDimitry Andric << " score=" << Best.second << "\n");
365*b5893f02SDimitry Andric return OriginalPaths[Best.first];
3664ba319b5SDimitry Andric }
3674ba319b5SDimitry Andric
3684ba319b5SDimitry Andric private:
3694ba319b5SDimitry Andric using SubstringAndIndex = std::pair<StringRef, size_t>;
3704ba319b5SDimitry Andric // Directory matching parameters: we look at the last two segments of the
3714ba319b5SDimitry Andric // parent directory (usually the semantically significant ones in practice).
3724ba319b5SDimitry Andric // We search only the last four of each candidate (for efficiency).
3734ba319b5SDimitry Andric constexpr static int DirectorySegmentsIndexed = 4;
3744ba319b5SDimitry Andric constexpr static int DirectorySegmentsQueried = 2;
3754ba319b5SDimitry Andric constexpr static int ShortDirectorySegment = 1; // Only look at longer names.
3764ba319b5SDimitry Andric
3774ba319b5SDimitry Andric // Award points to candidate entries that should be considered for the file.
3784ba319b5SDimitry Andric // Returned keys are indexes into paths, and the values are (nonzero) scores.
scoreCandidates(StringRef Filename) const3794ba319b5SDimitry Andric DenseMap<size_t, int> scoreCandidates(StringRef Filename) const {
3804ba319b5SDimitry Andric // Decompose Filename into the parts we care about.
3814ba319b5SDimitry Andric // /some/path/complicated/project/Interesting.h
3824ba319b5SDimitry Andric // [-prefix--][---dir---] [-dir-] [--stem---]
3834ba319b5SDimitry Andric StringRef Stem = sys::path::stem(Filename);
3844ba319b5SDimitry Andric llvm::SmallVector<StringRef, DirectorySegmentsQueried> Dirs;
3854ba319b5SDimitry Andric llvm::StringRef Prefix;
3864ba319b5SDimitry Andric auto Dir = ++sys::path::rbegin(Filename),
3874ba319b5SDimitry Andric DirEnd = sys::path::rend(Filename);
3884ba319b5SDimitry Andric for (int I = 0; I < DirectorySegmentsQueried && Dir != DirEnd; ++I, ++Dir) {
3894ba319b5SDimitry Andric if (Dir->size() > ShortDirectorySegment)
3904ba319b5SDimitry Andric Dirs.push_back(*Dir);
3914ba319b5SDimitry Andric Prefix = Filename.substr(0, Dir - DirEnd);
3924ba319b5SDimitry Andric }
3934ba319b5SDimitry Andric
3944ba319b5SDimitry Andric // Now award points based on lookups into our various indexes.
3954ba319b5SDimitry Andric DenseMap<size_t, int> Candidates; // Index -> score.
3964ba319b5SDimitry Andric auto Award = [&](int Points, ArrayRef<SubstringAndIndex> Range) {
3974ba319b5SDimitry Andric for (const auto &Entry : Range)
3984ba319b5SDimitry Andric Candidates[Entry.second] += Points;
3994ba319b5SDimitry Andric };
4004ba319b5SDimitry Andric // Award one point if the file's basename is a prefix of the candidate,
4014ba319b5SDimitry Andric // and another if it's an exact match (so exact matches get two points).
4024ba319b5SDimitry Andric Award(1, indexLookup</*Prefix=*/true>(Stem, Stems));
4034ba319b5SDimitry Andric Award(1, indexLookup</*Prefix=*/false>(Stem, Stems));
4044ba319b5SDimitry Andric // For each of the last few directories in the Filename, award a point
4054ba319b5SDimitry Andric // if it's present in the candidate.
4064ba319b5SDimitry Andric for (StringRef Dir : Dirs)
4074ba319b5SDimitry Andric Award(1, indexLookup</*Prefix=*/false>(Dir, Components));
4084ba319b5SDimitry Andric // Award one more point if the whole rest of the path matches.
4094ba319b5SDimitry Andric if (sys::path::root_directory(Prefix) != Prefix)
4104ba319b5SDimitry Andric Award(1, indexLookup</*Prefix=*/true>(Prefix, Paths));
4114ba319b5SDimitry Andric return Candidates;
4124ba319b5SDimitry Andric }
4134ba319b5SDimitry Andric
4144ba319b5SDimitry Andric // Pick a single winner from the set of scored candidates.
4154ba319b5SDimitry Andric // Returns (index, score).
pickWinner(const DenseMap<size_t,int> & Candidates,StringRef Filename,types::ID PreferredLanguage) const4164ba319b5SDimitry Andric std::pair<size_t, int> pickWinner(const DenseMap<size_t, int> &Candidates,
4174ba319b5SDimitry Andric StringRef Filename,
4184ba319b5SDimitry Andric types::ID PreferredLanguage) const {
4194ba319b5SDimitry Andric struct ScoredCandidate {
4204ba319b5SDimitry Andric size_t Index;
4214ba319b5SDimitry Andric bool Preferred;
4224ba319b5SDimitry Andric int Points;
4234ba319b5SDimitry Andric size_t PrefixLength;
4244ba319b5SDimitry Andric };
4254ba319b5SDimitry Andric // Choose the best candidate by (preferred, points, prefix length, alpha).
4264ba319b5SDimitry Andric ScoredCandidate Best = {size_t(-1), false, 0, 0};
4274ba319b5SDimitry Andric for (const auto &Candidate : Candidates) {
4284ba319b5SDimitry Andric ScoredCandidate S;
4294ba319b5SDimitry Andric S.Index = Candidate.first;
4304ba319b5SDimitry Andric S.Preferred = PreferredLanguage == types::TY_INVALID ||
431*b5893f02SDimitry Andric PreferredLanguage == Types[S.Index];
4324ba319b5SDimitry Andric S.Points = Candidate.second;
4334ba319b5SDimitry Andric if (!S.Preferred && Best.Preferred)
4344ba319b5SDimitry Andric continue;
4354ba319b5SDimitry Andric if (S.Preferred == Best.Preferred) {
4364ba319b5SDimitry Andric if (S.Points < Best.Points)
4374ba319b5SDimitry Andric continue;
4384ba319b5SDimitry Andric if (S.Points == Best.Points) {
4394ba319b5SDimitry Andric S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
4404ba319b5SDimitry Andric if (S.PrefixLength < Best.PrefixLength)
4414ba319b5SDimitry Andric continue;
4424ba319b5SDimitry Andric // hidden heuristics should at least be deterministic!
4434ba319b5SDimitry Andric if (S.PrefixLength == Best.PrefixLength)
4444ba319b5SDimitry Andric if (S.Index > Best.Index)
4454ba319b5SDimitry Andric continue;
4464ba319b5SDimitry Andric }
4474ba319b5SDimitry Andric }
4484ba319b5SDimitry Andric // PrefixLength was only set above if actually needed for a tiebreak.
4494ba319b5SDimitry Andric // But it definitely needs to be set to break ties in the future.
4504ba319b5SDimitry Andric S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
4514ba319b5SDimitry Andric Best = S;
4524ba319b5SDimitry Andric }
4534ba319b5SDimitry Andric // Edge case: no candidate got any points.
4544ba319b5SDimitry Andric // We ignore PreferredLanguage at this point (not ideal).
4554ba319b5SDimitry Andric if (Best.Index == size_t(-1))
4564ba319b5SDimitry Andric return {longestMatch(Filename, Paths).second, 0};
4574ba319b5SDimitry Andric return {Best.Index, Best.Points};
4584ba319b5SDimitry Andric }
4594ba319b5SDimitry Andric
4604ba319b5SDimitry Andric // Returns the range within a sorted index that compares equal to Key.
4614ba319b5SDimitry Andric // If Prefix is true, it's instead the range starting with Key.
4624ba319b5SDimitry Andric template <bool Prefix>
4634ba319b5SDimitry Andric ArrayRef<SubstringAndIndex>
indexLookup(StringRef Key,ArrayRef<SubstringAndIndex> Idx) const464*b5893f02SDimitry Andric indexLookup(StringRef Key, ArrayRef<SubstringAndIndex> Idx) const {
4654ba319b5SDimitry Andric // Use pointers as iteratiors to ease conversion of result to ArrayRef.
4664ba319b5SDimitry Andric auto Range = std::equal_range(Idx.data(), Idx.data() + Idx.size(), Key,
4674ba319b5SDimitry Andric Less<Prefix>());
4684ba319b5SDimitry Andric return {Range.first, Range.second};
4694ba319b5SDimitry Andric }
4704ba319b5SDimitry Andric
4714ba319b5SDimitry Andric // Performs a point lookup into a nonempty index, returning a longest match.
longestMatch(StringRef Key,ArrayRef<SubstringAndIndex> Idx) const472*b5893f02SDimitry Andric SubstringAndIndex longestMatch(StringRef Key,
473*b5893f02SDimitry Andric ArrayRef<SubstringAndIndex> Idx) const {
4744ba319b5SDimitry Andric assert(!Idx.empty());
4754ba319b5SDimitry Andric // Longest substring match will be adjacent to a direct lookup.
4764ba319b5SDimitry Andric auto It =
4774ba319b5SDimitry Andric std::lower_bound(Idx.begin(), Idx.end(), SubstringAndIndex{Key, 0});
4784ba319b5SDimitry Andric if (It == Idx.begin())
4794ba319b5SDimitry Andric return *It;
4804ba319b5SDimitry Andric if (It == Idx.end())
4814ba319b5SDimitry Andric return *--It;
4824ba319b5SDimitry Andric // Have to choose between It and It-1
4834ba319b5SDimitry Andric size_t Prefix = matchingPrefix(Key, It->first);
4844ba319b5SDimitry Andric size_t PrevPrefix = matchingPrefix(Key, (It - 1)->first);
4854ba319b5SDimitry Andric return Prefix > PrevPrefix ? *It : *--It;
4864ba319b5SDimitry Andric }
4874ba319b5SDimitry Andric
488*b5893f02SDimitry Andric // Original paths, everything else is in lowercase.
489*b5893f02SDimitry Andric std::vector<std::string> OriginalPaths;
4904ba319b5SDimitry Andric BumpPtrAllocator Arena;
4914ba319b5SDimitry Andric StringSaver Strings;
4924ba319b5SDimitry Andric // Indexes of candidates by certain substrings.
4934ba319b5SDimitry Andric // String is lowercase and sorted, index points into OriginalPaths.
4944ba319b5SDimitry Andric std::vector<SubstringAndIndex> Paths; // Full path.
495*b5893f02SDimitry Andric // Lang types obtained by guessing on the corresponding path. I-th element is
496*b5893f02SDimitry Andric // a type for the I-th path.
497*b5893f02SDimitry Andric std::vector<types::ID> Types;
4984ba319b5SDimitry Andric std::vector<SubstringAndIndex> Stems; // Basename, without extension.
4994ba319b5SDimitry Andric std::vector<SubstringAndIndex> Components; // Last path components.
5004ba319b5SDimitry Andric };
5014ba319b5SDimitry Andric
5024ba319b5SDimitry Andric // The actual CompilationDatabase wrapper delegates to its inner database.
503*b5893f02SDimitry Andric // If no match, looks up a proxy file in FileIndex and transfers its
504*b5893f02SDimitry Andric // command to the requested file.
5054ba319b5SDimitry Andric class InterpolatingCompilationDatabase : public CompilationDatabase {
5064ba319b5SDimitry Andric public:
InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)5074ba319b5SDimitry Andric InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)
508*b5893f02SDimitry Andric : Inner(std::move(Inner)), Index(this->Inner->getAllFiles()) {}
5094ba319b5SDimitry Andric
5104ba319b5SDimitry Andric std::vector<CompileCommand>
getCompileCommands(StringRef Filename) const5114ba319b5SDimitry Andric getCompileCommands(StringRef Filename) const override {
5124ba319b5SDimitry Andric auto Known = Inner->getCompileCommands(Filename);
5134ba319b5SDimitry Andric if (Index.empty() || !Known.empty())
5144ba319b5SDimitry Andric return Known;
5154ba319b5SDimitry Andric bool TypeCertain;
5164ba319b5SDimitry Andric auto Lang = guessType(Filename, &TypeCertain);
5174ba319b5SDimitry Andric if (!TypeCertain)
5184ba319b5SDimitry Andric Lang = types::TY_INVALID;
519*b5893f02SDimitry Andric auto ProxyCommands =
520*b5893f02SDimitry Andric Inner->getCompileCommands(Index.chooseProxy(Filename, foldType(Lang)));
521*b5893f02SDimitry Andric if (ProxyCommands.empty())
522*b5893f02SDimitry Andric return {};
523*b5893f02SDimitry Andric return {TransferableCommand(ProxyCommands[0]).transferTo(Filename)};
5244ba319b5SDimitry Andric }
5254ba319b5SDimitry Andric
getAllFiles() const5264ba319b5SDimitry Andric std::vector<std::string> getAllFiles() const override {
5274ba319b5SDimitry Andric return Inner->getAllFiles();
5284ba319b5SDimitry Andric }
5294ba319b5SDimitry Andric
getAllCompileCommands() const5304ba319b5SDimitry Andric std::vector<CompileCommand> getAllCompileCommands() const override {
5314ba319b5SDimitry Andric return Inner->getAllCompileCommands();
5324ba319b5SDimitry Andric }
5334ba319b5SDimitry Andric
5344ba319b5SDimitry Andric private:
5354ba319b5SDimitry Andric std::unique_ptr<CompilationDatabase> Inner;
536*b5893f02SDimitry Andric FileIndex Index;
5374ba319b5SDimitry Andric };
5384ba319b5SDimitry Andric
5394ba319b5SDimitry Andric } // namespace
5404ba319b5SDimitry Andric
5414ba319b5SDimitry Andric std::unique_ptr<CompilationDatabase>
inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner)5424ba319b5SDimitry Andric inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner) {
5434ba319b5SDimitry Andric return llvm::make_unique<InterpolatingCompilationDatabase>(std::move(Inner));
5444ba319b5SDimitry Andric }
5454ba319b5SDimitry Andric
5464ba319b5SDimitry Andric } // namespace tooling
5474ba319b5SDimitry Andric } // namespace clang
548