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