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 if (I < (E - 1) && Src[I + 1] == '"') { 878 // Consecutive double-quotes inside a quoted string implies one 879 // double-quote. 880 Token.push_back('"'); 881 I = I + 1; 882 continue; 883 } 884 State = UNQUOTED; 885 continue; 886 } 887 if (C == '\\') { 888 I = parseBackslash(Src, I, Token); 889 continue; 890 } 891 Token.push_back(C); 892 } 893 } 894 // Append the last token after hitting EOF with no whitespace. 895 if (!Token.empty()) 896 NewArgv.push_back(Saver.save(StringRef(Token)).data()); 897 // Mark the end of response files 898 if (MarkEOLs) 899 NewArgv.push_back(nullptr); 900 } 901 902 void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver, 903 SmallVectorImpl<const char *> &NewArgv, 904 bool MarkEOLs) { 905 for (const char *Cur = Source.begin(); Cur != Source.end();) { 906 SmallString<128> Line; 907 // Check for comment line. 908 if (isWhitespace(*Cur)) { 909 while (Cur != Source.end() && isWhitespace(*Cur)) 910 ++Cur; 911 continue; 912 } 913 if (*Cur == '#') { 914 while (Cur != Source.end() && *Cur != '\n') 915 ++Cur; 916 continue; 917 } 918 // Find end of the current line. 919 const char *Start = Cur; 920 for (const char *End = Source.end(); Cur != End; ++Cur) { 921 if (*Cur == '\\') { 922 if (Cur + 1 != End) { 923 ++Cur; 924 if (*Cur == '\n' || 925 (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) { 926 Line.append(Start, Cur - 1); 927 if (*Cur == '\r') 928 ++Cur; 929 Start = Cur + 1; 930 } 931 } 932 } else if (*Cur == '\n') 933 break; 934 } 935 // Tokenize line. 936 Line.append(Start, Cur); 937 cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs); 938 } 939 } 940 941 // It is called byte order marker but the UTF-8 BOM is actually not affected 942 // by the host system's endianness. 943 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) { 944 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf'); 945 } 946 947 static bool ExpandResponseFile(StringRef FName, StringSaver &Saver, 948 TokenizerCallback Tokenizer, 949 SmallVectorImpl<const char *> &NewArgv, 950 bool MarkEOLs, bool RelativeNames) { 951 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr = 952 MemoryBuffer::getFile(FName); 953 if (!MemBufOrErr) 954 return false; 955 MemoryBuffer &MemBuf = *MemBufOrErr.get(); 956 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize()); 957 958 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing. 959 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd()); 960 std::string UTF8Buf; 961 if (hasUTF16ByteOrderMark(BufRef)) { 962 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf)) 963 return false; 964 Str = StringRef(UTF8Buf); 965 } 966 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove 967 // these bytes before parsing. 968 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark 969 else if (hasUTF8ByteOrderMark(BufRef)) 970 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3); 971 972 // Tokenize the contents into NewArgv. 973 Tokenizer(Str, Saver, NewArgv, MarkEOLs); 974 975 // If names of nested response files should be resolved relative to including 976 // file, replace the included response file names with their full paths 977 // obtained by required resolution. 978 if (RelativeNames) 979 for (unsigned I = 0; I < NewArgv.size(); ++I) 980 if (NewArgv[I]) { 981 StringRef Arg = NewArgv[I]; 982 if (Arg.front() == '@') { 983 StringRef FileName = Arg.drop_front(); 984 if (llvm::sys::path::is_relative(FileName)) { 985 SmallString<128> ResponseFile; 986 ResponseFile.append(1, '@'); 987 if (llvm::sys::path::is_relative(FName)) { 988 SmallString<128> curr_dir; 989 llvm::sys::fs::current_path(curr_dir); 990 ResponseFile.append(curr_dir.str()); 991 } 992 llvm::sys::path::append( 993 ResponseFile, llvm::sys::path::parent_path(FName), FileName); 994 NewArgv[I] = Saver.save(ResponseFile.c_str()).data(); 995 } 996 } 997 } 998 999 return true; 1000 } 1001 1002 /// Expand response files on a command line recursively using the given 1003 /// StringSaver and tokenization strategy. 1004 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, 1005 SmallVectorImpl<const char *> &Argv, 1006 bool MarkEOLs, bool RelativeNames) { 1007 unsigned RspFiles = 0; 1008 bool AllExpanded = true; 1009 1010 // Don't cache Argv.size() because it can change. 1011 for (unsigned I = 0; I != Argv.size();) { 1012 const char *Arg = Argv[I]; 1013 // Check if it is an EOL marker 1014 if (Arg == nullptr) { 1015 ++I; 1016 continue; 1017 } 1018 if (Arg[0] != '@') { 1019 ++I; 1020 continue; 1021 } 1022 1023 // If we have too many response files, leave some unexpanded. This avoids 1024 // crashing on self-referential response files. 1025 if (RspFiles++ > 20) 1026 return false; 1027 1028 // Replace this response file argument with the tokenization of its 1029 // contents. Nested response files are expanded in subsequent iterations. 1030 SmallVector<const char *, 0> ExpandedArgv; 1031 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv, 1032 MarkEOLs, RelativeNames)) { 1033 // We couldn't read this file, so we leave it in the argument stream and 1034 // move on. 1035 AllExpanded = false; 1036 ++I; 1037 continue; 1038 } 1039 Argv.erase(Argv.begin() + I); 1040 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end()); 1041 } 1042 return AllExpanded; 1043 } 1044 1045 bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver, 1046 SmallVectorImpl<const char *> &Argv) { 1047 if (!ExpandResponseFile(CfgFile, Saver, cl::tokenizeConfigFile, Argv, 1048 /*MarkEOLs*/ false, /*RelativeNames*/ true)) 1049 return false; 1050 return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv, 1051 /*MarkEOLs*/ false, /*RelativeNames*/ true); 1052 } 1053 1054 /// ParseEnvironmentOptions - An alternative entry point to the 1055 /// CommandLine library, which allows you to read the program's name 1056 /// from the caller (as PROGNAME) and its command-line arguments from 1057 /// an environment variable (whose name is given in ENVVAR). 1058 /// 1059 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar, 1060 const char *Overview) { 1061 // Check args. 1062 assert(progName && "Program name not specified"); 1063 assert(envVar && "Environment variable name missing"); 1064 1065 // Get the environment variable they want us to parse options out of. 1066 llvm::Optional<std::string> envValue = sys::Process::GetEnv(StringRef(envVar)); 1067 if (!envValue) 1068 return; 1069 1070 // Get program's "name", which we wouldn't know without the caller 1071 // telling us. 1072 SmallVector<const char *, 20> newArgv; 1073 BumpPtrAllocator A; 1074 StringSaver Saver(A); 1075 newArgv.push_back(Saver.save(progName).data()); 1076 1077 // Parse the value of the environment variable into a "command line" 1078 // and hand it off to ParseCommandLineOptions(). 1079 TokenizeGNUCommandLine(*envValue, Saver, newArgv); 1080 int newArgc = static_cast<int>(newArgv.size()); 1081 ParseCommandLineOptions(newArgc, &newArgv[0], StringRef(Overview)); 1082 } 1083 1084 bool cl::ParseCommandLineOptions(int argc, const char *const *argv, 1085 StringRef Overview, raw_ostream *Errs, 1086 const char *EnvVar) { 1087 SmallVector<const char *, 20> NewArgv; 1088 BumpPtrAllocator A; 1089 StringSaver Saver(A); 1090 NewArgv.push_back(argv[0]); 1091 1092 // Parse options from environment variable. 1093 if (EnvVar) { 1094 if (llvm::Optional<std::string> EnvValue = 1095 sys::Process::GetEnv(StringRef(EnvVar))) 1096 TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv); 1097 } 1098 1099 // Append options from command line. 1100 for (int I = 1; I < argc; ++I) 1101 NewArgv.push_back(argv[I]); 1102 int NewArgc = static_cast<int>(NewArgv.size()); 1103 1104 // Parse all options. 1105 return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview, 1106 Errs); 1107 } 1108 1109 void CommandLineParser::ResetAllOptionOccurrences() { 1110 // So that we can parse different command lines multiple times in succession 1111 // we reset all option values to look like they have never been seen before. 1112 for (auto SC : RegisteredSubCommands) { 1113 for (auto &O : SC->OptionsMap) 1114 O.second->reset(); 1115 } 1116 } 1117 1118 bool CommandLineParser::ParseCommandLineOptions(int argc, 1119 const char *const *argv, 1120 StringRef Overview, 1121 raw_ostream *Errs) { 1122 assert(hasOptions() && "No options specified!"); 1123 1124 // Expand response files. 1125 SmallVector<const char *, 20> newArgv(argv, argv + argc); 1126 BumpPtrAllocator A; 1127 StringSaver Saver(A); 1128 ExpandResponseFiles(Saver, 1129 Triple(sys::getProcessTriple()).isOSWindows() ? 1130 cl::TokenizeWindowsCommandLine : cl::TokenizeGNUCommandLine, 1131 newArgv); 1132 argv = &newArgv[0]; 1133 argc = static_cast<int>(newArgv.size()); 1134 1135 // Copy the program name into ProgName, making sure not to overflow it. 1136 ProgramName = sys::path::filename(StringRef(argv[0])); 1137 1138 ProgramOverview = Overview; 1139 bool IgnoreErrors = Errs; 1140 if (!Errs) 1141 Errs = &errs(); 1142 bool ErrorParsing = false; 1143 1144 // Check out the positional arguments to collect information about them. 1145 unsigned NumPositionalRequired = 0; 1146 1147 // Determine whether or not there are an unlimited number of positionals 1148 bool HasUnlimitedPositionals = false; 1149 1150 int FirstArg = 1; 1151 SubCommand *ChosenSubCommand = &*TopLevelSubCommand; 1152 if (argc >= 2 && argv[FirstArg][0] != '-') { 1153 // If the first argument specifies a valid subcommand, start processing 1154 // options from the second argument. 1155 ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg])); 1156 if (ChosenSubCommand != &*TopLevelSubCommand) 1157 FirstArg = 2; 1158 } 1159 GlobalParser->ActiveSubCommand = ChosenSubCommand; 1160 1161 assert(ChosenSubCommand); 1162 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt; 1163 auto &PositionalOpts = ChosenSubCommand->PositionalOpts; 1164 auto &SinkOpts = ChosenSubCommand->SinkOpts; 1165 auto &OptionsMap = ChosenSubCommand->OptionsMap; 1166 1167 if (ConsumeAfterOpt) { 1168 assert(PositionalOpts.size() > 0 && 1169 "Cannot specify cl::ConsumeAfter without a positional argument!"); 1170 } 1171 if (!PositionalOpts.empty()) { 1172 1173 // Calculate how many positional values are _required_. 1174 bool UnboundedFound = false; 1175 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { 1176 Option *Opt = PositionalOpts[i]; 1177 if (RequiresValue(Opt)) 1178 ++NumPositionalRequired; 1179 else if (ConsumeAfterOpt) { 1180 // ConsumeAfter cannot be combined with "optional" positional options 1181 // unless there is only one positional argument... 1182 if (PositionalOpts.size() > 1) { 1183 if (!IgnoreErrors) 1184 Opt->error("error - this positional option will never be matched, " 1185 "because it does not Require a value, and a " 1186 "cl::ConsumeAfter option is active!"); 1187 ErrorParsing = true; 1188 } 1189 } else if (UnboundedFound && !Opt->hasArgStr()) { 1190 // This option does not "require" a value... Make sure this option is 1191 // not specified after an option that eats all extra arguments, or this 1192 // one will never get any! 1193 // 1194 if (!IgnoreErrors) 1195 Opt->error("error - option can never match, because " 1196 "another positional argument will match an " 1197 "unbounded number of values, and this option" 1198 " does not require a value!"); 1199 *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr 1200 << "' is all messed up!\n"; 1201 *Errs << PositionalOpts.size(); 1202 ErrorParsing = true; 1203 } 1204 UnboundedFound |= EatsUnboundedNumberOfValues(Opt); 1205 } 1206 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; 1207 } 1208 1209 // PositionalVals - A vector of "positional" arguments we accumulate into 1210 // the process at the end. 1211 // 1212 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals; 1213 1214 // If the program has named positional arguments, and the name has been run 1215 // across, keep track of which positional argument was named. Otherwise put 1216 // the positional args into the PositionalVals list... 1217 Option *ActivePositionalArg = nullptr; 1218 1219 // Loop over all of the arguments... processing them. 1220 bool DashDashFound = false; // Have we read '--'? 1221 for (int i = FirstArg; i < argc; ++i) { 1222 Option *Handler = nullptr; 1223 Option *NearestHandler = nullptr; 1224 std::string NearestHandlerString; 1225 StringRef Value; 1226 StringRef ArgName = ""; 1227 1228 // Check to see if this is a positional argument. This argument is 1229 // considered to be positional if it doesn't start with '-', if it is "-" 1230 // itself, or if we have seen "--" already. 1231 // 1232 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { 1233 // Positional argument! 1234 if (ActivePositionalArg) { 1235 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i); 1236 continue; // We are done! 1237 } 1238 1239 if (!PositionalOpts.empty()) { 1240 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i)); 1241 1242 // All of the positional arguments have been fulfulled, give the rest to 1243 // the consume after option... if it's specified... 1244 // 1245 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) { 1246 for (++i; i < argc; ++i) 1247 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i)); 1248 break; // Handle outside of the argument processing loop... 1249 } 1250 1251 // Delay processing positional arguments until the end... 1252 continue; 1253 } 1254 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 && 1255 !DashDashFound) { 1256 DashDashFound = true; // This is the mythical "--"? 1257 continue; // Don't try to process it as an argument itself. 1258 } else if (ActivePositionalArg && 1259 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) { 1260 // If there is a positional argument eating options, check to see if this 1261 // option is another positional argument. If so, treat it as an argument, 1262 // otherwise feed it to the eating positional. 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 if (!Handler || Handler->getFormattingFlag() != cl::Positional) { 1270 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i); 1271 continue; // We are done! 1272 } 1273 1274 } else { // We start with a '-', must be an argument. 1275 ArgName = StringRef(argv[i] + 1); 1276 // Eat leading dashes. 1277 while (!ArgName.empty() && ArgName[0] == '-') 1278 ArgName = ArgName.substr(1); 1279 1280 Handler = LookupOption(*ChosenSubCommand, ArgName, Value); 1281 1282 // Check to see if this "option" is really a prefixed or grouped argument. 1283 if (!Handler) 1284 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing, 1285 OptionsMap); 1286 1287 // Otherwise, look for the closest available option to report to the user 1288 // in the upcoming error. 1289 if (!Handler && SinkOpts.empty()) 1290 NearestHandler = 1291 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString); 1292 } 1293 1294 if (!Handler) { 1295 if (SinkOpts.empty()) { 1296 *Errs << ProgramName << ": Unknown command line argument '" << argv[i] 1297 << "'. Try: '" << argv[0] << " -help'\n"; 1298 1299 if (NearestHandler) { 1300 // If we know a near match, report it as well. 1301 *Errs << ProgramName << ": Did you mean '-" << NearestHandlerString 1302 << "'?\n"; 1303 } 1304 1305 ErrorParsing = true; 1306 } else { 1307 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(), 1308 E = SinkOpts.end(); 1309 I != E; ++I) 1310 (*I)->addOccurrence(i, "", StringRef(argv[i])); 1311 } 1312 continue; 1313 } 1314 1315 // If this is a named positional argument, just remember that it is the 1316 // active one... 1317 if (Handler->getFormattingFlag() == cl::Positional) { 1318 if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) { 1319 Handler->error("This argument does not take a value.\n" 1320 "\tInstead, it consumes any positional arguments until " 1321 "the next recognized option.", *Errs); 1322 ErrorParsing = true; 1323 } 1324 ActivePositionalArg = Handler; 1325 } 1326 else 1327 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); 1328 } 1329 1330 // Check and handle positional arguments now... 1331 if (NumPositionalRequired > PositionalVals.size()) { 1332 *Errs << ProgramName 1333 << ": Not enough positional command line arguments specified!\n" 1334 << "Must specify at least " << NumPositionalRequired 1335 << " positional argument" << (NumPositionalRequired > 1 ? "s" : "") 1336 << ": See: " << argv[0] << " -help\n"; 1337 1338 ErrorParsing = true; 1339 } else if (!HasUnlimitedPositionals && 1340 PositionalVals.size() > PositionalOpts.size()) { 1341 *Errs << ProgramName << ": Too many positional arguments specified!\n" 1342 << "Can specify at most " << PositionalOpts.size() 1343 << " positional arguments: See: " << argv[0] << " -help\n"; 1344 ErrorParsing = true; 1345 1346 } else if (!ConsumeAfterOpt) { 1347 // Positional args have already been handled if ConsumeAfter is specified. 1348 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size()); 1349 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { 1350 if (RequiresValue(PositionalOpts[i])) { 1351 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, 1352 PositionalVals[ValNo].second); 1353 ValNo++; 1354 --NumPositionalRequired; // We fulfilled our duty... 1355 } 1356 1357 // If we _can_ give this option more arguments, do so now, as long as we 1358 // do not give it values that others need. 'Done' controls whether the 1359 // option even _WANTS_ any more. 1360 // 1361 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; 1362 while (NumVals - ValNo > NumPositionalRequired && !Done) { 1363 switch (PositionalOpts[i]->getNumOccurrencesFlag()) { 1364 case cl::Optional: 1365 Done = true; // Optional arguments want _at most_ one value 1366 LLVM_FALLTHROUGH; 1367 case cl::ZeroOrMore: // Zero or more will take all they can get... 1368 case cl::OneOrMore: // One or more will take all they can get... 1369 ProvidePositionalOption(PositionalOpts[i], 1370 PositionalVals[ValNo].first, 1371 PositionalVals[ValNo].second); 1372 ValNo++; 1373 break; 1374 default: 1375 llvm_unreachable("Internal error, unexpected NumOccurrences flag in " 1376 "positional argument processing!"); 1377 } 1378 } 1379 } 1380 } else { 1381 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); 1382 unsigned ValNo = 0; 1383 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j) 1384 if (RequiresValue(PositionalOpts[j])) { 1385 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j], 1386 PositionalVals[ValNo].first, 1387 PositionalVals[ValNo].second); 1388 ValNo++; 1389 } 1390 1391 // Handle the case where there is just one positional option, and it's 1392 // optional. In this case, we want to give JUST THE FIRST option to the 1393 // positional option and keep the rest for the consume after. The above 1394 // loop would have assigned no values to positional options in this case. 1395 // 1396 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) { 1397 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0], 1398 PositionalVals[ValNo].first, 1399 PositionalVals[ValNo].second); 1400 ValNo++; 1401 } 1402 1403 // Handle over all of the rest of the arguments to the 1404 // cl::ConsumeAfter command line option... 1405 for (; ValNo != PositionalVals.size(); ++ValNo) 1406 ErrorParsing |= 1407 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first, 1408 PositionalVals[ValNo].second); 1409 } 1410 1411 // Loop over args and make sure all required args are specified! 1412 for (const auto &Opt : OptionsMap) { 1413 switch (Opt.second->getNumOccurrencesFlag()) { 1414 case Required: 1415 case OneOrMore: 1416 if (Opt.second->getNumOccurrences() == 0) { 1417 Opt.second->error("must be specified at least once!"); 1418 ErrorParsing = true; 1419 } 1420 LLVM_FALLTHROUGH; 1421 default: 1422 break; 1423 } 1424 } 1425 1426 // Now that we know if -debug is specified, we can use it. 1427 // Note that if ReadResponseFiles == true, this must be done before the 1428 // memory allocated for the expanded command line is free()d below. 1429 LLVM_DEBUG(dbgs() << "Args: "; 1430 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' '; 1431 dbgs() << '\n';); 1432 1433 // Free all of the memory allocated to the map. Command line options may only 1434 // be processed once! 1435 MoreHelp.clear(); 1436 1437 // If we had an error processing our arguments, don't let the program execute 1438 if (ErrorParsing) { 1439 if (!IgnoreErrors) 1440 exit(1); 1441 return false; 1442 } 1443 return true; 1444 } 1445 1446 //===----------------------------------------------------------------------===// 1447 // Option Base class implementation 1448 // 1449 1450 bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) { 1451 if (!ArgName.data()) 1452 ArgName = ArgStr; 1453 if (ArgName.empty()) 1454 Errs << HelpStr; // Be nice for positional arguments 1455 else 1456 Errs << GlobalParser->ProgramName << ": for the -" << ArgName; 1457 1458 Errs << " option: " << Message << "\n"; 1459 return true; 1460 } 1461 1462 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value, 1463 bool MultiArg) { 1464 if (!MultiArg) 1465 NumOccurrences++; // Increment the number of times we have been seen 1466 1467 switch (getNumOccurrencesFlag()) { 1468 case Optional: 1469 if (NumOccurrences > 1) 1470 return error("may only occur zero or one times!", ArgName); 1471 break; 1472 case Required: 1473 if (NumOccurrences > 1) 1474 return error("must occur exactly one time!", ArgName); 1475 LLVM_FALLTHROUGH; 1476 case OneOrMore: 1477 case ZeroOrMore: 1478 case ConsumeAfter: 1479 break; 1480 } 1481 1482 return handleOccurrence(pos, ArgName, Value); 1483 } 1484 1485 // getValueStr - Get the value description string, using "DefaultMsg" if nothing 1486 // has been specified yet. 1487 // 1488 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) { 1489 if (O.ValueStr.empty()) 1490 return DefaultMsg; 1491 return O.ValueStr; 1492 } 1493 1494 static StringRef ArgPrefix = " -"; 1495 static StringRef ArgHelpPrefix = " - "; 1496 static size_t ArgPrefixesSize = ArgPrefix.size() + ArgHelpPrefix.size(); 1497 1498 //===----------------------------------------------------------------------===// 1499 // cl::alias class implementation 1500 // 1501 1502 // Return the width of the option tag for printing... 1503 size_t alias::getOptionWidth() const { return ArgStr.size() + ArgPrefixesSize; } 1504 1505 void Option::printHelpStr(StringRef HelpStr, size_t Indent, 1506 size_t FirstLineIndentedBy) { 1507 assert(Indent >= FirstLineIndentedBy); 1508 std::pair<StringRef, StringRef> Split = HelpStr.split('\n'); 1509 outs().indent(Indent - FirstLineIndentedBy) 1510 << ArgHelpPrefix << Split.first << "\n"; 1511 while (!Split.second.empty()) { 1512 Split = Split.second.split('\n'); 1513 outs().indent(Indent) << Split.first << "\n"; 1514 } 1515 } 1516 1517 // Print out the option for the alias. 1518 void alias::printOptionInfo(size_t GlobalWidth) const { 1519 outs() << ArgPrefix << ArgStr; 1520 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + ArgPrefixesSize); 1521 } 1522 1523 //===----------------------------------------------------------------------===// 1524 // Parser Implementation code... 1525 // 1526 1527 // basic_parser implementation 1528 // 1529 1530 // Return the width of the option tag for printing... 1531 size_t basic_parser_impl::getOptionWidth(const Option &O) const { 1532 size_t Len = O.ArgStr.size(); 1533 auto ValName = getValueName(); 1534 if (!ValName.empty()) { 1535 size_t FormattingLen = 3; 1536 if (O.getMiscFlags() & PositionalEatsArgs) 1537 FormattingLen = 6; 1538 Len += getValueStr(O, ValName).size() + FormattingLen; 1539 } 1540 1541 return Len + ArgPrefixesSize; 1542 } 1543 1544 // printOptionInfo - Print out information about this option. The 1545 // to-be-maintained width is specified. 1546 // 1547 void basic_parser_impl::printOptionInfo(const Option &O, 1548 size_t GlobalWidth) const { 1549 outs() << ArgPrefix << O.ArgStr; 1550 1551 auto ValName = getValueName(); 1552 if (!ValName.empty()) { 1553 if (O.getMiscFlags() & PositionalEatsArgs) { 1554 outs() << " <" << getValueStr(O, ValName) << ">..."; 1555 } else { 1556 outs() << "=<" << getValueStr(O, ValName) << '>'; 1557 } 1558 } 1559 1560 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O)); 1561 } 1562 1563 void basic_parser_impl::printOptionName(const Option &O, 1564 size_t GlobalWidth) const { 1565 outs() << ArgPrefix << O.ArgStr; 1566 outs().indent(GlobalWidth - O.ArgStr.size()); 1567 } 1568 1569 // parser<bool> implementation 1570 // 1571 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg, 1572 bool &Value) { 1573 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 1574 Arg == "1") { 1575 Value = true; 1576 return false; 1577 } 1578 1579 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 1580 Value = false; 1581 return false; 1582 } 1583 return O.error("'" + Arg + 1584 "' is invalid value for boolean argument! Try 0 or 1"); 1585 } 1586 1587 // parser<boolOrDefault> implementation 1588 // 1589 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg, 1590 boolOrDefault &Value) { 1591 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 1592 Arg == "1") { 1593 Value = BOU_TRUE; 1594 return false; 1595 } 1596 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 1597 Value = BOU_FALSE; 1598 return false; 1599 } 1600 1601 return O.error("'" + Arg + 1602 "' is invalid value for boolean argument! Try 0 or 1"); 1603 } 1604 1605 // parser<int> implementation 1606 // 1607 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg, 1608 int &Value) { 1609 if (Arg.getAsInteger(0, Value)) 1610 return O.error("'" + Arg + "' value invalid for integer argument!"); 1611 return false; 1612 } 1613 1614 // parser<unsigned> implementation 1615 // 1616 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg, 1617 unsigned &Value) { 1618 1619 if (Arg.getAsInteger(0, Value)) 1620 return O.error("'" + Arg + "' value invalid for uint argument!"); 1621 return false; 1622 } 1623 1624 // parser<unsigned long long> implementation 1625 // 1626 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName, 1627 StringRef Arg, 1628 unsigned long long &Value) { 1629 1630 if (Arg.getAsInteger(0, Value)) 1631 return O.error("'" + Arg + "' value invalid for uint argument!"); 1632 return false; 1633 } 1634 1635 // parser<double>/parser<float> implementation 1636 // 1637 static bool parseDouble(Option &O, StringRef Arg, double &Value) { 1638 if (to_float(Arg, Value)) 1639 return false; 1640 return O.error("'" + Arg + "' value invalid for floating point argument!"); 1641 } 1642 1643 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg, 1644 double &Val) { 1645 return parseDouble(O, Arg, Val); 1646 } 1647 1648 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg, 1649 float &Val) { 1650 double dVal; 1651 if (parseDouble(O, Arg, dVal)) 1652 return true; 1653 Val = (float)dVal; 1654 return false; 1655 } 1656 1657 // generic_parser_base implementation 1658 // 1659 1660 // findOption - Return the option number corresponding to the specified 1661 // argument string. If the option is not found, getNumOptions() is returned. 1662 // 1663 unsigned generic_parser_base::findOption(StringRef Name) { 1664 unsigned e = getNumOptions(); 1665 1666 for (unsigned i = 0; i != e; ++i) { 1667 if (getOption(i) == Name) 1668 return i; 1669 } 1670 return e; 1671 } 1672 1673 static StringRef EqValue = "=<value>"; 1674 static StringRef EmptyOption = "<empty>"; 1675 static StringRef OptionPrefix = " ="; 1676 static size_t OptionPrefixesSize = OptionPrefix.size() + ArgHelpPrefix.size(); 1677 1678 static bool shouldPrintOption(StringRef Name, StringRef Description, 1679 const Option &O) { 1680 return O.getValueExpectedFlag() != ValueOptional || !Name.empty() || 1681 !Description.empty(); 1682 } 1683 1684 // Return the width of the option tag for printing... 1685 size_t generic_parser_base::getOptionWidth(const Option &O) const { 1686 if (O.hasArgStr()) { 1687 size_t Size = O.ArgStr.size() + ArgPrefixesSize + EqValue.size(); 1688 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1689 StringRef Name = getOption(i); 1690 if (!shouldPrintOption(Name, getDescription(i), O)) 1691 continue; 1692 size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size(); 1693 Size = std::max(Size, NameSize + OptionPrefixesSize); 1694 } 1695 return Size; 1696 } else { 1697 size_t BaseSize = 0; 1698 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1699 BaseSize = std::max(BaseSize, getOption(i).size() + 8); 1700 return BaseSize; 1701 } 1702 } 1703 1704 // printOptionInfo - Print out information about this option. The 1705 // to-be-maintained width is specified. 1706 // 1707 void generic_parser_base::printOptionInfo(const Option &O, 1708 size_t GlobalWidth) const { 1709 if (O.hasArgStr()) { 1710 // When the value is optional, first print a line just describing the 1711 // option without values. 1712 if (O.getValueExpectedFlag() == ValueOptional) { 1713 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1714 if (getOption(i).empty()) { 1715 outs() << ArgPrefix << O.ArgStr; 1716 Option::printHelpStr(O.HelpStr, GlobalWidth, 1717 O.ArgStr.size() + ArgPrefixesSize); 1718 break; 1719 } 1720 } 1721 } 1722 1723 outs() << ArgPrefix << O.ArgStr << EqValue; 1724 Option::printHelpStr(O.HelpStr, GlobalWidth, 1725 O.ArgStr.size() + EqValue.size() + ArgPrefixesSize); 1726 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1727 StringRef OptionName = getOption(i); 1728 StringRef Description = getDescription(i); 1729 if (!shouldPrintOption(OptionName, Description, O)) 1730 continue; 1731 assert(GlobalWidth >= OptionName.size() + OptionPrefixesSize); 1732 size_t NumSpaces = GlobalWidth - OptionName.size() - OptionPrefixesSize; 1733 outs() << OptionPrefix << OptionName; 1734 if (OptionName.empty()) { 1735 outs() << EmptyOption; 1736 assert(NumSpaces >= EmptyOption.size()); 1737 NumSpaces -= EmptyOption.size(); 1738 } 1739 if (!Description.empty()) 1740 outs().indent(NumSpaces) << ArgHelpPrefix << " " << Description; 1741 outs() << '\n'; 1742 } 1743 } else { 1744 if (!O.HelpStr.empty()) 1745 outs() << " " << O.HelpStr << '\n'; 1746 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1747 auto Option = getOption(i); 1748 outs() << " -" << Option; 1749 Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8); 1750 } 1751 } 1752 } 1753 1754 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff 1755 1756 // printGenericOptionDiff - Print the value of this option and it's default. 1757 // 1758 // "Generic" options have each value mapped to a name. 1759 void generic_parser_base::printGenericOptionDiff( 1760 const Option &O, const GenericOptionValue &Value, 1761 const GenericOptionValue &Default, size_t GlobalWidth) const { 1762 outs() << " -" << O.ArgStr; 1763 outs().indent(GlobalWidth - O.ArgStr.size()); 1764 1765 unsigned NumOpts = getNumOptions(); 1766 for (unsigned i = 0; i != NumOpts; ++i) { 1767 if (Value.compare(getOptionValue(i))) 1768 continue; 1769 1770 outs() << "= " << getOption(i); 1771 size_t L = getOption(i).size(); 1772 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0; 1773 outs().indent(NumSpaces) << " (default: "; 1774 for (unsigned j = 0; j != NumOpts; ++j) { 1775 if (Default.compare(getOptionValue(j))) 1776 continue; 1777 outs() << getOption(j); 1778 break; 1779 } 1780 outs() << ")\n"; 1781 return; 1782 } 1783 outs() << "= *unknown option value*\n"; 1784 } 1785 1786 // printOptionDiff - Specializations for printing basic value types. 1787 // 1788 #define PRINT_OPT_DIFF(T) \ 1789 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \ 1790 size_t GlobalWidth) const { \ 1791 printOptionName(O, GlobalWidth); \ 1792 std::string Str; \ 1793 { \ 1794 raw_string_ostream SS(Str); \ 1795 SS << V; \ 1796 } \ 1797 outs() << "= " << Str; \ 1798 size_t NumSpaces = \ 1799 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \ 1800 outs().indent(NumSpaces) << " (default: "; \ 1801 if (D.hasValue()) \ 1802 outs() << D.getValue(); \ 1803 else \ 1804 outs() << "*no default*"; \ 1805 outs() << ")\n"; \ 1806 } 1807 1808 PRINT_OPT_DIFF(bool) 1809 PRINT_OPT_DIFF(boolOrDefault) 1810 PRINT_OPT_DIFF(int) 1811 PRINT_OPT_DIFF(unsigned) 1812 PRINT_OPT_DIFF(unsigned long long) 1813 PRINT_OPT_DIFF(double) 1814 PRINT_OPT_DIFF(float) 1815 PRINT_OPT_DIFF(char) 1816 1817 void parser<std::string>::printOptionDiff(const Option &O, StringRef V, 1818 const OptionValue<std::string> &D, 1819 size_t GlobalWidth) const { 1820 printOptionName(O, GlobalWidth); 1821 outs() << "= " << V; 1822 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0; 1823 outs().indent(NumSpaces) << " (default: "; 1824 if (D.hasValue()) 1825 outs() << D.getValue(); 1826 else 1827 outs() << "*no default*"; 1828 outs() << ")\n"; 1829 } 1830 1831 // Print a placeholder for options that don't yet support printOptionDiff(). 1832 void basic_parser_impl::printOptionNoValue(const Option &O, 1833 size_t GlobalWidth) const { 1834 printOptionName(O, GlobalWidth); 1835 outs() << "= *cannot print option value*\n"; 1836 } 1837 1838 //===----------------------------------------------------------------------===// 1839 // -help and -help-hidden option implementation 1840 // 1841 1842 static int OptNameCompare(const std::pair<const char *, Option *> *LHS, 1843 const std::pair<const char *, Option *> *RHS) { 1844 return strcmp(LHS->first, RHS->first); 1845 } 1846 1847 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS, 1848 const std::pair<const char *, SubCommand *> *RHS) { 1849 return strcmp(LHS->first, RHS->first); 1850 } 1851 1852 // Copy Options into a vector so we can sort them as we like. 1853 static void sortOpts(StringMap<Option *> &OptMap, 1854 SmallVectorImpl<std::pair<const char *, Option *>> &Opts, 1855 bool ShowHidden) { 1856 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection. 1857 1858 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end(); 1859 I != E; ++I) { 1860 // Ignore really-hidden options. 1861 if (I->second->getOptionHiddenFlag() == ReallyHidden) 1862 continue; 1863 1864 // Unless showhidden is set, ignore hidden flags. 1865 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden) 1866 continue; 1867 1868 // If we've already seen this option, don't add it to the list again. 1869 if (!OptionSet.insert(I->second).second) 1870 continue; 1871 1872 Opts.push_back( 1873 std::pair<const char *, Option *>(I->getKey().data(), I->second)); 1874 } 1875 1876 // Sort the options list alphabetically. 1877 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare); 1878 } 1879 1880 static void 1881 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap, 1882 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) { 1883 for (const auto &S : SubMap) { 1884 if (S->getName().empty()) 1885 continue; 1886 Subs.push_back(std::make_pair(S->getName().data(), S)); 1887 } 1888 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare); 1889 } 1890 1891 namespace { 1892 1893 class HelpPrinter { 1894 protected: 1895 const bool ShowHidden; 1896 typedef SmallVector<std::pair<const char *, Option *>, 128> 1897 StrOptionPairVector; 1898 typedef SmallVector<std::pair<const char *, SubCommand *>, 128> 1899 StrSubCommandPairVector; 1900 // Print the options. Opts is assumed to be alphabetically sorted. 1901 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) { 1902 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1903 Opts[i].second->printOptionInfo(MaxArgLen); 1904 } 1905 1906 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) { 1907 for (const auto &S : Subs) { 1908 outs() << " " << S.first; 1909 if (!S.second->getDescription().empty()) { 1910 outs().indent(MaxSubLen - strlen(S.first)); 1911 outs() << " - " << S.second->getDescription(); 1912 } 1913 outs() << "\n"; 1914 } 1915 } 1916 1917 public: 1918 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {} 1919 virtual ~HelpPrinter() {} 1920 1921 // Invoke the printer. 1922 void operator=(bool Value) { 1923 if (!Value) 1924 return; 1925 printHelp(); 1926 1927 // Halt the program since help information was printed 1928 exit(0); 1929 } 1930 1931 void printHelp() { 1932 SubCommand *Sub = GlobalParser->getActiveSubCommand(); 1933 auto &OptionsMap = Sub->OptionsMap; 1934 auto &PositionalOpts = Sub->PositionalOpts; 1935 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt; 1936 1937 StrOptionPairVector Opts; 1938 sortOpts(OptionsMap, Opts, ShowHidden); 1939 1940 StrSubCommandPairVector Subs; 1941 sortSubCommands(GlobalParser->RegisteredSubCommands, Subs); 1942 1943 if (!GlobalParser->ProgramOverview.empty()) 1944 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n"; 1945 1946 if (Sub == &*TopLevelSubCommand) { 1947 outs() << "USAGE: " << GlobalParser->ProgramName; 1948 if (Subs.size() > 2) 1949 outs() << " [subcommand]"; 1950 outs() << " [options]"; 1951 } else { 1952 if (!Sub->getDescription().empty()) { 1953 outs() << "SUBCOMMAND '" << Sub->getName() 1954 << "': " << Sub->getDescription() << "\n\n"; 1955 } 1956 outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName() 1957 << " [options]"; 1958 } 1959 1960 for (auto Opt : PositionalOpts) { 1961 if (Opt->hasArgStr()) 1962 outs() << " --" << Opt->ArgStr; 1963 outs() << " " << Opt->HelpStr; 1964 } 1965 1966 // Print the consume after option info if it exists... 1967 if (ConsumeAfterOpt) 1968 outs() << " " << ConsumeAfterOpt->HelpStr; 1969 1970 if (Sub == &*TopLevelSubCommand && !Subs.empty()) { 1971 // Compute the maximum subcommand length... 1972 size_t MaxSubLen = 0; 1973 for (size_t i = 0, e = Subs.size(); i != e; ++i) 1974 MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first)); 1975 1976 outs() << "\n\n"; 1977 outs() << "SUBCOMMANDS:\n\n"; 1978 printSubCommands(Subs, MaxSubLen); 1979 outs() << "\n"; 1980 outs() << " Type \"" << GlobalParser->ProgramName 1981 << " <subcommand> -help\" to get more help on a specific " 1982 "subcommand"; 1983 } 1984 1985 outs() << "\n\n"; 1986 1987 // Compute the maximum argument length... 1988 size_t MaxArgLen = 0; 1989 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1990 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1991 1992 outs() << "OPTIONS:\n"; 1993 printOptions(Opts, MaxArgLen); 1994 1995 // Print any extra help the user has declared. 1996 for (auto I : GlobalParser->MoreHelp) 1997 outs() << I; 1998 GlobalParser->MoreHelp.clear(); 1999 } 2000 }; 2001 2002 class CategorizedHelpPrinter : public HelpPrinter { 2003 public: 2004 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {} 2005 2006 // Helper function for printOptions(). 2007 // It shall return a negative value if A's name should be lexicographically 2008 // ordered before B's name. It returns a value greater than zero if B's name 2009 // should be ordered before A's name, and it returns 0 otherwise. 2010 static int OptionCategoryCompare(OptionCategory *const *A, 2011 OptionCategory *const *B) { 2012 return (*A)->getName().compare((*B)->getName()); 2013 } 2014 2015 // Make sure we inherit our base class's operator=() 2016 using HelpPrinter::operator=; 2017 2018 protected: 2019 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override { 2020 std::vector<OptionCategory *> SortedCategories; 2021 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions; 2022 2023 // Collect registered option categories into vector in preparation for 2024 // sorting. 2025 for (auto I = GlobalParser->RegisteredOptionCategories.begin(), 2026 E = GlobalParser->RegisteredOptionCategories.end(); 2027 I != E; ++I) { 2028 SortedCategories.push_back(*I); 2029 } 2030 2031 // Sort the different option categories alphabetically. 2032 assert(SortedCategories.size() > 0 && "No option categories registered!"); 2033 array_pod_sort(SortedCategories.begin(), SortedCategories.end(), 2034 OptionCategoryCompare); 2035 2036 // Create map to empty vectors. 2037 for (std::vector<OptionCategory *>::const_iterator 2038 I = SortedCategories.begin(), 2039 E = SortedCategories.end(); 2040 I != E; ++I) 2041 CategorizedOptions[*I] = std::vector<Option *>(); 2042 2043 // Walk through pre-sorted options and assign into categories. 2044 // Because the options are already alphabetically sorted the 2045 // options within categories will also be alphabetically sorted. 2046 for (size_t I = 0, E = Opts.size(); I != E; ++I) { 2047 Option *Opt = Opts[I].second; 2048 assert(CategorizedOptions.count(Opt->Category) > 0 && 2049 "Option has an unregistered category"); 2050 CategorizedOptions[Opt->Category].push_back(Opt); 2051 } 2052 2053 // Now do printing. 2054 for (std::vector<OptionCategory *>::const_iterator 2055 Category = SortedCategories.begin(), 2056 E = SortedCategories.end(); 2057 Category != E; ++Category) { 2058 // Hide empty categories for -help, but show for -help-hidden. 2059 const auto &CategoryOptions = CategorizedOptions[*Category]; 2060 bool IsEmptyCategory = CategoryOptions.empty(); 2061 if (!ShowHidden && IsEmptyCategory) 2062 continue; 2063 2064 // Print category information. 2065 outs() << "\n"; 2066 outs() << (*Category)->getName() << ":\n"; 2067 2068 // Check if description is set. 2069 if (!(*Category)->getDescription().empty()) 2070 outs() << (*Category)->getDescription() << "\n\n"; 2071 else 2072 outs() << "\n"; 2073 2074 // When using -help-hidden explicitly state if the category has no 2075 // options associated with it. 2076 if (IsEmptyCategory) { 2077 outs() << " This option category has no options.\n"; 2078 continue; 2079 } 2080 // Loop over the options in the category and print. 2081 for (const Option *Opt : CategoryOptions) 2082 Opt->printOptionInfo(MaxArgLen); 2083 } 2084 } 2085 }; 2086 2087 // This wraps the Uncategorizing and Categorizing printers and decides 2088 // at run time which should be invoked. 2089 class HelpPrinterWrapper { 2090 private: 2091 HelpPrinter &UncategorizedPrinter; 2092 CategorizedHelpPrinter &CategorizedPrinter; 2093 2094 public: 2095 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter, 2096 CategorizedHelpPrinter &CategorizedPrinter) 2097 : UncategorizedPrinter(UncategorizedPrinter), 2098 CategorizedPrinter(CategorizedPrinter) {} 2099 2100 // Invoke the printer. 2101 void operator=(bool Value); 2102 }; 2103 2104 } // End anonymous namespace 2105 2106 // Declare the four HelpPrinter instances that are used to print out help, or 2107 // help-hidden as an uncategorized list or in categories. 2108 static HelpPrinter UncategorizedNormalPrinter(false); 2109 static HelpPrinter UncategorizedHiddenPrinter(true); 2110 static CategorizedHelpPrinter CategorizedNormalPrinter(false); 2111 static CategorizedHelpPrinter CategorizedHiddenPrinter(true); 2112 2113 // Declare HelpPrinter wrappers that will decide whether or not to invoke 2114 // a categorizing help printer 2115 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter, 2116 CategorizedNormalPrinter); 2117 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter, 2118 CategorizedHiddenPrinter); 2119 2120 // Define a category for generic options that all tools should have. 2121 static cl::OptionCategory GenericCategory("Generic Options"); 2122 2123 // Define uncategorized help printers. 2124 // -help-list is hidden by default because if Option categories are being used 2125 // then -help behaves the same as -help-list. 2126 static cl::opt<HelpPrinter, true, parser<bool>> HLOp( 2127 "help-list", 2128 cl::desc("Display list of available options (-help-list-hidden for more)"), 2129 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed, 2130 cl::cat(GenericCategory), cl::sub(*AllSubCommands)); 2131 2132 static cl::opt<HelpPrinter, true, parser<bool>> 2133 HLHOp("help-list-hidden", cl::desc("Display list of all available options"), 2134 cl::location(UncategorizedHiddenPrinter), cl::Hidden, 2135 cl::ValueDisallowed, cl::cat(GenericCategory), 2136 cl::sub(*AllSubCommands)); 2137 2138 // Define uncategorized/categorized help printers. These printers change their 2139 // behaviour at runtime depending on whether one or more Option categories have 2140 // been declared. 2141 static cl::opt<HelpPrinterWrapper, true, parser<bool>> 2142 HOp("help", cl::desc("Display available options (-help-hidden for more)"), 2143 cl::location(WrappedNormalPrinter), cl::ValueDisallowed, 2144 cl::cat(GenericCategory), cl::sub(*AllSubCommands)); 2145 2146 static cl::opt<HelpPrinterWrapper, true, parser<bool>> 2147 HHOp("help-hidden", cl::desc("Display all available options"), 2148 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed, 2149 cl::cat(GenericCategory), cl::sub(*AllSubCommands)); 2150 2151 static cl::opt<bool> PrintOptions( 2152 "print-options", 2153 cl::desc("Print non-default options after command line parsing"), 2154 cl::Hidden, cl::init(false), cl::cat(GenericCategory), 2155 cl::sub(*AllSubCommands)); 2156 2157 static cl::opt<bool> PrintAllOptions( 2158 "print-all-options", 2159 cl::desc("Print all option values after command line parsing"), cl::Hidden, 2160 cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands)); 2161 2162 void HelpPrinterWrapper::operator=(bool Value) { 2163 if (!Value) 2164 return; 2165 2166 // Decide which printer to invoke. If more than one option category is 2167 // registered then it is useful to show the categorized help instead of 2168 // uncategorized help. 2169 if (GlobalParser->RegisteredOptionCategories.size() > 1) { 2170 // unhide -help-list option so user can have uncategorized output if they 2171 // want it. 2172 HLOp.setHiddenFlag(NotHidden); 2173 2174 CategorizedPrinter = true; // Invoke categorized printer 2175 } else 2176 UncategorizedPrinter = true; // Invoke uncategorized printer 2177 } 2178 2179 // Print the value of each option. 2180 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); } 2181 2182 void CommandLineParser::printOptionValues() { 2183 if (!PrintOptions && !PrintAllOptions) 2184 return; 2185 2186 SmallVector<std::pair<const char *, Option *>, 128> Opts; 2187 sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true); 2188 2189 // Compute the maximum argument length... 2190 size_t MaxArgLen = 0; 2191 for (size_t i = 0, e = Opts.size(); i != e; ++i) 2192 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 2193 2194 for (size_t i = 0, e = Opts.size(); i != e; ++i) 2195 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions); 2196 } 2197 2198 static VersionPrinterTy OverrideVersionPrinter = nullptr; 2199 2200 static std::vector<VersionPrinterTy> *ExtraVersionPrinters = nullptr; 2201 2202 namespace { 2203 class VersionPrinter { 2204 public: 2205 void print() { 2206 raw_ostream &OS = outs(); 2207 #ifdef PACKAGE_VENDOR 2208 OS << PACKAGE_VENDOR << " "; 2209 #else 2210 OS << "LLVM (http://llvm.org/):\n "; 2211 #endif 2212 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION; 2213 #ifdef LLVM_VERSION_INFO 2214 OS << " " << LLVM_VERSION_INFO; 2215 #endif 2216 OS << "\n "; 2217 #ifndef __OPTIMIZE__ 2218 OS << "DEBUG build"; 2219 #else 2220 OS << "Optimized build"; 2221 #endif 2222 #ifndef NDEBUG 2223 OS << " with assertions"; 2224 #endif 2225 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO 2226 std::string CPU = sys::getHostCPUName(); 2227 if (CPU == "generic") 2228 CPU = "(unknown)"; 2229 OS << ".\n" 2230 << " Default target: " << sys::getDefaultTargetTriple() << '\n' 2231 << " Host CPU: " << CPU; 2232 #endif 2233 OS << '\n'; 2234 } 2235 void operator=(bool OptionWasSpecified) { 2236 if (!OptionWasSpecified) 2237 return; 2238 2239 if (OverrideVersionPrinter != nullptr) { 2240 OverrideVersionPrinter(outs()); 2241 exit(0); 2242 } 2243 print(); 2244 2245 // Iterate over any registered extra printers and call them to add further 2246 // information. 2247 if (ExtraVersionPrinters != nullptr) { 2248 outs() << '\n'; 2249 for (auto I : *ExtraVersionPrinters) 2250 I(outs()); 2251 } 2252 2253 exit(0); 2254 } 2255 }; 2256 } // End anonymous namespace 2257 2258 // Define the --version option that prints out the LLVM version for the tool 2259 static VersionPrinter VersionPrinterInstance; 2260 2261 static cl::opt<VersionPrinter, true, parser<bool>> 2262 VersOp("version", cl::desc("Display the version of this program"), 2263 cl::location(VersionPrinterInstance), cl::ValueDisallowed, 2264 cl::cat(GenericCategory)); 2265 2266 // Utility function for printing the help message. 2267 void cl::PrintHelpMessage(bool Hidden, bool Categorized) { 2268 if (!Hidden && !Categorized) 2269 UncategorizedNormalPrinter.printHelp(); 2270 else if (!Hidden && Categorized) 2271 CategorizedNormalPrinter.printHelp(); 2272 else if (Hidden && !Categorized) 2273 UncategorizedHiddenPrinter.printHelp(); 2274 else 2275 CategorizedHiddenPrinter.printHelp(); 2276 } 2277 2278 /// Utility function for printing version number. 2279 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); } 2280 2281 void cl::SetVersionPrinter(VersionPrinterTy func) { OverrideVersionPrinter = func; } 2282 2283 void cl::AddExtraVersionPrinter(VersionPrinterTy func) { 2284 if (!ExtraVersionPrinters) 2285 ExtraVersionPrinters = new std::vector<VersionPrinterTy>; 2286 2287 ExtraVersionPrinters->push_back(func); 2288 } 2289 2290 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) { 2291 auto &Subs = GlobalParser->RegisteredSubCommands; 2292 (void)Subs; 2293 assert(is_contained(Subs, &Sub)); 2294 return Sub.OptionsMap; 2295 } 2296 2297 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator> 2298 cl::getRegisteredSubcommands() { 2299 return GlobalParser->getRegisteredSubcommands(); 2300 } 2301 2302 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) { 2303 for (auto &I : Sub.OptionsMap) { 2304 if (I.second->Category != &Category && 2305 I.second->Category != &GenericCategory) 2306 I.second->setHiddenFlag(cl::ReallyHidden); 2307 } 2308 } 2309 2310 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories, 2311 SubCommand &Sub) { 2312 auto CategoriesBegin = Categories.begin(); 2313 auto CategoriesEnd = Categories.end(); 2314 for (auto &I : Sub.OptionsMap) { 2315 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) == 2316 CategoriesEnd && 2317 I.second->Category != &GenericCategory) 2318 I.second->setHiddenFlag(cl::ReallyHidden); 2319 } 2320 } 2321 2322 void cl::ResetCommandLineParser() { GlobalParser->reset(); } 2323 void cl::ResetAllOptionOccurrences() { 2324 GlobalParser->ResetAllOptionOccurrences(); 2325 } 2326 2327 void LLVMParseCommandLineOptions(int argc, const char *const *argv, 2328 const char *Overview) { 2329 llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview), 2330 &llvm::nulls()); 2331 } 2332