InterpolatingCompilationDatabase.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. Cmd.CommandLine.emplace_back(OldArgs.front());
  144. for (unsigned Pos = 1; Pos < OldArgs.size();) {
  145. using namespace driver::options;
  146. const unsigned OldPos = Pos;
  147. std::unique_ptr<llvm::opt::Arg> Arg(OptTable->ParseOneArg(
  148. ArgList, Pos,
  149. /* Include */ClangCLMode ? CoreOption | CLOption : 0,
  150. /* Exclude */ClangCLMode ? 0 : CLOption));
  151. if (!Arg)
  152. continue;
  153. const llvm::opt::Option &Opt = Arg->getOption();
  154. // Strip input and output files.
  155. if (Opt.matches(OPT_INPUT) || Opt.matches(OPT_o) ||
  156. (ClangCLMode && (Opt.matches(OPT__SLASH_Fa) ||
  157. Opt.matches(OPT__SLASH_Fe) ||
  158. Opt.matches(OPT__SLASH_Fi) ||
  159. Opt.matches(OPT__SLASH_Fo))))
  160. continue;
  161. // Strip -x, but record the overridden language.
  162. if (const auto GivenType = tryParseTypeArg(*Arg)) {
  163. Type = *GivenType;
  164. continue;
  165. }
  166. // Strip -std, but record the value.
  167. if (const auto GivenStd = tryParseStdArg(*Arg)) {
  168. if (*GivenStd != LangStandard::lang_unspecified)
  169. Std = *GivenStd;
  170. continue;
  171. }
  172. Cmd.CommandLine.insert(Cmd.CommandLine.end(),
  173. OldArgs.data() + OldPos, OldArgs.data() + Pos);
  174. }
  175. if (Std != LangStandard::lang_unspecified) // -std take precedence over -x
  176. Type = toType(LangStandard::getLangStandardForKind(Std).getLanguage());
  177. Type = foldType(*Type);
  178. // The contract is to store None instead of TY_INVALID.
  179. if (Type == types::TY_INVALID)
  180. Type = llvm::None;
  181. }
  182. // Produce a CompileCommand for \p filename, based on this one.
  183. CompileCommand transferTo(StringRef Filename) const {
  184. CompileCommand Result = Cmd;
  185. Result.Filename = Filename;
  186. bool TypeCertain;
  187. auto TargetType = guessType(Filename, &TypeCertain);
  188. // If the filename doesn't determine the language (.h), transfer with -x.
  189. if (TargetType != types::TY_INVALID && !TypeCertain && Type) {
  190. TargetType = types::onlyPrecompileType(TargetType) // header?
  191. ? types::lookupHeaderTypeForSourceType(*Type)
  192. : *Type;
  193. if (ClangCLMode) {
  194. const StringRef Flag = toCLFlag(TargetType);
  195. if (!Flag.empty())
  196. Result.CommandLine.push_back(Flag);
  197. } else {
  198. Result.CommandLine.push_back("-x");
  199. Result.CommandLine.push_back(types::getTypeName(TargetType));
  200. }
  201. }
  202. // --std flag may only be transferred if the language is the same.
  203. // We may consider "translating" these, e.g. c++11 -> c11.
  204. if (Std != LangStandard::lang_unspecified && foldType(TargetType) == Type) {
  205. Result.CommandLine.emplace_back((
  206. llvm::Twine(ClangCLMode ? "/std:" : "-std=") +
  207. LangStandard::getLangStandardForKind(Std).getName()).str());
  208. }
  209. Result.CommandLine.push_back(Filename);
  210. Result.Heuristic = "inferred from " + Cmd.Filename;
  211. return Result;
  212. }
  213. private:
  214. // Determine whether the given command line is intended for the CL driver.
  215. static bool checkIsCLMode(ArrayRef<std::string> CmdLine) {
  216. // First look for --driver-mode.
  217. for (StringRef S : llvm::reverse(CmdLine)) {
  218. if (S.consume_front("--driver-mode="))
  219. return S == "cl";
  220. }
  221. // Otherwise just check the clang executable file name.
  222. return llvm::sys::path::stem(CmdLine.front()).endswith_lower("cl");
  223. }
  224. // Map the language from the --std flag to that of the -x flag.
  225. static types::ID toType(InputKind::Language Lang) {
  226. switch (Lang) {
  227. case InputKind::C:
  228. return types::TY_C;
  229. case InputKind::CXX:
  230. return types::TY_CXX;
  231. case InputKind::ObjC:
  232. return types::TY_ObjC;
  233. case InputKind::ObjCXX:
  234. return types::TY_ObjCXX;
  235. default:
  236. return types::TY_INVALID;
  237. }
  238. }
  239. // Convert a file type to the matching CL-style type flag.
  240. static StringRef toCLFlag(types::ID Type) {
  241. switch (Type) {
  242. case types::TY_C:
  243. case types::TY_CHeader:
  244. return "/TC";
  245. case types::TY_CXX:
  246. case types::TY_CXXHeader:
  247. return "/TP";
  248. default:
  249. return StringRef();
  250. }
  251. }
  252. // Try to interpret the argument as a type specifier, e.g. '-x'.
  253. Optional<types::ID> tryParseTypeArg(const llvm::opt::Arg &Arg) {
  254. const llvm::opt::Option &Opt = Arg.getOption();
  255. using namespace driver::options;
  256. if (ClangCLMode) {
  257. if (Opt.matches(OPT__SLASH_TC) || Opt.matches(OPT__SLASH_Tc))
  258. return types::TY_C;
  259. if (Opt.matches(OPT__SLASH_TP) || Opt.matches(OPT__SLASH_Tp))
  260. return types::TY_CXX;
  261. } else {
  262. if (Opt.matches(driver::options::OPT_x))
  263. return types::lookupTypeForTypeSpecifier(Arg.getValue());
  264. }
  265. return None;
  266. }
  267. // Try to interpret the argument as '-std='.
  268. Optional<LangStandard::Kind> tryParseStdArg(const llvm::opt::Arg &Arg) {
  269. using namespace driver::options;
  270. if (Arg.getOption().matches(ClangCLMode ? OPT__SLASH_std : OPT_std_EQ)) {
  271. return llvm::StringSwitch<LangStandard::Kind>(Arg.getValue())
  272. #define LANGSTANDARD(id, name, lang, ...) .Case(name, LangStandard::lang_##id)
  273. #define LANGSTANDARD_ALIAS(id, alias) .Case(alias, LangStandard::lang_##id)
  274. #include "clang/Frontend/LangStandards.def"
  275. #undef LANGSTANDARD_ALIAS
  276. #undef LANGSTANDARD
  277. .Default(LangStandard::lang_unspecified);
  278. }
  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 =
  441. std::lower_bound(Idx.begin(), Idx.end(), SubstringAndIndex{Key, 0});
  442. if (It == Idx.begin())
  443. return *It;
  444. if (It == Idx.end())
  445. return *--It;
  446. // Have to choose between It and It-1
  447. size_t Prefix = matchingPrefix(Key, It->first);
  448. size_t PrevPrefix = matchingPrefix(Key, (It - 1)->first);
  449. return Prefix > PrevPrefix ? *It : *--It;
  450. }
  451. // Original paths, everything else is in lowercase.
  452. std::vector<std::string> OriginalPaths;
  453. BumpPtrAllocator Arena;
  454. StringSaver Strings;
  455. // Indexes of candidates by certain substrings.
  456. // String is lowercase and sorted, index points into OriginalPaths.
  457. std::vector<SubstringAndIndex> Paths; // Full path.
  458. // Lang types obtained by guessing on the corresponding path. I-th element is
  459. // a type for the I-th path.
  460. std::vector<types::ID> Types;
  461. std::vector<SubstringAndIndex> Stems; // Basename, without extension.
  462. std::vector<SubstringAndIndex> Components; // Last path components.
  463. };
  464. // The actual CompilationDatabase wrapper delegates to its inner database.
  465. // If no match, looks up a proxy file in FileIndex and transfers its
  466. // command to the requested file.
  467. class InterpolatingCompilationDatabase : public CompilationDatabase {
  468. public:
  469. InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)
  470. : Inner(std::move(Inner)), Index(this->Inner->getAllFiles()) {}
  471. std::vector<CompileCommand>
  472. getCompileCommands(StringRef Filename) const override {
  473. auto Known = Inner->getCompileCommands(Filename);
  474. if (Index.empty() || !Known.empty())
  475. return Known;
  476. bool TypeCertain;
  477. auto Lang = guessType(Filename, &TypeCertain);
  478. if (!TypeCertain)
  479. Lang = types::TY_INVALID;
  480. auto ProxyCommands =
  481. Inner->getCompileCommands(Index.chooseProxy(Filename, foldType(Lang)));
  482. if (ProxyCommands.empty())
  483. return {};
  484. return {TransferableCommand(ProxyCommands[0]).transferTo(Filename)};
  485. }
  486. std::vector<std::string> getAllFiles() const override {
  487. return Inner->getAllFiles();
  488. }
  489. std::vector<CompileCommand> getAllCompileCommands() const override {
  490. return Inner->getAllCompileCommands();
  491. }
  492. private:
  493. std::unique_ptr<CompilationDatabase> Inner;
  494. FileIndex Index;
  495. };
  496. } // namespace
  497. std::unique_ptr<CompilationDatabase>
  498. inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner) {
  499. return llvm::make_unique<InterpolatingCompilationDatabase>(std::move(Inner));
  500. }
  501. } // namespace tooling
  502. } // namespace clang