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