InterpolatingCompilationDatabase.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. //===- InterpolatingCompilationDatabase.cpp ---------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // InterpolatingCompilationDatabase wraps another CompilationDatabase and
  10. // attempts to heuristically determine appropriate compile commands for files
  11. // that are not included, such as headers or newly created files.
  12. //
  13. // Motivating cases include:
  14. // Header files that live next to their implementation files. These typically
  15. // share a base filename. (libclang/CXString.h, libclang/CXString.cpp).
  16. // Some projects separate headers from includes. Filenames still typically
  17. // match, maybe other path segments too. (include/llvm/IR/Use.h, lib/IR/Use.cc).
  18. // Matches are sometimes only approximate (Sema.h, SemaDecl.cpp). This goes
  19. // for directories too (Support/Unix/Process.inc, lib/Support/Process.cpp).
  20. // Even if we can't find a "right" compile command, even a random one from
  21. // the project will tend to get important flags like -I and -x right.
  22. //
  23. // We "borrow" the compile command for the closest available file:
  24. // - points are awarded if the filename matches (ignoring extension)
  25. // - points are awarded if the directory structure matches
  26. // - ties are broken by length of path prefix match
  27. //
  28. // The compile command is adjusted, replacing the filename and removing output
  29. // file arguments. The -x and -std flags may be affected too.
  30. //
  31. // Source language is a tricky issue: is it OK to use a .c file's command
  32. // for building a .cc file? What language is a .h file in?
  33. // - We only consider compile commands for c-family languages as candidates.
  34. // - For files whose language is implied by the filename (e.g. .m, .hpp)
  35. // we prefer candidates from the same language.
  36. // If we must cross languages, we drop any -x and -std flags.
  37. // - For .h files, candidates from any c-family language are acceptable.
  38. // We use the candidate's language, inserting e.g. -x c++-header.
  39. //
  40. // This class is only useful when wrapping databases that can enumerate all
  41. // their compile commands. If getAllFilenames() is empty, no inference occurs.
  42. //
  43. //===----------------------------------------------------------------------===//
  44. #include "clang/Driver/Options.h"
  45. #include "clang/Driver/Types.h"
  46. #include "clang/Frontend/LangStandard.h"
  47. #include "clang/Tooling/CompilationDatabase.h"
  48. #include "llvm/ADT/DenseMap.h"
  49. #include "llvm/ADT/Optional.h"
  50. #include "llvm/ADT/StringExtras.h"
  51. #include "llvm/ADT/StringSwitch.h"
  52. #include "llvm/Option/ArgList.h"
  53. #include "llvm/Option/OptTable.h"
  54. #include "llvm/Support/Debug.h"
  55. #include "llvm/Support/Path.h"
  56. #include "llvm/Support/StringSaver.h"
  57. #include "llvm/Support/raw_ostream.h"
  58. #include <memory>
  59. namespace clang {
  60. namespace tooling {
  61. namespace {
  62. using namespace llvm;
  63. namespace types = clang::driver::types;
  64. namespace path = llvm::sys::path;
  65. // The length of the prefix these two strings have in common.
  66. size_t matchingPrefix(StringRef L, StringRef R) {
  67. size_t Limit = std::min(L.size(), R.size());
  68. for (size_t I = 0; I < Limit; ++I)
  69. if (L[I] != R[I])
  70. return I;
  71. return Limit;
  72. }
  73. // A comparator for searching SubstringWithIndexes with std::equal_range etc.
  74. // Optionaly prefix semantics: compares equal if the key is a prefix.
  75. template <bool Prefix> struct Less {
  76. bool operator()(StringRef Key, std::pair<StringRef, size_t> Value) const {
  77. StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
  78. return Key < V;
  79. }
  80. bool operator()(std::pair<StringRef, size_t> Value, StringRef Key) const {
  81. StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
  82. return V < Key;
  83. }
  84. };
  85. // Infer type from filename. If we might have gotten it wrong, set *Certain.
  86. // *.h will be inferred as a C header, but not certain.
  87. types::ID guessType(StringRef Filename, bool *Certain = nullptr) {
  88. // path::extension is ".cpp", lookupTypeForExtension wants "cpp".
  89. auto Lang =
  90. types::lookupTypeForExtension(path::extension(Filename).substr(1));
  91. if (Certain)
  92. *Certain = Lang != types::TY_CHeader && Lang != types::TY_INVALID;
  93. return Lang;
  94. }
  95. // Return Lang as one of the canonical supported types.
  96. // e.g. c-header --> c; fortran --> TY_INVALID
  97. static types::ID foldType(types::ID Lang) {
  98. switch (Lang) {
  99. case types::TY_C:
  100. case types::TY_CHeader:
  101. return types::TY_C;
  102. case types::TY_ObjC:
  103. case types::TY_ObjCHeader:
  104. return types::TY_ObjC;
  105. case types::TY_CXX:
  106. case types::TY_CXXHeader:
  107. return types::TY_CXX;
  108. case types::TY_ObjCXX:
  109. case types::TY_ObjCXXHeader:
  110. return types::TY_ObjCXX;
  111. default:
  112. return types::TY_INVALID;
  113. }
  114. }
  115. // A CompileCommand that can be applied to another file.
  116. struct TransferableCommand {
  117. // Flags that should not apply to all files are stripped from CommandLine.
  118. CompileCommand Cmd;
  119. // Language detected from -x or the filename. Never TY_INVALID.
  120. Optional<types::ID> Type;
  121. // Standard specified by -std.
  122. LangStandard::Kind Std = LangStandard::lang_unspecified;
  123. // Whether the command line is for the cl-compatible driver.
  124. bool ClangCLMode;
  125. TransferableCommand(CompileCommand C)
  126. : Cmd(std::move(C)), Type(guessType(Cmd.Filename)),
  127. ClangCLMode(checkIsCLMode(Cmd.CommandLine)) {
  128. std::vector<std::string> OldArgs = std::move(Cmd.CommandLine);
  129. Cmd.CommandLine.clear();
  130. // Wrap the old arguments in an InputArgList.
  131. llvm::opt::InputArgList ArgList;
  132. {
  133. SmallVector<const char *, 16> TmpArgv;
  134. for (const std::string &S : OldArgs)
  135. TmpArgv.push_back(S.c_str());
  136. ArgList = {TmpArgv.begin(), TmpArgv.end()};
  137. }
  138. // Parse the old args in order to strip out and record unwanted flags.
  139. // We parse each argument individually so that we can retain the exact
  140. // spelling of each argument; re-rendering is lossy for aliased flags.
  141. // E.g. in CL mode, /W4 maps to -Wall.
  142. auto OptTable = clang::driver::createDriverOptTable();
  143. if (!OldArgs.empty())
  144. Cmd.CommandLine.emplace_back(OldArgs.front());
  145. for (unsigned Pos = 1; Pos < OldArgs.size();) {
  146. using namespace driver::options;
  147. const unsigned OldPos = Pos;
  148. std::unique_ptr<llvm::opt::Arg> Arg(OptTable->ParseOneArg(
  149. ArgList, Pos,
  150. /* Include */ClangCLMode ? CoreOption | CLOption : 0,
  151. /* Exclude */ClangCLMode ? 0 : CLOption));
  152. if (!Arg)
  153. continue;
  154. const llvm::opt::Option &Opt = Arg->getOption();
  155. // Strip input and output files.
  156. if (Opt.matches(OPT_INPUT) || Opt.matches(OPT_o) ||
  157. (ClangCLMode && (Opt.matches(OPT__SLASH_Fa) ||
  158. Opt.matches(OPT__SLASH_Fe) ||
  159. Opt.matches(OPT__SLASH_Fi) ||
  160. Opt.matches(OPT__SLASH_Fo))))
  161. continue;
  162. // Strip -x, but record the overridden language.
  163. if (const auto GivenType = tryParseTypeArg(*Arg)) {
  164. Type = *GivenType;
  165. continue;
  166. }
  167. // Strip -std, but record the value.
  168. if (const auto GivenStd = tryParseStdArg(*Arg)) {
  169. if (*GivenStd != LangStandard::lang_unspecified)
  170. Std = *GivenStd;
  171. continue;
  172. }
  173. Cmd.CommandLine.insert(Cmd.CommandLine.end(),
  174. OldArgs.data() + OldPos, OldArgs.data() + Pos);
  175. }
  176. if (Std != LangStandard::lang_unspecified) // -std take precedence over -x
  177. Type = toType(LangStandard::getLangStandardForKind(Std).getLanguage());
  178. Type = foldType(*Type);
  179. // The contract is to store None instead of TY_INVALID.
  180. if (Type == types::TY_INVALID)
  181. Type = llvm::None;
  182. }
  183. // Produce a CompileCommand for \p filename, based on this one.
  184. CompileCommand transferTo(StringRef Filename) const {
  185. CompileCommand Result = Cmd;
  186. Result.Filename = Filename;
  187. bool TypeCertain;
  188. auto TargetType = guessType(Filename, &TypeCertain);
  189. // If the filename doesn't determine the language (.h), transfer with -x.
  190. if ((!TargetType || !TypeCertain) && Type) {
  191. // Use *Type, or its header variant if the file is a header.
  192. // Treat no/invalid extension as header (e.g. C++ standard library).
  193. TargetType =
  194. (!TargetType || types::onlyPrecompileType(TargetType)) // header?
  195. ? types::lookupHeaderTypeForSourceType(*Type)
  196. : *Type;
  197. if (ClangCLMode) {
  198. const StringRef Flag = toCLFlag(TargetType);
  199. if (!Flag.empty())
  200. Result.CommandLine.push_back(Flag);
  201. } else {
  202. Result.CommandLine.push_back("-x");
  203. Result.CommandLine.push_back(types::getTypeName(TargetType));
  204. }
  205. }
  206. // --std flag may only be transferred if the language is the same.
  207. // We may consider "translating" these, e.g. c++11 -> c11.
  208. if (Std != LangStandard::lang_unspecified && foldType(TargetType) == Type) {
  209. Result.CommandLine.emplace_back((
  210. llvm::Twine(ClangCLMode ? "/std:" : "-std=") +
  211. LangStandard::getLangStandardForKind(Std).getName()).str());
  212. }
  213. Result.CommandLine.push_back(Filename);
  214. Result.Heuristic = "inferred from " + Cmd.Filename;
  215. return Result;
  216. }
  217. private:
  218. // Determine whether the given command line is intended for the CL driver.
  219. static bool checkIsCLMode(ArrayRef<std::string> CmdLine) {
  220. // First look for --driver-mode.
  221. for (StringRef S : llvm::reverse(CmdLine)) {
  222. if (S.consume_front("--driver-mode="))
  223. return S == "cl";
  224. }
  225. // Otherwise just check the clang executable file name.
  226. return !CmdLine.empty() &&
  227. llvm::sys::path::stem(CmdLine.front()).endswith_lower("cl");
  228. }
  229. // Map the language from the --std flag to that of the -x flag.
  230. static types::ID toType(InputKind::Language Lang) {
  231. switch (Lang) {
  232. case InputKind::C:
  233. return types::TY_C;
  234. case InputKind::CXX:
  235. return types::TY_CXX;
  236. case InputKind::ObjC:
  237. return types::TY_ObjC;
  238. case InputKind::ObjCXX:
  239. return types::TY_ObjCXX;
  240. default:
  241. return types::TY_INVALID;
  242. }
  243. }
  244. // Convert a file type to the matching CL-style type flag.
  245. static StringRef toCLFlag(types::ID Type) {
  246. switch (Type) {
  247. case types::TY_C:
  248. case types::TY_CHeader:
  249. return "/TC";
  250. case types::TY_CXX:
  251. case types::TY_CXXHeader:
  252. return "/TP";
  253. default:
  254. return StringRef();
  255. }
  256. }
  257. // Try to interpret the argument as a type specifier, e.g. '-x'.
  258. Optional<types::ID> tryParseTypeArg(const llvm::opt::Arg &Arg) {
  259. const llvm::opt::Option &Opt = Arg.getOption();
  260. using namespace driver::options;
  261. if (ClangCLMode) {
  262. if (Opt.matches(OPT__SLASH_TC) || Opt.matches(OPT__SLASH_Tc))
  263. return types::TY_C;
  264. if (Opt.matches(OPT__SLASH_TP) || Opt.matches(OPT__SLASH_Tp))
  265. return types::TY_CXX;
  266. } else {
  267. if (Opt.matches(driver::options::OPT_x))
  268. return types::lookupTypeForTypeSpecifier(Arg.getValue());
  269. }
  270. return None;
  271. }
  272. // Try to interpret the argument as '-std='.
  273. Optional<LangStandard::Kind> tryParseStdArg(const llvm::opt::Arg &Arg) {
  274. using namespace driver::options;
  275. if (Arg.getOption().matches(ClangCLMode ? OPT__SLASH_std : OPT_std_EQ)) {
  276. return llvm::StringSwitch<LangStandard::Kind>(Arg.getValue())
  277. #define LANGSTANDARD(id, name, lang, ...) .Case(name, LangStandard::lang_##id)
  278. #define LANGSTANDARD_ALIAS(id, alias) .Case(alias, LangStandard::lang_##id)
  279. #include "clang/Frontend/LangStandards.def"
  280. #undef LANGSTANDARD_ALIAS
  281. #undef LANGSTANDARD
  282. .Default(LangStandard::lang_unspecified);
  283. }
  284. return None;
  285. }
  286. };
  287. // Given a filename, FileIndex picks the best matching file from the underlying
  288. // DB. This is the proxy file whose CompileCommand will be reused. The
  289. // heuristics incorporate file name, extension, and directory structure.
  290. // Strategy:
  291. // - Build indexes of each of the substrings we want to look up by.
  292. // These indexes are just sorted lists of the substrings.
  293. // - Each criterion corresponds to a range lookup into the index, so we only
  294. // need O(log N) string comparisons to determine scores.
  295. //
  296. // Apart from path proximity signals, also takes file extensions into account
  297. // when scoring the candidates.
  298. class FileIndex {
  299. public:
  300. FileIndex(std::vector<std::string> Files)
  301. : OriginalPaths(std::move(Files)), Strings(Arena) {
  302. // Sort commands by filename for determinism (index is a tiebreaker later).
  303. llvm::sort(OriginalPaths);
  304. Paths.reserve(OriginalPaths.size());
  305. Types.reserve(OriginalPaths.size());
  306. Stems.reserve(OriginalPaths.size());
  307. for (size_t I = 0; I < OriginalPaths.size(); ++I) {
  308. StringRef Path = Strings.save(StringRef(OriginalPaths[I]).lower());
  309. Paths.emplace_back(Path, I);
  310. Types.push_back(foldType(guessType(Path)));
  311. Stems.emplace_back(sys::path::stem(Path), I);
  312. auto Dir = ++sys::path::rbegin(Path), DirEnd = sys::path::rend(Path);
  313. for (int J = 0; J < DirectorySegmentsIndexed && Dir != DirEnd; ++J, ++Dir)
  314. if (Dir->size() > ShortDirectorySegment) // not trivial ones
  315. Components.emplace_back(*Dir, I);
  316. }
  317. llvm::sort(Paths);
  318. llvm::sort(Stems);
  319. llvm::sort(Components);
  320. }
  321. bool empty() const { return Paths.empty(); }
  322. // Returns the path for the file that best fits OriginalFilename.
  323. // Candidates with extensions matching PreferLanguage will be chosen over
  324. // others (unless it's TY_INVALID, or all candidates are bad).
  325. StringRef chooseProxy(StringRef OriginalFilename,
  326. types::ID PreferLanguage) const {
  327. assert(!empty() && "need at least one candidate!");
  328. std::string Filename = OriginalFilename.lower();
  329. auto Candidates = scoreCandidates(Filename);
  330. std::pair<size_t, int> Best =
  331. pickWinner(Candidates, Filename, PreferLanguage);
  332. DEBUG_WITH_TYPE(
  333. "interpolate",
  334. llvm::dbgs() << "interpolate: chose " << OriginalPaths[Best.first]
  335. << " as proxy for " << OriginalFilename << " preferring "
  336. << (PreferLanguage == types::TY_INVALID
  337. ? "none"
  338. : types::getTypeName(PreferLanguage))
  339. << " score=" << Best.second << "\n");
  340. return OriginalPaths[Best.first];
  341. }
  342. private:
  343. using SubstringAndIndex = std::pair<StringRef, size_t>;
  344. // Directory matching parameters: we look at the last two segments of the
  345. // parent directory (usually the semantically significant ones in practice).
  346. // We search only the last four of each candidate (for efficiency).
  347. constexpr static int DirectorySegmentsIndexed = 4;
  348. constexpr static int DirectorySegmentsQueried = 2;
  349. constexpr static int ShortDirectorySegment = 1; // Only look at longer names.
  350. // Award points to candidate entries that should be considered for the file.
  351. // Returned keys are indexes into paths, and the values are (nonzero) scores.
  352. DenseMap<size_t, int> scoreCandidates(StringRef Filename) const {
  353. // Decompose Filename into the parts we care about.
  354. // /some/path/complicated/project/Interesting.h
  355. // [-prefix--][---dir---] [-dir-] [--stem---]
  356. StringRef Stem = sys::path::stem(Filename);
  357. llvm::SmallVector<StringRef, DirectorySegmentsQueried> Dirs;
  358. llvm::StringRef Prefix;
  359. auto Dir = ++sys::path::rbegin(Filename),
  360. DirEnd = sys::path::rend(Filename);
  361. for (int I = 0; I < DirectorySegmentsQueried && Dir != DirEnd; ++I, ++Dir) {
  362. if (Dir->size() > ShortDirectorySegment)
  363. Dirs.push_back(*Dir);
  364. Prefix = Filename.substr(0, Dir - DirEnd);
  365. }
  366. // Now award points based on lookups into our various indexes.
  367. DenseMap<size_t, int> Candidates; // Index -> score.
  368. auto Award = [&](int Points, ArrayRef<SubstringAndIndex> Range) {
  369. for (const auto &Entry : Range)
  370. Candidates[Entry.second] += Points;
  371. };
  372. // Award one point if the file's basename is a prefix of the candidate,
  373. // and another if it's an exact match (so exact matches get two points).
  374. Award(1, indexLookup</*Prefix=*/true>(Stem, Stems));
  375. Award(1, indexLookup</*Prefix=*/false>(Stem, Stems));
  376. // For each of the last few directories in the Filename, award a point
  377. // if it's present in the candidate.
  378. for (StringRef Dir : Dirs)
  379. Award(1, indexLookup</*Prefix=*/false>(Dir, Components));
  380. // Award one more point if the whole rest of the path matches.
  381. if (sys::path::root_directory(Prefix) != Prefix)
  382. Award(1, indexLookup</*Prefix=*/true>(Prefix, Paths));
  383. return Candidates;
  384. }
  385. // Pick a single winner from the set of scored candidates.
  386. // Returns (index, score).
  387. std::pair<size_t, int> pickWinner(const DenseMap<size_t, int> &Candidates,
  388. StringRef Filename,
  389. types::ID PreferredLanguage) const {
  390. struct ScoredCandidate {
  391. size_t Index;
  392. bool Preferred;
  393. int Points;
  394. size_t PrefixLength;
  395. };
  396. // Choose the best candidate by (preferred, points, prefix length, alpha).
  397. ScoredCandidate Best = {size_t(-1), false, 0, 0};
  398. for (const auto &Candidate : Candidates) {
  399. ScoredCandidate S;
  400. S.Index = Candidate.first;
  401. S.Preferred = PreferredLanguage == types::TY_INVALID ||
  402. PreferredLanguage == Types[S.Index];
  403. S.Points = Candidate.second;
  404. if (!S.Preferred && Best.Preferred)
  405. continue;
  406. if (S.Preferred == Best.Preferred) {
  407. if (S.Points < Best.Points)
  408. continue;
  409. if (S.Points == Best.Points) {
  410. S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
  411. if (S.PrefixLength < Best.PrefixLength)
  412. continue;
  413. // hidden heuristics should at least be deterministic!
  414. if (S.PrefixLength == Best.PrefixLength)
  415. if (S.Index > Best.Index)
  416. continue;
  417. }
  418. }
  419. // PrefixLength was only set above if actually needed for a tiebreak.
  420. // But it definitely needs to be set to break ties in the future.
  421. S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
  422. Best = S;
  423. }
  424. // Edge case: no candidate got any points.
  425. // We ignore PreferredLanguage at this point (not ideal).
  426. if (Best.Index == size_t(-1))
  427. return {longestMatch(Filename, Paths).second, 0};
  428. return {Best.Index, Best.Points};
  429. }
  430. // Returns the range within a sorted index that compares equal to Key.
  431. // If Prefix is true, it's instead the range starting with Key.
  432. template <bool Prefix>
  433. ArrayRef<SubstringAndIndex>
  434. indexLookup(StringRef Key, ArrayRef<SubstringAndIndex> Idx) const {
  435. // Use pointers as iteratiors to ease conversion of result to ArrayRef.
  436. auto Range = std::equal_range(Idx.data(), Idx.data() + Idx.size(), Key,
  437. Less<Prefix>());
  438. return {Range.first, Range.second};
  439. }
  440. // Performs a point lookup into a nonempty index, returning a longest match.
  441. SubstringAndIndex longestMatch(StringRef Key,
  442. ArrayRef<SubstringAndIndex> Idx) const {
  443. assert(!Idx.empty());
  444. // Longest substring match will be adjacent to a direct lookup.
  445. auto It =
  446. std::lower_bound(Idx.begin(), Idx.end(), SubstringAndIndex{Key, 0});
  447. if (It == Idx.begin())
  448. return *It;
  449. if (It == Idx.end())
  450. return *--It;
  451. // Have to choose between It and It-1
  452. size_t Prefix = matchingPrefix(Key, It->first);
  453. size_t PrevPrefix = matchingPrefix(Key, (It - 1)->first);
  454. return Prefix > PrevPrefix ? *It : *--It;
  455. }
  456. // Original paths, everything else is in lowercase.
  457. std::vector<std::string> OriginalPaths;
  458. BumpPtrAllocator Arena;
  459. StringSaver Strings;
  460. // Indexes of candidates by certain substrings.
  461. // String is lowercase and sorted, index points into OriginalPaths.
  462. std::vector<SubstringAndIndex> Paths; // Full path.
  463. // Lang types obtained by guessing on the corresponding path. I-th element is
  464. // a type for the I-th path.
  465. std::vector<types::ID> Types;
  466. std::vector<SubstringAndIndex> Stems; // Basename, without extension.
  467. std::vector<SubstringAndIndex> Components; // Last path components.
  468. };
  469. // The actual CompilationDatabase wrapper delegates to its inner database.
  470. // If no match, looks up a proxy file in FileIndex and transfers its
  471. // command to the requested file.
  472. class InterpolatingCompilationDatabase : public CompilationDatabase {
  473. public:
  474. InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)
  475. : Inner(std::move(Inner)), Index(this->Inner->getAllFiles()) {}
  476. std::vector<CompileCommand>
  477. getCompileCommands(StringRef Filename) const override {
  478. auto Known = Inner->getCompileCommands(Filename);
  479. if (Index.empty() || !Known.empty())
  480. return Known;
  481. bool TypeCertain;
  482. auto Lang = guessType(Filename, &TypeCertain);
  483. if (!TypeCertain)
  484. Lang = types::TY_INVALID;
  485. auto ProxyCommands =
  486. Inner->getCompileCommands(Index.chooseProxy(Filename, foldType(Lang)));
  487. if (ProxyCommands.empty())
  488. return {};
  489. return {TransferableCommand(ProxyCommands[0]).transferTo(Filename)};
  490. }
  491. std::vector<std::string> getAllFiles() const override {
  492. return Inner->getAllFiles();
  493. }
  494. std::vector<CompileCommand> getAllCompileCommands() const override {
  495. return Inner->getAllCompileCommands();
  496. }
  497. private:
  498. std::unique_ptr<CompilationDatabase> Inner;
  499. FileIndex Index;
  500. };
  501. } // namespace
  502. std::unique_ptr<CompilationDatabase>
  503. inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner) {
  504. return llvm::make_unique<InterpolatingCompilationDatabase>(std::move(Inner));
  505. }
  506. } // namespace tooling
  507. } // namespace clang