InterpolatingCompilationDatabase.cpp 21 KB

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