| 1 | //===-- CommandLine.cpp - Command line parser implementation --------------===// |
| 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 | // This class implements a command line argument processor that is useful when |
| 10 | // creating a tool. It provides a simple, minimalistic interface that is easily |
| 11 | // extensible and supports nonlocal (library) command line options. |
| 12 | // |
| 13 | // Note that rather than trying to figure out what this code does, you could try |
| 14 | // reading the library documentation located in docs/CommandLine.html |
| 15 | // |
| 16 | //===----------------------------------------------------------------------===// |
| 17 | |
| 18 | #include "llvm/Support/CommandLine.h" |
| 19 | |
| 20 | #include "DebugOptions.h" |
| 21 | |
| 22 | #include "llvm-c/Support.h" |
| 23 | #include "llvm/ADT/ArrayRef.h" |
| 24 | #include "llvm/ADT/STLFunctionalExtras.h" |
| 25 | #include "llvm/ADT/SmallPtrSet.h" |
| 26 | #include "llvm/ADT/SmallString.h" |
| 27 | #include "llvm/ADT/StringExtras.h" |
| 28 | #include "llvm/ADT/StringMap.h" |
| 29 | #include "llvm/ADT/StringRef.h" |
| 30 | #include "llvm/ADT/Twine.h" |
| 31 | #include "llvm/Config/config.h" |
| 32 | #include "llvm/Support/Compiler.h" |
| 33 | #include "llvm/Support/ConvertUTF.h" |
| 34 | #include "llvm/Support/Debug.h" |
| 35 | #include "llvm/Support/Error.h" |
| 36 | #include "llvm/Support/ErrorHandling.h" |
| 37 | #include "llvm/Support/FileSystem.h" |
| 38 | #include "llvm/Support/ManagedStatic.h" |
| 39 | #include "llvm/Support/MemoryBuffer.h" |
| 40 | #include "llvm/Support/Path.h" |
| 41 | #include "llvm/Support/Process.h" |
| 42 | #include "llvm/Support/StringSaver.h" |
| 43 | #include "llvm/Support/VirtualFileSystem.h" |
| 44 | #include "llvm/Support/raw_ostream.h" |
| 45 | #include <cstdlib> |
| 46 | #include <optional> |
| 47 | #include <string> |
| 48 | using namespace llvm; |
| 49 | using namespace cl; |
| 50 | |
| 51 | #define DEBUG_TYPE "commandline" |
| 52 | |
| 53 | //===----------------------------------------------------------------------===// |
| 54 | // Template instantiations and anchors. |
| 55 | // |
| 56 | namespace llvm { |
| 57 | namespace cl { |
| 58 | template class LLVM_EXPORT_TEMPLATE basic_parser<bool>; |
| 59 | template class LLVM_EXPORT_TEMPLATE basic_parser<boolOrDefault>; |
| 60 | template class LLVM_EXPORT_TEMPLATE basic_parser<int>; |
| 61 | template class LLVM_EXPORT_TEMPLATE basic_parser<long>; |
| 62 | template class LLVM_EXPORT_TEMPLATE basic_parser<long long>; |
| 63 | template class LLVM_EXPORT_TEMPLATE basic_parser<unsigned>; |
| 64 | template class LLVM_EXPORT_TEMPLATE basic_parser<unsigned long>; |
| 65 | template class LLVM_EXPORT_TEMPLATE basic_parser<unsigned long long>; |
| 66 | template class LLVM_EXPORT_TEMPLATE basic_parser<double>; |
| 67 | template class LLVM_EXPORT_TEMPLATE basic_parser<float>; |
| 68 | template class LLVM_EXPORT_TEMPLATE basic_parser<std::string>; |
| 69 | template class LLVM_EXPORT_TEMPLATE basic_parser<char>; |
| 70 | |
| 71 | #if !(defined(LLVM_ENABLE_LLVM_EXPORT_ANNOTATIONS) && defined(_MSC_VER)) |
| 72 | // Only instantiate opt<std::string> when not building a Windows DLL. When |
| 73 | // exporting opt<std::string>, MSVC implicitly exports symbols for |
| 74 | // std::basic_string through transitive inheritance via std::string. These |
| 75 | // symbols may appear in clients, leading to duplicate symbol conflicts. |
| 76 | template class LLVM_EXPORT_TEMPLATE opt<std::string>; |
| 77 | #endif |
| 78 | |
| 79 | template class LLVM_EXPORT_TEMPLATE opt<bool>; |
| 80 | template class LLVM_EXPORT_TEMPLATE opt<char>; |
| 81 | template class LLVM_EXPORT_TEMPLATE opt<int>; |
| 82 | template class LLVM_EXPORT_TEMPLATE opt<unsigned>; |
| 83 | |
| 84 | } // namespace cl |
| 85 | } // namespace llvm |
| 86 | |
| 87 | // Pin the vtables to this file. |
| 88 | void GenericOptionValue::anchor() {} |
| 89 | void OptionValue<boolOrDefault>::anchor() {} |
| 90 | void OptionValue<std::string>::anchor() {} |
| 91 | void Option::anchor() {} |
| 92 | void basic_parser_impl::anchor() {} |
| 93 | void parser<bool>::anchor() {} |
| 94 | void parser<boolOrDefault>::anchor() {} |
| 95 | void parser<int>::anchor() {} |
| 96 | void parser<long>::anchor() {} |
| 97 | void parser<long long>::anchor() {} |
| 98 | void parser<unsigned>::anchor() {} |
| 99 | void parser<unsigned long>::anchor() {} |
| 100 | void parser<unsigned long long>::anchor() {} |
| 101 | void parser<double>::anchor() {} |
| 102 | void parser<float>::anchor() {} |
| 103 | void parser<std::string>::anchor() {} |
| 104 | void parser<std::optional<std::string>>::anchor() {} |
| 105 | void parser<char>::anchor() {} |
| 106 | |
| 107 | // These anchor functions instantiate opt<T> and reference its virtual |
| 108 | // destructor to ensure MSVC exports the corresponding vtable and typeinfo when |
| 109 | // building a Windows DLL. Without an explicit reference, MSVC may omit the |
| 110 | // instantiation at link time even if it is marked DLL-export. |
| 111 | void opt_bool_anchor() { opt<bool> anchor{"" }; } |
| 112 | void opt_char_anchor() { opt<char> anchor{"" }; } |
| 113 | void opt_int_anchor() { opt<int> anchor{"" }; } |
| 114 | void opt_unsigned_anchor() { opt<unsigned> anchor{"" }; } |
| 115 | |
| 116 | //===----------------------------------------------------------------------===// |
| 117 | |
| 118 | const static size_t DefaultPad = 2; |
| 119 | |
| 120 | static StringRef ArgPrefix = "-" ; |
| 121 | static StringRef ArgPrefixLong = "--" ; |
| 122 | static StringRef ArgHelpPrefix = " - " ; |
| 123 | |
| 124 | static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad = DefaultPad) { |
| 125 | size_t Len = ArgName.size(); |
| 126 | if (Len == 1) |
| 127 | return Len + Pad + ArgPrefix.size() + ArgHelpPrefix.size(); |
| 128 | return Len + Pad + ArgPrefixLong.size() + ArgHelpPrefix.size(); |
| 129 | } |
| 130 | |
| 131 | static SmallString<8> argPrefix(StringRef ArgName, size_t Pad = DefaultPad) { |
| 132 | SmallString<8> Prefix; |
| 133 | for (size_t I = 0; I < Pad; ++I) { |
| 134 | Prefix.push_back(Elt: ' '); |
| 135 | } |
| 136 | Prefix.append(RHS: ArgName.size() > 1 ? ArgPrefixLong : ArgPrefix); |
| 137 | return Prefix; |
| 138 | } |
| 139 | |
| 140 | // Option predicates... |
| 141 | static inline bool isGrouping(const Option *O) { |
| 142 | return O->getMiscFlags() & cl::Grouping; |
| 143 | } |
| 144 | static inline bool isPrefixedOrGrouping(const Option *O) { |
| 145 | return isGrouping(O) || O->getFormattingFlag() == cl::Prefix || |
| 146 | O->getFormattingFlag() == cl::AlwaysPrefix; |
| 147 | } |
| 148 | |
| 149 | using OptionsMapTy = DenseMap<StringRef, Option *>; |
| 150 | |
| 151 | namespace { |
| 152 | |
| 153 | class PrintArg { |
| 154 | StringRef ArgName; |
| 155 | size_t Pad; |
| 156 | public: |
| 157 | PrintArg(StringRef ArgName, size_t Pad = DefaultPad) : ArgName(ArgName), Pad(Pad) {} |
| 158 | friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg &); |
| 159 | }; |
| 160 | |
| 161 | raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) { |
| 162 | OS << argPrefix(ArgName: Arg.ArgName, Pad: Arg.Pad) << Arg.ArgName; |
| 163 | return OS; |
| 164 | } |
| 165 | |
| 166 | class CommandLineParser { |
| 167 | public: |
| 168 | // Globals for name and overview of program. Program name is not a string to |
| 169 | // avoid static ctor/dtor issues. |
| 170 | std::string ProgramName; |
| 171 | StringRef ProgramOverview; |
| 172 | |
| 173 | // This collects additional help to be printed. |
| 174 | std::vector<StringRef> MoreHelp; |
| 175 | |
| 176 | // This collects Options added with the cl::DefaultOption flag. Since they can |
| 177 | // be overridden, they are not added to the appropriate SubCommands until |
| 178 | // ParseCommandLineOptions actually runs. |
| 179 | SmallVector<Option*, 4> DefaultOptions; |
| 180 | |
| 181 | // This collects the different option categories that have been registered. |
| 182 | SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories; |
| 183 | |
| 184 | // This collects the different subcommands that have been registered. |
| 185 | SmallPtrSet<SubCommand *, 4> RegisteredSubCommands; |
| 186 | |
| 187 | CommandLineParser() { registerSubCommand(sub: &SubCommand::getTopLevel()); } |
| 188 | |
| 189 | void ResetAllOptionOccurrences(); |
| 190 | |
| 191 | bool ParseCommandLineOptions(int argc, const char *const *argv, |
| 192 | StringRef Overview, raw_ostream *Errs = nullptr, |
| 193 | vfs::FileSystem *VFS = nullptr, |
| 194 | bool LongOptionsUseDoubleDash = false); |
| 195 | |
| 196 | void forEachSubCommand(Option &Opt, function_ref<void(SubCommand &)> Action) { |
| 197 | if (Opt.Subs.empty()) { |
| 198 | Action(SubCommand::getTopLevel()); |
| 199 | return; |
| 200 | } |
| 201 | if (Opt.Subs.size() == 1 && *Opt.Subs.begin() == &SubCommand::getAll()) { |
| 202 | for (auto *SC : RegisteredSubCommands) |
| 203 | Action(*SC); |
| 204 | Action(SubCommand::getAll()); |
| 205 | return; |
| 206 | } |
| 207 | for (auto *SC : Opt.Subs) { |
| 208 | assert(SC != &SubCommand::getAll() && |
| 209 | "SubCommand::getAll() should not be used with other subcommands" ); |
| 210 | Action(*SC); |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) { |
| 215 | if (Opt.hasArgStr()) |
| 216 | return; |
| 217 | if (!SC->OptionsMap.insert(KV: std::make_pair(x&: Name, y: &Opt)).second) { |
| 218 | errs() << ProgramName << ": CommandLine Error: Option '" << Name |
| 219 | << "' registered more than once!\n" ; |
| 220 | report_fatal_error(reason: "inconsistency in registered CommandLine options" ); |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | void addLiteralOption(Option &Opt, StringRef Name) { |
| 225 | forEachSubCommand( |
| 226 | Opt, Action: [&](SubCommand &SC) { addLiteralOption(Opt, SC: &SC, Name); }); |
| 227 | } |
| 228 | |
| 229 | void addOption(Option *O, SubCommand *SC) { |
| 230 | bool HadErrors = false; |
| 231 | if (O->hasArgStr()) { |
| 232 | // If it's a DefaultOption, check to make sure it isn't already there. |
| 233 | if (O->isDefaultOption() && SC->OptionsMap.contains(Val: O->ArgStr)) |
| 234 | return; |
| 235 | |
| 236 | // Add argument to the argument map! |
| 237 | if (!SC->OptionsMap.insert(KV: std::make_pair(x&: O->ArgStr, y&: O)).second) { |
| 238 | errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr |
| 239 | << "' registered more than once!\n" ; |
| 240 | HadErrors = true; |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | // Remember information about positional options. |
| 245 | if (O->getFormattingFlag() == cl::Positional) |
| 246 | SC->PositionalOpts.push_back(Elt: O); |
| 247 | else if (O->getMiscFlags() & cl::Sink) // Remember sink options |
| 248 | SC->SinkOpts.push_back(Elt: O); |
| 249 | else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) { |
| 250 | if (SC->ConsumeAfterOpt) { |
| 251 | O->error(Message: "Cannot specify more than one option with cl::ConsumeAfter!" ); |
| 252 | HadErrors = true; |
| 253 | } |
| 254 | SC->ConsumeAfterOpt = O; |
| 255 | } |
| 256 | |
| 257 | // Fail hard if there were errors. These are strictly unrecoverable and |
| 258 | // indicate serious issues such as conflicting option names or an |
| 259 | // incorrectly |
| 260 | // linked LLVM distribution. |
| 261 | if (HadErrors) |
| 262 | report_fatal_error(reason: "inconsistency in registered CommandLine options" ); |
| 263 | } |
| 264 | |
| 265 | void addOption(Option *O, bool ProcessDefaultOption = false) { |
| 266 | if (!ProcessDefaultOption && O->isDefaultOption()) { |
| 267 | DefaultOptions.push_back(Elt: O); |
| 268 | return; |
| 269 | } |
| 270 | forEachSubCommand(Opt&: *O, Action: [&](SubCommand &SC) { addOption(O, SC: &SC); }); |
| 271 | } |
| 272 | |
| 273 | void removeOption(Option *O, SubCommand *SC) { |
| 274 | SmallVector<StringRef, 16> OptionNames; |
| 275 | O->getExtraOptionNames(OptionNames); |
| 276 | if (O->hasArgStr()) |
| 277 | OptionNames.push_back(Elt: O->ArgStr); |
| 278 | |
| 279 | SubCommand &Sub = *SC; |
| 280 | auto End = Sub.OptionsMap.end(); |
| 281 | for (auto Name : OptionNames) { |
| 282 | auto I = Sub.OptionsMap.find(Val: Name); |
| 283 | if (I != End && I->second == O) |
| 284 | Sub.OptionsMap.erase(I); |
| 285 | } |
| 286 | |
| 287 | if (O->getFormattingFlag() == cl::Positional) |
| 288 | for (auto *Opt = Sub.PositionalOpts.begin(); |
| 289 | Opt != Sub.PositionalOpts.end(); ++Opt) { |
| 290 | if (*Opt == O) { |
| 291 | Sub.PositionalOpts.erase(CI: Opt); |
| 292 | break; |
| 293 | } |
| 294 | } |
| 295 | else if (O->getMiscFlags() & cl::Sink) |
| 296 | for (auto *Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) { |
| 297 | if (*Opt == O) { |
| 298 | Sub.SinkOpts.erase(CI: Opt); |
| 299 | break; |
| 300 | } |
| 301 | } |
| 302 | else if (O == Sub.ConsumeAfterOpt) |
| 303 | Sub.ConsumeAfterOpt = nullptr; |
| 304 | } |
| 305 | |
| 306 | void removeOption(Option *O) { |
| 307 | forEachSubCommand(Opt&: *O, Action: [&](SubCommand &SC) { removeOption(O, SC: &SC); }); |
| 308 | } |
| 309 | |
| 310 | bool hasOptions(const SubCommand &Sub) const { |
| 311 | return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() || |
| 312 | nullptr != Sub.ConsumeAfterOpt); |
| 313 | } |
| 314 | |
| 315 | bool hasOptions() const { |
| 316 | for (const auto *S : RegisteredSubCommands) { |
| 317 | if (hasOptions(Sub: *S)) |
| 318 | return true; |
| 319 | } |
| 320 | return false; |
| 321 | } |
| 322 | |
| 323 | bool hasNamedSubCommands() const { |
| 324 | for (const auto *S : RegisteredSubCommands) |
| 325 | if (!S->getName().empty()) |
| 326 | return true; |
| 327 | return false; |
| 328 | } |
| 329 | |
| 330 | SubCommand *getActiveSubCommand() { return ActiveSubCommand; } |
| 331 | |
| 332 | void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) { |
| 333 | SubCommand &Sub = *SC; |
| 334 | if (!Sub.OptionsMap.insert(KV: std::make_pair(x&: NewName, y&: O)).second) { |
| 335 | errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr |
| 336 | << "' registered more than once!\n" ; |
| 337 | report_fatal_error(reason: "inconsistency in registered CommandLine options" ); |
| 338 | } |
| 339 | Sub.OptionsMap.erase(Val: O->ArgStr); |
| 340 | } |
| 341 | |
| 342 | void updateArgStr(Option *O, StringRef NewName) { |
| 343 | forEachSubCommand(Opt&: *O, |
| 344 | Action: [&](SubCommand &SC) { updateArgStr(O, NewName, SC: &SC); }); |
| 345 | } |
| 346 | |
| 347 | void printOptionValues(); |
| 348 | |
| 349 | void registerCategory(OptionCategory *cat) { |
| 350 | assert(count_if(RegisteredOptionCategories, |
| 351 | [cat](const OptionCategory *Category) { |
| 352 | return cat->getName() == Category->getName(); |
| 353 | }) == 0 && |
| 354 | "Duplicate option categories" ); |
| 355 | |
| 356 | RegisteredOptionCategories.insert(Ptr: cat); |
| 357 | } |
| 358 | |
| 359 | void registerSubCommand(SubCommand *sub) { |
| 360 | assert(count_if(RegisteredSubCommands, |
| 361 | [sub](const SubCommand *Sub) { |
| 362 | return (!sub->getName().empty()) && |
| 363 | (Sub->getName() == sub->getName()); |
| 364 | }) == 0 && |
| 365 | "Duplicate subcommands" ); |
| 366 | RegisteredSubCommands.insert(Ptr: sub); |
| 367 | |
| 368 | // For all options that have been registered for all subcommands, add the |
| 369 | // option to this subcommand now. |
| 370 | assert(sub != &SubCommand::getAll() && |
| 371 | "SubCommand::getAll() should not be registered" ); |
| 372 | for (auto &E : SubCommand::getAll().OptionsMap) { |
| 373 | Option *O = E.second; |
| 374 | if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) || |
| 375 | O->hasArgStr()) |
| 376 | addOption(O, SC: sub); |
| 377 | else |
| 378 | addLiteralOption(Opt&: *O, SC: sub, Name: E.first); |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | void unregisterSubCommand(SubCommand *sub) { |
| 383 | RegisteredSubCommands.erase(Ptr: sub); |
| 384 | } |
| 385 | |
| 386 | iterator_range<SmallPtrSet<SubCommand *, 4>::iterator> |
| 387 | getRegisteredSubcommands() { |
| 388 | return make_range(x: RegisteredSubCommands.begin(), |
| 389 | y: RegisteredSubCommands.end()); |
| 390 | } |
| 391 | |
| 392 | void reset() { |
| 393 | ActiveSubCommand = nullptr; |
| 394 | ProgramName.clear(); |
| 395 | ProgramOverview = StringRef(); |
| 396 | |
| 397 | MoreHelp.clear(); |
| 398 | RegisteredOptionCategories.clear(); |
| 399 | |
| 400 | ResetAllOptionOccurrences(); |
| 401 | RegisteredSubCommands.clear(); |
| 402 | |
| 403 | SubCommand::getTopLevel().reset(); |
| 404 | SubCommand::getAll().reset(); |
| 405 | registerSubCommand(sub: &SubCommand::getTopLevel()); |
| 406 | |
| 407 | DefaultOptions.clear(); |
| 408 | } |
| 409 | |
| 410 | private: |
| 411 | SubCommand *ActiveSubCommand = nullptr; |
| 412 | |
| 413 | Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value); |
| 414 | Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value, |
| 415 | bool LongOptionsUseDoubleDash, bool HaveDoubleDash) { |
| 416 | Option *Opt = LookupOption(Sub, Arg, Value); |
| 417 | if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(O: Opt)) |
| 418 | return nullptr; |
| 419 | return Opt; |
| 420 | } |
| 421 | SubCommand *LookupSubCommand(StringRef Name, std::string &NearestString); |
| 422 | }; |
| 423 | |
| 424 | } // namespace |
| 425 | |
| 426 | static ManagedStatic<CommandLineParser> GlobalParser; |
| 427 | |
| 428 | template <typename T, T TrueVal, T FalseVal> |
| 429 | static bool parseBool(Option &O, StringRef ArgName, StringRef Arg, T &Value) { |
| 430 | if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || |
| 431 | Arg == "1" ) { |
| 432 | Value = TrueVal; |
| 433 | return false; |
| 434 | } |
| 435 | |
| 436 | if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0" ) { |
| 437 | Value = FalseVal; |
| 438 | return false; |
| 439 | } |
| 440 | return O.error(Message: "'" + Arg + |
| 441 | "' is invalid value for boolean argument! Try 0 or 1" ); |
| 442 | } |
| 443 | |
| 444 | void cl::AddLiteralOption(Option &O, StringRef Name) { |
| 445 | GlobalParser->addLiteralOption(Opt&: O, Name); |
| 446 | } |
| 447 | |
| 448 | extrahelp::(StringRef Help) : morehelp(Help) { |
| 449 | GlobalParser->MoreHelp.push_back(x: Help); |
| 450 | } |
| 451 | |
| 452 | void Option::addArgument() { |
| 453 | GlobalParser->addOption(O: this); |
| 454 | FullyInitialized = true; |
| 455 | } |
| 456 | |
| 457 | void Option::removeArgument() { GlobalParser->removeOption(O: this); } |
| 458 | |
| 459 | void Option::setArgStr(StringRef S) { |
| 460 | if (FullyInitialized) |
| 461 | GlobalParser->updateArgStr(O: this, NewName: S); |
| 462 | assert(!S.starts_with("-" ) && "Option can't start with '-" ); |
| 463 | ArgStr = S; |
| 464 | if (ArgStr.size() == 1) |
| 465 | setMiscFlag(Grouping); |
| 466 | } |
| 467 | |
| 468 | void Option::addCategory(OptionCategory &C) { |
| 469 | assert(!Categories.empty() && "Categories cannot be empty." ); |
| 470 | // Maintain backward compatibility by replacing the default GeneralCategory |
| 471 | // if it's still set. Otherwise, just add the new one. The GeneralCategory |
| 472 | // must be explicitly added if you want multiple categories that include it. |
| 473 | if (&C != &getGeneralCategory() && Categories[0] == &getGeneralCategory()) |
| 474 | Categories[0] = &C; |
| 475 | else if (!is_contained(Range&: Categories, Element: &C)) |
| 476 | Categories.push_back(Elt: &C); |
| 477 | } |
| 478 | |
| 479 | void Option::reset() { |
| 480 | NumOccurrences = 0; |
| 481 | setDefault(); |
| 482 | if (isDefaultOption()) |
| 483 | removeArgument(); |
| 484 | } |
| 485 | |
| 486 | void OptionCategory::registerCategory() { |
| 487 | GlobalParser->registerCategory(cat: this); |
| 488 | } |
| 489 | |
| 490 | // A special subcommand representing no subcommand. It is particularly important |
| 491 | // that this ManagedStatic uses constant initailization and not dynamic |
| 492 | // initialization because it is referenced from cl::opt constructors, which run |
| 493 | // dynamically in an arbitrary order. |
| 494 | LLVM_REQUIRE_CONSTANT_INITIALIZATION |
| 495 | static ManagedStatic<SubCommand> TopLevelSubCommand; |
| 496 | |
| 497 | // A special subcommand that can be used to put an option into all subcommands. |
| 498 | static ManagedStatic<SubCommand> AllSubCommands; |
| 499 | |
| 500 | SubCommand &SubCommand::getTopLevel() { return *TopLevelSubCommand; } |
| 501 | |
| 502 | SubCommand &SubCommand::getAll() { return *AllSubCommands; } |
| 503 | |
| 504 | void SubCommand::registerSubCommand() { |
| 505 | GlobalParser->registerSubCommand(sub: this); |
| 506 | } |
| 507 | |
| 508 | void SubCommand::unregisterSubCommand() { |
| 509 | GlobalParser->unregisterSubCommand(sub: this); |
| 510 | } |
| 511 | |
| 512 | void SubCommand::reset() { |
| 513 | PositionalOpts.clear(); |
| 514 | SinkOpts.clear(); |
| 515 | OptionsMap.clear(); |
| 516 | |
| 517 | ConsumeAfterOpt = nullptr; |
| 518 | } |
| 519 | |
| 520 | SubCommand::operator bool() const { |
| 521 | return (GlobalParser->getActiveSubCommand() == this); |
| 522 | } |
| 523 | |
| 524 | //===----------------------------------------------------------------------===// |
| 525 | // Basic, shared command line option processing machinery. |
| 526 | // |
| 527 | |
| 528 | /// LookupOption - Lookup the option specified by the specified option on the |
| 529 | /// command line. If there is a value specified (after an equal sign) return |
| 530 | /// that as well. This assumes that leading dashes have already been stripped. |
| 531 | Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg, |
| 532 | StringRef &Value) { |
| 533 | // Reject all dashes. |
| 534 | if (Arg.empty()) |
| 535 | return nullptr; |
| 536 | assert(&Sub != &SubCommand::getAll()); |
| 537 | |
| 538 | size_t EqualPos = Arg.find(C: '='); |
| 539 | |
| 540 | // If we have an equals sign, remember the value. |
| 541 | if (EqualPos == StringRef::npos) { |
| 542 | // Look up the option. |
| 543 | return Sub.OptionsMap.lookup(Val: Arg); |
| 544 | } |
| 545 | |
| 546 | // If the argument before the = is a valid option name and the option allows |
| 547 | // non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match |
| 548 | // failure by returning nullptr. |
| 549 | auto I = Sub.OptionsMap.find(Val: Arg.substr(Start: 0, N: EqualPos)); |
| 550 | if (I == Sub.OptionsMap.end()) |
| 551 | return nullptr; |
| 552 | |
| 553 | auto *O = I->second; |
| 554 | if (O->getFormattingFlag() == cl::AlwaysPrefix) |
| 555 | return nullptr; |
| 556 | |
| 557 | Value = Arg.substr(Start: EqualPos + 1); |
| 558 | Arg = Arg.substr(Start: 0, N: EqualPos); |
| 559 | return I->second; |
| 560 | } |
| 561 | |
| 562 | SubCommand *CommandLineParser::LookupSubCommand(StringRef Name, |
| 563 | std::string &NearestString) { |
| 564 | if (Name.empty()) |
| 565 | return &SubCommand::getTopLevel(); |
| 566 | // Find a subcommand with the edit distance == 1. |
| 567 | SubCommand *NearestMatch = nullptr; |
| 568 | for (auto *S : RegisteredSubCommands) { |
| 569 | assert(S != &SubCommand::getAll() && |
| 570 | "SubCommand::getAll() is not expected in RegisteredSubCommands" ); |
| 571 | if (S->getName().empty()) |
| 572 | continue; |
| 573 | |
| 574 | if (S->getName() == Name) |
| 575 | return S; |
| 576 | |
| 577 | if (!NearestMatch && S->getName().edit_distance(Other: Name) < 2) |
| 578 | NearestMatch = S; |
| 579 | } |
| 580 | |
| 581 | if (NearestMatch) |
| 582 | NearestString = NearestMatch->getName(); |
| 583 | |
| 584 | return &SubCommand::getTopLevel(); |
| 585 | } |
| 586 | |
| 587 | /// LookupNearestOption - Lookup the closest match to the option specified by |
| 588 | /// the specified option on the command line. If there is a value specified |
| 589 | /// (after an equal sign) return that as well. This assumes that leading dashes |
| 590 | /// have already been stripped. |
| 591 | static Option *LookupNearestOption(StringRef Arg, |
| 592 | const OptionsMapTy &OptionsMap, |
| 593 | std::string &NearestString) { |
| 594 | // Reject all dashes. |
| 595 | if (Arg.empty()) |
| 596 | return nullptr; |
| 597 | |
| 598 | // Split on any equal sign. |
| 599 | std::pair<StringRef, StringRef> SplitArg = Arg.split(Separator: '='); |
| 600 | StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present. |
| 601 | StringRef &RHS = SplitArg.second; |
| 602 | |
| 603 | // Find the closest match. |
| 604 | Option *Best = nullptr; |
| 605 | unsigned BestDistance = 0; |
| 606 | for (const auto &[_, O] : OptionsMap) { |
| 607 | // Do not suggest really hidden options (not shown in any help). |
| 608 | if (O->getOptionHiddenFlag() == ReallyHidden) |
| 609 | continue; |
| 610 | |
| 611 | SmallVector<StringRef, 16> OptionNames; |
| 612 | O->getExtraOptionNames(OptionNames); |
| 613 | if (O->hasArgStr()) |
| 614 | OptionNames.push_back(Elt: O->ArgStr); |
| 615 | |
| 616 | bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed; |
| 617 | StringRef Flag = PermitValue ? LHS : Arg; |
| 618 | for (const auto &Name : OptionNames) { |
| 619 | unsigned Distance = StringRef(Name).edit_distance( |
| 620 | Other: Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance); |
| 621 | if (!Best || Distance < BestDistance) { |
| 622 | Best = O; |
| 623 | BestDistance = Distance; |
| 624 | if (RHS.empty() || !PermitValue) |
| 625 | NearestString = std::string(Name); |
| 626 | else |
| 627 | NearestString = (Twine(Name) + "=" + RHS).str(); |
| 628 | } |
| 629 | } |
| 630 | } |
| 631 | |
| 632 | return Best; |
| 633 | } |
| 634 | |
| 635 | /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence() |
| 636 | /// that does special handling of cl::CommaSeparated options. |
| 637 | static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos, |
| 638 | StringRef ArgName, StringRef Value, |
| 639 | bool MultiArg = false) { |
| 640 | // Check to see if this option accepts a comma separated list of values. If |
| 641 | // it does, we have to split up the value into multiple values. |
| 642 | if (Handler->getMiscFlags() & CommaSeparated) { |
| 643 | StringRef Val(Value); |
| 644 | StringRef::size_type Pos = Val.find(C: ','); |
| 645 | |
| 646 | while (Pos != StringRef::npos) { |
| 647 | // Process the portion before the comma. |
| 648 | if (Handler->addOccurrence(pos, ArgName, Value: Val.substr(Start: 0, N: Pos), MultiArg)) |
| 649 | return true; |
| 650 | // Erase the portion before the comma, AND the comma. |
| 651 | Val = Val.substr(Start: Pos + 1); |
| 652 | // Check for another comma. |
| 653 | Pos = Val.find(C: ','); |
| 654 | } |
| 655 | |
| 656 | Value = Val; |
| 657 | } |
| 658 | |
| 659 | return Handler->addOccurrence(pos, ArgName, Value, MultiArg); |
| 660 | } |
| 661 | |
| 662 | /// ProvideOption - For Value, this differentiates between an empty value ("") |
| 663 | /// and a null value (StringRef()). The later is accepted for arguments that |
| 664 | /// don't allow a value (-foo) the former is rejected (-foo=). |
| 665 | static inline bool ProvideOption(Option *Handler, StringRef ArgName, |
| 666 | StringRef Value, int argc, |
| 667 | const char *const *argv, int &i) { |
| 668 | // Is this a multi-argument option? |
| 669 | unsigned NumAdditionalVals = Handler->getNumAdditionalVals(); |
| 670 | |
| 671 | // Enforce value requirements |
| 672 | switch (Handler->getValueExpectedFlag()) { |
| 673 | case ValueRequired: |
| 674 | if (!Value.data()) { // No value specified? |
| 675 | // If no other argument or the option only supports prefix form, we |
| 676 | // cannot look at the next argument. |
| 677 | if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix) |
| 678 | return Handler->error(Message: "requires a value!" ); |
| 679 | // Steal the next argument, like for '-o filename' |
| 680 | assert(argv && "null check" ); |
| 681 | Value = StringRef(argv[++i]); |
| 682 | } |
| 683 | break; |
| 684 | case ValueDisallowed: |
| 685 | if (NumAdditionalVals > 0) |
| 686 | return Handler->error(Message: "multi-valued option specified" |
| 687 | " with ValueDisallowed modifier!" ); |
| 688 | |
| 689 | if (Value.data()) |
| 690 | return Handler->error(Message: "does not allow a value! '" + Twine(Value) + |
| 691 | "' specified." ); |
| 692 | break; |
| 693 | case ValueOptional: |
| 694 | break; |
| 695 | } |
| 696 | |
| 697 | // If this isn't a multi-arg option, just run the handler. |
| 698 | if (NumAdditionalVals == 0) |
| 699 | return CommaSeparateAndAddOccurrence(Handler, pos: i, ArgName, Value); |
| 700 | |
| 701 | // If it is, run the handle several times. |
| 702 | bool MultiArg = false; |
| 703 | |
| 704 | if (Value.data()) { |
| 705 | if (CommaSeparateAndAddOccurrence(Handler, pos: i, ArgName, Value, MultiArg)) |
| 706 | return true; |
| 707 | --NumAdditionalVals; |
| 708 | MultiArg = true; |
| 709 | } |
| 710 | |
| 711 | while (NumAdditionalVals > 0) { |
| 712 | if (i + 1 >= argc) |
| 713 | return Handler->error(Message: "not enough values!" ); |
| 714 | assert(argv && "null check" ); |
| 715 | Value = StringRef(argv[++i]); |
| 716 | |
| 717 | if (CommaSeparateAndAddOccurrence(Handler, pos: i, ArgName, Value, MultiArg)) |
| 718 | return true; |
| 719 | MultiArg = true; |
| 720 | --NumAdditionalVals; |
| 721 | } |
| 722 | return false; |
| 723 | } |
| 724 | |
| 725 | bool llvm::cl::ProvidePositionalOption(Option *Handler, StringRef Arg, int i) { |
| 726 | int Dummy = i; |
| 727 | return ProvideOption(Handler, ArgName: Handler->ArgStr, Value: Arg, argc: 0, argv: nullptr, i&: Dummy); |
| 728 | } |
| 729 | |
| 730 | // getOptionPred - Check to see if there are any options that satisfy the |
| 731 | // specified predicate with names that are the prefixes in Name. This is |
| 732 | // checked by progressively stripping characters off of the name, checking to |
| 733 | // see if there options that satisfy the predicate. If we find one, return it, |
| 734 | // otherwise return null. |
| 735 | // |
| 736 | static Option *getOptionPred(StringRef Name, size_t &Length, |
| 737 | bool (*Pred)(const Option *), |
| 738 | const OptionsMapTy &OptionsMap) { |
| 739 | auto OMI = OptionsMap.find(Val: Name); |
| 740 | if (OMI != OptionsMap.end() && !Pred(OMI->second)) |
| 741 | OMI = OptionsMap.end(); |
| 742 | |
| 743 | // Loop while we haven't found an option and Name still has at least two |
| 744 | // characters in it (so that the next iteration will not be the empty |
| 745 | // string. |
| 746 | while (OMI == OptionsMap.end() && Name.size() > 1) { |
| 747 | Name = Name.drop_back(); |
| 748 | OMI = OptionsMap.find(Val: Name); |
| 749 | if (OMI != OptionsMap.end() && !Pred(OMI->second)) |
| 750 | OMI = OptionsMap.end(); |
| 751 | } |
| 752 | |
| 753 | if (OMI != OptionsMap.end() && Pred(OMI->second)) { |
| 754 | Length = Name.size(); |
| 755 | return OMI->second; // Found one! |
| 756 | } |
| 757 | return nullptr; // No option found! |
| 758 | } |
| 759 | |
| 760 | /// HandlePrefixedOrGroupedOption - The specified argument string (which started |
| 761 | /// with at least one '-') does not fully match an available option. Check to |
| 762 | /// see if this is a prefix or grouped option. If so, split arg into output an |
| 763 | /// Arg/Value pair and return the Option to parse it with. |
| 764 | static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, |
| 765 | bool &ErrorParsing, |
| 766 | const OptionsMapTy &OptionsMap) { |
| 767 | if (Arg.size() == 1) |
| 768 | return nullptr; |
| 769 | |
| 770 | // Do the lookup! |
| 771 | size_t Length = 0; |
| 772 | Option *PGOpt = getOptionPred(Name: Arg, Length, Pred: isPrefixedOrGrouping, OptionsMap); |
| 773 | if (!PGOpt) |
| 774 | return nullptr; |
| 775 | |
| 776 | do { |
| 777 | StringRef MaybeValue = |
| 778 | (Length < Arg.size()) ? Arg.substr(Start: Length) : StringRef(); |
| 779 | Arg = Arg.substr(Start: 0, N: Length); |
| 780 | assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt); |
| 781 | |
| 782 | // cl::Prefix options do not preserve '=' when used separately. |
| 783 | // The behavior for them with grouped options should be the same. |
| 784 | if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix || |
| 785 | (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) { |
| 786 | Value = MaybeValue; |
| 787 | return PGOpt; |
| 788 | } |
| 789 | |
| 790 | if (MaybeValue[0] == '=') { |
| 791 | Value = MaybeValue.substr(Start: 1); |
| 792 | return PGOpt; |
| 793 | } |
| 794 | |
| 795 | // This must be a grouped option. |
| 796 | assert(isGrouping(PGOpt) && "Broken getOptionPred!" ); |
| 797 | |
| 798 | // Grouping options inside a group can't have values. |
| 799 | if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) { |
| 800 | ErrorParsing |= PGOpt->error(Message: "may not occur within a group!" ); |
| 801 | return nullptr; |
| 802 | } |
| 803 | |
| 804 | // Because the value for the option is not required, we don't need to pass |
| 805 | // argc/argv in. |
| 806 | int Dummy = 0; |
| 807 | ErrorParsing |= ProvideOption(Handler: PGOpt, ArgName: Arg, Value: StringRef(), argc: 0, argv: nullptr, i&: Dummy); |
| 808 | |
| 809 | // Get the next grouping option. |
| 810 | Arg = MaybeValue; |
| 811 | PGOpt = getOptionPred(Name: Arg, Length, Pred: isGrouping, OptionsMap); |
| 812 | } while (PGOpt); |
| 813 | |
| 814 | // We could not find a grouping option in the remainder of Arg. |
| 815 | return nullptr; |
| 816 | } |
| 817 | |
| 818 | static bool RequiresValue(const Option *O) { |
| 819 | return O->getNumOccurrencesFlag() == cl::Required || |
| 820 | O->getNumOccurrencesFlag() == cl::OneOrMore; |
| 821 | } |
| 822 | |
| 823 | static bool EatsUnboundedNumberOfValues(const Option *O) { |
| 824 | return O->getNumOccurrencesFlag() == cl::ZeroOrMore || |
| 825 | O->getNumOccurrencesFlag() == cl::OneOrMore; |
| 826 | } |
| 827 | |
| 828 | static bool isWhitespace(char C) { |
| 829 | return C == ' ' || C == '\t' || C == '\r' || C == '\n'; |
| 830 | } |
| 831 | |
| 832 | static bool isWhitespaceOrNull(char C) { |
| 833 | return isWhitespace(C) || C == '\0'; |
| 834 | } |
| 835 | |
| 836 | static bool isQuote(char C) { return C == '\"' || C == '\''; } |
| 837 | |
| 838 | void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver, |
| 839 | SmallVectorImpl<const char *> &NewArgv, |
| 840 | bool MarkEOLs) { |
| 841 | SmallString<128> Token; |
| 842 | for (size_t I = 0, E = Src.size(); I != E; ++I) { |
| 843 | // Consume runs of whitespace. |
| 844 | if (Token.empty()) { |
| 845 | while (I != E && isWhitespace(C: Src[I])) { |
| 846 | // Mark the end of lines in response files. |
| 847 | if (MarkEOLs && Src[I] == '\n') |
| 848 | NewArgv.push_back(Elt: nullptr); |
| 849 | ++I; |
| 850 | } |
| 851 | if (I == E) |
| 852 | break; |
| 853 | } |
| 854 | |
| 855 | char C = Src[I]; |
| 856 | |
| 857 | // Backslash escapes the next character. |
| 858 | if (I + 1 < E && C == '\\') { |
| 859 | ++I; // Skip the escape. |
| 860 | Token.push_back(Elt: Src[I]); |
| 861 | continue; |
| 862 | } |
| 863 | |
| 864 | // Consume a quoted string. |
| 865 | if (isQuote(C)) { |
| 866 | ++I; |
| 867 | while (I != E && Src[I] != C) { |
| 868 | // Backslash escapes the next character. |
| 869 | if (Src[I] == '\\' && I + 1 != E) |
| 870 | ++I; |
| 871 | Token.push_back(Elt: Src[I]); |
| 872 | ++I; |
| 873 | } |
| 874 | if (I == E) |
| 875 | break; |
| 876 | continue; |
| 877 | } |
| 878 | |
| 879 | // End the token if this is whitespace. |
| 880 | if (isWhitespace(C)) { |
| 881 | if (!Token.empty()) |
| 882 | NewArgv.push_back(Elt: Saver.save(S: Token.str()).data()); |
| 883 | // Mark the end of lines in response files. |
| 884 | if (MarkEOLs && C == '\n') |
| 885 | NewArgv.push_back(Elt: nullptr); |
| 886 | Token.clear(); |
| 887 | continue; |
| 888 | } |
| 889 | |
| 890 | // This is a normal character. Append it. |
| 891 | Token.push_back(Elt: C); |
| 892 | } |
| 893 | |
| 894 | // Append the last token after hitting EOF with no whitespace. |
| 895 | if (!Token.empty()) |
| 896 | NewArgv.push_back(Elt: Saver.save(S: Token.str()).data()); |
| 897 | } |
| 898 | |
| 899 | /// Backslashes are interpreted in a rather complicated way in the Windows-style |
| 900 | /// command line, because backslashes are used both to separate path and to |
| 901 | /// escape double quote. This method consumes runs of backslashes as well as the |
| 902 | /// following double quote if it's escaped. |
| 903 | /// |
| 904 | /// * If an even number of backslashes is followed by a double quote, one |
| 905 | /// backslash is output for every pair of backslashes, and the last double |
| 906 | /// quote remains unconsumed. The double quote will later be interpreted as |
| 907 | /// the start or end of a quoted string in the main loop outside of this |
| 908 | /// function. |
| 909 | /// |
| 910 | /// * If an odd number of backslashes is followed by a double quote, one |
| 911 | /// backslash is output for every pair of backslashes, and a double quote is |
| 912 | /// output for the last pair of backslash-double quote. The double quote is |
| 913 | /// consumed in this case. |
| 914 | /// |
| 915 | /// * Otherwise, backslashes are interpreted literally. |
| 916 | static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) { |
| 917 | size_t E = Src.size(); |
| 918 | int BackslashCount = 0; |
| 919 | // Skip the backslashes. |
| 920 | do { |
| 921 | ++I; |
| 922 | ++BackslashCount; |
| 923 | } while (I != E && Src[I] == '\\'); |
| 924 | |
| 925 | bool FollowedByDoubleQuote = (I != E && Src[I] == '"'); |
| 926 | if (FollowedByDoubleQuote) { |
| 927 | Token.append(NumInputs: BackslashCount / 2, Elt: '\\'); |
| 928 | if (BackslashCount % 2 == 0) |
| 929 | return I - 1; |
| 930 | Token.push_back(Elt: '"'); |
| 931 | return I; |
| 932 | } |
| 933 | Token.append(NumInputs: BackslashCount, Elt: '\\'); |
| 934 | return I - 1; |
| 935 | } |
| 936 | |
| 937 | // Windows treats whitespace, double quotes, and backslashes specially, except |
| 938 | // when parsing the first token of a full command line, in which case |
| 939 | // backslashes are not special. |
| 940 | static bool isWindowsSpecialChar(char C) { |
| 941 | return isWhitespaceOrNull(C) || C == '\\' || C == '\"'; |
| 942 | } |
| 943 | static bool isWindowsSpecialCharInCommandName(char C) { |
| 944 | return isWhitespaceOrNull(C) || C == '\"'; |
| 945 | } |
| 946 | |
| 947 | // Windows tokenization implementation. The implementation is designed to be |
| 948 | // inlined and specialized for the two user entry points. |
| 949 | static inline void tokenizeWindowsCommandLineImpl( |
| 950 | StringRef Src, StringSaver &Saver, function_ref<void(StringRef)> AddToken, |
| 951 | bool AlwaysCopy, function_ref<void()> MarkEOL, bool InitialCommandName) { |
| 952 | SmallString<128> Token; |
| 953 | |
| 954 | // Sometimes, this function will be handling a full command line including an |
| 955 | // executable pathname at the start. In that situation, the initial pathname |
| 956 | // needs different handling from the following arguments, because when |
| 957 | // CreateProcess or cmd.exe scans the pathname, it doesn't treat \ as |
| 958 | // escaping the quote character, whereas when libc scans the rest of the |
| 959 | // command line, it does. |
| 960 | bool CommandName = InitialCommandName; |
| 961 | |
| 962 | // Try to do as much work inside the state machine as possible. |
| 963 | enum { INIT, UNQUOTED, QUOTED } State = INIT; |
| 964 | |
| 965 | for (size_t I = 0, E = Src.size(); I < E; ++I) { |
| 966 | switch (State) { |
| 967 | case INIT: { |
| 968 | assert(Token.empty() && "token should be empty in initial state" ); |
| 969 | // Eat whitespace before a token. |
| 970 | while (I < E && isWhitespaceOrNull(C: Src[I])) { |
| 971 | if (Src[I] == '\n') |
| 972 | MarkEOL(); |
| 973 | ++I; |
| 974 | } |
| 975 | // Stop if this was trailing whitespace. |
| 976 | if (I >= E) |
| 977 | break; |
| 978 | size_t Start = I; |
| 979 | if (CommandName) { |
| 980 | while (I < E && !isWindowsSpecialCharInCommandName(C: Src[I])) |
| 981 | ++I; |
| 982 | } else { |
| 983 | while (I < E && !isWindowsSpecialChar(C: Src[I])) |
| 984 | ++I; |
| 985 | } |
| 986 | StringRef NormalChars = Src.slice(Start, End: I); |
| 987 | if (I >= E || isWhitespaceOrNull(C: Src[I])) { |
| 988 | // No special characters: slice out the substring and start the next |
| 989 | // token. Copy the string if the caller asks us to. |
| 990 | AddToken(AlwaysCopy ? Saver.save(S: NormalChars) : NormalChars); |
| 991 | if (I < E && Src[I] == '\n') { |
| 992 | MarkEOL(); |
| 993 | CommandName = InitialCommandName; |
| 994 | } else { |
| 995 | CommandName = false; |
| 996 | } |
| 997 | } else if (Src[I] == '\"') { |
| 998 | Token += NormalChars; |
| 999 | State = QUOTED; |
| 1000 | } else if (Src[I] == '\\') { |
| 1001 | assert(!CommandName && "or else we'd have treated it as a normal char" ); |
| 1002 | Token += NormalChars; |
| 1003 | I = parseBackslash(Src, I, Token); |
| 1004 | State = UNQUOTED; |
| 1005 | } else { |
| 1006 | llvm_unreachable("unexpected special character" ); |
| 1007 | } |
| 1008 | break; |
| 1009 | } |
| 1010 | |
| 1011 | case UNQUOTED: |
| 1012 | if (isWhitespaceOrNull(C: Src[I])) { |
| 1013 | // Whitespace means the end of the token. If we are in this state, the |
| 1014 | // token must have contained a special character, so we must copy the |
| 1015 | // token. |
| 1016 | AddToken(Saver.save(S: Token.str())); |
| 1017 | Token.clear(); |
| 1018 | if (Src[I] == '\n') { |
| 1019 | CommandName = InitialCommandName; |
| 1020 | MarkEOL(); |
| 1021 | } else { |
| 1022 | CommandName = false; |
| 1023 | } |
| 1024 | State = INIT; |
| 1025 | } else if (Src[I] == '\"') { |
| 1026 | State = QUOTED; |
| 1027 | } else if (Src[I] == '\\' && !CommandName) { |
| 1028 | I = parseBackslash(Src, I, Token); |
| 1029 | } else { |
| 1030 | Token.push_back(Elt: Src[I]); |
| 1031 | } |
| 1032 | break; |
| 1033 | |
| 1034 | case QUOTED: |
| 1035 | if (Src[I] == '\"') { |
| 1036 | if (I < (E - 1) && Src[I + 1] == '"') { |
| 1037 | // Consecutive double-quotes inside a quoted string implies one |
| 1038 | // double-quote. |
| 1039 | Token.push_back(Elt: '"'); |
| 1040 | ++I; |
| 1041 | } else { |
| 1042 | // Otherwise, end the quoted portion and return to the unquoted state. |
| 1043 | State = UNQUOTED; |
| 1044 | } |
| 1045 | } else if (Src[I] == '\\' && !CommandName) { |
| 1046 | I = parseBackslash(Src, I, Token); |
| 1047 | } else { |
| 1048 | Token.push_back(Elt: Src[I]); |
| 1049 | } |
| 1050 | break; |
| 1051 | } |
| 1052 | } |
| 1053 | |
| 1054 | if (State != INIT) |
| 1055 | AddToken(Saver.save(S: Token.str())); |
| 1056 | } |
| 1057 | |
| 1058 | void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver, |
| 1059 | SmallVectorImpl<const char *> &NewArgv, |
| 1060 | bool MarkEOLs) { |
| 1061 | auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Elt: Tok.data()); }; |
| 1062 | auto OnEOL = [&]() { |
| 1063 | if (MarkEOLs) |
| 1064 | NewArgv.push_back(Elt: nullptr); |
| 1065 | }; |
| 1066 | tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, |
| 1067 | /*AlwaysCopy=*/true, MarkEOL: OnEOL, InitialCommandName: false); |
| 1068 | } |
| 1069 | |
| 1070 | void cl::TokenizeWindowsCommandLineNoCopy(StringRef Src, StringSaver &Saver, |
| 1071 | SmallVectorImpl<StringRef> &NewArgv) { |
| 1072 | auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Elt: Tok); }; |
| 1073 | auto OnEOL = []() {}; |
| 1074 | tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, /*AlwaysCopy=*/false, |
| 1075 | MarkEOL: OnEOL, InitialCommandName: false); |
| 1076 | } |
| 1077 | |
| 1078 | void cl::TokenizeWindowsCommandLineFull(StringRef Src, StringSaver &Saver, |
| 1079 | SmallVectorImpl<const char *> &NewArgv, |
| 1080 | bool MarkEOLs) { |
| 1081 | auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Elt: Tok.data()); }; |
| 1082 | auto OnEOL = [&]() { |
| 1083 | if (MarkEOLs) |
| 1084 | NewArgv.push_back(Elt: nullptr); |
| 1085 | }; |
| 1086 | tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, |
| 1087 | /*AlwaysCopy=*/true, MarkEOL: OnEOL, InitialCommandName: true); |
| 1088 | } |
| 1089 | |
| 1090 | void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver, |
| 1091 | SmallVectorImpl<const char *> &NewArgv, |
| 1092 | bool MarkEOLs) { |
| 1093 | for (const char *Cur = Source.begin(); Cur != Source.end();) { |
| 1094 | SmallString<128> Line; |
| 1095 | // Check for comment line. |
| 1096 | if (isWhitespace(C: *Cur)) { |
| 1097 | while (Cur != Source.end() && isWhitespace(C: *Cur)) |
| 1098 | ++Cur; |
| 1099 | continue; |
| 1100 | } |
| 1101 | if (*Cur == '#') { |
| 1102 | while (Cur != Source.end() && *Cur != '\n') |
| 1103 | ++Cur; |
| 1104 | continue; |
| 1105 | } |
| 1106 | // Find end of the current line. |
| 1107 | const char *Start = Cur; |
| 1108 | for (const char *End = Source.end(); Cur != End; ++Cur) { |
| 1109 | if (*Cur == '\\') { |
| 1110 | if (Cur + 1 != End) { |
| 1111 | ++Cur; |
| 1112 | if (*Cur == '\n' || |
| 1113 | (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) { |
| 1114 | Line.append(in_start: Start, in_end: Cur - 1); |
| 1115 | if (*Cur == '\r') |
| 1116 | ++Cur; |
| 1117 | Start = Cur + 1; |
| 1118 | } |
| 1119 | } |
| 1120 | } else if (*Cur == '\n') |
| 1121 | break; |
| 1122 | } |
| 1123 | // Tokenize line. |
| 1124 | Line.append(in_start: Start, in_end: Cur); |
| 1125 | cl::TokenizeGNUCommandLine(Src: Line, Saver, NewArgv, MarkEOLs); |
| 1126 | } |
| 1127 | } |
| 1128 | |
| 1129 | // It is called byte order marker but the UTF-8 BOM is actually not affected |
| 1130 | // by the host system's endianness. |
| 1131 | static bool hasUTF8ByteOrderMark(ArrayRef<char> S) { |
| 1132 | return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf'); |
| 1133 | } |
| 1134 | |
| 1135 | // Substitute <CFGDIR> with the file's base path. |
| 1136 | static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver, |
| 1137 | const char *&Arg) { |
| 1138 | assert(sys::path::is_absolute(BasePath)); |
| 1139 | constexpr StringLiteral Token("<CFGDIR>" ); |
| 1140 | const StringRef ArgString(Arg); |
| 1141 | |
| 1142 | SmallString<128> ResponseFile; |
| 1143 | StringRef::size_type StartPos = 0; |
| 1144 | for (StringRef::size_type TokenPos = ArgString.find(Str: Token); |
| 1145 | TokenPos != StringRef::npos; |
| 1146 | TokenPos = ArgString.find(Str: Token, From: StartPos)) { |
| 1147 | // Token may appear more than once per arg (e.g. comma-separated linker |
| 1148 | // args). Support by using path-append on any subsequent appearances. |
| 1149 | const StringRef LHS = ArgString.substr(Start: StartPos, N: TokenPos - StartPos); |
| 1150 | if (ResponseFile.empty()) |
| 1151 | ResponseFile = LHS; |
| 1152 | else |
| 1153 | llvm::sys::path::append(path&: ResponseFile, a: LHS); |
| 1154 | ResponseFile.append(RHS: BasePath); |
| 1155 | StartPos = TokenPos + Token.size(); |
| 1156 | } |
| 1157 | |
| 1158 | if (!ResponseFile.empty()) { |
| 1159 | // Path-append the remaining arg substring if at least one token appeared. |
| 1160 | const StringRef Remaining = ArgString.substr(Start: StartPos); |
| 1161 | if (!Remaining.empty()) |
| 1162 | llvm::sys::path::append(path&: ResponseFile, a: Remaining); |
| 1163 | Arg = Saver.save(S: ResponseFile.str()).data(); |
| 1164 | } |
| 1165 | } |
| 1166 | |
| 1167 | // FName must be an absolute path. |
| 1168 | Error ExpansionContext::expandResponseFile( |
| 1169 | StringRef FName, SmallVectorImpl<const char *> &NewArgv) { |
| 1170 | assert(sys::path::is_absolute(FName)); |
| 1171 | llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr = |
| 1172 | FS->getBufferForFile(Name: FName); |
| 1173 | if (!MemBufOrErr) { |
| 1174 | std::error_code EC = MemBufOrErr.getError(); |
| 1175 | return llvm::createStringError(EC, S: Twine("cannot not open file '" ) + FName + |
| 1176 | "': " + EC.message()); |
| 1177 | } |
| 1178 | MemoryBuffer &MemBuf = *MemBufOrErr.get(); |
| 1179 | StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize()); |
| 1180 | |
| 1181 | // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing. |
| 1182 | ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd()); |
| 1183 | std::string UTF8Buf; |
| 1184 | if (hasUTF16ByteOrderMark(SrcBytes: BufRef)) { |
| 1185 | if (!convertUTF16ToUTF8String(SrcBytes: BufRef, Out&: UTF8Buf)) |
| 1186 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
| 1187 | Fmt: "Could not convert UTF16 to UTF8" ); |
| 1188 | Str = StringRef(UTF8Buf); |
| 1189 | } |
| 1190 | // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove |
| 1191 | // these bytes before parsing. |
| 1192 | // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark |
| 1193 | else if (hasUTF8ByteOrderMark(S: BufRef)) |
| 1194 | Str = StringRef(BufRef.data() + 3, BufRef.size() - 3); |
| 1195 | |
| 1196 | // Tokenize the contents into NewArgv. |
| 1197 | Tokenizer(Str, Saver, NewArgv, MarkEOLs); |
| 1198 | |
| 1199 | // Expanded file content may require additional transformations, like using |
| 1200 | // absolute paths instead of relative in '@file' constructs or expanding |
| 1201 | // macros. |
| 1202 | if (!RelativeNames && !InConfigFile) |
| 1203 | return Error::success(); |
| 1204 | |
| 1205 | StringRef BasePath = llvm::sys::path::parent_path(path: FName); |
| 1206 | for (const char *&Arg : NewArgv) { |
| 1207 | if (!Arg) |
| 1208 | continue; |
| 1209 | |
| 1210 | // Substitute <CFGDIR> with the file's base path. |
| 1211 | if (InConfigFile) |
| 1212 | ExpandBasePaths(BasePath, Saver, Arg); |
| 1213 | |
| 1214 | // Discover the case, when argument should be transformed into '@file' and |
| 1215 | // evaluate 'file' for it. |
| 1216 | StringRef ArgStr(Arg); |
| 1217 | StringRef FileName; |
| 1218 | bool ConfigInclusion = false; |
| 1219 | if (ArgStr.consume_front(Prefix: "@" )) { |
| 1220 | FileName = ArgStr; |
| 1221 | if (!llvm::sys::path::is_relative(path: FileName)) |
| 1222 | continue; |
| 1223 | } else if (ArgStr.consume_front(Prefix: "--config=" )) { |
| 1224 | FileName = ArgStr; |
| 1225 | ConfigInclusion = true; |
| 1226 | } else { |
| 1227 | continue; |
| 1228 | } |
| 1229 | |
| 1230 | // Update expansion construct. |
| 1231 | SmallString<128> ResponseFile; |
| 1232 | ResponseFile.push_back(Elt: '@'); |
| 1233 | if (ConfigInclusion && !llvm::sys::path::has_parent_path(path: FileName)) { |
| 1234 | SmallString<128> FilePath; |
| 1235 | if (!findConfigFile(FileName, FilePath)) |
| 1236 | return createStringError( |
| 1237 | EC: std::make_error_code(e: std::errc::no_such_file_or_directory), |
| 1238 | S: "cannot not find configuration file: " + FileName); |
| 1239 | ResponseFile.append(RHS: FilePath); |
| 1240 | } else { |
| 1241 | ResponseFile.append(RHS: BasePath); |
| 1242 | llvm::sys::path::append(path&: ResponseFile, a: FileName); |
| 1243 | } |
| 1244 | Arg = Saver.save(S: ResponseFile.str()).data(); |
| 1245 | } |
| 1246 | return Error::success(); |
| 1247 | } |
| 1248 | |
| 1249 | /// Expand response files on a command line recursively using the given |
| 1250 | /// StringSaver and tokenization strategy. |
| 1251 | Error ExpansionContext::expandResponseFiles( |
| 1252 | SmallVectorImpl<const char *> &Argv) { |
| 1253 | struct ResponseFileRecord { |
| 1254 | std::string File; |
| 1255 | size_t End; |
| 1256 | }; |
| 1257 | |
| 1258 | // To detect recursive response files, we maintain a stack of files and the |
| 1259 | // position of the last argument in the file. This position is updated |
| 1260 | // dynamically as we recursively expand files. |
| 1261 | SmallVector<ResponseFileRecord, 3> FileStack; |
| 1262 | |
| 1263 | // Push a dummy entry that represents the initial command line, removing |
| 1264 | // the need to check for an empty list. |
| 1265 | FileStack.push_back(Elt: {.File: "" , .End: Argv.size()}); |
| 1266 | |
| 1267 | // Don't cache Argv.size() because it can change. |
| 1268 | for (unsigned I = 0; I != Argv.size();) { |
| 1269 | while (I == FileStack.back().End) { |
| 1270 | // Passing the end of a file's argument list, so we can remove it from the |
| 1271 | // stack. |
| 1272 | FileStack.pop_back(); |
| 1273 | } |
| 1274 | |
| 1275 | const char *Arg = Argv[I]; |
| 1276 | // Check if it is an EOL marker |
| 1277 | if (Arg == nullptr) { |
| 1278 | ++I; |
| 1279 | continue; |
| 1280 | } |
| 1281 | |
| 1282 | if (Arg[0] != '@') { |
| 1283 | ++I; |
| 1284 | continue; |
| 1285 | } |
| 1286 | |
| 1287 | const char *FName = Arg + 1; |
| 1288 | // Note that CurrentDir is only used for top-level rsp files, the rest will |
| 1289 | // always have an absolute path deduced from the containing file. |
| 1290 | SmallString<128> CurrDir; |
| 1291 | if (llvm::sys::path::is_relative(path: FName)) { |
| 1292 | if (CurrentDir.empty()) { |
| 1293 | if (auto CWD = FS->getCurrentWorkingDirectory()) { |
| 1294 | CurrDir = *CWD; |
| 1295 | } else { |
| 1296 | return createStringError( |
| 1297 | EC: CWD.getError(), S: Twine("cannot get absolute path for: " ) + FName); |
| 1298 | } |
| 1299 | } else { |
| 1300 | CurrDir = CurrentDir; |
| 1301 | } |
| 1302 | llvm::sys::path::append(path&: CurrDir, a: FName); |
| 1303 | FName = CurrDir.c_str(); |
| 1304 | } |
| 1305 | |
| 1306 | ErrorOr<llvm::vfs::Status> Res = FS->status(Path: FName); |
| 1307 | if (!Res || !Res->exists()) { |
| 1308 | std::error_code EC = Res.getError(); |
| 1309 | if (!InConfigFile) { |
| 1310 | // If the specified file does not exist, leave '@file' unexpanded, as |
| 1311 | // libiberty does. |
| 1312 | if (!EC || EC == llvm::errc::no_such_file_or_directory) { |
| 1313 | ++I; |
| 1314 | continue; |
| 1315 | } |
| 1316 | } |
| 1317 | if (!EC) |
| 1318 | EC = llvm::errc::no_such_file_or_directory; |
| 1319 | return createStringError(EC, S: Twine("cannot not open file '" ) + FName + |
| 1320 | "': " + EC.message()); |
| 1321 | } |
| 1322 | const llvm::vfs::Status &FileStatus = Res.get(); |
| 1323 | |
| 1324 | auto IsEquivalent = |
| 1325 | [FileStatus, this](const ResponseFileRecord &RFile) -> ErrorOr<bool> { |
| 1326 | ErrorOr<llvm::vfs::Status> RHS = FS->status(Path: RFile.File); |
| 1327 | if (!RHS) |
| 1328 | return RHS.getError(); |
| 1329 | return FileStatus.equivalent(Other: *RHS); |
| 1330 | }; |
| 1331 | |
| 1332 | // Check for recursive response files. |
| 1333 | for (const auto &F : drop_begin(RangeOrContainer&: FileStack)) { |
| 1334 | if (ErrorOr<bool> R = IsEquivalent(F)) { |
| 1335 | if (R.get()) |
| 1336 | return createStringError( |
| 1337 | EC: R.getError(), S: Twine("recursive expansion of: '" ) + F.File + "'" ); |
| 1338 | } else { |
| 1339 | return createStringError(EC: R.getError(), |
| 1340 | S: Twine("cannot open file: " ) + F.File); |
| 1341 | } |
| 1342 | } |
| 1343 | |
| 1344 | // Replace this response file argument with the tokenization of its |
| 1345 | // contents. Nested response files are expanded in subsequent iterations. |
| 1346 | SmallVector<const char *, 0> ExpandedArgv; |
| 1347 | if (Error Err = expandResponseFile(FName, NewArgv&: ExpandedArgv)) |
| 1348 | return Err; |
| 1349 | |
| 1350 | for (ResponseFileRecord &Record : FileStack) { |
| 1351 | // Increase the end of all active records by the number of newly expanded |
| 1352 | // arguments, minus the response file itself. |
| 1353 | Record.End += ExpandedArgv.size() - 1; |
| 1354 | } |
| 1355 | |
| 1356 | FileStack.push_back(Elt: {.File: FName, .End: I + ExpandedArgv.size()}); |
| 1357 | Argv.erase(CI: Argv.begin() + I); |
| 1358 | Argv.insert(I: Argv.begin() + I, From: ExpandedArgv.begin(), To: ExpandedArgv.end()); |
| 1359 | } |
| 1360 | |
| 1361 | // If successful, the top of the file stack will mark the end of the Argv |
| 1362 | // stream. A failure here indicates a bug in the stack popping logic above. |
| 1363 | // Note that FileStack may have more than one element at this point because we |
| 1364 | // don't have a chance to pop the stack when encountering recursive files at |
| 1365 | // the end of the stream, so seeing that doesn't indicate a bug. |
| 1366 | assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End); |
| 1367 | return Error::success(); |
| 1368 | } |
| 1369 | |
| 1370 | bool cl::expandResponseFiles(int Argc, const char *const *Argv, |
| 1371 | const char *EnvVar, StringSaver &Saver, |
| 1372 | SmallVectorImpl<const char *> &NewArgv) { |
| 1373 | #ifdef _WIN32 |
| 1374 | auto Tokenize = cl::TokenizeWindowsCommandLine; |
| 1375 | #else |
| 1376 | auto Tokenize = cl::TokenizeGNUCommandLine; |
| 1377 | #endif |
| 1378 | // The environment variable specifies initial options. |
| 1379 | if (EnvVar) |
| 1380 | if (std::optional<std::string> EnvValue = sys::Process::GetEnv(name: EnvVar)) |
| 1381 | Tokenize(*EnvValue, Saver, NewArgv, /*MarkEOLs=*/false); |
| 1382 | |
| 1383 | // Command line options can override the environment variable. |
| 1384 | NewArgv.append(in_start: Argv + 1, in_end: Argv + Argc); |
| 1385 | ExpansionContext ECtx(Saver.getAllocator(), Tokenize); |
| 1386 | if (Error Err = ECtx.expandResponseFiles(Argv&: NewArgv)) { |
| 1387 | errs() << toString(E: std::move(Err)) << '\n'; |
| 1388 | return false; |
| 1389 | } |
| 1390 | return true; |
| 1391 | } |
| 1392 | |
| 1393 | bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, |
| 1394 | SmallVectorImpl<const char *> &Argv) { |
| 1395 | ExpansionContext ECtx(Saver.getAllocator(), Tokenizer); |
| 1396 | if (Error Err = ECtx.expandResponseFiles(Argv)) { |
| 1397 | errs() << toString(E: std::move(Err)) << '\n'; |
| 1398 | return false; |
| 1399 | } |
| 1400 | return true; |
| 1401 | } |
| 1402 | |
| 1403 | ExpansionContext::ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T, |
| 1404 | vfs::FileSystem *FS) |
| 1405 | : Saver(A), Tokenizer(T), FS(FS ? FS : vfs::getRealFileSystem().get()) {} |
| 1406 | |
| 1407 | bool ExpansionContext::findConfigFile(StringRef FileName, |
| 1408 | SmallVectorImpl<char> &FilePath) { |
| 1409 | SmallString<128> CfgFilePath; |
| 1410 | const auto FileExists = [this](SmallString<128> Path) -> bool { |
| 1411 | auto Status = FS->status(Path); |
| 1412 | return Status && |
| 1413 | Status->getType() == llvm::sys::fs::file_type::regular_file; |
| 1414 | }; |
| 1415 | |
| 1416 | // If file name contains directory separator, treat it as a path to |
| 1417 | // configuration file. |
| 1418 | if (llvm::sys::path::has_parent_path(path: FileName)) { |
| 1419 | CfgFilePath = FileName; |
| 1420 | if (llvm::sys::path::is_relative(path: FileName) && FS->makeAbsolute(Path&: CfgFilePath)) |
| 1421 | return false; |
| 1422 | if (!FileExists(CfgFilePath)) |
| 1423 | return false; |
| 1424 | FilePath.assign(in_start: CfgFilePath.begin(), in_end: CfgFilePath.end()); |
| 1425 | return true; |
| 1426 | } |
| 1427 | |
| 1428 | // Look for the file in search directories. |
| 1429 | for (const StringRef &Dir : SearchDirs) { |
| 1430 | if (Dir.empty()) |
| 1431 | continue; |
| 1432 | CfgFilePath.assign(RHS: Dir); |
| 1433 | llvm::sys::path::append(path&: CfgFilePath, a: FileName); |
| 1434 | llvm::sys::path::native(path&: CfgFilePath); |
| 1435 | if (FileExists(CfgFilePath)) { |
| 1436 | FilePath.assign(in_start: CfgFilePath.begin(), in_end: CfgFilePath.end()); |
| 1437 | return true; |
| 1438 | } |
| 1439 | } |
| 1440 | |
| 1441 | return false; |
| 1442 | } |
| 1443 | |
| 1444 | Error ExpansionContext::readConfigFile(StringRef CfgFile, |
| 1445 | SmallVectorImpl<const char *> &Argv) { |
| 1446 | SmallString<128> AbsPath; |
| 1447 | if (sys::path::is_relative(path: CfgFile)) { |
| 1448 | AbsPath.assign(RHS: CfgFile); |
| 1449 | if (std::error_code EC = FS->makeAbsolute(Path&: AbsPath)) |
| 1450 | return make_error<StringError>( |
| 1451 | Args&: EC, Args: Twine("cannot get absolute path for " + CfgFile)); |
| 1452 | CfgFile = AbsPath.str(); |
| 1453 | } |
| 1454 | InConfigFile = true; |
| 1455 | RelativeNames = true; |
| 1456 | if (Error Err = expandResponseFile(FName: CfgFile, NewArgv&: Argv)) |
| 1457 | return Err; |
| 1458 | return expandResponseFiles(Argv); |
| 1459 | } |
| 1460 | |
| 1461 | static void initCommonOptions(); |
| 1462 | bool cl::ParseCommandLineOptions(int argc, const char *const *argv, |
| 1463 | StringRef Overview, raw_ostream *Errs, |
| 1464 | vfs::FileSystem *VFS, const char *EnvVar, |
| 1465 | bool LongOptionsUseDoubleDash) { |
| 1466 | initCommonOptions(); |
| 1467 | SmallVector<const char *, 20> NewArgv; |
| 1468 | BumpPtrAllocator A; |
| 1469 | StringSaver Saver(A); |
| 1470 | NewArgv.push_back(Elt: argv[0]); |
| 1471 | |
| 1472 | // Parse options from environment variable. |
| 1473 | if (EnvVar) { |
| 1474 | if (std::optional<std::string> EnvValue = |
| 1475 | sys::Process::GetEnv(name: StringRef(EnvVar))) |
| 1476 | TokenizeGNUCommandLine(Src: *EnvValue, Saver, NewArgv); |
| 1477 | } |
| 1478 | |
| 1479 | // Append options from command line. |
| 1480 | for (int I = 1; I < argc; ++I) |
| 1481 | NewArgv.push_back(Elt: argv[I]); |
| 1482 | int NewArgc = static_cast<int>(NewArgv.size()); |
| 1483 | |
| 1484 | // Parse all options. |
| 1485 | return GlobalParser->ParseCommandLineOptions( |
| 1486 | argc: NewArgc, argv: &NewArgv[0], Overview, Errs, VFS, LongOptionsUseDoubleDash); |
| 1487 | } |
| 1488 | |
| 1489 | /// Reset all options at least once, so that we can parse different options. |
| 1490 | void CommandLineParser::ResetAllOptionOccurrences() { |
| 1491 | // Reset all option values to look like they have never been seen before. |
| 1492 | // Options might be reset twice (they can be reference in both OptionsMap |
| 1493 | // and one of the other members), but that does not harm. |
| 1494 | for (auto *SC : RegisteredSubCommands) { |
| 1495 | for (auto &O : SC->OptionsMap) |
| 1496 | O.second->reset(); |
| 1497 | for (Option *O : SC->PositionalOpts) |
| 1498 | O->reset(); |
| 1499 | for (Option *O : SC->SinkOpts) |
| 1500 | O->reset(); |
| 1501 | if (SC->ConsumeAfterOpt) |
| 1502 | SC->ConsumeAfterOpt->reset(); |
| 1503 | } |
| 1504 | } |
| 1505 | |
| 1506 | bool CommandLineParser::ParseCommandLineOptions( |
| 1507 | int argc, const char *const *argv, StringRef Overview, raw_ostream *Errs, |
| 1508 | vfs::FileSystem *VFS, bool LongOptionsUseDoubleDash) { |
| 1509 | assert(hasOptions() && "No options specified!" ); |
| 1510 | |
| 1511 | ProgramOverview = Overview; |
| 1512 | bool IgnoreErrors = Errs; |
| 1513 | if (!Errs) |
| 1514 | Errs = &errs(); |
| 1515 | if (!VFS) |
| 1516 | VFS = vfs::getRealFileSystem().get(); |
| 1517 | bool ErrorParsing = false; |
| 1518 | |
| 1519 | // Expand response files. |
| 1520 | SmallVector<const char *, 20> newArgv(argv, argv + argc); |
| 1521 | BumpPtrAllocator A; |
| 1522 | #ifdef _WIN32 |
| 1523 | auto Tokenize = cl::TokenizeWindowsCommandLine; |
| 1524 | #else |
| 1525 | auto Tokenize = cl::TokenizeGNUCommandLine; |
| 1526 | #endif |
| 1527 | ExpansionContext ECtx(A, Tokenize, VFS); |
| 1528 | if (Error Err = ECtx.expandResponseFiles(Argv&: newArgv)) { |
| 1529 | *Errs << toString(E: std::move(Err)) << '\n'; |
| 1530 | return false; |
| 1531 | } |
| 1532 | argv = &newArgv[0]; |
| 1533 | argc = static_cast<int>(newArgv.size()); |
| 1534 | |
| 1535 | // Copy the program name into ProgName, making sure not to overflow it. |
| 1536 | ProgramName = std::string(sys::path::filename(path: StringRef(argv[0]))); |
| 1537 | |
| 1538 | // Check out the positional arguments to collect information about them. |
| 1539 | unsigned NumPositionalRequired = 0; |
| 1540 | |
| 1541 | // Determine whether or not there are an unlimited number of positionals |
| 1542 | bool HasUnlimitedPositionals = false; |
| 1543 | |
| 1544 | int FirstArg = 1; |
| 1545 | SubCommand *ChosenSubCommand = &SubCommand::getTopLevel(); |
| 1546 | std::string NearestSubCommandString; |
| 1547 | bool MaybeNamedSubCommand = |
| 1548 | argc >= 2 && argv[FirstArg][0] != '-' && hasNamedSubCommands(); |
| 1549 | if (MaybeNamedSubCommand) { |
| 1550 | // If the first argument specifies a valid subcommand, start processing |
| 1551 | // options from the second argument. |
| 1552 | ChosenSubCommand = |
| 1553 | LookupSubCommand(Name: StringRef(argv[FirstArg]), NearestString&: NearestSubCommandString); |
| 1554 | if (ChosenSubCommand != &SubCommand::getTopLevel()) |
| 1555 | FirstArg = 2; |
| 1556 | } |
| 1557 | GlobalParser->ActiveSubCommand = ChosenSubCommand; |
| 1558 | |
| 1559 | assert(ChosenSubCommand); |
| 1560 | auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt; |
| 1561 | auto &PositionalOpts = ChosenSubCommand->PositionalOpts; |
| 1562 | auto &SinkOpts = ChosenSubCommand->SinkOpts; |
| 1563 | auto &OptionsMap = ChosenSubCommand->OptionsMap; |
| 1564 | |
| 1565 | for (auto *O: DefaultOptions) { |
| 1566 | addOption(O, ProcessDefaultOption: true); |
| 1567 | } |
| 1568 | |
| 1569 | if (ConsumeAfterOpt) { |
| 1570 | assert(PositionalOpts.size() > 0 && |
| 1571 | "Cannot specify cl::ConsumeAfter without a positional argument!" ); |
| 1572 | } |
| 1573 | if (!PositionalOpts.empty()) { |
| 1574 | |
| 1575 | // Calculate how many positional values are _required_. |
| 1576 | bool UnboundedFound = false; |
| 1577 | for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { |
| 1578 | Option *Opt = PositionalOpts[i]; |
| 1579 | if (RequiresValue(O: Opt)) |
| 1580 | ++NumPositionalRequired; |
| 1581 | else if (ConsumeAfterOpt) { |
| 1582 | // ConsumeAfter cannot be combined with "optional" positional options |
| 1583 | // unless there is only one positional argument... |
| 1584 | if (PositionalOpts.size() > 1) { |
| 1585 | if (!IgnoreErrors) |
| 1586 | Opt->error(Message: "error - this positional option will never be matched, " |
| 1587 | "because it does not Require a value, and a " |
| 1588 | "cl::ConsumeAfter option is active!" ); |
| 1589 | ErrorParsing = true; |
| 1590 | } |
| 1591 | } else if (UnboundedFound && !Opt->hasArgStr()) { |
| 1592 | // This option does not "require" a value... Make sure this option is |
| 1593 | // not specified after an option that eats all extra arguments, or this |
| 1594 | // one will never get any! |
| 1595 | // |
| 1596 | if (!IgnoreErrors) |
| 1597 | Opt->error(Message: "error - option can never match, because " |
| 1598 | "another positional argument will match an " |
| 1599 | "unbounded number of values, and this option" |
| 1600 | " does not require a value!" ); |
| 1601 | *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr |
| 1602 | << "' is all messed up!\n" ; |
| 1603 | *Errs << PositionalOpts.size(); |
| 1604 | ErrorParsing = true; |
| 1605 | } |
| 1606 | UnboundedFound |= EatsUnboundedNumberOfValues(O: Opt); |
| 1607 | } |
| 1608 | HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; |
| 1609 | } |
| 1610 | |
| 1611 | // PositionalVals - A vector of "positional" arguments we accumulate into |
| 1612 | // the process at the end. |
| 1613 | // |
| 1614 | SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals; |
| 1615 | |
| 1616 | // If the program has named positional arguments, and the name has been run |
| 1617 | // across, keep track of which positional argument was named. Otherwise put |
| 1618 | // the positional args into the PositionalVals list... |
| 1619 | Option *ActivePositionalArg = nullptr; |
| 1620 | |
| 1621 | // Loop over all of the arguments... processing them. |
| 1622 | bool DashDashFound = false; // Have we read '--'? |
| 1623 | for (int i = FirstArg; i < argc; ++i) { |
| 1624 | Option *Handler = nullptr; |
| 1625 | std::string NearestHandlerString; |
| 1626 | StringRef Value; |
| 1627 | StringRef ArgName = "" ; |
| 1628 | bool HaveDoubleDash = false; |
| 1629 | |
| 1630 | // Check to see if this is a positional argument. This argument is |
| 1631 | // considered to be positional if it doesn't start with '-', if it is "-" |
| 1632 | // itself, or if we have seen "--" already. |
| 1633 | // |
| 1634 | if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { |
| 1635 | // Positional argument! |
| 1636 | if (ActivePositionalArg) { |
| 1637 | ProvidePositionalOption(Handler: ActivePositionalArg, Arg: StringRef(argv[i]), i); |
| 1638 | continue; // We are done! |
| 1639 | } |
| 1640 | |
| 1641 | if (!PositionalOpts.empty()) { |
| 1642 | PositionalVals.push_back(Elt: std::make_pair(x: StringRef(argv[i]), y&: i)); |
| 1643 | |
| 1644 | // All of the positional arguments have been fulfulled, give the rest to |
| 1645 | // the consume after option... if it's specified... |
| 1646 | // |
| 1647 | if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) { |
| 1648 | for (++i; i < argc; ++i) |
| 1649 | PositionalVals.push_back(Elt: std::make_pair(x: StringRef(argv[i]), y&: i)); |
| 1650 | break; // Handle outside of the argument processing loop... |
| 1651 | } |
| 1652 | |
| 1653 | // Delay processing positional arguments until the end... |
| 1654 | continue; |
| 1655 | } |
| 1656 | } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 && |
| 1657 | !DashDashFound) { |
| 1658 | DashDashFound = true; // This is the mythical "--"? |
| 1659 | continue; // Don't try to process it as an argument itself. |
| 1660 | } else if (ActivePositionalArg && |
| 1661 | (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) { |
| 1662 | // If there is a positional argument eating options, check to see if this |
| 1663 | // option is another positional argument. If so, treat it as an argument, |
| 1664 | // otherwise feed it to the eating positional. |
| 1665 | ArgName = StringRef(argv[i] + 1); |
| 1666 | // Eat second dash. |
| 1667 | if (ArgName.consume_front(Prefix: "-" )) |
| 1668 | HaveDoubleDash = true; |
| 1669 | |
| 1670 | Handler = LookupLongOption(Sub&: *ChosenSubCommand, Arg&: ArgName, Value, |
| 1671 | LongOptionsUseDoubleDash, HaveDoubleDash); |
| 1672 | if (!Handler || Handler->getFormattingFlag() != cl::Positional) { |
| 1673 | ProvidePositionalOption(Handler: ActivePositionalArg, Arg: StringRef(argv[i]), i); |
| 1674 | continue; // We are done! |
| 1675 | } |
| 1676 | } else { // We start with a '-', must be an argument. |
| 1677 | ArgName = StringRef(argv[i] + 1); |
| 1678 | // Eat second dash. |
| 1679 | if (ArgName.consume_front(Prefix: "-" )) |
| 1680 | HaveDoubleDash = true; |
| 1681 | |
| 1682 | Handler = LookupLongOption(Sub&: *ChosenSubCommand, Arg&: ArgName, Value, |
| 1683 | LongOptionsUseDoubleDash, HaveDoubleDash); |
| 1684 | |
| 1685 | // If Handler is not found in a specialized subcommand, look up handler |
| 1686 | // in the top-level subcommand. |
| 1687 | // cl::opt without cl::sub belongs to top-level subcommand. |
| 1688 | if (!Handler && ChosenSubCommand != &SubCommand::getTopLevel()) |
| 1689 | Handler = LookupLongOption(Sub&: SubCommand::getTopLevel(), Arg&: ArgName, Value, |
| 1690 | LongOptionsUseDoubleDash, HaveDoubleDash); |
| 1691 | |
| 1692 | // Check to see if this "option" is really a prefixed or grouped argument. |
| 1693 | if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash)) |
| 1694 | Handler = HandlePrefixedOrGroupedOption(Arg&: ArgName, Value, ErrorParsing, |
| 1695 | OptionsMap); |
| 1696 | |
| 1697 | // Otherwise, look for the closest available option to report to the user |
| 1698 | // in the upcoming error. |
| 1699 | if (!Handler && SinkOpts.empty()) |
| 1700 | LookupNearestOption(Arg: ArgName, OptionsMap, NearestString&: NearestHandlerString); |
| 1701 | } |
| 1702 | |
| 1703 | if (!Handler) { |
| 1704 | if (!SinkOpts.empty()) { |
| 1705 | for (Option *SinkOpt : SinkOpts) |
| 1706 | SinkOpt->addOccurrence(pos: i, ArgName: "" , Value: StringRef(argv[i])); |
| 1707 | continue; |
| 1708 | } |
| 1709 | |
| 1710 | auto ReportUnknownArgument = [&](bool IsArg, |
| 1711 | StringRef NearestArgumentName) { |
| 1712 | *Errs << ProgramName << ": Unknown " |
| 1713 | << (IsArg ? "command line argument" : "subcommand" ) << " '" |
| 1714 | << argv[i] << "'. Try: '" << argv[0] << " --help'\n" ; |
| 1715 | |
| 1716 | if (NearestArgumentName.empty()) |
| 1717 | return; |
| 1718 | |
| 1719 | *Errs << ProgramName << ": Did you mean '" ; |
| 1720 | if (IsArg) |
| 1721 | *Errs << PrintArg(NearestArgumentName, 0); |
| 1722 | else |
| 1723 | *Errs << NearestArgumentName; |
| 1724 | *Errs << "'?\n" ; |
| 1725 | }; |
| 1726 | |
| 1727 | if (i > 1 || !MaybeNamedSubCommand) |
| 1728 | ReportUnknownArgument(/*IsArg=*/true, NearestHandlerString); |
| 1729 | else |
| 1730 | ReportUnknownArgument(/*IsArg=*/false, NearestSubCommandString); |
| 1731 | |
| 1732 | ErrorParsing = true; |
| 1733 | continue; |
| 1734 | } |
| 1735 | |
| 1736 | // If this is a named positional argument, just remember that it is the |
| 1737 | // active one... |
| 1738 | if (Handler->getFormattingFlag() == cl::Positional) { |
| 1739 | if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) { |
| 1740 | Handler->error(Message: "This argument does not take a value.\n" |
| 1741 | "\tInstead, it consumes any positional arguments until " |
| 1742 | "the next recognized option." , Errs&: *Errs); |
| 1743 | ErrorParsing = true; |
| 1744 | } |
| 1745 | ActivePositionalArg = Handler; |
| 1746 | } |
| 1747 | else |
| 1748 | ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); |
| 1749 | } |
| 1750 | |
| 1751 | // Check and handle positional arguments now... |
| 1752 | if (NumPositionalRequired > PositionalVals.size()) { |
| 1753 | *Errs << ProgramName |
| 1754 | << ": Not enough positional command line arguments specified!\n" |
| 1755 | << "Must specify at least " << NumPositionalRequired |
| 1756 | << " positional argument" << (NumPositionalRequired > 1 ? "s" : "" ) |
| 1757 | << ": See: " << argv[0] << " --help\n" ; |
| 1758 | |
| 1759 | ErrorParsing = true; |
| 1760 | } else if (!HasUnlimitedPositionals && |
| 1761 | PositionalVals.size() > PositionalOpts.size()) { |
| 1762 | *Errs << ProgramName << ": Too many positional arguments specified!\n" |
| 1763 | << "Can specify at most " << PositionalOpts.size() |
| 1764 | << " positional arguments: See: " << argv[0] << " --help\n" ; |
| 1765 | ErrorParsing = true; |
| 1766 | |
| 1767 | } else if (!ConsumeAfterOpt) { |
| 1768 | // Positional args have already been handled if ConsumeAfter is specified. |
| 1769 | unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size()); |
| 1770 | for (Option *Opt : PositionalOpts) { |
| 1771 | if (RequiresValue(O: Opt)) { |
| 1772 | ProvidePositionalOption(Handler: Opt, Arg: PositionalVals[ValNo].first, |
| 1773 | i: PositionalVals[ValNo].second); |
| 1774 | ValNo++; |
| 1775 | --NumPositionalRequired; // We fulfilled our duty... |
| 1776 | } |
| 1777 | |
| 1778 | // If we _can_ give this option more arguments, do so now, as long as we |
| 1779 | // do not give it values that others need. 'Done' controls whether the |
| 1780 | // option even _WANTS_ any more. |
| 1781 | // |
| 1782 | bool Done = Opt->getNumOccurrencesFlag() == cl::Required; |
| 1783 | while (NumVals - ValNo > NumPositionalRequired && !Done) { |
| 1784 | switch (Opt->getNumOccurrencesFlag()) { |
| 1785 | case cl::Optional: |
| 1786 | Done = true; // Optional arguments want _at most_ one value |
| 1787 | [[fallthrough]]; |
| 1788 | case cl::ZeroOrMore: // Zero or more will take all they can get... |
| 1789 | case cl::OneOrMore: // One or more will take all they can get... |
| 1790 | ProvidePositionalOption(Handler: Opt, Arg: PositionalVals[ValNo].first, |
| 1791 | i: PositionalVals[ValNo].second); |
| 1792 | ValNo++; |
| 1793 | break; |
| 1794 | default: |
| 1795 | llvm_unreachable("Internal error, unexpected NumOccurrences flag in " |
| 1796 | "positional argument processing!" ); |
| 1797 | } |
| 1798 | } |
| 1799 | } |
| 1800 | } else { |
| 1801 | assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); |
| 1802 | unsigned ValNo = 0; |
| 1803 | for (Option *Opt : PositionalOpts) |
| 1804 | if (RequiresValue(O: Opt)) { |
| 1805 | ErrorParsing |= ProvidePositionalOption( |
| 1806 | Handler: Opt, Arg: PositionalVals[ValNo].first, i: PositionalVals[ValNo].second); |
| 1807 | ValNo++; |
| 1808 | } |
| 1809 | |
| 1810 | // Handle the case where there is just one positional option, and it's |
| 1811 | // optional. In this case, we want to give JUST THE FIRST option to the |
| 1812 | // positional option and keep the rest for the consume after. The above |
| 1813 | // loop would have assigned no values to positional options in this case. |
| 1814 | // |
| 1815 | if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) { |
| 1816 | ErrorParsing |= ProvidePositionalOption(Handler: PositionalOpts[0], |
| 1817 | Arg: PositionalVals[ValNo].first, |
| 1818 | i: PositionalVals[ValNo].second); |
| 1819 | ValNo++; |
| 1820 | } |
| 1821 | |
| 1822 | // Handle over all of the rest of the arguments to the |
| 1823 | // cl::ConsumeAfter command line option... |
| 1824 | for (; ValNo != PositionalVals.size(); ++ValNo) |
| 1825 | ErrorParsing |= |
| 1826 | ProvidePositionalOption(Handler: ConsumeAfterOpt, Arg: PositionalVals[ValNo].first, |
| 1827 | i: PositionalVals[ValNo].second); |
| 1828 | } |
| 1829 | |
| 1830 | // Loop over args and make sure all required args are specified! |
| 1831 | for (const auto &Opt : OptionsMap) { |
| 1832 | switch (Opt.second->getNumOccurrencesFlag()) { |
| 1833 | case Required: |
| 1834 | case OneOrMore: |
| 1835 | if (Opt.second->getNumOccurrences() == 0) { |
| 1836 | Opt.second->error(Message: "must be specified at least once!" ); |
| 1837 | ErrorParsing = true; |
| 1838 | } |
| 1839 | [[fallthrough]]; |
| 1840 | default: |
| 1841 | break; |
| 1842 | } |
| 1843 | } |
| 1844 | |
| 1845 | // Now that we know if -debug is specified, we can use it. |
| 1846 | // Note that if ReadResponseFiles == true, this must be done before the |
| 1847 | // memory allocated for the expanded command line is free()d below. |
| 1848 | LLVM_DEBUG(dbgs() << "Args: " ; |
| 1849 | for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' '; |
| 1850 | dbgs() << '\n';); |
| 1851 | |
| 1852 | // Free all of the memory allocated to the map. Command line options may only |
| 1853 | // be processed once! |
| 1854 | MoreHelp.clear(); |
| 1855 | |
| 1856 | // If we had an error processing our arguments, don't let the program execute |
| 1857 | if (ErrorParsing) { |
| 1858 | if (!IgnoreErrors) |
| 1859 | exit(status: 1); |
| 1860 | return false; |
| 1861 | } |
| 1862 | return true; |
| 1863 | } |
| 1864 | |
| 1865 | //===----------------------------------------------------------------------===// |
| 1866 | // Option Base class implementation |
| 1867 | // |
| 1868 | |
| 1869 | bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) { |
| 1870 | if (!ArgName.data()) |
| 1871 | ArgName = ArgStr; |
| 1872 | if (ArgName.empty()) |
| 1873 | Errs << HelpStr; // Be nice for positional arguments |
| 1874 | else |
| 1875 | Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0); |
| 1876 | |
| 1877 | Errs << " option: " << Message << "\n" ; |
| 1878 | return true; |
| 1879 | } |
| 1880 | |
| 1881 | bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value, |
| 1882 | bool MultiArg) { |
| 1883 | if (!MultiArg) |
| 1884 | NumOccurrences++; // Increment the number of times we have been seen |
| 1885 | |
| 1886 | return handleOccurrence(pos, ArgName, Arg: Value); |
| 1887 | } |
| 1888 | |
| 1889 | // getValueStr - Get the value description string, using "DefaultMsg" if nothing |
| 1890 | // has been specified yet. |
| 1891 | // |
| 1892 | static StringRef getValueStr(const Option &O, StringRef DefaultMsg) { |
| 1893 | if (O.ValueStr.empty()) |
| 1894 | return DefaultMsg; |
| 1895 | return O.ValueStr; |
| 1896 | } |
| 1897 | |
| 1898 | //===----------------------------------------------------------------------===// |
| 1899 | // cl::alias class implementation |
| 1900 | // |
| 1901 | |
| 1902 | // Return the width of the option tag for printing... |
| 1903 | size_t alias::getOptionWidth() const { |
| 1904 | return argPlusPrefixesSize(ArgName: ArgStr); |
| 1905 | } |
| 1906 | |
| 1907 | void Option::printHelpStr(StringRef HelpStr, size_t Indent, |
| 1908 | size_t FirstLineIndentedBy) { |
| 1909 | assert(Indent >= FirstLineIndentedBy); |
| 1910 | std::pair<StringRef, StringRef> Split = HelpStr.split(Separator: '\n'); |
| 1911 | outs().indent(NumSpaces: Indent - FirstLineIndentedBy) |
| 1912 | << ArgHelpPrefix << Split.first << "\n" ; |
| 1913 | while (!Split.second.empty()) { |
| 1914 | Split = Split.second.split(Separator: '\n'); |
| 1915 | outs().indent(NumSpaces: Indent) << Split.first << "\n" ; |
| 1916 | } |
| 1917 | } |
| 1918 | |
| 1919 | void Option::printEnumValHelpStr(StringRef HelpStr, size_t BaseIndent, |
| 1920 | size_t FirstLineIndentedBy) { |
| 1921 | const StringRef ValHelpPrefix = " " ; |
| 1922 | assert(BaseIndent >= FirstLineIndentedBy); |
| 1923 | std::pair<StringRef, StringRef> Split = HelpStr.split(Separator: '\n'); |
| 1924 | outs().indent(NumSpaces: BaseIndent - FirstLineIndentedBy) |
| 1925 | << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n" ; |
| 1926 | while (!Split.second.empty()) { |
| 1927 | Split = Split.second.split(Separator: '\n'); |
| 1928 | outs().indent(NumSpaces: BaseIndent + ValHelpPrefix.size()) << Split.first << "\n" ; |
| 1929 | } |
| 1930 | } |
| 1931 | |
| 1932 | // Print out the option for the alias. |
| 1933 | void alias::printOptionInfo(size_t GlobalWidth) const { |
| 1934 | outs() << PrintArg(ArgStr); |
| 1935 | printHelpStr(HelpStr, Indent: GlobalWidth, FirstLineIndentedBy: argPlusPrefixesSize(ArgName: ArgStr)); |
| 1936 | } |
| 1937 | |
| 1938 | //===----------------------------------------------------------------------===// |
| 1939 | // Parser Implementation code... |
| 1940 | // |
| 1941 | |
| 1942 | // basic_parser implementation |
| 1943 | // |
| 1944 | |
| 1945 | // Return the width of the option tag for printing... |
| 1946 | size_t basic_parser_impl::getOptionWidth(const Option &O) const { |
| 1947 | size_t Len = argPlusPrefixesSize(ArgName: O.ArgStr); |
| 1948 | auto ValName = getValueName(); |
| 1949 | if (!ValName.empty()) { |
| 1950 | size_t FormattingLen = 3; |
| 1951 | if (O.getMiscFlags() & PositionalEatsArgs) |
| 1952 | FormattingLen = 6; |
| 1953 | Len += getValueStr(O, DefaultMsg: ValName).size() + FormattingLen; |
| 1954 | } |
| 1955 | |
| 1956 | return Len; |
| 1957 | } |
| 1958 | |
| 1959 | // printOptionInfo - Print out information about this option. The |
| 1960 | // to-be-maintained width is specified. |
| 1961 | // |
| 1962 | void basic_parser_impl::printOptionInfo(const Option &O, |
| 1963 | size_t GlobalWidth) const { |
| 1964 | outs() << PrintArg(O.ArgStr); |
| 1965 | |
| 1966 | auto ValName = getValueName(); |
| 1967 | if (!ValName.empty()) { |
| 1968 | if (O.getMiscFlags() & PositionalEatsArgs) { |
| 1969 | outs() << " <" << getValueStr(O, DefaultMsg: ValName) << ">..." ; |
| 1970 | } else if (O.getValueExpectedFlag() == ValueOptional) |
| 1971 | outs() << "[=<" << getValueStr(O, DefaultMsg: ValName) << ">]" ; |
| 1972 | else { |
| 1973 | outs() << (O.ArgStr.size() == 1 ? " <" : "=<" ) << getValueStr(O, DefaultMsg: ValName) |
| 1974 | << '>'; |
| 1975 | } |
| 1976 | } |
| 1977 | |
| 1978 | Option::printHelpStr(HelpStr: O.HelpStr, Indent: GlobalWidth, FirstLineIndentedBy: getOptionWidth(O)); |
| 1979 | } |
| 1980 | |
| 1981 | void basic_parser_impl::printOptionName(const Option &O, |
| 1982 | size_t GlobalWidth) const { |
| 1983 | outs() << PrintArg(O.ArgStr); |
| 1984 | outs().indent(NumSpaces: GlobalWidth - O.ArgStr.size()); |
| 1985 | } |
| 1986 | |
| 1987 | // parser<bool> implementation |
| 1988 | // |
| 1989 | bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg, |
| 1990 | bool &Value) { |
| 1991 | return parseBool<bool, true, false>(O, ArgName, Arg, Value); |
| 1992 | } |
| 1993 | |
| 1994 | // parser<boolOrDefault> implementation |
| 1995 | // |
| 1996 | bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg, |
| 1997 | boolOrDefault &Value) { |
| 1998 | return parseBool<boolOrDefault, BOU_TRUE, BOU_FALSE>(O, ArgName, Arg, Value); |
| 1999 | } |
| 2000 | |
| 2001 | // parser<int> implementation |
| 2002 | // |
| 2003 | bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg, |
| 2004 | int &Value) { |
| 2005 | if (Arg.getAsInteger(Radix: 0, Result&: Value)) |
| 2006 | return O.error(Message: "'" + Arg + "' value invalid for integer argument!" ); |
| 2007 | return false; |
| 2008 | } |
| 2009 | |
| 2010 | // parser<long> implementation |
| 2011 | // |
| 2012 | bool parser<long>::parse(Option &O, StringRef ArgName, StringRef Arg, |
| 2013 | long &Value) { |
| 2014 | if (Arg.getAsInteger(Radix: 0, Result&: Value)) |
| 2015 | return O.error(Message: "'" + Arg + "' value invalid for long argument!" ); |
| 2016 | return false; |
| 2017 | } |
| 2018 | |
| 2019 | // parser<long long> implementation |
| 2020 | // |
| 2021 | bool parser<long long>::parse(Option &O, StringRef ArgName, StringRef Arg, |
| 2022 | long long &Value) { |
| 2023 | if (Arg.getAsInteger(Radix: 0, Result&: Value)) |
| 2024 | return O.error(Message: "'" + Arg + "' value invalid for llong argument!" ); |
| 2025 | return false; |
| 2026 | } |
| 2027 | |
| 2028 | // parser<unsigned> implementation |
| 2029 | // |
| 2030 | bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg, |
| 2031 | unsigned &Value) { |
| 2032 | |
| 2033 | if (Arg.getAsInteger(Radix: 0, Result&: Value)) |
| 2034 | return O.error(Message: "'" + Arg + "' value invalid for uint argument!" ); |
| 2035 | return false; |
| 2036 | } |
| 2037 | |
| 2038 | // parser<unsigned long> implementation |
| 2039 | // |
| 2040 | bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg, |
| 2041 | unsigned long &Value) { |
| 2042 | |
| 2043 | if (Arg.getAsInteger(Radix: 0, Result&: Value)) |
| 2044 | return O.error(Message: "'" + Arg + "' value invalid for ulong argument!" ); |
| 2045 | return false; |
| 2046 | } |
| 2047 | |
| 2048 | // parser<unsigned long long> implementation |
| 2049 | // |
| 2050 | bool parser<unsigned long long>::parse(Option &O, StringRef ArgName, |
| 2051 | StringRef Arg, |
| 2052 | unsigned long long &Value) { |
| 2053 | |
| 2054 | if (Arg.getAsInteger(Radix: 0, Result&: Value)) |
| 2055 | return O.error(Message: "'" + Arg + "' value invalid for ullong argument!" ); |
| 2056 | return false; |
| 2057 | } |
| 2058 | |
| 2059 | // parser<double>/parser<float> implementation |
| 2060 | // |
| 2061 | static bool parseDouble(Option &O, StringRef Arg, double &Value) { |
| 2062 | if (to_float(T: Arg, Num&: Value)) |
| 2063 | return false; |
| 2064 | return O.error(Message: "'" + Arg + "' value invalid for floating point argument!" ); |
| 2065 | } |
| 2066 | |
| 2067 | bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg, |
| 2068 | double &Val) { |
| 2069 | return parseDouble(O, Arg, Value&: Val); |
| 2070 | } |
| 2071 | |
| 2072 | bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg, |
| 2073 | float &Val) { |
| 2074 | double dVal; |
| 2075 | if (parseDouble(O, Arg, Value&: dVal)) |
| 2076 | return true; |
| 2077 | Val = (float)dVal; |
| 2078 | return false; |
| 2079 | } |
| 2080 | |
| 2081 | // generic_parser_base implementation |
| 2082 | // |
| 2083 | |
| 2084 | // findOption - Return the option number corresponding to the specified |
| 2085 | // argument string. If the option is not found, getNumOptions() is returned. |
| 2086 | // |
| 2087 | unsigned generic_parser_base::findOption(StringRef Name) { |
| 2088 | unsigned e = getNumOptions(); |
| 2089 | |
| 2090 | for (unsigned i = 0; i != e; ++i) { |
| 2091 | if (getOption(N: i) == Name) |
| 2092 | return i; |
| 2093 | } |
| 2094 | return e; |
| 2095 | } |
| 2096 | |
| 2097 | static StringRef EqValue = "=<value>" ; |
| 2098 | static StringRef EmptyOption = "<empty>" ; |
| 2099 | static StringRef OptionPrefix = " =" ; |
| 2100 | static size_t getOptionPrefixesSize() { |
| 2101 | return OptionPrefix.size() + ArgHelpPrefix.size(); |
| 2102 | } |
| 2103 | |
| 2104 | static bool shouldPrintOption(StringRef Name, StringRef Description, |
| 2105 | const Option &O) { |
| 2106 | return O.getValueExpectedFlag() != ValueOptional || !Name.empty() || |
| 2107 | !Description.empty(); |
| 2108 | } |
| 2109 | |
| 2110 | // Return the width of the option tag for printing... |
| 2111 | size_t generic_parser_base::getOptionWidth(const Option &O) const { |
| 2112 | if (O.hasArgStr()) { |
| 2113 | size_t Size = |
| 2114 | argPlusPrefixesSize(ArgName: O.ArgStr) + EqValue.size(); |
| 2115 | for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { |
| 2116 | StringRef Name = getOption(N: i); |
| 2117 | if (!shouldPrintOption(Name, Description: getDescription(N: i), O)) |
| 2118 | continue; |
| 2119 | size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size(); |
| 2120 | Size = std::max(a: Size, b: NameSize + getOptionPrefixesSize()); |
| 2121 | } |
| 2122 | return Size; |
| 2123 | } else { |
| 2124 | size_t BaseSize = 0; |
| 2125 | for (unsigned i = 0, e = getNumOptions(); i != e; ++i) |
| 2126 | BaseSize = std::max(a: BaseSize, b: getOption(N: i).size() + 8); |
| 2127 | return BaseSize; |
| 2128 | } |
| 2129 | } |
| 2130 | |
| 2131 | // printOptionInfo - Print out information about this option. The |
| 2132 | // to-be-maintained width is specified. |
| 2133 | // |
| 2134 | void generic_parser_base::printOptionInfo(const Option &O, |
| 2135 | size_t GlobalWidth) const { |
| 2136 | if (O.hasArgStr()) { |
| 2137 | // When the value is optional, first print a line just describing the |
| 2138 | // option without values. |
| 2139 | if (O.getValueExpectedFlag() == ValueOptional) { |
| 2140 | for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { |
| 2141 | if (getOption(N: i).empty()) { |
| 2142 | outs() << PrintArg(O.ArgStr); |
| 2143 | Option::printHelpStr(HelpStr: O.HelpStr, Indent: GlobalWidth, |
| 2144 | FirstLineIndentedBy: argPlusPrefixesSize(ArgName: O.ArgStr)); |
| 2145 | break; |
| 2146 | } |
| 2147 | } |
| 2148 | } |
| 2149 | |
| 2150 | outs() << PrintArg(O.ArgStr) << EqValue; |
| 2151 | Option::printHelpStr(HelpStr: O.HelpStr, Indent: GlobalWidth, |
| 2152 | FirstLineIndentedBy: EqValue.size() + |
| 2153 | argPlusPrefixesSize(ArgName: O.ArgStr)); |
| 2154 | for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { |
| 2155 | StringRef OptionName = getOption(N: i); |
| 2156 | StringRef Description = getDescription(N: i); |
| 2157 | if (!shouldPrintOption(Name: OptionName, Description, O)) |
| 2158 | continue; |
| 2159 | size_t FirstLineIndent = OptionName.size() + getOptionPrefixesSize(); |
| 2160 | outs() << OptionPrefix << OptionName; |
| 2161 | if (OptionName.empty()) { |
| 2162 | outs() << EmptyOption; |
| 2163 | assert(FirstLineIndent >= EmptyOption.size()); |
| 2164 | FirstLineIndent += EmptyOption.size(); |
| 2165 | } |
| 2166 | if (!Description.empty()) |
| 2167 | Option::printEnumValHelpStr(HelpStr: Description, BaseIndent: GlobalWidth, FirstLineIndentedBy: FirstLineIndent); |
| 2168 | else |
| 2169 | outs() << '\n'; |
| 2170 | } |
| 2171 | } else { |
| 2172 | if (!O.HelpStr.empty()) |
| 2173 | outs() << " " << O.HelpStr << '\n'; |
| 2174 | for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { |
| 2175 | StringRef Option = getOption(N: i); |
| 2176 | outs() << " " << PrintArg(Option); |
| 2177 | Option::printHelpStr(HelpStr: getDescription(N: i), Indent: GlobalWidth, FirstLineIndentedBy: Option.size() + 8); |
| 2178 | } |
| 2179 | } |
| 2180 | } |
| 2181 | |
| 2182 | static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff |
| 2183 | |
| 2184 | // printGenericOptionDiff - Print the value of this option and it's default. |
| 2185 | // |
| 2186 | // "Generic" options have each value mapped to a name. |
| 2187 | void generic_parser_base::printGenericOptionDiff( |
| 2188 | const Option &O, const GenericOptionValue &Value, |
| 2189 | const GenericOptionValue &Default, size_t GlobalWidth) const { |
| 2190 | outs() << " " << PrintArg(O.ArgStr); |
| 2191 | outs().indent(NumSpaces: GlobalWidth - O.ArgStr.size()); |
| 2192 | |
| 2193 | unsigned NumOpts = getNumOptions(); |
| 2194 | for (unsigned i = 0; i != NumOpts; ++i) { |
| 2195 | if (!Value.compare(V: getOptionValue(N: i))) |
| 2196 | continue; |
| 2197 | |
| 2198 | outs() << "= " << getOption(N: i); |
| 2199 | size_t L = getOption(N: i).size(); |
| 2200 | size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0; |
| 2201 | outs().indent(NumSpaces) << " (default: " ; |
| 2202 | for (unsigned j = 0; j != NumOpts; ++j) { |
| 2203 | if (!Default.compare(V: getOptionValue(N: j))) |
| 2204 | continue; |
| 2205 | outs() << getOption(N: j); |
| 2206 | break; |
| 2207 | } |
| 2208 | outs() << ")\n" ; |
| 2209 | return; |
| 2210 | } |
| 2211 | outs() << "= *unknown option value*\n" ; |
| 2212 | } |
| 2213 | |
| 2214 | // printOptionDiff - Specializations for printing basic value types. |
| 2215 | // |
| 2216 | #define PRINT_OPT_DIFF(T) \ |
| 2217 | void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \ |
| 2218 | size_t GlobalWidth) const { \ |
| 2219 | printOptionName(O, GlobalWidth); \ |
| 2220 | std::string Str; \ |
| 2221 | { \ |
| 2222 | raw_string_ostream SS(Str); \ |
| 2223 | SS << V; \ |
| 2224 | } \ |
| 2225 | outs() << "= " << Str; \ |
| 2226 | size_t NumSpaces = \ |
| 2227 | MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \ |
| 2228 | outs().indent(NumSpaces) << " (default: "; \ |
| 2229 | if (D.hasValue()) \ |
| 2230 | outs() << D.getValue(); \ |
| 2231 | else \ |
| 2232 | outs() << "*no default*"; \ |
| 2233 | outs() << ")\n"; \ |
| 2234 | } |
| 2235 | |
| 2236 | PRINT_OPT_DIFF(bool) |
| 2237 | PRINT_OPT_DIFF(boolOrDefault) |
| 2238 | PRINT_OPT_DIFF(int) |
| 2239 | PRINT_OPT_DIFF(long) |
| 2240 | PRINT_OPT_DIFF(long long) |
| 2241 | PRINT_OPT_DIFF(unsigned) |
| 2242 | PRINT_OPT_DIFF(unsigned long) |
| 2243 | PRINT_OPT_DIFF(unsigned long long) |
| 2244 | PRINT_OPT_DIFF(double) |
| 2245 | PRINT_OPT_DIFF(float) |
| 2246 | PRINT_OPT_DIFF(char) |
| 2247 | |
| 2248 | void parser<std::string>::printOptionDiff(const Option &O, StringRef V, |
| 2249 | const OptionValue<std::string> &D, |
| 2250 | size_t GlobalWidth) const { |
| 2251 | printOptionName(O, GlobalWidth); |
| 2252 | outs() << "= " << V; |
| 2253 | size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0; |
| 2254 | outs().indent(NumSpaces) << " (default: " ; |
| 2255 | if (D.hasValue()) |
| 2256 | outs() << D.getValue(); |
| 2257 | else |
| 2258 | outs() << "*no default*" ; |
| 2259 | outs() << ")\n" ; |
| 2260 | } |
| 2261 | |
| 2262 | void parser<std::optional<std::string>>::printOptionDiff( |
| 2263 | const Option &O, std::optional<StringRef> V, |
| 2264 | const OptionValue<std::optional<std::string>> &D, |
| 2265 | size_t GlobalWidth) const { |
| 2266 | printOptionName(O, GlobalWidth); |
| 2267 | outs() << "= " << V; |
| 2268 | size_t VSize = V.has_value() ? V.value().size() : 0; |
| 2269 | size_t NumSpaces = MaxOptWidth > VSize ? MaxOptWidth - VSize : 0; |
| 2270 | outs().indent(NumSpaces) << " (default: " ; |
| 2271 | if (D.hasValue() && D.getValue().has_value()) |
| 2272 | outs() << D.getValue(); |
| 2273 | else |
| 2274 | outs() << "*no value*" ; |
| 2275 | outs() << ")\n" ; |
| 2276 | } |
| 2277 | |
| 2278 | // Print a placeholder for options that don't yet support printOptionDiff(). |
| 2279 | void basic_parser_impl::printOptionNoValue(const Option &O, |
| 2280 | size_t GlobalWidth) const { |
| 2281 | printOptionName(O, GlobalWidth); |
| 2282 | outs() << "= *cannot print option value*\n" ; |
| 2283 | } |
| 2284 | |
| 2285 | //===----------------------------------------------------------------------===// |
| 2286 | // -help and -help-hidden option implementation |
| 2287 | // |
| 2288 | |
| 2289 | static int OptNameCompare(const std::pair<const char *, Option *> *LHS, |
| 2290 | const std::pair<const char *, Option *> *RHS) { |
| 2291 | return strcmp(s1: LHS->first, s2: RHS->first); |
| 2292 | } |
| 2293 | |
| 2294 | static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS, |
| 2295 | const std::pair<const char *, SubCommand *> *RHS) { |
| 2296 | return strcmp(s1: LHS->first, s2: RHS->first); |
| 2297 | } |
| 2298 | |
| 2299 | // Copy Options into a vector so we can sort them as we like. |
| 2300 | static void sortOpts(OptionsMapTy &OptMap, |
| 2301 | SmallVectorImpl<std::pair<const char *, Option *>> &Opts, |
| 2302 | bool ShowHidden) { |
| 2303 | SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection. |
| 2304 | |
| 2305 | for (auto I = OptMap.begin(), E = OptMap.end(); I != E; ++I) { |
| 2306 | // Ignore really-hidden options. |
| 2307 | if (I->second->getOptionHiddenFlag() == ReallyHidden) |
| 2308 | continue; |
| 2309 | |
| 2310 | // Unless showhidden is set, ignore hidden flags. |
| 2311 | if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden) |
| 2312 | continue; |
| 2313 | |
| 2314 | // If we've already seen this option, don't add it to the list again. |
| 2315 | if (!OptionSet.insert(Ptr: I->second).second) |
| 2316 | continue; |
| 2317 | |
| 2318 | Opts.push_back( |
| 2319 | Elt: std::pair<const char *, Option *>(I->first.data(), I->second)); |
| 2320 | } |
| 2321 | |
| 2322 | // Sort the options list alphabetically. |
| 2323 | array_pod_sort(Start: Opts.begin(), End: Opts.end(), Compare: OptNameCompare); |
| 2324 | } |
| 2325 | |
| 2326 | static void |
| 2327 | sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap, |
| 2328 | SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) { |
| 2329 | for (auto *S : SubMap) { |
| 2330 | if (S->getName().empty()) |
| 2331 | continue; |
| 2332 | Subs.push_back(Elt: std::make_pair(x: S->getName().data(), y&: S)); |
| 2333 | } |
| 2334 | array_pod_sort(Start: Subs.begin(), End: Subs.end(), Compare: SubNameCompare); |
| 2335 | } |
| 2336 | |
| 2337 | namespace { |
| 2338 | |
| 2339 | class HelpPrinter { |
| 2340 | protected: |
| 2341 | const bool ShowHidden; |
| 2342 | using StrOptionPairVector = |
| 2343 | SmallVector<std::pair<const char *, Option *>, 128>; |
| 2344 | using StrSubCommandPairVector = |
| 2345 | SmallVector<std::pair<const char *, SubCommand *>, 128>; |
| 2346 | // Print the options. Opts is assumed to be alphabetically sorted. |
| 2347 | virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) { |
| 2348 | for (const auto &Opt : Opts) |
| 2349 | Opt.second->printOptionInfo(GlobalWidth: MaxArgLen); |
| 2350 | } |
| 2351 | |
| 2352 | void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) { |
| 2353 | for (const auto &S : Subs) { |
| 2354 | outs() << " " << S.first; |
| 2355 | if (!S.second->getDescription().empty()) { |
| 2356 | outs().indent(NumSpaces: MaxSubLen - strlen(s: S.first)); |
| 2357 | outs() << " - " << S.second->getDescription(); |
| 2358 | } |
| 2359 | outs() << "\n" ; |
| 2360 | } |
| 2361 | } |
| 2362 | |
| 2363 | public: |
| 2364 | explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {} |
| 2365 | virtual ~HelpPrinter() = default; |
| 2366 | |
| 2367 | // Invoke the printer. |
| 2368 | void operator=(bool Value) { |
| 2369 | if (!Value) |
| 2370 | return; |
| 2371 | printHelp(); |
| 2372 | |
| 2373 | // Halt the program since help information was printed |
| 2374 | exit(status: 0); |
| 2375 | } |
| 2376 | |
| 2377 | void printHelp() { |
| 2378 | SubCommand *Sub = GlobalParser->getActiveSubCommand(); |
| 2379 | auto &OptionsMap = Sub->OptionsMap; |
| 2380 | auto &PositionalOpts = Sub->PositionalOpts; |
| 2381 | auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt; |
| 2382 | |
| 2383 | StrOptionPairVector Opts; |
| 2384 | sortOpts(OptMap&: OptionsMap, Opts, ShowHidden); |
| 2385 | |
| 2386 | StrSubCommandPairVector Subs; |
| 2387 | sortSubCommands(SubMap: GlobalParser->RegisteredSubCommands, Subs); |
| 2388 | |
| 2389 | if (!GlobalParser->ProgramOverview.empty()) |
| 2390 | outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n" ; |
| 2391 | |
| 2392 | if (Sub == &SubCommand::getTopLevel()) { |
| 2393 | outs() << "USAGE: " << GlobalParser->ProgramName; |
| 2394 | if (!Subs.empty()) |
| 2395 | outs() << " [subcommand]" ; |
| 2396 | outs() << " [options]" ; |
| 2397 | } else { |
| 2398 | if (!Sub->getDescription().empty()) { |
| 2399 | outs() << "SUBCOMMAND '" << Sub->getName() |
| 2400 | << "': " << Sub->getDescription() << "\n\n" ; |
| 2401 | } |
| 2402 | outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName() |
| 2403 | << " [options]" ; |
| 2404 | } |
| 2405 | |
| 2406 | for (auto *Opt : PositionalOpts) { |
| 2407 | if (Opt->hasArgStr()) |
| 2408 | outs() << " --" << Opt->ArgStr; |
| 2409 | outs() << " " << Opt->HelpStr; |
| 2410 | } |
| 2411 | |
| 2412 | // Print the consume after option info if it exists... |
| 2413 | if (ConsumeAfterOpt) |
| 2414 | outs() << " " << ConsumeAfterOpt->HelpStr; |
| 2415 | |
| 2416 | if (Sub == &SubCommand::getTopLevel() && !Subs.empty()) { |
| 2417 | // Compute the maximum subcommand length... |
| 2418 | size_t MaxSubLen = 0; |
| 2419 | for (const auto &Sub : Subs) |
| 2420 | MaxSubLen = std::max(a: MaxSubLen, b: strlen(s: Sub.first)); |
| 2421 | |
| 2422 | outs() << "\n\n" ; |
| 2423 | outs() << "SUBCOMMANDS:\n\n" ; |
| 2424 | printSubCommands(Subs, MaxSubLen); |
| 2425 | outs() << "\n" ; |
| 2426 | outs() << " Type \"" << GlobalParser->ProgramName |
| 2427 | << " <subcommand> --help\" to get more help on a specific " |
| 2428 | "subcommand" ; |
| 2429 | } |
| 2430 | |
| 2431 | outs() << "\n\n" ; |
| 2432 | |
| 2433 | // Compute the maximum argument length... |
| 2434 | size_t MaxArgLen = 0; |
| 2435 | for (const auto &Opt : Opts) |
| 2436 | MaxArgLen = std::max(a: MaxArgLen, b: Opt.second->getOptionWidth()); |
| 2437 | |
| 2438 | outs() << "OPTIONS:\n" ; |
| 2439 | printOptions(Opts, MaxArgLen); |
| 2440 | |
| 2441 | // Print any extra help the user has declared. |
| 2442 | for (const auto &I : GlobalParser->MoreHelp) |
| 2443 | outs() << I; |
| 2444 | GlobalParser->MoreHelp.clear(); |
| 2445 | } |
| 2446 | }; |
| 2447 | |
| 2448 | class CategorizedHelpPrinter : public HelpPrinter { |
| 2449 | public: |
| 2450 | explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {} |
| 2451 | |
| 2452 | // Helper function for printOptions(). |
| 2453 | // It shall return a negative value if A's name should be lexicographically |
| 2454 | // ordered before B's name. It returns a value greater than zero if B's name |
| 2455 | // should be ordered before A's name, and it returns 0 otherwise. |
| 2456 | static int OptionCategoryCompare(OptionCategory *const *A, |
| 2457 | OptionCategory *const *B) { |
| 2458 | return (*A)->getName().compare(RHS: (*B)->getName()); |
| 2459 | } |
| 2460 | |
| 2461 | // Make sure we inherit our base class's operator=() |
| 2462 | using HelpPrinter::operator=; |
| 2463 | |
| 2464 | protected: |
| 2465 | void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override { |
| 2466 | std::vector<OptionCategory *> SortedCategories; |
| 2467 | DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions; |
| 2468 | |
| 2469 | // Collect registered option categories into vector in preparation for |
| 2470 | // sorting. |
| 2471 | llvm::append_range(C&: SortedCategories, |
| 2472 | R&: GlobalParser->RegisteredOptionCategories); |
| 2473 | |
| 2474 | // Sort the different option categories alphabetically. |
| 2475 | assert(SortedCategories.size() > 0 && "No option categories registered!" ); |
| 2476 | array_pod_sort(Start: SortedCategories.begin(), End: SortedCategories.end(), |
| 2477 | Compare: OptionCategoryCompare); |
| 2478 | |
| 2479 | // Walk through pre-sorted options and assign into categories. |
| 2480 | // Because the options are already alphabetically sorted the |
| 2481 | // options within categories will also be alphabetically sorted. |
| 2482 | for (const auto &I : Opts) { |
| 2483 | Option *Opt = I.second; |
| 2484 | for (OptionCategory *Cat : Opt->Categories) { |
| 2485 | assert(llvm::is_contained(SortedCategories, Cat) && |
| 2486 | "Option has an unregistered category" ); |
| 2487 | CategorizedOptions[Cat].push_back(x: Opt); |
| 2488 | } |
| 2489 | } |
| 2490 | |
| 2491 | // Now do printing. |
| 2492 | for (OptionCategory *Category : SortedCategories) { |
| 2493 | // Hide empty categories for --help, but show for --help-hidden. |
| 2494 | const auto &CategoryOptions = CategorizedOptions[Category]; |
| 2495 | if (CategoryOptions.empty()) |
| 2496 | continue; |
| 2497 | |
| 2498 | // Print category information. |
| 2499 | outs() << "\n" ; |
| 2500 | outs() << Category->getName() << ":\n" ; |
| 2501 | |
| 2502 | // Check if description is set. |
| 2503 | if (!Category->getDescription().empty()) |
| 2504 | outs() << Category->getDescription() << "\n\n" ; |
| 2505 | else |
| 2506 | outs() << "\n" ; |
| 2507 | |
| 2508 | // Loop over the options in the category and print. |
| 2509 | for (const Option *Opt : CategoryOptions) |
| 2510 | Opt->printOptionInfo(GlobalWidth: MaxArgLen); |
| 2511 | } |
| 2512 | } |
| 2513 | }; |
| 2514 | |
| 2515 | // This wraps the Uncategorizing and Categorizing printers and decides |
| 2516 | // at run time which should be invoked. |
| 2517 | class HelpPrinterWrapper { |
| 2518 | private: |
| 2519 | HelpPrinter &UncategorizedPrinter; |
| 2520 | CategorizedHelpPrinter &CategorizedPrinter; |
| 2521 | |
| 2522 | public: |
| 2523 | explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter, |
| 2524 | CategorizedHelpPrinter &CategorizedPrinter) |
| 2525 | : UncategorizedPrinter(UncategorizedPrinter), |
| 2526 | CategorizedPrinter(CategorizedPrinter) {} |
| 2527 | |
| 2528 | // Invoke the printer. |
| 2529 | void operator=(bool Value); |
| 2530 | }; |
| 2531 | |
| 2532 | } // End anonymous namespace |
| 2533 | |
| 2534 | #if defined(__GNUC__) |
| 2535 | // GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are |
| 2536 | // enabled. |
| 2537 | # if defined(__OPTIMIZE__) |
| 2538 | # define LLVM_IS_DEBUG_BUILD 0 |
| 2539 | # else |
| 2540 | # define LLVM_IS_DEBUG_BUILD 1 |
| 2541 | # endif |
| 2542 | #elif defined(_MSC_VER) |
| 2543 | // MSVC doesn't have a predefined macro indicating if optimizations are enabled. |
| 2544 | // Use _DEBUG instead. This macro actually corresponds to the choice between |
| 2545 | // debug and release CRTs, but it is a reasonable proxy. |
| 2546 | # if defined(_DEBUG) |
| 2547 | # define LLVM_IS_DEBUG_BUILD 1 |
| 2548 | # else |
| 2549 | # define LLVM_IS_DEBUG_BUILD 0 |
| 2550 | # endif |
| 2551 | #else |
| 2552 | // Otherwise, for an unknown compiler, assume this is an optimized build. |
| 2553 | # define LLVM_IS_DEBUG_BUILD 0 |
| 2554 | #endif |
| 2555 | |
| 2556 | namespace { |
| 2557 | class VersionPrinter { |
| 2558 | public: |
| 2559 | void print(const std::vector<VersionPrinterTy> &) { |
| 2560 | raw_ostream &OS = outs(); |
| 2561 | #ifdef PACKAGE_VENDOR |
| 2562 | OS << PACKAGE_VENDOR << " " ; |
| 2563 | #else |
| 2564 | OS << "LLVM (http://llvm.org/):\n " ; |
| 2565 | #endif |
| 2566 | OS << PACKAGE_NAME << " version " << PACKAGE_VERSION << "\n " ; |
| 2567 | #if LLVM_IS_DEBUG_BUILD |
| 2568 | OS << "DEBUG build" ; |
| 2569 | #else |
| 2570 | OS << "Optimized build" ; |
| 2571 | #endif |
| 2572 | #ifndef NDEBUG |
| 2573 | OS << " with assertions" ; |
| 2574 | #endif |
| 2575 | OS << ".\n" ; |
| 2576 | |
| 2577 | // Iterate over any registered extra printers and call them to add further |
| 2578 | // information. |
| 2579 | if (!ExtraPrinters.empty()) { |
| 2580 | for (const auto &I : ExtraPrinters) |
| 2581 | I(outs()); |
| 2582 | } |
| 2583 | } |
| 2584 | void operator=(bool OptionWasSpecified); |
| 2585 | }; |
| 2586 | |
| 2587 | struct CommandLineCommonOptions { |
| 2588 | // Declare the four HelpPrinter instances that are used to print out help, or |
| 2589 | // help-hidden as an uncategorized list or in categories. |
| 2590 | HelpPrinter UncategorizedNormalPrinter{false}; |
| 2591 | HelpPrinter UncategorizedHiddenPrinter{true}; |
| 2592 | CategorizedHelpPrinter CategorizedNormalPrinter{false}; |
| 2593 | CategorizedHelpPrinter CategorizedHiddenPrinter{true}; |
| 2594 | // Declare HelpPrinter wrappers that will decide whether or not to invoke |
| 2595 | // a categorizing help printer |
| 2596 | HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter, |
| 2597 | CategorizedNormalPrinter}; |
| 2598 | HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter, |
| 2599 | CategorizedHiddenPrinter}; |
| 2600 | // Define a category for generic options that all tools should have. |
| 2601 | cl::OptionCategory GenericCategory{"Generic Options" }; |
| 2602 | |
| 2603 | // Define uncategorized help printers. |
| 2604 | // --help-list is hidden by default because if Option categories are being |
| 2605 | // used then --help behaves the same as --help-list. |
| 2606 | cl::opt<HelpPrinter, true, parser<bool>> HLOp{ |
| 2607 | "help-list" , |
| 2608 | cl::desc( |
| 2609 | "Display list of available options (--help-list-hidden for more)" ), |
| 2610 | cl::location(L&: UncategorizedNormalPrinter), |
| 2611 | cl::Hidden, |
| 2612 | cl::ValueDisallowed, |
| 2613 | cl::cat(GenericCategory), |
| 2614 | cl::sub(SubCommand::getAll())}; |
| 2615 | |
| 2616 | cl::opt<HelpPrinter, true, parser<bool>> HLHOp{ |
| 2617 | "help-list-hidden" , |
| 2618 | cl::desc("Display list of all available options" ), |
| 2619 | cl::location(L&: UncategorizedHiddenPrinter), |
| 2620 | cl::Hidden, |
| 2621 | cl::ValueDisallowed, |
| 2622 | cl::cat(GenericCategory), |
| 2623 | cl::sub(SubCommand::getAll())}; |
| 2624 | |
| 2625 | // Define uncategorized/categorized help printers. These printers change their |
| 2626 | // behaviour at runtime depending on whether one or more Option categories |
| 2627 | // have been declared. |
| 2628 | cl::opt<HelpPrinterWrapper, true, parser<bool>> HOp{ |
| 2629 | "help" , |
| 2630 | cl::desc("Display available options (--help-hidden for more)" ), |
| 2631 | cl::location(L&: WrappedNormalPrinter), |
| 2632 | cl::ValueDisallowed, |
| 2633 | cl::cat(GenericCategory), |
| 2634 | cl::sub(SubCommand::getAll())}; |
| 2635 | |
| 2636 | cl::alias HOpA{"h" , cl::desc("Alias for --help" ), cl::aliasopt(HOp), |
| 2637 | cl::DefaultOption}; |
| 2638 | |
| 2639 | cl::opt<HelpPrinterWrapper, true, parser<bool>> HHOp{ |
| 2640 | "help-hidden" , |
| 2641 | cl::desc("Display all available options" ), |
| 2642 | cl::location(L&: WrappedHiddenPrinter), |
| 2643 | cl::Hidden, |
| 2644 | cl::ValueDisallowed, |
| 2645 | cl::cat(GenericCategory), |
| 2646 | cl::sub(SubCommand::getAll())}; |
| 2647 | |
| 2648 | cl::opt<bool> PrintOptions{ |
| 2649 | "print-options" , |
| 2650 | cl::desc("Print non-default options after command line parsing" ), |
| 2651 | cl::Hidden, |
| 2652 | cl::init(Val: false), |
| 2653 | cl::cat(GenericCategory), |
| 2654 | cl::sub(SubCommand::getAll())}; |
| 2655 | |
| 2656 | cl::opt<bool> PrintAllOptions{ |
| 2657 | "print-all-options" , |
| 2658 | cl::desc("Print all option values after command line parsing" ), |
| 2659 | cl::Hidden, |
| 2660 | cl::init(Val: false), |
| 2661 | cl::cat(GenericCategory), |
| 2662 | cl::sub(SubCommand::getAll())}; |
| 2663 | |
| 2664 | VersionPrinterTy OverrideVersionPrinter = nullptr; |
| 2665 | |
| 2666 | std::vector<VersionPrinterTy> ExtraVersionPrinters; |
| 2667 | |
| 2668 | // Define the --version option that prints out the LLVM version for the tool |
| 2669 | VersionPrinter VersionPrinterInstance; |
| 2670 | |
| 2671 | cl::opt<VersionPrinter, true, parser<bool>> VersOp{ |
| 2672 | "version" , cl::desc("Display the version of this program" ), |
| 2673 | cl::location(L&: VersionPrinterInstance), cl::ValueDisallowed, |
| 2674 | cl::cat(GenericCategory)}; |
| 2675 | }; |
| 2676 | } // End anonymous namespace |
| 2677 | |
| 2678 | // Lazy-initialized global instance of options controlling the command-line |
| 2679 | // parser and general handling. |
| 2680 | static ManagedStatic<CommandLineCommonOptions> CommonOptions; |
| 2681 | |
| 2682 | static void initCommonOptions() { |
| 2683 | *CommonOptions; |
| 2684 | initDebugCounterOptions(); |
| 2685 | initGraphWriterOptions(); |
| 2686 | initSignalsOptions(); |
| 2687 | initStatisticOptions(); |
| 2688 | initTimerOptions(); |
| 2689 | initWithColorOptions(); |
| 2690 | initDebugOptions(); |
| 2691 | initRandomSeedOptions(); |
| 2692 | } |
| 2693 | |
| 2694 | OptionCategory &cl::getGeneralCategory() { |
| 2695 | // Initialise the general option category. |
| 2696 | static OptionCategory GeneralCategory{"General options" }; |
| 2697 | return GeneralCategory; |
| 2698 | } |
| 2699 | |
| 2700 | void VersionPrinter::operator=(bool OptionWasSpecified) { |
| 2701 | if (!OptionWasSpecified) |
| 2702 | return; |
| 2703 | |
| 2704 | if (CommonOptions->OverrideVersionPrinter != nullptr) { |
| 2705 | CommonOptions->OverrideVersionPrinter(outs()); |
| 2706 | exit(status: 0); |
| 2707 | } |
| 2708 | print(ExtraPrinters: CommonOptions->ExtraVersionPrinters); |
| 2709 | |
| 2710 | exit(status: 0); |
| 2711 | } |
| 2712 | |
| 2713 | void HelpPrinterWrapper::operator=(bool Value) { |
| 2714 | if (!Value) |
| 2715 | return; |
| 2716 | |
| 2717 | // Decide which printer to invoke. If more than one option category is |
| 2718 | // registered then it is useful to show the categorized help instead of |
| 2719 | // uncategorized help. |
| 2720 | if (GlobalParser->RegisteredOptionCategories.size() > 1) { |
| 2721 | // unhide --help-list option so user can have uncategorized output if they |
| 2722 | // want it. |
| 2723 | CommonOptions->HLOp.setHiddenFlag(NotHidden); |
| 2724 | |
| 2725 | CategorizedPrinter = true; // Invoke categorized printer |
| 2726 | } else { |
| 2727 | UncategorizedPrinter = true; // Invoke uncategorized printer |
| 2728 | } |
| 2729 | } |
| 2730 | |
| 2731 | // Print the value of each option. |
| 2732 | void cl::PrintOptionValues() { GlobalParser->printOptionValues(); } |
| 2733 | |
| 2734 | void CommandLineParser::printOptionValues() { |
| 2735 | if (!CommonOptions->PrintOptions && !CommonOptions->PrintAllOptions) |
| 2736 | return; |
| 2737 | |
| 2738 | SmallVector<std::pair<const char *, Option *>, 128> Opts; |
| 2739 | sortOpts(OptMap&: ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true); |
| 2740 | |
| 2741 | // Compute the maximum argument length... |
| 2742 | size_t MaxArgLen = 0; |
| 2743 | for (const auto &Opt : Opts) |
| 2744 | MaxArgLen = std::max(a: MaxArgLen, b: Opt.second->getOptionWidth()); |
| 2745 | |
| 2746 | for (const auto &Opt : Opts) |
| 2747 | Opt.second->printOptionValue(GlobalWidth: MaxArgLen, Force: CommonOptions->PrintAllOptions); |
| 2748 | } |
| 2749 | |
| 2750 | // Utility function for printing the help message. |
| 2751 | void cl::PrintHelpMessage(bool Hidden, bool Categorized) { |
| 2752 | if (!Hidden && !Categorized) |
| 2753 | CommonOptions->UncategorizedNormalPrinter.printHelp(); |
| 2754 | else if (!Hidden && Categorized) |
| 2755 | CommonOptions->CategorizedNormalPrinter.printHelp(); |
| 2756 | else if (Hidden && !Categorized) |
| 2757 | CommonOptions->UncategorizedHiddenPrinter.printHelp(); |
| 2758 | else |
| 2759 | CommonOptions->CategorizedHiddenPrinter.printHelp(); |
| 2760 | } |
| 2761 | |
| 2762 | ArrayRef<StringRef> cl::getCompilerBuildConfig() { |
| 2763 | static const StringRef Config[] = { |
| 2764 | // Placeholder to ensure the array always has elements, since it's an |
| 2765 | // error to have a zero-sized array. Slice this off before returning. |
| 2766 | "" , |
| 2767 | // Actual compiler build config feature list: |
| 2768 | #if LLVM_IS_DEBUG_BUILD |
| 2769 | "+unoptimized" , |
| 2770 | #endif |
| 2771 | #ifndef NDEBUG |
| 2772 | "+assertions" , |
| 2773 | #endif |
| 2774 | #ifdef EXPENSIVE_CHECKS |
| 2775 | "+expensive-checks" , |
| 2776 | #endif |
| 2777 | #if __has_feature(address_sanitizer) |
| 2778 | "+asan" , |
| 2779 | #endif |
| 2780 | #if __has_feature(dataflow_sanitizer) |
| 2781 | "+dfsan" , |
| 2782 | #endif |
| 2783 | #if __has_feature(hwaddress_sanitizer) |
| 2784 | "+hwasan" , |
| 2785 | #endif |
| 2786 | #if __has_feature(memory_sanitizer) |
| 2787 | "+msan" , |
| 2788 | #endif |
| 2789 | #if __has_feature(thread_sanitizer) |
| 2790 | "+tsan" , |
| 2791 | #endif |
| 2792 | #if __has_feature(undefined_behavior_sanitizer) |
| 2793 | "+ubsan" , |
| 2794 | #endif |
| 2795 | }; |
| 2796 | return ArrayRef(Config).drop_front(N: 1); |
| 2797 | } |
| 2798 | |
| 2799 | // Utility function for printing the build config. |
| 2800 | void cl::printBuildConfig(raw_ostream &OS) { |
| 2801 | #if LLVM_VERSION_PRINTER_SHOW_BUILD_CONFIG |
| 2802 | OS << "Build config: " ; |
| 2803 | llvm::interleaveComma(c: cl::getCompilerBuildConfig(), os&: OS); |
| 2804 | OS << '\n'; |
| 2805 | #endif |
| 2806 | } |
| 2807 | |
| 2808 | /// Utility function for printing version number. |
| 2809 | void cl::PrintVersionMessage() { |
| 2810 | CommonOptions->VersionPrinterInstance.print(ExtraPrinters: CommonOptions->ExtraVersionPrinters); |
| 2811 | } |
| 2812 | |
| 2813 | void cl::SetVersionPrinter(VersionPrinterTy func) { |
| 2814 | CommonOptions->OverrideVersionPrinter = func; |
| 2815 | } |
| 2816 | |
| 2817 | void cl::(VersionPrinterTy func) { |
| 2818 | CommonOptions->ExtraVersionPrinters.push_back(x: func); |
| 2819 | } |
| 2820 | |
| 2821 | OptionsMapTy &cl::getRegisteredOptions(SubCommand &Sub) { |
| 2822 | initCommonOptions(); |
| 2823 | auto &Subs = GlobalParser->RegisteredSubCommands; |
| 2824 | (void)Subs; |
| 2825 | assert(Subs.contains(&Sub)); |
| 2826 | return Sub.OptionsMap; |
| 2827 | } |
| 2828 | |
| 2829 | iterator_range<SmallPtrSet<SubCommand *, 4>::iterator> |
| 2830 | cl::getRegisteredSubcommands() { |
| 2831 | return GlobalParser->getRegisteredSubcommands(); |
| 2832 | } |
| 2833 | |
| 2834 | void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) { |
| 2835 | initCommonOptions(); |
| 2836 | for (auto &I : Sub.OptionsMap) { |
| 2837 | bool Unrelated = true; |
| 2838 | for (auto &Cat : I.second->Categories) { |
| 2839 | if (Cat == &Category || Cat == &CommonOptions->GenericCategory) |
| 2840 | Unrelated = false; |
| 2841 | } |
| 2842 | if (Unrelated) |
| 2843 | I.second->setHiddenFlag(cl::ReallyHidden); |
| 2844 | } |
| 2845 | } |
| 2846 | |
| 2847 | void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories, |
| 2848 | SubCommand &Sub) { |
| 2849 | initCommonOptions(); |
| 2850 | for (auto &I : Sub.OptionsMap) { |
| 2851 | bool Unrelated = true; |
| 2852 | for (auto &Cat : I.second->Categories) { |
| 2853 | if (is_contained(Range&: Categories, Element: Cat) || |
| 2854 | Cat == &CommonOptions->GenericCategory) |
| 2855 | Unrelated = false; |
| 2856 | } |
| 2857 | if (Unrelated) |
| 2858 | I.second->setHiddenFlag(cl::ReallyHidden); |
| 2859 | } |
| 2860 | } |
| 2861 | |
| 2862 | void cl::ResetCommandLineParser() { GlobalParser->reset(); } |
| 2863 | void cl::ResetAllOptionOccurrences() { |
| 2864 | GlobalParser->ResetAllOptionOccurrences(); |
| 2865 | } |
| 2866 | |
| 2867 | void LLVMParseCommandLineOptions(int argc, const char *const *argv, |
| 2868 | const char *Overview) { |
| 2869 | llvm::cl::ParseCommandLineOptions(argc, argv, Overview: StringRef(Overview), |
| 2870 | Errs: &llvm::nulls()); |
| 2871 | } |
| 2872 | |