148675466SDimitry Andric //===- InterpolatingCompilationDatabase.cpp ---------------------*- C++ -*-===//
248675466SDimitry Andric //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
648675466SDimitry Andric //
748675466SDimitry Andric //===----------------------------------------------------------------------===//
848675466SDimitry Andric //
948675466SDimitry Andric // InterpolatingCompilationDatabase wraps another CompilationDatabase and
1048675466SDimitry Andric // attempts to heuristically determine appropriate compile commands for files
1148675466SDimitry Andric // that are not included, such as headers or newly created files.
1248675466SDimitry Andric //
1348675466SDimitry Andric // Motivating cases include:
1448675466SDimitry Andric // Header files that live next to their implementation files. These typically
1548675466SDimitry Andric // share a base filename. (libclang/CXString.h, libclang/CXString.cpp).
1648675466SDimitry Andric // Some projects separate headers from includes. Filenames still typically
1748675466SDimitry Andric // match, maybe other path segments too. (include/llvm/IR/Use.h, lib/IR/Use.cc).
1848675466SDimitry Andric // Matches are sometimes only approximate (Sema.h, SemaDecl.cpp). This goes
1948675466SDimitry Andric // for directories too (Support/Unix/Process.inc, lib/Support/Process.cpp).
2048675466SDimitry Andric // Even if we can't find a "right" compile command, even a random one from
2148675466SDimitry Andric // the project will tend to get important flags like -I and -x right.
2248675466SDimitry Andric //
2348675466SDimitry Andric // We "borrow" the compile command for the closest available file:
2448675466SDimitry Andric // - points are awarded if the filename matches (ignoring extension)
2548675466SDimitry Andric // - points are awarded if the directory structure matches
2648675466SDimitry Andric // - ties are broken by length of path prefix match
2748675466SDimitry Andric //
2848675466SDimitry Andric // The compile command is adjusted, replacing the filename and removing output
2948675466SDimitry Andric // file arguments. The -x and -std flags may be affected too.
3048675466SDimitry Andric //
3148675466SDimitry Andric // Source language is a tricky issue: is it OK to use a .c file's command
3248675466SDimitry Andric // for building a .cc file? What language is a .h file in?
3348675466SDimitry Andric // - We only consider compile commands for c-family languages as candidates.
3448675466SDimitry Andric // - For files whose language is implied by the filename (e.g. .m, .hpp)
3548675466SDimitry Andric // we prefer candidates from the same language.
3648675466SDimitry Andric // If we must cross languages, we drop any -x and -std flags.
3748675466SDimitry Andric // - For .h files, candidates from any c-family language are acceptable.
3848675466SDimitry Andric // We use the candidate's language, inserting e.g. -x c++-header.
3948675466SDimitry Andric //
4048675466SDimitry Andric // This class is only useful when wrapping databases that can enumerate all
4148675466SDimitry Andric // their compile commands. If getAllFilenames() is empty, no inference occurs.
4248675466SDimitry Andric //
4348675466SDimitry Andric //===----------------------------------------------------------------------===//
4448675466SDimitry Andric
45519fc96cSDimitry Andric #include "clang/Basic/LangStandard.h"
46344a3780SDimitry Andric #include "clang/Driver/Driver.h"
4748675466SDimitry Andric #include "clang/Driver/Options.h"
4848675466SDimitry Andric #include "clang/Driver/Types.h"
4948675466SDimitry Andric #include "clang/Tooling/CompilationDatabase.h"
50344a3780SDimitry Andric #include "llvm/ADT/ArrayRef.h"
5148675466SDimitry Andric #include "llvm/ADT/DenseMap.h"
5248675466SDimitry Andric #include "llvm/ADT/StringExtras.h"
5348675466SDimitry Andric #include "llvm/Option/ArgList.h"
5448675466SDimitry Andric #include "llvm/Option/OptTable.h"
5548675466SDimitry Andric #include "llvm/Support/Debug.h"
5648675466SDimitry Andric #include "llvm/Support/Path.h"
5748675466SDimitry Andric #include "llvm/Support/StringSaver.h"
5848675466SDimitry Andric #include "llvm/Support/raw_ostream.h"
5948675466SDimitry Andric #include <memory>
60e3b55780SDimitry Andric #include <optional>
6148675466SDimitry Andric
6248675466SDimitry Andric namespace clang {
6348675466SDimitry Andric namespace tooling {
6448675466SDimitry Andric namespace {
6548675466SDimitry Andric using namespace llvm;
6648675466SDimitry Andric namespace types = clang::driver::types;
6748675466SDimitry Andric namespace path = llvm::sys::path;
6848675466SDimitry Andric
6948675466SDimitry Andric // The length of the prefix these two strings have in common.
matchingPrefix(StringRef L,StringRef R)7048675466SDimitry Andric size_t matchingPrefix(StringRef L, StringRef R) {
7148675466SDimitry Andric size_t Limit = std::min(L.size(), R.size());
7248675466SDimitry Andric for (size_t I = 0; I < Limit; ++I)
7348675466SDimitry Andric if (L[I] != R[I])
7448675466SDimitry Andric return I;
7548675466SDimitry Andric return Limit;
7648675466SDimitry Andric }
7748675466SDimitry Andric
7848675466SDimitry Andric // A comparator for searching SubstringWithIndexes with std::equal_range etc.
7948675466SDimitry Andric // Optionaly prefix semantics: compares equal if the key is a prefix.
8048675466SDimitry Andric template <bool Prefix> struct Less {
operator ()clang::tooling::__anon9618e36e0111::Less8148675466SDimitry Andric bool operator()(StringRef Key, std::pair<StringRef, size_t> Value) const {
8248675466SDimitry Andric StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
8348675466SDimitry Andric return Key < V;
8448675466SDimitry Andric }
operator ()clang::tooling::__anon9618e36e0111::Less8548675466SDimitry Andric bool operator()(std::pair<StringRef, size_t> Value, StringRef Key) const {
8648675466SDimitry Andric StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
8748675466SDimitry Andric return V < Key;
8848675466SDimitry Andric }
8948675466SDimitry Andric };
9048675466SDimitry Andric
9148675466SDimitry Andric // Infer type from filename. If we might have gotten it wrong, set *Certain.
9248675466SDimitry Andric // *.h will be inferred as a C header, but not certain.
guessType(StringRef Filename,bool * Certain=nullptr)9348675466SDimitry Andric types::ID guessType(StringRef Filename, bool *Certain = nullptr) {
9448675466SDimitry Andric // path::extension is ".cpp", lookupTypeForExtension wants "cpp".
9548675466SDimitry Andric auto Lang =
9648675466SDimitry Andric types::lookupTypeForExtension(path::extension(Filename).substr(1));
9748675466SDimitry Andric if (Certain)
9848675466SDimitry Andric *Certain = Lang != types::TY_CHeader && Lang != types::TY_INVALID;
9948675466SDimitry Andric return Lang;
10048675466SDimitry Andric }
10148675466SDimitry Andric
10248675466SDimitry Andric // Return Lang as one of the canonical supported types.
10348675466SDimitry Andric // e.g. c-header --> c; fortran --> TY_INVALID
foldType(types::ID Lang)10448675466SDimitry Andric static types::ID foldType(types::ID Lang) {
10548675466SDimitry Andric switch (Lang) {
10648675466SDimitry Andric case types::TY_C:
10748675466SDimitry Andric case types::TY_CHeader:
10848675466SDimitry Andric return types::TY_C;
10948675466SDimitry Andric case types::TY_ObjC:
11048675466SDimitry Andric case types::TY_ObjCHeader:
11148675466SDimitry Andric return types::TY_ObjC;
11248675466SDimitry Andric case types::TY_CXX:
11348675466SDimitry Andric case types::TY_CXXHeader:
11448675466SDimitry Andric return types::TY_CXX;
11548675466SDimitry Andric case types::TY_ObjCXX:
11648675466SDimitry Andric case types::TY_ObjCXXHeader:
11748675466SDimitry Andric return types::TY_ObjCXX;
118cfca06d7SDimitry Andric case types::TY_CUDA:
119cfca06d7SDimitry Andric case types::TY_CUDA_DEVICE:
120cfca06d7SDimitry Andric return types::TY_CUDA;
12148675466SDimitry Andric default:
12248675466SDimitry Andric return types::TY_INVALID;
12348675466SDimitry Andric }
12448675466SDimitry Andric }
12548675466SDimitry Andric
12648675466SDimitry Andric // A CompileCommand that can be applied to another file.
12748675466SDimitry Andric struct TransferableCommand {
12848675466SDimitry Andric // Flags that should not apply to all files are stripped from CommandLine.
12948675466SDimitry Andric CompileCommand Cmd;
130676fbe81SDimitry Andric // Language detected from -x or the filename. Never TY_INVALID.
131e3b55780SDimitry Andric std::optional<types::ID> Type;
13248675466SDimitry Andric // Standard specified by -std.
13348675466SDimitry Andric LangStandard::Kind Std = LangStandard::lang_unspecified;
134676fbe81SDimitry Andric // Whether the command line is for the cl-compatible driver.
135676fbe81SDimitry Andric bool ClangCLMode;
13648675466SDimitry Andric
TransferableCommandclang::tooling::__anon9618e36e0111::TransferableCommand13748675466SDimitry Andric TransferableCommand(CompileCommand C)
138344a3780SDimitry Andric : Cmd(std::move(C)), Type(guessType(Cmd.Filename)) {
139676fbe81SDimitry Andric std::vector<std::string> OldArgs = std::move(Cmd.CommandLine);
140676fbe81SDimitry Andric Cmd.CommandLine.clear();
141676fbe81SDimitry Andric
142676fbe81SDimitry Andric // Wrap the old arguments in an InputArgList.
143676fbe81SDimitry Andric llvm::opt::InputArgList ArgList;
144676fbe81SDimitry Andric {
145676fbe81SDimitry Andric SmallVector<const char *, 16> TmpArgv;
146676fbe81SDimitry Andric for (const std::string &S : OldArgs)
147676fbe81SDimitry Andric TmpArgv.push_back(S.c_str());
148344a3780SDimitry Andric ClangCLMode = !TmpArgv.empty() &&
149344a3780SDimitry Andric driver::IsClangCL(driver::getDriverMode(
150e3b55780SDimitry Andric TmpArgv.front(), llvm::ArrayRef(TmpArgv).slice(1)));
151676fbe81SDimitry Andric ArgList = {TmpArgv.begin(), TmpArgv.end()};
152676fbe81SDimitry Andric }
153676fbe81SDimitry Andric
15448675466SDimitry Andric // Parse the old args in order to strip out and record unwanted flags.
155676fbe81SDimitry Andric // We parse each argument individually so that we can retain the exact
156676fbe81SDimitry Andric // spelling of each argument; re-rendering is lossy for aliased flags.
157676fbe81SDimitry Andric // E.g. in CL mode, /W4 maps to -Wall.
158519fc96cSDimitry Andric auto &OptTable = clang::driver::getDriverOptTable();
15922989816SDimitry Andric if (!OldArgs.empty())
160676fbe81SDimitry Andric Cmd.CommandLine.emplace_back(OldArgs.front());
161676fbe81SDimitry Andric for (unsigned Pos = 1; Pos < OldArgs.size();) {
162676fbe81SDimitry Andric using namespace driver::options;
163676fbe81SDimitry Andric
164676fbe81SDimitry Andric const unsigned OldPos = Pos;
165519fc96cSDimitry Andric std::unique_ptr<llvm::opt::Arg> Arg(OptTable.ParseOneArg(
166676fbe81SDimitry Andric ArgList, Pos,
167b1c73532SDimitry Andric llvm::opt::Visibility(ClangCLMode ? CLOption : ClangOption)));
168676fbe81SDimitry Andric
169676fbe81SDimitry Andric if (!Arg)
170676fbe81SDimitry Andric continue;
171676fbe81SDimitry Andric
172676fbe81SDimitry Andric const llvm::opt::Option &Opt = Arg->getOption();
173676fbe81SDimitry Andric
17448675466SDimitry Andric // Strip input and output files.
175676fbe81SDimitry Andric if (Opt.matches(OPT_INPUT) || Opt.matches(OPT_o) ||
176676fbe81SDimitry Andric (ClangCLMode && (Opt.matches(OPT__SLASH_Fa) ||
177676fbe81SDimitry Andric Opt.matches(OPT__SLASH_Fe) ||
178676fbe81SDimitry Andric Opt.matches(OPT__SLASH_Fi) ||
179676fbe81SDimitry Andric Opt.matches(OPT__SLASH_Fo))))
18048675466SDimitry Andric continue;
181676fbe81SDimitry Andric
182344a3780SDimitry Andric // ...including when the inputs are passed after --.
183344a3780SDimitry Andric if (Opt.matches(OPT__DASH_DASH))
184344a3780SDimitry Andric break;
185344a3780SDimitry Andric
18648675466SDimitry Andric // Strip -x, but record the overridden language.
187676fbe81SDimitry Andric if (const auto GivenType = tryParseTypeArg(*Arg)) {
188676fbe81SDimitry Andric Type = *GivenType;
18948675466SDimitry Andric continue;
19048675466SDimitry Andric }
191676fbe81SDimitry Andric
192676fbe81SDimitry Andric // Strip -std, but record the value.
193676fbe81SDimitry Andric if (const auto GivenStd = tryParseStdArg(*Arg)) {
194676fbe81SDimitry Andric if (*GivenStd != LangStandard::lang_unspecified)
195676fbe81SDimitry Andric Std = *GivenStd;
19648675466SDimitry Andric continue;
19748675466SDimitry Andric }
198676fbe81SDimitry Andric
199676fbe81SDimitry Andric Cmd.CommandLine.insert(Cmd.CommandLine.end(),
200676fbe81SDimitry Andric OldArgs.data() + OldPos, OldArgs.data() + Pos);
20148675466SDimitry Andric }
20248675466SDimitry Andric
203706b4fc4SDimitry Andric // Make use of -std iff -x was missing.
204706b4fc4SDimitry Andric if (Type == types::TY_INVALID && Std != LangStandard::lang_unspecified)
20548675466SDimitry Andric Type = toType(LangStandard::getLangStandardForKind(Std).getLanguage());
206676fbe81SDimitry Andric Type = foldType(*Type);
207676fbe81SDimitry Andric // The contract is to store None instead of TY_INVALID.
208676fbe81SDimitry Andric if (Type == types::TY_INVALID)
209e3b55780SDimitry Andric Type = std::nullopt;
21048675466SDimitry Andric }
21148675466SDimitry Andric
21248675466SDimitry Andric // Produce a CompileCommand for \p filename, based on this one.
213344a3780SDimitry Andric // (This consumes the TransferableCommand just to avoid copying Cmd).
transferToclang::tooling::__anon9618e36e0111::TransferableCommand214344a3780SDimitry Andric CompileCommand transferTo(StringRef Filename) && {
215344a3780SDimitry Andric CompileCommand Result = std::move(Cmd);
216344a3780SDimitry Andric Result.Heuristic = "inferred from " + Result.Filename;
217cfca06d7SDimitry Andric Result.Filename = std::string(Filename);
21848675466SDimitry Andric bool TypeCertain;
21948675466SDimitry Andric auto TargetType = guessType(Filename, &TypeCertain);
22048675466SDimitry Andric // If the filename doesn't determine the language (.h), transfer with -x.
22122989816SDimitry Andric if ((!TargetType || !TypeCertain) && Type) {
22222989816SDimitry Andric // Use *Type, or its header variant if the file is a header.
22322989816SDimitry Andric // Treat no/invalid extension as header (e.g. C++ standard library).
22422989816SDimitry Andric TargetType =
22522989816SDimitry Andric (!TargetType || types::onlyPrecompileType(TargetType)) // header?
226676fbe81SDimitry Andric ? types::lookupHeaderTypeForSourceType(*Type)
227676fbe81SDimitry Andric : *Type;
228676fbe81SDimitry Andric if (ClangCLMode) {
229676fbe81SDimitry Andric const StringRef Flag = toCLFlag(TargetType);
230676fbe81SDimitry Andric if (!Flag.empty())
231cfca06d7SDimitry Andric Result.CommandLine.push_back(std::string(Flag));
232676fbe81SDimitry Andric } else {
23348675466SDimitry Andric Result.CommandLine.push_back("-x");
23448675466SDimitry Andric Result.CommandLine.push_back(types::getTypeName(TargetType));
23548675466SDimitry Andric }
236676fbe81SDimitry Andric }
23748675466SDimitry Andric // --std flag may only be transferred if the language is the same.
23848675466SDimitry Andric // We may consider "translating" these, e.g. c++11 -> c11.
23948675466SDimitry Andric if (Std != LangStandard::lang_unspecified && foldType(TargetType) == Type) {
240676fbe81SDimitry Andric Result.CommandLine.emplace_back((
241676fbe81SDimitry Andric llvm::Twine(ClangCLMode ? "/std:" : "-std=") +
242676fbe81SDimitry Andric LangStandard::getLangStandardForKind(Std).getName()).str());
24348675466SDimitry Andric }
244344a3780SDimitry Andric Result.CommandLine.push_back("--");
245cfca06d7SDimitry Andric Result.CommandLine.push_back(std::string(Filename));
24648675466SDimitry Andric return Result;
24748675466SDimitry Andric }
24848675466SDimitry Andric
24948675466SDimitry Andric private:
25048675466SDimitry Andric // Map the language from the --std flag to that of the -x flag.
toTypeclang::tooling::__anon9618e36e0111::TransferableCommand251519fc96cSDimitry Andric static types::ID toType(Language Lang) {
25248675466SDimitry Andric switch (Lang) {
253519fc96cSDimitry Andric case Language::C:
25448675466SDimitry Andric return types::TY_C;
255519fc96cSDimitry Andric case Language::CXX:
25648675466SDimitry Andric return types::TY_CXX;
257519fc96cSDimitry Andric case Language::ObjC:
25848675466SDimitry Andric return types::TY_ObjC;
259519fc96cSDimitry Andric case Language::ObjCXX:
26048675466SDimitry Andric return types::TY_ObjCXX;
26148675466SDimitry Andric default:
26248675466SDimitry Andric return types::TY_INVALID;
26348675466SDimitry Andric }
26448675466SDimitry Andric }
265676fbe81SDimitry Andric
266676fbe81SDimitry Andric // Convert a file type to the matching CL-style type flag.
toCLFlagclang::tooling::__anon9618e36e0111::TransferableCommand267676fbe81SDimitry Andric static StringRef toCLFlag(types::ID Type) {
268676fbe81SDimitry Andric switch (Type) {
269676fbe81SDimitry Andric case types::TY_C:
270676fbe81SDimitry Andric case types::TY_CHeader:
271676fbe81SDimitry Andric return "/TC";
272676fbe81SDimitry Andric case types::TY_CXX:
273676fbe81SDimitry Andric case types::TY_CXXHeader:
274676fbe81SDimitry Andric return "/TP";
275676fbe81SDimitry Andric default:
276676fbe81SDimitry Andric return StringRef();
277676fbe81SDimitry Andric }
278676fbe81SDimitry Andric }
279676fbe81SDimitry Andric
280676fbe81SDimitry Andric // Try to interpret the argument as a type specifier, e.g. '-x'.
tryParseTypeArgclang::tooling::__anon9618e36e0111::TransferableCommand281e3b55780SDimitry Andric std::optional<types::ID> tryParseTypeArg(const llvm::opt::Arg &Arg) {
282676fbe81SDimitry Andric const llvm::opt::Option &Opt = Arg.getOption();
283676fbe81SDimitry Andric using namespace driver::options;
284676fbe81SDimitry Andric if (ClangCLMode) {
285676fbe81SDimitry Andric if (Opt.matches(OPT__SLASH_TC) || Opt.matches(OPT__SLASH_Tc))
286676fbe81SDimitry Andric return types::TY_C;
287676fbe81SDimitry Andric if (Opt.matches(OPT__SLASH_TP) || Opt.matches(OPT__SLASH_Tp))
288676fbe81SDimitry Andric return types::TY_CXX;
289676fbe81SDimitry Andric } else {
290676fbe81SDimitry Andric if (Opt.matches(driver::options::OPT_x))
291676fbe81SDimitry Andric return types::lookupTypeForTypeSpecifier(Arg.getValue());
292676fbe81SDimitry Andric }
293e3b55780SDimitry Andric return std::nullopt;
294676fbe81SDimitry Andric }
295676fbe81SDimitry Andric
296676fbe81SDimitry Andric // Try to interpret the argument as '-std='.
tryParseStdArgclang::tooling::__anon9618e36e0111::TransferableCommand297e3b55780SDimitry Andric std::optional<LangStandard::Kind> tryParseStdArg(const llvm::opt::Arg &Arg) {
298676fbe81SDimitry Andric using namespace driver::options;
299519fc96cSDimitry Andric if (Arg.getOption().matches(ClangCLMode ? OPT__SLASH_std : OPT_std_EQ))
300519fc96cSDimitry Andric return LangStandard::getLangKind(Arg.getValue());
301e3b55780SDimitry Andric return std::nullopt;
302676fbe81SDimitry Andric }
30348675466SDimitry Andric };
30448675466SDimitry Andric
305676fbe81SDimitry Andric // Given a filename, FileIndex picks the best matching file from the underlying
306676fbe81SDimitry Andric // DB. This is the proxy file whose CompileCommand will be reused. The
307676fbe81SDimitry Andric // heuristics incorporate file name, extension, and directory structure.
308676fbe81SDimitry Andric // Strategy:
30948675466SDimitry Andric // - Build indexes of each of the substrings we want to look up by.
31048675466SDimitry Andric // These indexes are just sorted lists of the substrings.
31148675466SDimitry Andric // - Each criterion corresponds to a range lookup into the index, so we only
31248675466SDimitry Andric // need O(log N) string comparisons to determine scores.
313676fbe81SDimitry Andric //
314676fbe81SDimitry Andric // Apart from path proximity signals, also takes file extensions into account
315676fbe81SDimitry Andric // when scoring the candidates.
316676fbe81SDimitry Andric class FileIndex {
31748675466SDimitry Andric public:
FileIndex(std::vector<std::string> Files)318676fbe81SDimitry Andric FileIndex(std::vector<std::string> Files)
319676fbe81SDimitry Andric : OriginalPaths(std::move(Files)), Strings(Arena) {
32048675466SDimitry Andric // Sort commands by filename for determinism (index is a tiebreaker later).
321676fbe81SDimitry Andric llvm::sort(OriginalPaths);
322676fbe81SDimitry Andric Paths.reserve(OriginalPaths.size());
323676fbe81SDimitry Andric Types.reserve(OriginalPaths.size());
324676fbe81SDimitry Andric Stems.reserve(OriginalPaths.size());
325676fbe81SDimitry Andric for (size_t I = 0; I < OriginalPaths.size(); ++I) {
326676fbe81SDimitry Andric StringRef Path = Strings.save(StringRef(OriginalPaths[I]).lower());
327676fbe81SDimitry Andric
328676fbe81SDimitry Andric Paths.emplace_back(Path, I);
329145449b1SDimitry Andric Types.push_back(foldType(guessType(OriginalPaths[I])));
33048675466SDimitry Andric Stems.emplace_back(sys::path::stem(Path), I);
33148675466SDimitry Andric auto Dir = ++sys::path::rbegin(Path), DirEnd = sys::path::rend(Path);
33248675466SDimitry Andric for (int J = 0; J < DirectorySegmentsIndexed && Dir != DirEnd; ++J, ++Dir)
33348675466SDimitry Andric if (Dir->size() > ShortDirectorySegment) // not trivial ones
33448675466SDimitry Andric Components.emplace_back(*Dir, I);
33548675466SDimitry Andric }
336676fbe81SDimitry Andric llvm::sort(Paths);
337676fbe81SDimitry Andric llvm::sort(Stems);
338676fbe81SDimitry Andric llvm::sort(Components);
33948675466SDimitry Andric }
34048675466SDimitry Andric
empty() const341676fbe81SDimitry Andric bool empty() const { return Paths.empty(); }
34248675466SDimitry Andric
343676fbe81SDimitry Andric // Returns the path for the file that best fits OriginalFilename.
344676fbe81SDimitry Andric // Candidates with extensions matching PreferLanguage will be chosen over
345676fbe81SDimitry Andric // others (unless it's TY_INVALID, or all candidates are bad).
chooseProxy(StringRef OriginalFilename,types::ID PreferLanguage) const346676fbe81SDimitry Andric StringRef chooseProxy(StringRef OriginalFilename,
34748675466SDimitry Andric types::ID PreferLanguage) const {
34848675466SDimitry Andric assert(!empty() && "need at least one candidate!");
34948675466SDimitry Andric std::string Filename = OriginalFilename.lower();
35048675466SDimitry Andric auto Candidates = scoreCandidates(Filename);
35148675466SDimitry Andric std::pair<size_t, int> Best =
35248675466SDimitry Andric pickWinner(Candidates, Filename, PreferLanguage);
35348675466SDimitry Andric
354676fbe81SDimitry Andric DEBUG_WITH_TYPE(
355676fbe81SDimitry Andric "interpolate",
356676fbe81SDimitry Andric llvm::dbgs() << "interpolate: chose " << OriginalPaths[Best.first]
357676fbe81SDimitry Andric << " as proxy for " << OriginalFilename << " preferring "
35848675466SDimitry Andric << (PreferLanguage == types::TY_INVALID
35948675466SDimitry Andric ? "none"
36048675466SDimitry Andric : types::getTypeName(PreferLanguage))
36148675466SDimitry Andric << " score=" << Best.second << "\n");
362676fbe81SDimitry Andric return OriginalPaths[Best.first];
36348675466SDimitry Andric }
36448675466SDimitry Andric
36548675466SDimitry Andric private:
36648675466SDimitry Andric using SubstringAndIndex = std::pair<StringRef, size_t>;
36748675466SDimitry Andric // Directory matching parameters: we look at the last two segments of the
36848675466SDimitry Andric // parent directory (usually the semantically significant ones in practice).
36948675466SDimitry Andric // We search only the last four of each candidate (for efficiency).
37048675466SDimitry Andric constexpr static int DirectorySegmentsIndexed = 4;
37148675466SDimitry Andric constexpr static int DirectorySegmentsQueried = 2;
37248675466SDimitry Andric constexpr static int ShortDirectorySegment = 1; // Only look at longer names.
37348675466SDimitry Andric
37448675466SDimitry Andric // Award points to candidate entries that should be considered for the file.
37548675466SDimitry Andric // Returned keys are indexes into paths, and the values are (nonzero) scores.
scoreCandidates(StringRef Filename) const37648675466SDimitry Andric DenseMap<size_t, int> scoreCandidates(StringRef Filename) const {
37748675466SDimitry Andric // Decompose Filename into the parts we care about.
37848675466SDimitry Andric // /some/path/complicated/project/Interesting.h
37948675466SDimitry Andric // [-prefix--][---dir---] [-dir-] [--stem---]
38048675466SDimitry Andric StringRef Stem = sys::path::stem(Filename);
38148675466SDimitry Andric llvm::SmallVector<StringRef, DirectorySegmentsQueried> Dirs;
38248675466SDimitry Andric llvm::StringRef Prefix;
38348675466SDimitry Andric auto Dir = ++sys::path::rbegin(Filename),
38448675466SDimitry Andric DirEnd = sys::path::rend(Filename);
38548675466SDimitry Andric for (int I = 0; I < DirectorySegmentsQueried && Dir != DirEnd; ++I, ++Dir) {
38648675466SDimitry Andric if (Dir->size() > ShortDirectorySegment)
38748675466SDimitry Andric Dirs.push_back(*Dir);
38848675466SDimitry Andric Prefix = Filename.substr(0, Dir - DirEnd);
38948675466SDimitry Andric }
39048675466SDimitry Andric
39148675466SDimitry Andric // Now award points based on lookups into our various indexes.
39248675466SDimitry Andric DenseMap<size_t, int> Candidates; // Index -> score.
39348675466SDimitry Andric auto Award = [&](int Points, ArrayRef<SubstringAndIndex> Range) {
39448675466SDimitry Andric for (const auto &Entry : Range)
39548675466SDimitry Andric Candidates[Entry.second] += Points;
39648675466SDimitry Andric };
39748675466SDimitry Andric // Award one point if the file's basename is a prefix of the candidate,
39848675466SDimitry Andric // and another if it's an exact match (so exact matches get two points).
39948675466SDimitry Andric Award(1, indexLookup</*Prefix=*/true>(Stem, Stems));
40048675466SDimitry Andric Award(1, indexLookup</*Prefix=*/false>(Stem, Stems));
40148675466SDimitry Andric // For each of the last few directories in the Filename, award a point
40248675466SDimitry Andric // if it's present in the candidate.
40348675466SDimitry Andric for (StringRef Dir : Dirs)
40448675466SDimitry Andric Award(1, indexLookup</*Prefix=*/false>(Dir, Components));
40548675466SDimitry Andric // Award one more point if the whole rest of the path matches.
40648675466SDimitry Andric if (sys::path::root_directory(Prefix) != Prefix)
40748675466SDimitry Andric Award(1, indexLookup</*Prefix=*/true>(Prefix, Paths));
40848675466SDimitry Andric return Candidates;
40948675466SDimitry Andric }
41048675466SDimitry Andric
41148675466SDimitry Andric // Pick a single winner from the set of scored candidates.
41248675466SDimitry Andric // Returns (index, score).
pickWinner(const DenseMap<size_t,int> & Candidates,StringRef Filename,types::ID PreferredLanguage) const41348675466SDimitry Andric std::pair<size_t, int> pickWinner(const DenseMap<size_t, int> &Candidates,
41448675466SDimitry Andric StringRef Filename,
41548675466SDimitry Andric types::ID PreferredLanguage) const {
41648675466SDimitry Andric struct ScoredCandidate {
41748675466SDimitry Andric size_t Index;
41848675466SDimitry Andric bool Preferred;
41948675466SDimitry Andric int Points;
42048675466SDimitry Andric size_t PrefixLength;
42148675466SDimitry Andric };
42248675466SDimitry Andric // Choose the best candidate by (preferred, points, prefix length, alpha).
42348675466SDimitry Andric ScoredCandidate Best = {size_t(-1), false, 0, 0};
42448675466SDimitry Andric for (const auto &Candidate : Candidates) {
42548675466SDimitry Andric ScoredCandidate S;
42648675466SDimitry Andric S.Index = Candidate.first;
42748675466SDimitry Andric S.Preferred = PreferredLanguage == types::TY_INVALID ||
428676fbe81SDimitry Andric PreferredLanguage == Types[S.Index];
42948675466SDimitry Andric S.Points = Candidate.second;
43048675466SDimitry Andric if (!S.Preferred && Best.Preferred)
43148675466SDimitry Andric continue;
43248675466SDimitry Andric if (S.Preferred == Best.Preferred) {
43348675466SDimitry Andric if (S.Points < Best.Points)
43448675466SDimitry Andric continue;
43548675466SDimitry Andric if (S.Points == Best.Points) {
43648675466SDimitry Andric S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
43748675466SDimitry Andric if (S.PrefixLength < Best.PrefixLength)
43848675466SDimitry Andric continue;
43948675466SDimitry Andric // hidden heuristics should at least be deterministic!
44048675466SDimitry Andric if (S.PrefixLength == Best.PrefixLength)
44148675466SDimitry Andric if (S.Index > Best.Index)
44248675466SDimitry Andric continue;
44348675466SDimitry Andric }
44448675466SDimitry Andric }
44548675466SDimitry Andric // PrefixLength was only set above if actually needed for a tiebreak.
44648675466SDimitry Andric // But it definitely needs to be set to break ties in the future.
44748675466SDimitry Andric S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
44848675466SDimitry Andric Best = S;
44948675466SDimitry Andric }
45048675466SDimitry Andric // Edge case: no candidate got any points.
45148675466SDimitry Andric // We ignore PreferredLanguage at this point (not ideal).
45248675466SDimitry Andric if (Best.Index == size_t(-1))
45348675466SDimitry Andric return {longestMatch(Filename, Paths).second, 0};
45448675466SDimitry Andric return {Best.Index, Best.Points};
45548675466SDimitry Andric }
45648675466SDimitry Andric
45748675466SDimitry Andric // Returns the range within a sorted index that compares equal to Key.
45848675466SDimitry Andric // If Prefix is true, it's instead the range starting with Key.
45948675466SDimitry Andric template <bool Prefix>
46048675466SDimitry Andric ArrayRef<SubstringAndIndex>
indexLookup(StringRef Key,ArrayRef<SubstringAndIndex> Idx) const461676fbe81SDimitry Andric indexLookup(StringRef Key, ArrayRef<SubstringAndIndex> Idx) const {
46248675466SDimitry Andric // Use pointers as iteratiors to ease conversion of result to ArrayRef.
46348675466SDimitry Andric auto Range = std::equal_range(Idx.data(), Idx.data() + Idx.size(), Key,
46448675466SDimitry Andric Less<Prefix>());
46548675466SDimitry Andric return {Range.first, Range.second};
46648675466SDimitry Andric }
46748675466SDimitry Andric
46848675466SDimitry Andric // Performs a point lookup into a nonempty index, returning a longest match.
longestMatch(StringRef Key,ArrayRef<SubstringAndIndex> Idx) const469676fbe81SDimitry Andric SubstringAndIndex longestMatch(StringRef Key,
470676fbe81SDimitry Andric ArrayRef<SubstringAndIndex> Idx) const {
47148675466SDimitry Andric assert(!Idx.empty());
47248675466SDimitry Andric // Longest substring match will be adjacent to a direct lookup.
47322989816SDimitry Andric auto It = llvm::lower_bound(Idx, SubstringAndIndex{Key, 0});
47448675466SDimitry Andric if (It == Idx.begin())
47548675466SDimitry Andric return *It;
47648675466SDimitry Andric if (It == Idx.end())
47748675466SDimitry Andric return *--It;
47848675466SDimitry Andric // Have to choose between It and It-1
47948675466SDimitry Andric size_t Prefix = matchingPrefix(Key, It->first);
48048675466SDimitry Andric size_t PrevPrefix = matchingPrefix(Key, (It - 1)->first);
48148675466SDimitry Andric return Prefix > PrevPrefix ? *It : *--It;
48248675466SDimitry Andric }
48348675466SDimitry Andric
484676fbe81SDimitry Andric // Original paths, everything else is in lowercase.
485676fbe81SDimitry Andric std::vector<std::string> OriginalPaths;
48648675466SDimitry Andric BumpPtrAllocator Arena;
48748675466SDimitry Andric StringSaver Strings;
48848675466SDimitry Andric // Indexes of candidates by certain substrings.
48948675466SDimitry Andric // String is lowercase and sorted, index points into OriginalPaths.
49048675466SDimitry Andric std::vector<SubstringAndIndex> Paths; // Full path.
491676fbe81SDimitry Andric // Lang types obtained by guessing on the corresponding path. I-th element is
492676fbe81SDimitry Andric // a type for the I-th path.
493676fbe81SDimitry Andric std::vector<types::ID> Types;
49448675466SDimitry Andric std::vector<SubstringAndIndex> Stems; // Basename, without extension.
49548675466SDimitry Andric std::vector<SubstringAndIndex> Components; // Last path components.
49648675466SDimitry Andric };
49748675466SDimitry Andric
49848675466SDimitry Andric // The actual CompilationDatabase wrapper delegates to its inner database.
499676fbe81SDimitry Andric // If no match, looks up a proxy file in FileIndex and transfers its
500676fbe81SDimitry Andric // command to the requested file.
50148675466SDimitry Andric class InterpolatingCompilationDatabase : public CompilationDatabase {
50248675466SDimitry Andric public:
InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)50348675466SDimitry Andric InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)
504676fbe81SDimitry Andric : Inner(std::move(Inner)), Index(this->Inner->getAllFiles()) {}
50548675466SDimitry Andric
50648675466SDimitry Andric std::vector<CompileCommand>
getCompileCommands(StringRef Filename) const50748675466SDimitry Andric getCompileCommands(StringRef Filename) const override {
50848675466SDimitry Andric auto Known = Inner->getCompileCommands(Filename);
50948675466SDimitry Andric if (Index.empty() || !Known.empty())
51048675466SDimitry Andric return Known;
51148675466SDimitry Andric bool TypeCertain;
51248675466SDimitry Andric auto Lang = guessType(Filename, &TypeCertain);
51348675466SDimitry Andric if (!TypeCertain)
51448675466SDimitry Andric Lang = types::TY_INVALID;
515676fbe81SDimitry Andric auto ProxyCommands =
516676fbe81SDimitry Andric Inner->getCompileCommands(Index.chooseProxy(Filename, foldType(Lang)));
517676fbe81SDimitry Andric if (ProxyCommands.empty())
518676fbe81SDimitry Andric return {};
519344a3780SDimitry Andric return {transferCompileCommand(std::move(ProxyCommands.front()), Filename)};
52048675466SDimitry Andric }
52148675466SDimitry Andric
getAllFiles() const52248675466SDimitry Andric std::vector<std::string> getAllFiles() const override {
52348675466SDimitry Andric return Inner->getAllFiles();
52448675466SDimitry Andric }
52548675466SDimitry Andric
getAllCompileCommands() const52648675466SDimitry Andric std::vector<CompileCommand> getAllCompileCommands() const override {
52748675466SDimitry Andric return Inner->getAllCompileCommands();
52848675466SDimitry Andric }
52948675466SDimitry Andric
53048675466SDimitry Andric private:
53148675466SDimitry Andric std::unique_ptr<CompilationDatabase> Inner;
532676fbe81SDimitry Andric FileIndex Index;
53348675466SDimitry Andric };
53448675466SDimitry Andric
53548675466SDimitry Andric } // namespace
53648675466SDimitry Andric
53748675466SDimitry Andric std::unique_ptr<CompilationDatabase>
inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner)53848675466SDimitry Andric inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner) {
539519fc96cSDimitry Andric return std::make_unique<InterpolatingCompilationDatabase>(std::move(Inner));
54048675466SDimitry Andric }
54148675466SDimitry Andric
transferCompileCommand(CompileCommand Cmd,StringRef Filename)542344a3780SDimitry Andric tooling::CompileCommand transferCompileCommand(CompileCommand Cmd,
543344a3780SDimitry Andric StringRef Filename) {
544344a3780SDimitry Andric return TransferableCommand(std::move(Cmd)).transferTo(Filename);
545344a3780SDimitry Andric }
546344a3780SDimitry Andric
54748675466SDimitry Andric } // namespace tooling
54848675466SDimitry Andric } // namespace clang
549