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