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