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