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