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