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