clang-tools  15.0.0git
CompileCommands.cpp
Go to the documentation of this file.
1 //===--- CompileCommands.cpp ----------------------------------------------===//
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 #include "CompileCommands.h"
10 #include "Config.h"
11 #include "support/Logger.h"
12 #include "support/Trace.h"
13 #include "clang/Driver/Driver.h"
14 #include "clang/Driver/Options.h"
15 #include "clang/Frontend/CompilerInvocation.h"
16 #include "clang/Tooling/ArgumentsAdjusters.h"
17 #include "clang/Tooling/CompilationDatabase.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/Option/ArgList.h"
23 #include "llvm/Option/Option.h"
24 #include "llvm/Support/Allocator.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/FileUtilities.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/Program.h"
31 #include <iterator>
32 #include <string>
33 #include <vector>
34 
35 namespace clang {
36 namespace clangd {
37 namespace {
38 
39 // Query apple's `xcrun` launcher, which is the source of truth for "how should"
40 // clang be invoked on this system.
41 llvm::Optional<std::string> queryXcrun(llvm::ArrayRef<llvm::StringRef> Argv) {
42  auto Xcrun = llvm::sys::findProgramByName("xcrun");
43  if (!Xcrun) {
44  log("Couldn't find xcrun. Hopefully you have a non-apple toolchain...");
45  return llvm::None;
46  }
47  llvm::SmallString<64> OutFile;
48  llvm::sys::fs::createTemporaryFile("clangd-xcrun", "", OutFile);
49  llvm::FileRemover OutRemover(OutFile);
50  llvm::Optional<llvm::StringRef> Redirects[3] = {
51  /*stdin=*/{""}, /*stdout=*/{OutFile.str()}, /*stderr=*/{""}};
52  vlog("Invoking {0} to find clang installation", *Xcrun);
53  int Ret = llvm::sys::ExecuteAndWait(*Xcrun, Argv,
54  /*Env=*/llvm::None, Redirects,
55  /*SecondsToWait=*/10);
56  if (Ret != 0) {
57  log("xcrun exists but failed with code {0}. "
58  "If you have a non-apple toolchain, this is OK. "
59  "Otherwise, try xcode-select --install.",
60  Ret);
61  return llvm::None;
62  }
63 
64  auto Buf = llvm::MemoryBuffer::getFile(OutFile);
65  if (!Buf) {
66  log("Can't read xcrun output: {0}", Buf.getError().message());
67  return llvm::None;
68  }
69  StringRef Path = Buf->get()->getBuffer().trim();
70  if (Path.empty()) {
71  log("xcrun produced no output");
72  return llvm::None;
73  }
74  return Path.str();
75 }
76 
77 // Resolve symlinks if possible.
78 std::string resolve(std::string Path) {
79  llvm::SmallString<128> Resolved;
80  if (llvm::sys::fs::real_path(Path, Resolved)) {
81  log("Failed to resolve possible symlink {0}", Path);
82  return Path;
83  }
84  return std::string(Resolved.str());
85 }
86 
87 // Get a plausible full `clang` path.
88 // This is used in the fallback compile command, or when the CDB returns a
89 // generic driver with no path.
90 std::string detectClangPath() {
91  // The driver and/or cc1 sometimes depend on the binary name to compute
92  // useful things like the standard library location.
93  // We need to emulate what clang on this system is likely to see.
94  // cc1 in particular looks at the "real path" of the running process, and
95  // so if /usr/bin/clang is a symlink, it sees the resolved path.
96  // clangd doesn't have that luxury, so we resolve symlinks ourselves.
97 
98  // On Mac, `which clang` is /usr/bin/clang. It runs `xcrun clang`, which knows
99  // where the real clang is kept. We need to do the same thing,
100  // because cc1 (not the driver!) will find libc++ relative to argv[0].
101 #ifdef __APPLE__
102  if (auto MacClang = queryXcrun({"xcrun", "--find", "clang"}))
103  return resolve(std::move(*MacClang));
104 #endif
105  // On other platforms, just look for compilers on the PATH.
106  for (const char *Name : {"clang", "gcc", "cc"})
107  if (auto PathCC = llvm::sys::findProgramByName(Name))
108  return resolve(std::move(*PathCC));
109  // Fallback: a nonexistent 'clang' binary next to clangd.
110  static int StaticForMainAddr;
111  std::string ClangdExecutable =
112  llvm::sys::fs::getMainExecutable("clangd", (void *)&StaticForMainAddr);
113  SmallString<128> ClangPath;
114  ClangPath = llvm::sys::path::parent_path(ClangdExecutable);
115  llvm::sys::path::append(ClangPath, "clang");
116  return std::string(ClangPath.str());
117 }
118 
119 // On mac, /usr/bin/clang sets SDKROOT and then invokes the real clang.
120 // The effect of this is to set -isysroot correctly. We do the same.
121 const llvm::Optional<std::string> detectSysroot() {
122 #ifndef __APPLE__
123  return llvm::None;
124 #endif
125 
126  // SDKROOT overridden in environment, respect it. Driver will set isysroot.
127  if (::getenv("SDKROOT"))
128  return llvm::None;
129  return queryXcrun({"xcrun", "--show-sdk-path"});
130 }
131 
132 std::string detectStandardResourceDir() {
133  static int StaticForMainAddr; // Just an address in this process.
134  return CompilerInvocation::GetResourcesPath("clangd",
135  (void *)&StaticForMainAddr);
136 }
137 
138 // The path passed to argv[0] is important:
139 // - its parent directory is Driver::Dir, used for library discovery
140 // - its basename affects CLI parsing (clang-cl) and other settings
141 // Where possible it should be an absolute path with sensible directory, but
142 // with the original basename.
143 static std::string resolveDriver(llvm::StringRef Driver, bool FollowSymlink,
144  llvm::Optional<std::string> ClangPath) {
145  auto SiblingOf = [&](llvm::StringRef AbsPath) {
146  llvm::SmallString<128> Result = llvm::sys::path::parent_path(AbsPath);
147  llvm::sys::path::append(Result, llvm::sys::path::filename(Driver));
148  return Result.str().str();
149  };
150 
151  // First, eliminate relative paths.
152  std::string Storage;
153  if (!llvm::sys::path::is_absolute(Driver)) {
154  // If it's working-dir relative like bin/clang, we can't resolve it.
155  // FIXME: we could if we had the working directory here.
156  // Let's hope it's not a symlink.
157  if (llvm::any_of(Driver,
158  [](char C) { return llvm::sys::path::is_separator(C); }))
159  return Driver.str();
160  // If the driver is a generic like "g++" with no path, add clang dir.
161  if (ClangPath &&
162  (Driver == "clang" || Driver == "clang++" || Driver == "gcc" ||
163  Driver == "g++" || Driver == "cc" || Driver == "c++")) {
164  return SiblingOf(*ClangPath);
165  }
166  // Otherwise try to look it up on PATH. This won't change basename.
167  auto Absolute = llvm::sys::findProgramByName(Driver);
168  if (Absolute && llvm::sys::path::is_absolute(*Absolute))
169  Driver = Storage = std::move(*Absolute);
170  else if (ClangPath) // If we don't find it, use clang dir again.
171  return SiblingOf(*ClangPath);
172  else // Nothing to do: can't find the command and no detected dir.
173  return Driver.str();
174  }
175 
176  // Now we have an absolute path, but it may be a symlink.
177  assert(llvm::sys::path::is_absolute(Driver));
178  if (FollowSymlink) {
179  llvm::SmallString<256> Resolved;
180  if (!llvm::sys::fs::real_path(Driver, Resolved))
181  return SiblingOf(Resolved);
182  }
183  return Driver.str();
184 }
185 
186 } // namespace
187 
189  CommandMangler Result;
190  Result.ClangPath = detectClangPath();
191  Result.ResourceDir = detectStandardResourceDir();
192  Result.Sysroot = detectSysroot();
193  return Result;
194 }
195 
197 
198 void CommandMangler::adjust(std::vector<std::string> &Cmd,
199  llvm::StringRef File) const {
200  trace::Span S("AdjustCompileFlags");
201  // Most of the modifications below assumes the Cmd starts with a driver name.
202  // We might consider injecting a generic driver name like "cc" or "c++", but
203  // a Cmd missing the driver is probably rare enough in practice and errnous.
204  if (Cmd.empty())
205  return;
206  auto &OptTable = clang::driver::getDriverOptTable();
207  // OriginalArgs needs to outlive ArgList.
208  llvm::SmallVector<const char *, 16> OriginalArgs;
209  OriginalArgs.reserve(Cmd.size());
210  for (const auto &S : Cmd)
211  OriginalArgs.push_back(S.c_str());
212  bool IsCLMode = driver::IsClangCL(driver::getDriverMode(
213  OriginalArgs[0], llvm::makeArrayRef(OriginalArgs).slice(1)));
214  // ParseArgs propagates missig arg/opt counts on error, but preserves
215  // everything it could parse in ArgList. So we just ignore those counts.
216  unsigned IgnoredCount;
217  // Drop the executable name, as ParseArgs doesn't expect it. This means
218  // indices are actually of by one between ArgList and OriginalArgs.
219  llvm::opt::InputArgList ArgList;
220  ArgList = OptTable.ParseArgs(
221  llvm::makeArrayRef(OriginalArgs).drop_front(), IgnoredCount, IgnoredCount,
222  /*FlagsToInclude=*/
223  IsCLMode ? (driver::options::CLOption | driver::options::CoreOption)
224  : /*everything*/ 0,
225  /*FlagsToExclude=*/driver::options::NoDriverOption |
226  (IsCLMode ? 0 : driver::options::CLOption));
227 
228  llvm::SmallVector<unsigned, 1> IndicesToDrop;
229  // Having multiple architecture options (e.g. when building fat binaries)
230  // results in multiple compiler jobs, which clangd cannot handle. In such
231  // cases strip all the `-arch` options and fallback to default architecture.
232  // As there are no signals to figure out which one user actually wants. They
233  // can explicitly specify one through `CompileFlags.Add` if need be.
234  unsigned ArchOptCount = 0;
235  for (auto *Input : ArgList.filtered(driver::options::OPT_arch)) {
236  ++ArchOptCount;
237  for (auto I = 0U; I <= Input->getNumValues(); ++I)
238  IndicesToDrop.push_back(Input->getIndex() + I);
239  }
240  // If there is a single `-arch` option, keep it.
241  if (ArchOptCount < 2)
242  IndicesToDrop.clear();
243 
244  // In some cases people may try to reuse the command from another file, e.g.
245  // { File: "foo.h", CommandLine: "clang foo.cpp" }.
246  // We assume the intent is to parse foo.h the same way as foo.cpp, or as if
247  // it were being included from foo.cpp.
248  //
249  // We're going to rewrite the command to refer to foo.h, and this may change
250  // its semantics (e.g. by parsing the file as C). If we do this, we should
251  // use transferCompileCommand to adjust the argv.
252  // In practice only the extension of the file matters, so do this only when
253  // it differs.
254  llvm::StringRef FileExtension = llvm::sys::path::extension(File);
255  llvm::Optional<std::string> TransferFrom;
256  auto SawInput = [&](llvm::StringRef Input) {
257  if (llvm::sys::path::extension(Input) != FileExtension)
258  TransferFrom.emplace(Input);
259  };
260 
261  // Strip all the inputs and `--`. We'll put the input for the requested file
262  // explicitly at the end of the flags. This ensures modifications done in the
263  // following steps apply in more cases (like setting -x, which only affects
264  // inputs that come after it).
265  for (auto *Input : ArgList.filtered(driver::options::OPT_INPUT)) {
266  SawInput(Input->getValue(0));
267  IndicesToDrop.push_back(Input->getIndex());
268  }
269  // Anything after `--` is also treated as input, drop them as well.
270  if (auto *DashDash =
271  ArgList.getLastArgNoClaim(driver::options::OPT__DASH_DASH)) {
272  auto DashDashIndex = DashDash->getIndex() + 1; // +1 accounts for Cmd[0]
273  for (unsigned I = DashDashIndex; I < Cmd.size(); ++I)
274  SawInput(Cmd[I]);
275  Cmd.resize(DashDashIndex);
276  }
277  llvm::sort(IndicesToDrop);
278  llvm::for_each(llvm::reverse(IndicesToDrop),
279  // +1 to account for the executable name in Cmd[0] that
280  // doesn't exist in ArgList.
281  [&Cmd](unsigned Idx) { Cmd.erase(Cmd.begin() + Idx + 1); });
282  // All the inputs are stripped, append the name for the requested file. Rest
283  // of the modifications should respect `--`.
284  Cmd.push_back("--");
285  Cmd.push_back(File.str());
286 
287  if (TransferFrom) {
288  tooling::CompileCommand TransferCmd;
289  TransferCmd.Filename = std::move(*TransferFrom);
290  TransferCmd.CommandLine = std::move(Cmd);
291  TransferCmd = transferCompileCommand(std::move(TransferCmd), File);
292  Cmd = std::move(TransferCmd.CommandLine);
293  assert(Cmd.size() >= 2 && Cmd.back() == File &&
294  Cmd[Cmd.size() - 2] == "--" &&
295  "TransferCommand should produce a command ending in -- filename");
296  }
297 
298  for (auto &Edit : Config::current().CompileFlags.Edits)
299  Edit(Cmd);
300 
301  // Check whether the flag exists, either as -flag or -flag=*
302  auto Has = [&](llvm::StringRef Flag) {
303  for (llvm::StringRef Arg : Cmd) {
304  if (Arg.consume_front(Flag) && (Arg.empty() || Arg[0] == '='))
305  return true;
306  }
307  return false;
308  };
309 
310  llvm::erase_if(Cmd, [](llvm::StringRef Elem) {
311  return Elem.startswith("--save-temps") || Elem.startswith("-save-temps");
312  });
313 
314  std::vector<std::string> ToAppend;
315  if (ResourceDir && !Has("-resource-dir"))
316  ToAppend.push_back(("-resource-dir=" + *ResourceDir));
317 
318  // Don't set `-isysroot` if it is already set or if `--sysroot` is set.
319  // `--sysroot` is a superset of the `-isysroot` argument.
320  if (Sysroot && !Has("-isysroot") && !Has("--sysroot")) {
321  ToAppend.push_back("-isysroot");
322  ToAppend.push_back(*Sysroot);
323  }
324 
325  if (!ToAppend.empty()) {
326  Cmd.insert(llvm::find(Cmd, "--"), std::make_move_iterator(ToAppend.begin()),
327  std::make_move_iterator(ToAppend.end()));
328  }
329 
330  if (!Cmd.empty()) {
331  bool FollowSymlink = !Has("-no-canonical-prefixes");
332  Cmd.front() =
333  (FollowSymlink ? ResolvedDrivers : ResolvedDriversNoFollow)
334  .get(Cmd.front(), [&, this] {
335  return resolveDriver(Cmd.front(), FollowSymlink, ClangPath);
336  });
337  }
338 }
339 
340 CommandMangler::operator clang::tooling::ArgumentsAdjuster() && {
341  // ArgumentsAdjuster is a std::function and so must be copyable.
342  return [Mangler = std::make_shared<CommandMangler>(std::move(*this))](
343  const std::vector<std::string> &Args, llvm::StringRef File) {
344  auto Result = Args;
345  Mangler->adjust(Result, File);
346  return Result;
347  };
348 }
349 
350 // ArgStripper implementation
351 namespace {
352 
353 // Determine total number of args consumed by this option.
354 // Return answers for {Exact, Prefix} match. 0 means not allowed.
355 std::pair<unsigned, unsigned> getArgCount(const llvm::opt::Option &Opt) {
356  constexpr static unsigned Rest = 10000; // Should be all the rest!
357  // Reference is llvm::opt::Option::acceptInternal()
358  using llvm::opt::Option;
359  switch (Opt.getKind()) {
360  case Option::FlagClass:
361  return {1, 0};
362  case Option::JoinedClass:
363  case Option::CommaJoinedClass:
364  return {1, 1};
365  case Option::GroupClass:
366  case Option::InputClass:
367  case Option::UnknownClass:
368  case Option::ValuesClass:
369  return {1, 0};
370  case Option::JoinedAndSeparateClass:
371  return {2, 2};
372  case Option::SeparateClass:
373  return {2, 0};
374  case Option::MultiArgClass:
375  return {1 + Opt.getNumArgs(), 0};
376  case Option::JoinedOrSeparateClass:
377  return {2, 1};
378  case Option::RemainingArgsClass:
379  return {Rest, 0};
380  case Option::RemainingArgsJoinedClass:
381  return {Rest, Rest};
382  }
383  llvm_unreachable("Unhandled option kind");
384 }
385 
386 // Flag-parsing mode, which affects which flags are available.
387 enum DriverMode : unsigned char {
388  DM_None = 0,
389  DM_GCC = 1, // Default mode e.g. when invoked as 'clang'
390  DM_CL = 2, // MS CL.exe compatible mode e.g. when invoked as 'clang-cl'
391  DM_CC1 = 4, // When invoked as 'clang -cc1' or after '-Xclang'
392  DM_All = 7
393 };
394 
395 // Examine args list to determine if we're in GCC, CL-compatible, or cc1 mode.
396 DriverMode getDriverMode(const std::vector<std::string> &Args) {
397  DriverMode Mode = DM_GCC;
398  llvm::StringRef Argv0 = Args.front();
399  if (Argv0.endswith_insensitive(".exe"))
400  Argv0 = Argv0.drop_back(strlen(".exe"));
401  if (Argv0.endswith_insensitive("cl"))
402  Mode = DM_CL;
403  for (const llvm::StringRef Arg : Args) {
404  if (Arg == "--driver-mode=cl") {
405  Mode = DM_CL;
406  break;
407  }
408  if (Arg == "-cc1") {
409  Mode = DM_CC1;
410  break;
411  }
412  }
413  return Mode;
414 }
415 
416 // Returns the set of DriverModes where an option may be used.
417 unsigned char getModes(const llvm::opt::Option &Opt) {
418  // Why is this so complicated?!
419  // Reference is clang::driver::Driver::getIncludeExcludeOptionFlagMasks()
420  unsigned char Result = DM_None;
421  if (Opt.hasFlag(driver::options::CC1Option))
422  Result |= DM_CC1;
423  if (!Opt.hasFlag(driver::options::NoDriverOption)) {
424  if (Opt.hasFlag(driver::options::CLOption)) {
425  Result |= DM_CL;
426  } else {
427  Result |= DM_GCC;
428  if (Opt.hasFlag(driver::options::CoreOption)) {
429  Result |= DM_CL;
430  }
431  }
432  }
433  return Result;
434 }
435 
436 } // namespace
437 
438 llvm::ArrayRef<ArgStripper::Rule> ArgStripper::rulesFor(llvm::StringRef Arg) {
439  // All the hard work is done once in a static initializer.
440  // We compute a table containing strings to look for and #args to skip.
441  // e.g. "-x" => {-x 2 args, -x* 1 arg, --language 2 args, --language=* 1 arg}
442  using TableTy =
443  llvm::StringMap<llvm::SmallVector<Rule, 4>, llvm::BumpPtrAllocator>;
444  static TableTy *Table = [] {
445  auto &DriverTable = driver::getDriverOptTable();
446  using DriverID = clang::driver::options::ID;
447 
448  // Collect sets of aliases, so we can treat -foo and -foo= as synonyms.
449  // Conceptually a double-linked list: PrevAlias[I] -> I -> NextAlias[I].
450  // If PrevAlias[I] is INVALID, then I is canonical.
451  DriverID PrevAlias[DriverID::LastOption] = {DriverID::OPT_INVALID};
452  DriverID NextAlias[DriverID::LastOption] = {DriverID::OPT_INVALID};
453  auto AddAlias = [&](DriverID Self, DriverID T) {
454  if (NextAlias[T]) {
455  PrevAlias[NextAlias[T]] = Self;
456  NextAlias[Self] = NextAlias[T];
457  }
458  PrevAlias[Self] = T;
459  NextAlias[T] = Self;
460  };
461  // Also grab prefixes for each option, these are not fully exposed.
462  const char *const *Prefixes[DriverID::LastOption] = {nullptr};
463 #define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE;
464 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
465  HELP, METAVAR, VALUES) \
466  Prefixes[DriverID::OPT_##ID] = PREFIX;
467 #include "clang/Driver/Options.inc"
468 #undef OPTION
469 #undef PREFIX
470 
471  struct {
472  DriverID ID;
473  DriverID AliasID;
474  const void *AliasArgs;
475  } AliasTable[] = {
476 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
477  HELP, METAVAR, VALUES) \
478  {DriverID::OPT_##ID, DriverID::OPT_##ALIAS, ALIASARGS},
479 #include "clang/Driver/Options.inc"
480 #undef OPTION
481  };
482  for (auto &E : AliasTable)
483  if (E.AliasID != DriverID::OPT_INVALID && E.AliasArgs == nullptr)
484  AddAlias(E.ID, E.AliasID);
485 
486  auto Result = std::make_unique<TableTy>();
487  // Iterate over distinct options (represented by the canonical alias).
488  // Every spelling of this option will get the same set of rules.
489  for (unsigned ID = 1 /*Skip INVALID */; ID < DriverID::LastOption; ++ID) {
490  if (PrevAlias[ID] || ID == DriverID::OPT_Xclang)
491  continue; // Not canonical, or specially handled.
492  llvm::SmallVector<Rule> Rules;
493  // Iterate over each alias, to add rules for parsing it.
494  for (unsigned A = ID; A != DriverID::OPT_INVALID; A = NextAlias[A]) {
495  if (Prefixes[A] == nullptr) // option groups.
496  continue;
497  auto Opt = DriverTable.getOption(A);
498  // Exclude - and -foo pseudo-options.
499  if (Opt.getName().empty())
500  continue;
501  auto Modes = getModes(Opt);
502  std::pair<unsigned, unsigned> ArgCount = getArgCount(Opt);
503  // Iterate over each spelling of the alias, e.g. -foo vs --foo.
504  for (auto *Prefix = Prefixes[A]; *Prefix != nullptr; ++Prefix) {
505  llvm::SmallString<64> Buf(*Prefix);
506  Buf.append(Opt.getName());
507  llvm::StringRef Spelling = Result->try_emplace(Buf).first->getKey();
508  Rules.emplace_back();
509  Rule &R = Rules.back();
510  R.Text = Spelling;
511  R.Modes = Modes;
512  R.ExactArgs = ArgCount.first;
513  R.PrefixArgs = ArgCount.second;
514  // Concrete priority is the index into the option table.
515  // Effectively, earlier entries take priority over later ones.
516  assert(ID < std::numeric_limits<decltype(R.Priority)>::max() &&
517  "Rules::Priority overflowed by options table");
518  R.Priority = ID;
519  }
520  }
521  // Register the set of rules under each possible name.
522  for (const auto &R : Rules)
523  Result->find(R.Text)->second.append(Rules.begin(), Rules.end());
524  }
525 #ifndef NDEBUG
526  // Dump the table and various measures of its size.
527  unsigned RuleCount = 0;
528  dlog("ArgStripper Option spelling table");
529  for (const auto &Entry : *Result) {
530  dlog("{0}", Entry.first());
531  RuleCount += Entry.second.size();
532  for (const auto &R : Entry.second)
533  dlog(" {0} #={1} *={2} Mode={3}", R.Text, R.ExactArgs, R.PrefixArgs,
534  int(R.Modes));
535  }
536  dlog("Table spellings={0} rules={1} string-bytes={2}", Result->size(),
537  RuleCount, Result->getAllocator().getBytesAllocated());
538 #endif
539  // The static table will never be destroyed.
540  return Result.release();
541  }();
542 
543  auto It = Table->find(Arg);
544  return (It == Table->end()) ? llvm::ArrayRef<Rule>() : It->second;
545 }
546 
547 void ArgStripper::strip(llvm::StringRef Arg) {
548  auto OptionRules = rulesFor(Arg);
549  if (OptionRules.empty()) {
550  // Not a recognized flag. Strip it literally.
551  Storage.emplace_back(Arg);
552  Rules.emplace_back();
553  Rules.back().Text = Storage.back();
554  Rules.back().ExactArgs = 1;
555  if (Rules.back().Text.consume_back("*"))
556  Rules.back().PrefixArgs = 1;
557  Rules.back().Modes = DM_All;
558  Rules.back().Priority = -1; // Max unsigned = lowest priority.
559  } else {
560  Rules.append(OptionRules.begin(), OptionRules.end());
561  }
562 }
563 
564 const ArgStripper::Rule *ArgStripper::matchingRule(llvm::StringRef Arg,
565  unsigned Mode,
566  unsigned &ArgCount) const {
567  const ArgStripper::Rule *BestRule = nullptr;
568  for (const Rule &R : Rules) {
569  // Rule can fail to match if...
570  if (!(R.Modes & Mode))
571  continue; // not applicable to current driver mode
572  if (BestRule && BestRule->Priority < R.Priority)
573  continue; // lower-priority than best candidate.
574  if (!Arg.startswith(R.Text))
575  continue; // current arg doesn't match the prefix string
576  bool PrefixMatch = Arg.size() > R.Text.size();
577  // Can rule apply as an exact/prefix match?
578  if (unsigned Count = PrefixMatch ? R.PrefixArgs : R.ExactArgs) {
579  BestRule = &R;
580  ArgCount = Count;
581  }
582  // Continue in case we find a higher-priority rule.
583  }
584  return BestRule;
585 }
586 
587 void ArgStripper::process(std::vector<std::string> &Args) const {
588  if (Args.empty())
589  return;
590 
591  // We're parsing the args list in some mode (e.g. gcc-compatible) but may
592  // temporarily switch to another mode with the -Xclang flag.
593  DriverMode MainMode = getDriverMode(Args);
594  DriverMode CurrentMode = MainMode;
595 
596  // Read and write heads for in-place deletion.
597  unsigned Read = 0, Write = 0;
598  bool WasXclang = false;
599  while (Read < Args.size()) {
600  unsigned ArgCount = 0;
601  if (matchingRule(Args[Read], CurrentMode, ArgCount)) {
602  // Delete it and its args.
603  if (WasXclang) {
604  assert(Write > 0);
605  --Write; // Drop previous -Xclang arg
606  CurrentMode = MainMode;
607  WasXclang = false;
608  }
609  // Advance to last arg. An arg may be foo or -Xclang foo.
610  for (unsigned I = 1; Read < Args.size() && I < ArgCount; ++I) {
611  ++Read;
612  if (Read < Args.size() && Args[Read] == "-Xclang")
613  ++Read;
614  }
615  } else {
616  // No match, just copy the arg through.
617  WasXclang = Args[Read] == "-Xclang";
618  CurrentMode = WasXclang ? DM_CC1 : MainMode;
619  if (Write != Read)
620  Args[Write] = std::move(Args[Read]);
621  ++Write;
622  }
623  ++Read;
624  }
625  Args.resize(Write);
626 }
627 
628 std::string printArgv(llvm::ArrayRef<llvm::StringRef> Args) {
629  std::string Buf;
630  llvm::raw_string_ostream OS(Buf);
631  bool Sep = false;
632  for (llvm::StringRef Arg : Args) {
633  if (Sep)
634  OS << ' ';
635  Sep = true;
636  if (llvm::all_of(Arg, llvm::isPrint) &&
637  Arg.find_first_of(" \t\n\"\\") == llvm::StringRef::npos) {
638  OS << Arg;
639  continue;
640  }
641  OS << '"';
642  OS.write_escaped(Arg, /*UseHexEscapes=*/true);
643  OS << '"';
644  }
645  return std::move(OS.str());
646 }
647 
648 std::string printArgv(llvm::ArrayRef<std::string> Args) {
649  std::vector<llvm::StringRef> Refs(Args.size());
650  llvm::copy(Args, Refs.begin());
651  return printArgv(Refs);
652 }
653 
654 } // namespace clangd
655 } // namespace clang
dlog
#define dlog(...)
Definition: Logger.h:101
clang::clangd::Edit
A set of edits generated for a single file.
Definition: SourceCode.h:184
E
const Expr * E
Definition: AvoidBindCheck.cpp:88
clang::clangd::printArgv
std::string printArgv(llvm::ArrayRef< llvm::StringRef > Args)
Definition: CompileCommands.cpp:628
Refs
RefSlab Refs
Definition: SymbolCollectorTests.cpp:312
clang::clangd::Path
std::string Path
A typedef to represent a file path.
Definition: Path.h:26
clang::clangd::Config::Edits
std::vector< llvm::unique_function< void(std::vector< std::string > &) const > > Edits
Edits to apply to the compile command, in sequence.
Definition: Config.h:67
clang::clangd::ArgStripper::strip
void strip(llvm::StringRef Arg)
Definition: CompileCommands.cpp:547
clang::clangd::ArgStripper::process
void process(std::vector< std::string > &Args) const
Definition: CompileCommands.cpp:587
Trace.h
clang::clangd::CommandMangler
Definition: CompileCommands.h:28
clang::clangd::CommandMangler::ResourceDir
llvm::Optional< std::string > ResourceDir
Definition: CompileCommands.h:32
ns1::ns2::A
@ A
Definition: CategoricalFeature.h:3
clang::clangd::CommandMangler::detect
static CommandMangler detect()
Definition: CompileCommands.cpp:188
CompileCommands.h
Logger.h
Args
llvm::json::Object Args
Definition: Trace.cpp:138
clang::clangd::CommandMangler::adjust
void adjust(std::vector< std::string > &Cmd, llvm::StringRef File) const
Definition: CompileCommands.cpp:198
clang::clangd::vlog
void vlog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:72
clang::clangd::CommandMangler::Sysroot
llvm::Optional< std::string > Sysroot
Definition: CompileCommands.h:34
Name
Token Name
Definition: MacroToEnumCheck.cpp:89
Argv0
const char * Argv0
Definition: Modularize.cpp:332
clang::clangd::DocumentHighlightKind::Write
@ Write
clang::clangd::log
void log(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:67
Entry
Definition: Modularize.cpp:427
Config.h
ID
static char ID
Definition: Logger.cpp:74
clang::clangd::RefSlab::begin
const_iterator begin() const
Definition: Ref.h:119
clang::clangd::CommandMangler::ClangPath
llvm::Optional< std::string > ClangPath
Definition: CompileCommands.h:30
C
const Criteria C
Definition: FunctionCognitiveComplexityCheck.cpp:93
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
OS
llvm::raw_string_ostream OS
Definition: TraceTests.cpp:160
clang::clangd::Config::current
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
Definition: Config.cpp:17
clang::clangd::DocumentHighlightKind::Read
@ Read
clang::clangd::CommandMangler::forTests
static CommandMangler forTests()
Definition: CompileCommands.cpp:196
clang::clangd::trace::Span
Records an event whose duration is the lifetime of the Span object.
Definition: Trace.h:143