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/Driver/ToolChain.h" 16 #include "clang/Frontend/CompilerInvocation.h" 17 #include "clang/Tooling/ArgumentsAdjusters.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}, /*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 return llvm::None; 131 } 132 133 std::string detectStandardResourceDir() { 134 static int StaticForMainAddr; // Just an address in this process. 135 return CompilerInvocation::GetResourcesPath("clangd", 136 (void *)&StaticForMainAddr); 137 } 138 139 // The path passed to argv[0] is important: 140 // - its parent directory is Driver::Dir, used for library discovery 141 // - its basename affects CLI parsing (clang-cl) and other settings 142 // Where possible it should be an absolute path with sensible directory, but 143 // with the original basename. 144 static std::string resolveDriver(llvm::StringRef Driver, bool FollowSymlink, 145 llvm::Optional<std::string> ClangPath) { 146 auto SiblingOf = [&](llvm::StringRef AbsPath) { 147 llvm::SmallString<128> Result = llvm::sys::path::parent_path(AbsPath); 148 llvm::sys::path::append(Result, llvm::sys::path::filename(Driver)); 149 return Result.str().str(); 150 }; 151 152 // First, eliminate relative paths. 153 std::string Storage; 154 if (!llvm::sys::path::is_absolute(Driver)) { 155 // If it's working-dir relative like bin/clang, we can't resolve it. 156 // FIXME: we could if we had the working directory here. 157 // Let's hope it's not a symlink. 158 if (llvm::any_of(Driver, 159 [](char C) { return llvm::sys::path::is_separator(C); })) 160 return Driver.str(); 161 // If the driver is a generic like "g++" with no path, add clang dir. 162 if (ClangPath && 163 (Driver == "clang" || Driver == "clang++" || Driver == "gcc" || 164 Driver == "g++" || Driver == "cc" || Driver == "c++")) { 165 return SiblingOf(*ClangPath); 166 } 167 // Otherwise try to look it up on PATH. This won't change basename. 168 auto Absolute = llvm::sys::findProgramByName(Driver); 169 if (Absolute && llvm::sys::path::is_absolute(*Absolute)) 170 Driver = Storage = std::move(*Absolute); 171 else if (ClangPath) // If we don't find it, use clang dir again. 172 return SiblingOf(*ClangPath); 173 else // Nothing to do: can't find the command and no detected dir. 174 return Driver.str(); 175 } 176 177 // Now we have an absolute path, but it may be a symlink. 178 assert(llvm::sys::path::is_absolute(Driver)); 179 if (FollowSymlink) { 180 llvm::SmallString<256> Resolved; 181 if (!llvm::sys::fs::real_path(Driver, Resolved)) 182 return SiblingOf(Resolved); 183 } 184 return Driver.str(); 185 } 186 187 } // namespace 188 189 CommandMangler CommandMangler::detect() { 190 CommandMangler Result; 191 Result.ClangPath = detectClangPath(); 192 Result.ResourceDir = detectStandardResourceDir(); 193 Result.Sysroot = detectSysroot(); 194 return Result; 195 } 196 197 CommandMangler CommandMangler::forTests() { return CommandMangler(); } 198 199 void CommandMangler::adjust(std::vector<std::string> &Cmd, 200 llvm::StringRef File) const { 201 trace::Span S("AdjustCompileFlags"); 202 auto &OptTable = clang::driver::getDriverOptTable(); 203 // OriginalArgs needs to outlive ArgList. 204 llvm::SmallVector<const char *, 16> OriginalArgs; 205 OriginalArgs.reserve(Cmd.size()); 206 for (const auto &S : Cmd) 207 OriginalArgs.push_back(S.c_str()); 208 bool IsCLMode = 209 !OriginalArgs.empty() && 210 driver::IsClangCL(driver::getDriverMode( 211 OriginalArgs[0], llvm::makeArrayRef(OriginalArgs).slice(1))); 212 // ParseArgs propagates missig arg/opt counts on error, but preserves 213 // everything it could parse in ArgList. So we just ignore those counts. 214 unsigned IgnoredCount; 215 // Drop the executable name, as ParseArgs doesn't expect it. This means 216 // indices are actually of by one between ArgList and OriginalArgs. 217 auto ArgList = OptTable.ParseArgs( 218 llvm::makeArrayRef(OriginalArgs).drop_front(), IgnoredCount, IgnoredCount, 219 /*FlagsToInclude=*/ 220 IsCLMode ? (driver::options::CLOption | driver::options::CoreOption) 221 : /*everything*/ 0, 222 /*FlagsToExclude=*/driver::options::NoDriverOption | 223 (IsCLMode ? 0 : driver::options::CLOption)); 224 225 // Move the inputs to the end, separated via `--` from flags. This ensures 226 // modifications done in the following steps apply in more cases (like setting 227 // -x, which only affects inputs that come after it). 228 if (!ArgList.hasArgNoClaim(driver::options::OPT__DASH_DASH)) { 229 // Drop all the inputs and only add one for the current file. 230 llvm::SmallVector<unsigned, 1> IndicesToDrop; 231 for (auto *Input : ArgList.filtered(driver::options::OPT_INPUT)) 232 IndicesToDrop.push_back(Input->getIndex()); 233 llvm::sort(IndicesToDrop); 234 llvm::for_each(llvm::reverse(IndicesToDrop), 235 // +1 to account for the executable name in Cmd[0] that 236 // doesn't exist in ArgList. 237 [&Cmd](unsigned Idx) { Cmd.erase(Cmd.begin() + Idx + 1); }); 238 Cmd.push_back("--"); 239 Cmd.push_back(File.str()); 240 } 241 242 for (auto &Edit : Config::current().CompileFlags.Edits) 243 Edit(Cmd); 244 245 // Check whether the flag exists, either as -flag or -flag=* 246 auto Has = [&](llvm::StringRef Flag) { 247 for (llvm::StringRef Arg : Cmd) { 248 if (Arg.consume_front(Flag) && (Arg.empty() || Arg[0] == '=')) 249 return true; 250 } 251 return false; 252 }; 253 254 llvm::erase_if(Cmd, [](llvm::StringRef Elem) { 255 return Elem.startswith("--save-temps") || Elem.startswith("-save-temps"); 256 }); 257 258 std::vector<std::string> ToAppend; 259 if (ResourceDir && !Has("-resource-dir")) 260 ToAppend.push_back(("-resource-dir=" + *ResourceDir)); 261 262 // Don't set `-isysroot` if it is already set or if `--sysroot` is set. 263 // `--sysroot` is a superset of the `-isysroot` argument. 264 if (Sysroot && !Has("-isysroot") && !Has("--sysroot")) { 265 ToAppend.push_back("-isysroot"); 266 ToAppend.push_back(*Sysroot); 267 } 268 269 if (!ToAppend.empty()) { 270 Cmd.insert(llvm::find(Cmd, "--"), std::make_move_iterator(ToAppend.begin()), 271 std::make_move_iterator(ToAppend.end())); 272 } 273 274 if (!Cmd.empty()) { 275 bool FollowSymlink = !Has("-no-canonical-prefixes"); 276 Cmd.front() = 277 (FollowSymlink ? ResolvedDrivers : ResolvedDriversNoFollow) 278 .get(Cmd.front(), [&, this] { 279 return resolveDriver(Cmd.front(), FollowSymlink, ClangPath); 280 }); 281 } 282 } 283 284 CommandMangler::operator clang::tooling::ArgumentsAdjuster() && { 285 // ArgumentsAdjuster is a std::function and so must be copyable. 286 return [Mangler = std::make_shared<CommandMangler>(std::move(*this))]( 287 const std::vector<std::string> &Args, llvm::StringRef File) { 288 auto Result = Args; 289 Mangler->adjust(Result, File); 290 return Result; 291 }; 292 } 293 294 // ArgStripper implementation 295 namespace { 296 297 // Determine total number of args consumed by this option. 298 // Return answers for {Exact, Prefix} match. 0 means not allowed. 299 std::pair<unsigned, unsigned> getArgCount(const llvm::opt::Option &Opt) { 300 constexpr static unsigned Rest = 10000; // Should be all the rest! 301 // Reference is llvm::opt::Option::acceptInternal() 302 using llvm::opt::Option; 303 switch (Opt.getKind()) { 304 case Option::FlagClass: 305 return {1, 0}; 306 case Option::JoinedClass: 307 case Option::CommaJoinedClass: 308 return {1, 1}; 309 case Option::GroupClass: 310 case Option::InputClass: 311 case Option::UnknownClass: 312 case Option::ValuesClass: 313 return {1, 0}; 314 case Option::JoinedAndSeparateClass: 315 return {2, 2}; 316 case Option::SeparateClass: 317 return {2, 0}; 318 case Option::MultiArgClass: 319 return {1 + Opt.getNumArgs(), 0}; 320 case Option::JoinedOrSeparateClass: 321 return {2, 1}; 322 case Option::RemainingArgsClass: 323 return {Rest, 0}; 324 case Option::RemainingArgsJoinedClass: 325 return {Rest, Rest}; 326 } 327 llvm_unreachable("Unhandled option kind"); 328 } 329 330 // Flag-parsing mode, which affects which flags are available. 331 enum DriverMode : unsigned char { 332 DM_None = 0, 333 DM_GCC = 1, // Default mode e.g. when invoked as 'clang' 334 DM_CL = 2, // MS CL.exe compatible mode e.g. when invoked as 'clang-cl' 335 DM_CC1 = 4, // When invoked as 'clang -cc1' or after '-Xclang' 336 DM_All = 7 337 }; 338 339 // Examine args list to determine if we're in GCC, CL-compatible, or cc1 mode. 340 DriverMode getDriverMode(const std::vector<std::string> &Args) { 341 DriverMode Mode = DM_GCC; 342 llvm::StringRef Argv0 = Args.front(); 343 if (Argv0.endswith_insensitive(".exe")) 344 Argv0 = Argv0.drop_back(strlen(".exe")); 345 if (Argv0.endswith_insensitive("cl")) 346 Mode = DM_CL; 347 for (const llvm::StringRef Arg : Args) { 348 if (Arg == "--driver-mode=cl") { 349 Mode = DM_CL; 350 break; 351 } 352 if (Arg == "-cc1") { 353 Mode = DM_CC1; 354 break; 355 } 356 } 357 return Mode; 358 } 359 360 // Returns the set of DriverModes where an option may be used. 361 unsigned char getModes(const llvm::opt::Option &Opt) { 362 // Why is this so complicated?! 363 // Reference is clang::driver::Driver::getIncludeExcludeOptionFlagMasks() 364 unsigned char Result = DM_None; 365 if (Opt.hasFlag(driver::options::CC1Option)) 366 Result |= DM_CC1; 367 if (!Opt.hasFlag(driver::options::NoDriverOption)) { 368 if (Opt.hasFlag(driver::options::CLOption)) { 369 Result |= DM_CL; 370 } else { 371 Result |= DM_GCC; 372 if (Opt.hasFlag(driver::options::CoreOption)) { 373 Result |= DM_CL; 374 } 375 } 376 } 377 return Result; 378 } 379 380 } // namespace 381 382 llvm::ArrayRef<ArgStripper::Rule> ArgStripper::rulesFor(llvm::StringRef Arg) { 383 // All the hard work is done once in a static initializer. 384 // We compute a table containing strings to look for and #args to skip. 385 // e.g. "-x" => {-x 2 args, -x* 1 arg, --language 2 args, --language=* 1 arg} 386 using TableTy = 387 llvm::StringMap<llvm::SmallVector<Rule, 4>, llvm::BumpPtrAllocator>; 388 static TableTy *Table = [] { 389 auto &DriverTable = driver::getDriverOptTable(); 390 using DriverID = clang::driver::options::ID; 391 392 // Collect sets of aliases, so we can treat -foo and -foo= as synonyms. 393 // Conceptually a double-linked list: PrevAlias[I] -> I -> NextAlias[I]. 394 // If PrevAlias[I] is INVALID, then I is canonical. 395 DriverID PrevAlias[DriverID::LastOption] = {DriverID::OPT_INVALID}; 396 DriverID NextAlias[DriverID::LastOption] = {DriverID::OPT_INVALID}; 397 auto AddAlias = [&](DriverID Self, DriverID T) { 398 if (NextAlias[T]) { 399 PrevAlias[NextAlias[T]] = Self; 400 NextAlias[Self] = NextAlias[T]; 401 } 402 PrevAlias[Self] = T; 403 NextAlias[T] = Self; 404 }; 405 // Also grab prefixes for each option, these are not fully exposed. 406 const char *const *Prefixes[DriverID::LastOption] = {nullptr}; 407 #define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE; 408 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 409 HELP, METAVAR, VALUES) \ 410 if (DriverID::OPT_##ALIAS != DriverID::OPT_INVALID && ALIASARGS == nullptr) \ 411 AddAlias(DriverID::OPT_##ID, DriverID::OPT_##ALIAS); \ 412 Prefixes[DriverID::OPT_##ID] = PREFIX; 413 #include "clang/Driver/Options.inc" 414 #undef OPTION 415 #undef PREFIX 416 417 auto Result = std::make_unique<TableTy>(); 418 // Iterate over distinct options (represented by the canonical alias). 419 // Every spelling of this option will get the same set of rules. 420 for (unsigned ID = 1 /*Skip INVALID */; ID < DriverID::LastOption; ++ID) { 421 if (PrevAlias[ID] || ID == DriverID::OPT_Xclang) 422 continue; // Not canonical, or specially handled. 423 llvm::SmallVector<Rule> Rules; 424 // Iterate over each alias, to add rules for parsing it. 425 for (unsigned A = ID; A != DriverID::OPT_INVALID; A = NextAlias[A]) { 426 if (Prefixes[A] == nullptr) // option groups. 427 continue; 428 auto Opt = DriverTable.getOption(A); 429 // Exclude - and -foo pseudo-options. 430 if (Opt.getName().empty()) 431 continue; 432 auto Modes = getModes(Opt); 433 std::pair<unsigned, unsigned> ArgCount = getArgCount(Opt); 434 // Iterate over each spelling of the alias, e.g. -foo vs --foo. 435 for (auto *Prefix = Prefixes[A]; *Prefix != nullptr; ++Prefix) { 436 llvm::SmallString<64> Buf(*Prefix); 437 Buf.append(Opt.getName()); 438 llvm::StringRef Spelling = Result->try_emplace(Buf).first->getKey(); 439 Rules.emplace_back(); 440 Rule &R = Rules.back(); 441 R.Text = Spelling; 442 R.Modes = Modes; 443 R.ExactArgs = ArgCount.first; 444 R.PrefixArgs = ArgCount.second; 445 // Concrete priority is the index into the option table. 446 // Effectively, earlier entries take priority over later ones. 447 assert(ID < std::numeric_limits<decltype(R.Priority)>::max() && 448 "Rules::Priority overflowed by options table"); 449 R.Priority = ID; 450 } 451 } 452 // Register the set of rules under each possible name. 453 for (const auto &R : Rules) 454 Result->find(R.Text)->second.append(Rules.begin(), Rules.end()); 455 } 456 #ifndef NDEBUG 457 // Dump the table and various measures of its size. 458 unsigned RuleCount = 0; 459 dlog("ArgStripper Option spelling table"); 460 for (const auto &Entry : *Result) { 461 dlog("{0}", Entry.first()); 462 RuleCount += Entry.second.size(); 463 for (const auto &R : Entry.second) 464 dlog(" {0} #={1} *={2} Mode={3}", R.Text, R.ExactArgs, R.PrefixArgs, 465 int(R.Modes)); 466 } 467 dlog("Table spellings={0} rules={1} string-bytes={2}", Result->size(), 468 RuleCount, Result->getAllocator().getBytesAllocated()); 469 #endif 470 // The static table will never be destroyed. 471 return Result.release(); 472 }(); 473 474 auto It = Table->find(Arg); 475 return (It == Table->end()) ? llvm::ArrayRef<Rule>() : It->second; 476 } 477 478 void ArgStripper::strip(llvm::StringRef Arg) { 479 auto OptionRules = rulesFor(Arg); 480 if (OptionRules.empty()) { 481 // Not a recognized flag. Strip it literally. 482 Storage.emplace_back(Arg); 483 Rules.emplace_back(); 484 Rules.back().Text = Storage.back(); 485 Rules.back().ExactArgs = 1; 486 if (Rules.back().Text.consume_back("*")) 487 Rules.back().PrefixArgs = 1; 488 Rules.back().Modes = DM_All; 489 Rules.back().Priority = -1; // Max unsigned = lowest priority. 490 } else { 491 Rules.append(OptionRules.begin(), OptionRules.end()); 492 } 493 } 494 495 const ArgStripper::Rule *ArgStripper::matchingRule(llvm::StringRef Arg, 496 unsigned Mode, 497 unsigned &ArgCount) const { 498 const ArgStripper::Rule *BestRule = nullptr; 499 for (const Rule &R : Rules) { 500 // Rule can fail to match if... 501 if (!(R.Modes & Mode)) 502 continue; // not applicable to current driver mode 503 if (BestRule && BestRule->Priority < R.Priority) 504 continue; // lower-priority than best candidate. 505 if (!Arg.startswith(R.Text)) 506 continue; // current arg doesn't match the prefix string 507 bool PrefixMatch = Arg.size() > R.Text.size(); 508 // Can rule apply as an exact/prefix match? 509 if (unsigned Count = PrefixMatch ? R.PrefixArgs : R.ExactArgs) { 510 BestRule = &R; 511 ArgCount = Count; 512 } 513 // Continue in case we find a higher-priority rule. 514 } 515 return BestRule; 516 } 517 518 void ArgStripper::process(std::vector<std::string> &Args) const { 519 if (Args.empty()) 520 return; 521 522 // We're parsing the args list in some mode (e.g. gcc-compatible) but may 523 // temporarily switch to another mode with the -Xclang flag. 524 DriverMode MainMode = getDriverMode(Args); 525 DriverMode CurrentMode = MainMode; 526 527 // Read and write heads for in-place deletion. 528 unsigned Read = 0, Write = 0; 529 bool WasXclang = false; 530 while (Read < Args.size()) { 531 unsigned ArgCount = 0; 532 if (matchingRule(Args[Read], CurrentMode, ArgCount)) { 533 // Delete it and its args. 534 if (WasXclang) { 535 assert(Write > 0); 536 --Write; // Drop previous -Xclang arg 537 CurrentMode = MainMode; 538 WasXclang = false; 539 } 540 // Advance to last arg. An arg may be foo or -Xclang foo. 541 for (unsigned I = 1; Read < Args.size() && I < ArgCount; ++I) { 542 ++Read; 543 if (Read < Args.size() && Args[Read] == "-Xclang") 544 ++Read; 545 } 546 } else { 547 // No match, just copy the arg through. 548 WasXclang = Args[Read] == "-Xclang"; 549 CurrentMode = WasXclang ? DM_CC1 : MainMode; 550 if (Write != Read) 551 Args[Write] = std::move(Args[Read]); 552 ++Write; 553 } 554 ++Read; 555 } 556 Args.resize(Write); 557 } 558 559 std::string printArgv(llvm::ArrayRef<llvm::StringRef> Args) { 560 std::string Buf; 561 llvm::raw_string_ostream OS(Buf); 562 bool Sep = false; 563 for (llvm::StringRef Arg : Args) { 564 if (Sep) 565 OS << ' '; 566 Sep = true; 567 if (llvm::all_of(Arg, llvm::isPrint) && 568 Arg.find_first_of(" \t\n\"\\") == llvm::StringRef::npos) { 569 OS << Arg; 570 continue; 571 } 572 OS << '"'; 573 OS.write_escaped(Arg, /*UseHexEscapes=*/true); 574 OS << '"'; 575 } 576 return std::move(OS.str()); 577 } 578 579 std::string printArgv(llvm::ArrayRef<std::string> Args) { 580 std::vector<llvm::StringRef> Refs(Args.size()); 581 llvm::copy(Args, Refs.begin()); 582 return printArgv(Refs); 583 } 584 585 } // namespace clangd 586 } // namespace clang 587