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