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