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