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