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