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