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