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