Coverage Report

Created: 2020-09-22 08:39

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