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