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