InterpolatingCompilationDatabase.cpp 21 KB

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