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