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