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