1 //===--- CompileCommands.cpp ----------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "CompileCommands.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 "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 "llvm/TargetParser/Host.h"
41 // Query apple's `xcrun` launcher, which is the source of truth for "how should"
42 // clang be invoked on this system.
43 std::optional
<std::string
> queryXcrun(llvm::ArrayRef
<llvm::StringRef
> Argv
) {
44 auto Xcrun
= llvm::sys::findProgramByName("xcrun");
46 log("Couldn't find xcrun. Hopefully you have a non-apple toolchain...");
49 llvm::SmallString
<64> OutFile
;
50 llvm::sys::fs::createTemporaryFile("clangd-xcrun", "", OutFile
);
51 llvm::FileRemover
OutRemover(OutFile
);
52 std::optional
<llvm::StringRef
> Redirects
[3] = {
53 /*stdin=*/{""}, /*stdout=*/{OutFile
.str()}, /*stderr=*/{""}};
54 vlog("Invoking {0} to find clang installation", *Xcrun
);
55 int Ret
= llvm::sys::ExecuteAndWait(*Xcrun
, Argv
,
56 /*Env=*/std::nullopt
, Redirects
,
57 /*SecondsToWait=*/10);
59 log("xcrun exists but failed with code {0}. "
60 "If you have a non-apple toolchain, this is OK. "
61 "Otherwise, try xcode-select --install.",
66 auto Buf
= llvm::MemoryBuffer::getFile(OutFile
);
68 log("Can't read xcrun output: {0}", Buf
.getError().message());
71 StringRef Path
= Buf
->get()->getBuffer().trim();
73 log("xcrun produced no output");
79 // Resolve symlinks if possible.
80 std::string
resolve(std::string Path
) {
81 llvm::SmallString
<128> Resolved
;
82 if (llvm::sys::fs::real_path(Path
, Resolved
)) {
83 log("Failed to resolve possible symlink {0}", Path
);
86 return std::string(Resolved
.str());
89 // Get a plausible full `clang` path.
90 // This is used in the fallback compile command, or when the CDB returns a
91 // generic driver with no path.
92 std::string
detectClangPath() {
93 // The driver and/or cc1 sometimes depend on the binary name to compute
94 // useful things like the standard library location.
95 // We need to emulate what clang on this system is likely to see.
96 // cc1 in particular looks at the "real path" of the running process, and
97 // so if /usr/bin/clang is a symlink, it sees the resolved path.
98 // clangd doesn't have that luxury, so we resolve symlinks ourselves.
100 // On Mac, `which clang` is /usr/bin/clang. It runs `xcrun clang`, which knows
101 // where the real clang is kept. We need to do the same thing,
102 // because cc1 (not the driver!) will find libc++ relative to argv[0].
104 if (auto MacClang
= queryXcrun({"xcrun", "--find", "clang"}))
105 return resolve(std::move(*MacClang
));
107 // On other platforms, just look for compilers on the PATH.
108 for (const char *Name
: {"clang", "gcc", "cc"})
109 if (auto PathCC
= llvm::sys::findProgramByName(Name
))
110 return resolve(std::move(*PathCC
));
111 // Fallback: a nonexistent 'clang' binary next to clangd.
112 static int StaticForMainAddr
;
113 std::string ClangdExecutable
=
114 llvm::sys::fs::getMainExecutable("clangd", (void *)&StaticForMainAddr
);
115 SmallString
<128> ClangPath
;
116 ClangPath
= llvm::sys::path::parent_path(ClangdExecutable
);
117 llvm::sys::path::append(ClangPath
, "clang");
118 return std::string(ClangPath
.str());
121 // On mac, /usr/bin/clang sets SDKROOT and then invokes the real clang.
122 // The effect of this is to set -isysroot correctly. We do the same.
123 std::optional
<std::string
> detectSysroot() {
128 // SDKROOT overridden in environment, respect it. Driver will set isysroot.
129 if (::getenv("SDKROOT"))
131 return queryXcrun({"xcrun", "--show-sdk-path"});
134 std::string
detectStandardResourceDir() {
135 static int StaticForMainAddr
; // Just an address in this process.
136 return CompilerInvocation::GetResourcesPath("clangd",
137 (void *)&StaticForMainAddr
);
140 // The path passed to argv[0] is important:
141 // - its parent directory is Driver::Dir, used for library discovery
142 // - its basename affects CLI parsing (clang-cl) and other settings
143 // Where possible it should be an absolute path with sensible directory, but
144 // with the original basename.
145 static std::string
resolveDriver(llvm::StringRef Driver
, bool FollowSymlink
,
146 std::optional
<std::string
> ClangPath
) {
147 auto SiblingOf
= [&](llvm::StringRef AbsPath
) {
148 llvm::SmallString
<128> Result
= llvm::sys::path::parent_path(AbsPath
);
149 llvm::sys::path::append(Result
, llvm::sys::path::filename(Driver
));
150 return Result
.str().str();
153 // First, eliminate relative paths.
155 if (!llvm::sys::path::is_absolute(Driver
)) {
156 // If it's working-dir relative like bin/clang, we can't resolve it.
157 // FIXME: we could if we had the working directory here.
158 // Let's hope it's not a symlink.
159 if (llvm::any_of(Driver
,
160 [](char C
) { return llvm::sys::path::is_separator(C
); }))
162 // If the driver is a generic like "g++" with no path, add clang dir.
164 (Driver
== "clang" || Driver
== "clang++" || Driver
== "gcc" ||
165 Driver
== "g++" || Driver
== "cc" || Driver
== "c++")) {
166 return SiblingOf(*ClangPath
);
168 // Otherwise try to look it up on PATH. This won't change basename.
169 auto Absolute
= llvm::sys::findProgramByName(Driver
);
170 if (Absolute
&& llvm::sys::path::is_absolute(*Absolute
))
171 Driver
= Storage
= std::move(*Absolute
);
172 else if (ClangPath
) // If we don't find it, use clang dir again.
173 return SiblingOf(*ClangPath
);
174 else // Nothing to do: can't find the command and no detected dir.
178 // Now we have an absolute path, but it may be a symlink.
179 assert(llvm::sys::path::is_absolute(Driver
));
181 llvm::SmallString
<256> Resolved
;
182 if (!llvm::sys::fs::real_path(Driver
, Resolved
))
183 return SiblingOf(Resolved
);
190 CommandMangler::CommandMangler() {
191 Tokenizer
= llvm::Triple(llvm::sys::getProcessTriple()).isOSWindows()
192 ? llvm::cl::TokenizeWindowsCommandLine
193 : llvm::cl::TokenizeGNUCommandLine
;
196 CommandMangler
CommandMangler::detect() {
197 CommandMangler Result
;
198 Result
.ClangPath
= detectClangPath();
199 Result
.ResourceDir
= detectStandardResourceDir();
200 Result
.Sysroot
= detectSysroot();
204 CommandMangler
CommandMangler::forTests() { return CommandMangler(); }
206 void CommandMangler::operator()(tooling::CompileCommand
&Command
,
207 llvm::StringRef File
) const {
208 std::vector
<std::string
> &Cmd
= Command
.CommandLine
;
209 trace::Span
S("AdjustCompileFlags");
210 // Most of the modifications below assumes the Cmd starts with a driver name.
211 // We might consider injecting a generic driver name like "cc" or "c++", but
212 // a Cmd missing the driver is probably rare enough in practice and erroneous.
216 // FS used for expanding response files.
217 // FIXME: ExpandResponseFiles appears not to provide the usual
218 // thread-safety guarantees, as the access to FS is not locked!
219 // For now, use the real FS, which is known to be threadsafe (if we don't
220 // use/change working directory, which ExpandResponseFiles doesn't).
221 auto FS
= llvm::vfs::getRealFileSystem();
222 tooling::addExpandedResponseFiles(Cmd
, Command
.Directory
, Tokenizer
, *FS
);
224 auto &OptTable
= clang::driver::getDriverOptTable();
225 // OriginalArgs needs to outlive ArgList.
226 llvm::SmallVector
<const char *, 16> OriginalArgs
;
227 OriginalArgs
.reserve(Cmd
.size());
228 for (const auto &S
: Cmd
)
229 OriginalArgs
.push_back(S
.c_str());
230 bool IsCLMode
= driver::IsClangCL(driver::getDriverMode(
231 OriginalArgs
[0], llvm::ArrayRef(OriginalArgs
).slice(1)));
232 // ParseArgs propagates missing arg/opt counts on error, but preserves
233 // everything it could parse in ArgList. So we just ignore those counts.
234 unsigned IgnoredCount
;
235 // Drop the executable name, as ParseArgs doesn't expect it. This means
236 // indices are actually of by one between ArgList and OriginalArgs.
237 llvm::opt::InputArgList ArgList
;
238 ArgList
= OptTable
.ParseArgs(
239 llvm::ArrayRef(OriginalArgs
).drop_front(), IgnoredCount
, IgnoredCount
,
240 llvm::opt::Visibility(IsCLMode
? driver::options::CLOption
241 : driver::options::ClangOption
));
243 llvm::SmallVector
<unsigned, 1> IndicesToDrop
;
244 // Having multiple architecture options (e.g. when building fat binaries)
245 // results in multiple compiler jobs, which clangd cannot handle. In such
246 // cases strip all the `-arch` options and fallback to default architecture.
247 // As there are no signals to figure out which one user actually wants. They
248 // can explicitly specify one through `CompileFlags.Add` if need be.
249 unsigned ArchOptCount
= 0;
250 for (auto *Input
: ArgList
.filtered(driver::options::OPT_arch
)) {
252 for (auto I
= 0U; I
<= Input
->getNumValues(); ++I
)
253 IndicesToDrop
.push_back(Input
->getIndex() + I
);
255 // If there is a single `-arch` option, keep it.
256 if (ArchOptCount
< 2)
257 IndicesToDrop
.clear();
259 // In some cases people may try to reuse the command from another file, e.g.
260 // { File: "foo.h", CommandLine: "clang foo.cpp" }.
261 // We assume the intent is to parse foo.h the same way as foo.cpp, or as if
262 // it were being included from foo.cpp.
264 // We're going to rewrite the command to refer to foo.h, and this may change
265 // its semantics (e.g. by parsing the file as C). If we do this, we should
266 // use transferCompileCommand to adjust the argv.
267 // In practice only the extension of the file matters, so do this only when
269 llvm::StringRef FileExtension
= llvm::sys::path::extension(File
);
270 std::optional
<std::string
> TransferFrom
;
271 auto SawInput
= [&](llvm::StringRef Input
) {
272 if (llvm::sys::path::extension(Input
) != FileExtension
)
273 TransferFrom
.emplace(Input
);
276 // Strip all the inputs and `--`. We'll put the input for the requested file
277 // explicitly at the end of the flags. This ensures modifications done in the
278 // following steps apply in more cases (like setting -x, which only affects
279 // inputs that come after it).
280 for (auto *Input
: ArgList
.filtered(driver::options::OPT_INPUT
)) {
281 SawInput(Input
->getValue(0));
282 IndicesToDrop
.push_back(Input
->getIndex());
284 // Anything after `--` is also treated as input, drop them as well.
286 ArgList
.getLastArgNoClaim(driver::options::OPT__DASH_DASH
)) {
287 auto DashDashIndex
= DashDash
->getIndex() + 1; // +1 accounts for Cmd[0]
288 for (unsigned I
= DashDashIndex
; I
< Cmd
.size(); ++I
)
290 Cmd
.resize(DashDashIndex
);
292 llvm::sort(IndicesToDrop
);
293 for (unsigned Idx
: llvm::reverse(IndicesToDrop
))
294 // +1 to account for the executable name in Cmd[0] that
295 // doesn't exist in ArgList.
296 Cmd
.erase(Cmd
.begin() + Idx
+ 1);
297 // All the inputs are stripped, append the name for the requested file. Rest
298 // of the modifications should respect `--`.
300 Cmd
.push_back(File
.str());
303 tooling::CompileCommand TransferCmd
;
304 TransferCmd
.Filename
= std::move(*TransferFrom
);
305 TransferCmd
.CommandLine
= std::move(Cmd
);
306 TransferCmd
= transferCompileCommand(std::move(TransferCmd
), File
);
307 Cmd
= std::move(TransferCmd
.CommandLine
);
308 assert(Cmd
.size() >= 2 && Cmd
.back() == File
&&
309 Cmd
[Cmd
.size() - 2] == "--" &&
310 "TransferCommand should produce a command ending in -- filename");
313 for (auto &Edit
: Config::current().CompileFlags
.Edits
)
316 // The system include extractor needs to run:
317 // - AFTER transferCompileCommand(), because the -x flag it adds may be
318 // necessary for the system include extractor to identify the file type
319 // - AFTER applying CompileFlags.Edits, because the name of the compiler
320 // that needs to be invoked may come from the CompileFlags->Compiler key
321 // - BEFORE addTargetAndModeForProgramName(), because gcc doesn't support
322 // the target flag that might be added.
323 // - BEFORE resolveDriver() because that can mess up the driver path,
324 // e.g. changing gcc to /path/to/clang/bin/gcc
325 if (SystemIncludeExtractor
) {
326 SystemIncludeExtractor(Command
, File
);
329 tooling::addTargetAndModeForProgramName(Cmd
, Cmd
.front());
331 // Check whether the flag exists, either as -flag or -flag=*
332 auto Has
= [&](llvm::StringRef Flag
) {
333 for (llvm::StringRef Arg
: Cmd
) {
334 if (Arg
.consume_front(Flag
) && (Arg
.empty() || Arg
[0] == '='))
340 llvm::erase_if(Cmd
, [](llvm::StringRef Elem
) {
341 return Elem
.startswith("--save-temps") || Elem
.startswith("-save-temps");
344 std::vector
<std::string
> ToAppend
;
345 if (ResourceDir
&& !Has("-resource-dir"))
346 ToAppend
.push_back(("-resource-dir=" + *ResourceDir
));
348 // Don't set `-isysroot` if it is already set or if `--sysroot` is set.
349 // `--sysroot` is a superset of the `-isysroot` argument.
350 if (Sysroot
&& !Has("-isysroot") && !Has("--sysroot")) {
351 ToAppend
.push_back("-isysroot");
352 ToAppend
.push_back(*Sysroot
);
355 if (!ToAppend
.empty()) {
356 Cmd
.insert(llvm::find(Cmd
, "--"), std::make_move_iterator(ToAppend
.begin()),
357 std::make_move_iterator(ToAppend
.end()));
361 bool FollowSymlink
= !Has("-no-canonical-prefixes");
363 (FollowSymlink
? ResolvedDrivers
: ResolvedDriversNoFollow
)
364 .get(Cmd
.front(), [&, this] {
365 return resolveDriver(Cmd
.front(), FollowSymlink
, ClangPath
);
370 // ArgStripper implementation
373 // Determine total number of args consumed by this option.
374 // Return answers for {Exact, Prefix} match. 0 means not allowed.
375 std::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
:
382 case Option::JoinedClass
:
383 case Option::CommaJoinedClass
:
385 case Option::GroupClass
:
386 case Option::InputClass
:
387 case Option::UnknownClass
:
388 case Option::ValuesClass
:
390 case Option::JoinedAndSeparateClass
:
392 case Option::SeparateClass
:
394 case Option::MultiArgClass
:
395 return {1 + Opt
.getNumArgs(), 0};
396 case Option::JoinedOrSeparateClass
:
398 case Option::RemainingArgsClass
:
400 case Option::RemainingArgsJoinedClass
:
403 llvm_unreachable("Unhandled option kind");
406 // Flag-parsing mode, which affects which flags are available.
407 enum DriverMode
: unsigned char {
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'
415 // Examine args list to determine if we're in GCC, CL-compatible, or cc1 mode.
416 DriverMode
getDriverMode(const std::vector
<std::string
> &Args
) {
417 DriverMode Mode
= DM_GCC
;
418 llvm::StringRef Argv0
= Args
.front();
419 if (Argv0
.ends_with_insensitive(".exe"))
420 Argv0
= Argv0
.drop_back(strlen(".exe"));
421 if (Argv0
.ends_with_insensitive("cl"))
423 for (const llvm::StringRef Arg
: Args
) {
424 if (Arg
== "--driver-mode=cl") {
436 // Returns the set of DriverModes where an option may be used.
437 unsigned char getModes(const llvm::opt::Option
&Opt
) {
438 unsigned char Result
= DM_None
;
439 if (Opt
.hasVisibilityFlag(driver::options::ClangOption
))
441 if (Opt
.hasVisibilityFlag(driver::options::CC1Option
))
443 if (Opt
.hasVisibilityFlag(driver::options::CLOption
))
450 llvm::ArrayRef
<ArgStripper::Rule
> ArgStripper::rulesFor(llvm::StringRef Arg
) {
451 // All the hard work is done once in a static initializer.
452 // We compute a table containing strings to look for and #args to skip.
453 // e.g. "-x" => {-x 2 args, -x* 1 arg, --language 2 args, --language=* 1 arg}
455 llvm::StringMap
<llvm::SmallVector
<Rule
, 4>, llvm::BumpPtrAllocator
>;
456 static TableTy
*Table
= [] {
457 auto &DriverTable
= driver::getDriverOptTable();
458 using DriverID
= clang::driver::options::ID
;
460 // Collect sets of aliases, so we can treat -foo and -foo= as synonyms.
461 // Conceptually a double-linked list: PrevAlias[I] -> I -> NextAlias[I].
462 // If PrevAlias[I] is INVALID, then I is canonical.
463 DriverID PrevAlias
[DriverID::LastOption
] = {DriverID::OPT_INVALID
};
464 DriverID NextAlias
[DriverID::LastOption
] = {DriverID::OPT_INVALID
};
465 auto AddAlias
= [&](DriverID Self
, DriverID T
) {
467 PrevAlias
[NextAlias
[T
]] = Self
;
468 NextAlias
[Self
] = NextAlias
[T
];
473 // Also grab prefixes for each option, these are not fully exposed.
474 llvm::ArrayRef
<llvm::StringLiteral
> Prefixes
[DriverID::LastOption
];
476 #define PREFIX(NAME, VALUE) \
477 static constexpr llvm::StringLiteral NAME##_init[] = VALUE; \
478 static constexpr llvm::ArrayRef<llvm::StringLiteral> NAME( \
479 NAME##_init, std::size(NAME##_init) - 1);
480 #define OPTION(PREFIX, PREFIXED_NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, \
481 FLAGS, VISIBILITY, PARAM, HELP, METAVAR, VALUES) \
482 Prefixes[DriverID::OPT_##ID] = PREFIX;
483 #include "clang/Driver/Options.inc"
490 const void *AliasArgs
;
492 #define OPTION(PREFIX, PREFIXED_NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, \
493 FLAGS, VISIBILITY, PARAM, HELP, METAVAR, VALUES) \
494 {DriverID::OPT_##ID, DriverID::OPT_##ALIAS, ALIASARGS},
495 #include "clang/Driver/Options.inc"
498 for (auto &E
: AliasTable
)
499 if (E
.AliasID
!= DriverID::OPT_INVALID
&& E
.AliasArgs
== nullptr)
500 AddAlias(E
.ID
, E
.AliasID
);
502 auto Result
= std::make_unique
<TableTy
>();
503 // Iterate over distinct options (represented by the canonical alias).
504 // Every spelling of this option will get the same set of rules.
505 for (unsigned ID
= 1 /*Skip INVALID */; ID
< DriverID::LastOption
; ++ID
) {
506 if (PrevAlias
[ID
] || ID
== DriverID::OPT_Xclang
)
507 continue; // Not canonical, or specially handled.
508 llvm::SmallVector
<Rule
> Rules
;
509 // Iterate over each alias, to add rules for parsing it.
510 for (unsigned A
= ID
; A
!= DriverID::OPT_INVALID
; A
= NextAlias
[A
]) {
511 if (!Prefixes
[A
].size()) // option groups.
513 auto Opt
= DriverTable
.getOption(A
);
514 // Exclude - and -foo pseudo-options.
515 if (Opt
.getName().empty())
517 auto Modes
= getModes(Opt
);
518 std::pair
<unsigned, unsigned> ArgCount
= getArgCount(Opt
);
519 // Iterate over each spelling of the alias, e.g. -foo vs --foo.
520 for (StringRef Prefix
: Prefixes
[A
]) {
521 llvm::SmallString
<64> Buf(Prefix
);
522 Buf
.append(Opt
.getName());
523 llvm::StringRef Spelling
= Result
->try_emplace(Buf
).first
->getKey();
524 Rules
.emplace_back();
525 Rule
&R
= Rules
.back();
528 R
.ExactArgs
= ArgCount
.first
;
529 R
.PrefixArgs
= ArgCount
.second
;
530 // Concrete priority is the index into the option table.
531 // Effectively, earlier entries take priority over later ones.
532 assert(ID
< std::numeric_limits
<decltype(R
.Priority
)>::max() &&
533 "Rules::Priority overflowed by options table");
537 // Register the set of rules under each possible name.
538 for (const auto &R
: Rules
)
539 Result
->find(R
.Text
)->second
.append(Rules
.begin(), Rules
.end());
542 // Dump the table and various measures of its size.
543 unsigned RuleCount
= 0;
544 dlog("ArgStripper Option spelling table");
545 for (const auto &Entry
: *Result
) {
546 dlog("{0}", Entry
.first());
547 RuleCount
+= Entry
.second
.size();
548 for (const auto &R
: Entry
.second
)
549 dlog(" {0} #={1} *={2} Mode={3}", R
.Text
, R
.ExactArgs
, R
.PrefixArgs
,
552 dlog("Table spellings={0} rules={1} string-bytes={2}", Result
->size(),
553 RuleCount
, Result
->getAllocator().getBytesAllocated());
555 // The static table will never be destroyed.
556 return Result
.release();
559 auto It
= Table
->find(Arg
);
560 return (It
== Table
->end()) ? llvm::ArrayRef
<Rule
>() : It
->second
;
563 void ArgStripper::strip(llvm::StringRef Arg
) {
564 auto OptionRules
= rulesFor(Arg
);
565 if (OptionRules
.empty()) {
566 // Not a recognized flag. Strip it literally.
567 Storage
.emplace_back(Arg
);
568 Rules
.emplace_back();
569 Rules
.back().Text
= Storage
.back();
570 Rules
.back().ExactArgs
= 1;
571 if (Rules
.back().Text
.consume_back("*"))
572 Rules
.back().PrefixArgs
= 1;
573 Rules
.back().Modes
= DM_All
;
574 Rules
.back().Priority
= -1; // Max unsigned = lowest priority.
576 Rules
.append(OptionRules
.begin(), OptionRules
.end());
580 const ArgStripper::Rule
*ArgStripper::matchingRule(llvm::StringRef Arg
,
582 unsigned &ArgCount
) const {
583 const ArgStripper::Rule
*BestRule
= nullptr;
584 for (const Rule
&R
: Rules
) {
585 // Rule can fail to match if...
586 if (!(R
.Modes
& Mode
))
587 continue; // not applicable to current driver mode
588 if (BestRule
&& BestRule
->Priority
< R
.Priority
)
589 continue; // lower-priority than best candidate.
590 if (!Arg
.startswith(R
.Text
))
591 continue; // current arg doesn't match the prefix string
592 bool PrefixMatch
= Arg
.size() > R
.Text
.size();
593 // Can rule apply as an exact/prefix match?
594 if (unsigned Count
= PrefixMatch
? R
.PrefixArgs
: R
.ExactArgs
) {
598 // Continue in case we find a higher-priority rule.
603 void ArgStripper::process(std::vector
<std::string
> &Args
) const {
607 // We're parsing the args list in some mode (e.g. gcc-compatible) but may
608 // temporarily switch to another mode with the -Xclang flag.
609 DriverMode MainMode
= getDriverMode(Args
);
610 DriverMode CurrentMode
= MainMode
;
612 // Read and write heads for in-place deletion.
613 unsigned Read
= 0, Write
= 0;
614 bool WasXclang
= false;
615 while (Read
< Args
.size()) {
616 unsigned ArgCount
= 0;
617 if (matchingRule(Args
[Read
], CurrentMode
, ArgCount
)) {
618 // Delete it and its args.
621 --Write
; // Drop previous -Xclang arg
622 CurrentMode
= MainMode
;
625 // Advance to last arg. An arg may be foo or -Xclang foo.
626 for (unsigned I
= 1; Read
< Args
.size() && I
< ArgCount
; ++I
) {
628 if (Read
< Args
.size() && Args
[Read
] == "-Xclang")
632 // No match, just copy the arg through.
633 WasXclang
= Args
[Read
] == "-Xclang";
634 CurrentMode
= WasXclang
? DM_CC1
: MainMode
;
636 Args
[Write
] = std::move(Args
[Read
]);
644 std::string
printArgv(llvm::ArrayRef
<llvm::StringRef
> Args
) {
646 llvm::raw_string_ostream
OS(Buf
);
648 for (llvm::StringRef Arg
: Args
) {
652 if (llvm::all_of(Arg
, llvm::isPrint
) &&
653 Arg
.find_first_of(" \t\n\"\\") == llvm::StringRef::npos
) {
658 OS
.write_escaped(Arg
, /*UseHexEscapes=*/true);
661 return std::move(OS
.str());
664 std::string
printArgv(llvm::ArrayRef
<std::string
> Args
) {
665 std::vector
<llvm::StringRef
> Refs(Args
.size());
666 llvm::copy(Args
, Refs
.begin());
667 return printArgv(Refs
);
670 } // namespace clangd