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 } 76 } // end namespace llvm::cl 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 (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(StringRef(Token)).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(StringRef(Token)).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, llvm::vfs::FileSystem &FS, 1142 llvm::Optional<llvm::StringRef> CurrentDir) { 1143 bool AllExpanded = true; 1144 struct ResponseFileRecord { 1145 std::string File; 1146 size_t End; 1147 }; 1148 1149 // To detect recursive response files, we maintain a stack of files and the 1150 // position of the last argument in the file. This position is updated 1151 // dynamically as we recursively expand files. 1152 SmallVector<ResponseFileRecord, 3> FileStack; 1153 1154 // Push a dummy entry that represents the initial command line, removing 1155 // the need to check for an empty list. 1156 FileStack.push_back({"", Argv.size()}); 1157 1158 // Don't cache Argv.size() because it can change. 1159 for (unsigned I = 0; I != Argv.size();) { 1160 while (I == FileStack.back().End) { 1161 // Passing the end of a file's argument list, so we can remove it from the 1162 // stack. 1163 FileStack.pop_back(); 1164 } 1165 1166 const char *Arg = Argv[I]; 1167 // Check if it is an EOL marker 1168 if (Arg == nullptr) { 1169 ++I; 1170 continue; 1171 } 1172 1173 if (Arg[0] != '@') { 1174 ++I; 1175 continue; 1176 } 1177 1178 const char *FName = Arg + 1; 1179 // Note that CurrentDir is only used for top-level rsp files, the rest will 1180 // always have an absolute path deduced from the containing file. 1181 SmallString<128> CurrDir; 1182 if (llvm::sys::path::is_relative(FName)) { 1183 if (!CurrentDir) 1184 llvm::sys::fs::current_path(CurrDir); 1185 else 1186 CurrDir = *CurrentDir; 1187 llvm::sys::path::append(CurrDir, FName); 1188 FName = CurrDir.c_str(); 1189 } 1190 auto IsEquivalent = [FName, &FS](const ResponseFileRecord &RFile) { 1191 llvm::ErrorOr<llvm::vfs::Status> LHS = FS.status(FName); 1192 if (!LHS) { 1193 // TODO: The error should be propagated up the stack. 1194 llvm::consumeError(llvm::errorCodeToError(LHS.getError())); 1195 return false; 1196 } 1197 llvm::ErrorOr<llvm::vfs::Status> RHS = FS.status(RFile.File); 1198 if (!RHS) { 1199 // TODO: The error should be propagated up the stack. 1200 llvm::consumeError(llvm::errorCodeToError(RHS.getError())); 1201 return false; 1202 } 1203 return LHS->equivalent(*RHS); 1204 }; 1205 1206 // Check for recursive response files. 1207 if (any_of(drop_begin(FileStack), IsEquivalent)) { 1208 // This file is recursive, so we leave it in the argument stream and 1209 // move on. 1210 AllExpanded = false; 1211 ++I; 1212 continue; 1213 } 1214 1215 // Replace this response file argument with the tokenization of its 1216 // contents. Nested response files are expanded in subsequent iterations. 1217 SmallVector<const char *, 0> ExpandedArgv; 1218 if (llvm::Error Err = 1219 ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs, 1220 RelativeNames, FS)) { 1221 // We couldn't read this file, so we leave it in the argument stream and 1222 // move on. 1223 // TODO: The error should be propagated up the stack. 1224 llvm::consumeError(std::move(Err)); 1225 AllExpanded = false; 1226 ++I; 1227 continue; 1228 } 1229 1230 for (ResponseFileRecord &Record : FileStack) { 1231 // Increase the end of all active records by the number of newly expanded 1232 // arguments, minus the response file itself. 1233 Record.End += ExpandedArgv.size() - 1; 1234 } 1235 1236 FileStack.push_back({FName, I + ExpandedArgv.size()}); 1237 Argv.erase(Argv.begin() + I); 1238 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end()); 1239 } 1240 1241 // If successful, the top of the file stack will mark the end of the Argv 1242 // stream. A failure here indicates a bug in the stack popping logic above. 1243 // Note that FileStack may have more than one element at this point because we 1244 // don't have a chance to pop the stack when encountering recursive files at 1245 // the end of the stream, so seeing that doesn't indicate a bug. 1246 assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End); 1247 return AllExpanded; 1248 } 1249 1250 bool cl::expandResponseFiles(int Argc, const char *const *Argv, 1251 const char *EnvVar, StringSaver &Saver, 1252 SmallVectorImpl<const char *> &NewArgv) { 1253 auto Tokenize = Triple(sys::getProcessTriple()).isOSWindows() 1254 ? cl::TokenizeWindowsCommandLine 1255 : cl::TokenizeGNUCommandLine; 1256 // The environment variable specifies initial options. 1257 if (EnvVar) 1258 if (llvm::Optional<std::string> EnvValue = sys::Process::GetEnv(EnvVar)) 1259 Tokenize(*EnvValue, Saver, NewArgv, /*MarkEOLs=*/false); 1260 1261 // Command line options can override the environment variable. 1262 NewArgv.append(Argv + 1, Argv + Argc); 1263 return ExpandResponseFiles(Saver, Tokenize, NewArgv); 1264 } 1265 1266 bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver, 1267 SmallVectorImpl<const char *> &Argv) { 1268 SmallString<128> AbsPath; 1269 if (sys::path::is_relative(CfgFile)) { 1270 llvm::sys::fs::current_path(AbsPath); 1271 llvm::sys::path::append(AbsPath, CfgFile); 1272 CfgFile = AbsPath.str(); 1273 } 1274 if (llvm::Error Err = 1275 ExpandResponseFile(CfgFile, Saver, cl::tokenizeConfigFile, Argv, 1276 /*MarkEOLs*/ false, /*RelativeNames*/ true, 1277 *llvm::vfs::getRealFileSystem())) { 1278 // TODO: The error should be propagated up the stack. 1279 llvm::consumeError(std::move(Err)); 1280 return false; 1281 } 1282 return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv, 1283 /*MarkEOLs*/ false, /*RelativeNames*/ true); 1284 } 1285 1286 bool cl::ParseCommandLineOptions(int argc, const char *const *argv, 1287 StringRef Overview, raw_ostream *Errs, 1288 const char *EnvVar, 1289 bool LongOptionsUseDoubleDash) { 1290 SmallVector<const char *, 20> NewArgv; 1291 BumpPtrAllocator A; 1292 StringSaver Saver(A); 1293 NewArgv.push_back(argv[0]); 1294 1295 // Parse options from environment variable. 1296 if (EnvVar) { 1297 if (llvm::Optional<std::string> EnvValue = 1298 sys::Process::GetEnv(StringRef(EnvVar))) 1299 TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv); 1300 } 1301 1302 // Append options from command line. 1303 for (int I = 1; I < argc; ++I) 1304 NewArgv.push_back(argv[I]); 1305 int NewArgc = static_cast<int>(NewArgv.size()); 1306 1307 // Parse all options. 1308 return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview, 1309 Errs, LongOptionsUseDoubleDash); 1310 } 1311 1312 void CommandLineParser::ResetAllOptionOccurrences() { 1313 // So that we can parse different command lines multiple times in succession 1314 // we reset all option values to look like they have never been seen before. 1315 for (auto SC : RegisteredSubCommands) { 1316 for (auto &O : SC->OptionsMap) 1317 O.second->reset(); 1318 } 1319 } 1320 1321 bool CommandLineParser::ParseCommandLineOptions(int argc, 1322 const char *const *argv, 1323 StringRef Overview, 1324 raw_ostream *Errs, 1325 bool LongOptionsUseDoubleDash) { 1326 assert(hasOptions() && "No options specified!"); 1327 1328 // Expand response files. 1329 SmallVector<const char *, 20> newArgv(argv, argv + argc); 1330 BumpPtrAllocator A; 1331 StringSaver Saver(A); 1332 ExpandResponseFiles(Saver, 1333 Triple(sys::getProcessTriple()).isOSWindows() ? 1334 cl::TokenizeWindowsCommandLine : cl::TokenizeGNUCommandLine, 1335 newArgv); 1336 argv = &newArgv[0]; 1337 argc = static_cast<int>(newArgv.size()); 1338 1339 // Copy the program name into ProgName, making sure not to overflow it. 1340 ProgramName = std::string(sys::path::filename(StringRef(argv[0]))); 1341 1342 ProgramOverview = Overview; 1343 bool IgnoreErrors = Errs; 1344 if (!Errs) 1345 Errs = &errs(); 1346 bool ErrorParsing = false; 1347 1348 // Check out the positional arguments to collect information about them. 1349 unsigned NumPositionalRequired = 0; 1350 1351 // Determine whether or not there are an unlimited number of positionals 1352 bool HasUnlimitedPositionals = false; 1353 1354 int FirstArg = 1; 1355 SubCommand *ChosenSubCommand = &*TopLevelSubCommand; 1356 if (argc >= 2 && argv[FirstArg][0] != '-') { 1357 // If the first argument specifies a valid subcommand, start processing 1358 // options from the second argument. 1359 ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg])); 1360 if (ChosenSubCommand != &*TopLevelSubCommand) 1361 FirstArg = 2; 1362 } 1363 GlobalParser->ActiveSubCommand = ChosenSubCommand; 1364 1365 assert(ChosenSubCommand); 1366 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt; 1367 auto &PositionalOpts = ChosenSubCommand->PositionalOpts; 1368 auto &SinkOpts = ChosenSubCommand->SinkOpts; 1369 auto &OptionsMap = ChosenSubCommand->OptionsMap; 1370 1371 for (auto O: DefaultOptions) { 1372 addOption(O, true); 1373 } 1374 1375 if (ConsumeAfterOpt) { 1376 assert(PositionalOpts.size() > 0 && 1377 "Cannot specify cl::ConsumeAfter without a positional argument!"); 1378 } 1379 if (!PositionalOpts.empty()) { 1380 1381 // Calculate how many positional values are _required_. 1382 bool UnboundedFound = false; 1383 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { 1384 Option *Opt = PositionalOpts[i]; 1385 if (RequiresValue(Opt)) 1386 ++NumPositionalRequired; 1387 else if (ConsumeAfterOpt) { 1388 // ConsumeAfter cannot be combined with "optional" positional options 1389 // unless there is only one positional argument... 1390 if (PositionalOpts.size() > 1) { 1391 if (!IgnoreErrors) 1392 Opt->error("error - this positional option will never be matched, " 1393 "because it does not Require a value, and a " 1394 "cl::ConsumeAfter option is active!"); 1395 ErrorParsing = true; 1396 } 1397 } else if (UnboundedFound && !Opt->hasArgStr()) { 1398 // This option does not "require" a value... Make sure this option is 1399 // not specified after an option that eats all extra arguments, or this 1400 // one will never get any! 1401 // 1402 if (!IgnoreErrors) 1403 Opt->error("error - option can never match, because " 1404 "another positional argument will match an " 1405 "unbounded number of values, and this option" 1406 " does not require a value!"); 1407 *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr 1408 << "' is all messed up!\n"; 1409 *Errs << PositionalOpts.size(); 1410 ErrorParsing = true; 1411 } 1412 UnboundedFound |= EatsUnboundedNumberOfValues(Opt); 1413 } 1414 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; 1415 } 1416 1417 // PositionalVals - A vector of "positional" arguments we accumulate into 1418 // the process at the end. 1419 // 1420 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals; 1421 1422 // If the program has named positional arguments, and the name has been run 1423 // across, keep track of which positional argument was named. Otherwise put 1424 // the positional args into the PositionalVals list... 1425 Option *ActivePositionalArg = nullptr; 1426 1427 // Loop over all of the arguments... processing them. 1428 bool DashDashFound = false; // Have we read '--'? 1429 for (int i = FirstArg; i < argc; ++i) { 1430 Option *Handler = nullptr; 1431 Option *NearestHandler = nullptr; 1432 std::string NearestHandlerString; 1433 StringRef Value; 1434 StringRef ArgName = ""; 1435 bool HaveDoubleDash = false; 1436 1437 // Check to see if this is a positional argument. This argument is 1438 // considered to be positional if it doesn't start with '-', if it is "-" 1439 // itself, or if we have seen "--" already. 1440 // 1441 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { 1442 // Positional argument! 1443 if (ActivePositionalArg) { 1444 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i); 1445 continue; // We are done! 1446 } 1447 1448 if (!PositionalOpts.empty()) { 1449 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i)); 1450 1451 // All of the positional arguments have been fulfulled, give the rest to 1452 // the consume after option... if it's specified... 1453 // 1454 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) { 1455 for (++i; i < argc; ++i) 1456 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i)); 1457 break; // Handle outside of the argument processing loop... 1458 } 1459 1460 // Delay processing positional arguments until the end... 1461 continue; 1462 } 1463 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 && 1464 !DashDashFound) { 1465 DashDashFound = true; // This is the mythical "--"? 1466 continue; // Don't try to process it as an argument itself. 1467 } else if (ActivePositionalArg && 1468 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) { 1469 // If there is a positional argument eating options, check to see if this 1470 // option is another positional argument. If so, treat it as an argument, 1471 // otherwise feed it to the eating positional. 1472 ArgName = StringRef(argv[i] + 1); 1473 // Eat second dash. 1474 if (!ArgName.empty() && ArgName[0] == '-') { 1475 HaveDoubleDash = true; 1476 ArgName = ArgName.substr(1); 1477 } 1478 1479 Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value, 1480 LongOptionsUseDoubleDash, HaveDoubleDash); 1481 if (!Handler || Handler->getFormattingFlag() != cl::Positional) { 1482 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i); 1483 continue; // We are done! 1484 } 1485 } else { // We start with a '-', must be an argument. 1486 ArgName = StringRef(argv[i] + 1); 1487 // Eat second dash. 1488 if (!ArgName.empty() && ArgName[0] == '-') { 1489 HaveDoubleDash = true; 1490 ArgName = ArgName.substr(1); 1491 } 1492 1493 Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value, 1494 LongOptionsUseDoubleDash, HaveDoubleDash); 1495 1496 // Check to see if this "option" is really a prefixed or grouped argument. 1497 if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash)) 1498 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing, 1499 OptionsMap); 1500 1501 // Otherwise, look for the closest available option to report to the user 1502 // in the upcoming error. 1503 if (!Handler && SinkOpts.empty()) 1504 NearestHandler = 1505 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString); 1506 } 1507 1508 if (!Handler) { 1509 if (SinkOpts.empty()) { 1510 *Errs << ProgramName << ": Unknown command line argument '" << argv[i] 1511 << "'. Try: '" << argv[0] << " --help'\n"; 1512 1513 if (NearestHandler) { 1514 // If we know a near match, report it as well. 1515 *Errs << ProgramName << ": Did you mean '" 1516 << PrintArg(NearestHandlerString, 0) << "'?\n"; 1517 } 1518 1519 ErrorParsing = true; 1520 } else { 1521 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(), 1522 E = SinkOpts.end(); 1523 I != E; ++I) 1524 (*I)->addOccurrence(i, "", StringRef(argv[i])); 1525 } 1526 continue; 1527 } 1528 1529 // If this is a named positional argument, just remember that it is the 1530 // active one... 1531 if (Handler->getFormattingFlag() == cl::Positional) { 1532 if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) { 1533 Handler->error("This argument does not take a value.\n" 1534 "\tInstead, it consumes any positional arguments until " 1535 "the next recognized option.", *Errs); 1536 ErrorParsing = true; 1537 } 1538 ActivePositionalArg = Handler; 1539 } 1540 else 1541 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); 1542 } 1543 1544 // Check and handle positional arguments now... 1545 if (NumPositionalRequired > PositionalVals.size()) { 1546 *Errs << ProgramName 1547 << ": Not enough positional command line arguments specified!\n" 1548 << "Must specify at least " << NumPositionalRequired 1549 << " positional argument" << (NumPositionalRequired > 1 ? "s" : "") 1550 << ": See: " << argv[0] << " --help\n"; 1551 1552 ErrorParsing = true; 1553 } else if (!HasUnlimitedPositionals && 1554 PositionalVals.size() > PositionalOpts.size()) { 1555 *Errs << ProgramName << ": Too many positional arguments specified!\n" 1556 << "Can specify at most " << PositionalOpts.size() 1557 << " positional arguments: See: " << argv[0] << " --help\n"; 1558 ErrorParsing = true; 1559 1560 } else if (!ConsumeAfterOpt) { 1561 // Positional args have already been handled if ConsumeAfter is specified. 1562 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size()); 1563 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { 1564 if (RequiresValue(PositionalOpts[i])) { 1565 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, 1566 PositionalVals[ValNo].second); 1567 ValNo++; 1568 --NumPositionalRequired; // We fulfilled our duty... 1569 } 1570 1571 // If we _can_ give this option more arguments, do so now, as long as we 1572 // do not give it values that others need. 'Done' controls whether the 1573 // option even _WANTS_ any more. 1574 // 1575 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; 1576 while (NumVals - ValNo > NumPositionalRequired && !Done) { 1577 switch (PositionalOpts[i]->getNumOccurrencesFlag()) { 1578 case cl::Optional: 1579 Done = true; // Optional arguments want _at most_ one value 1580 LLVM_FALLTHROUGH; 1581 case cl::ZeroOrMore: // Zero or more will take all they can get... 1582 case cl::OneOrMore: // One or more will take all they can get... 1583 ProvidePositionalOption(PositionalOpts[i], 1584 PositionalVals[ValNo].first, 1585 PositionalVals[ValNo].second); 1586 ValNo++; 1587 break; 1588 default: 1589 llvm_unreachable("Internal error, unexpected NumOccurrences flag in " 1590 "positional argument processing!"); 1591 } 1592 } 1593 } 1594 } else { 1595 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); 1596 unsigned ValNo = 0; 1597 for (size_t J = 0, E = PositionalOpts.size(); J != E; ++J) 1598 if (RequiresValue(PositionalOpts[J])) { 1599 ErrorParsing |= ProvidePositionalOption(PositionalOpts[J], 1600 PositionalVals[ValNo].first, 1601 PositionalVals[ValNo].second); 1602 ValNo++; 1603 } 1604 1605 // Handle the case where there is just one positional option, and it's 1606 // optional. In this case, we want to give JUST THE FIRST option to the 1607 // positional option and keep the rest for the consume after. The above 1608 // loop would have assigned no values to positional options in this case. 1609 // 1610 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) { 1611 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0], 1612 PositionalVals[ValNo].first, 1613 PositionalVals[ValNo].second); 1614 ValNo++; 1615 } 1616 1617 // Handle over all of the rest of the arguments to the 1618 // cl::ConsumeAfter command line option... 1619 for (; ValNo != PositionalVals.size(); ++ValNo) 1620 ErrorParsing |= 1621 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first, 1622 PositionalVals[ValNo].second); 1623 } 1624 1625 // Loop over args and make sure all required args are specified! 1626 for (const auto &Opt : OptionsMap) { 1627 switch (Opt.second->getNumOccurrencesFlag()) { 1628 case Required: 1629 case OneOrMore: 1630 if (Opt.second->getNumOccurrences() == 0) { 1631 Opt.second->error("must be specified at least once!"); 1632 ErrorParsing = true; 1633 } 1634 LLVM_FALLTHROUGH; 1635 default: 1636 break; 1637 } 1638 } 1639 1640 // Now that we know if -debug is specified, we can use it. 1641 // Note that if ReadResponseFiles == true, this must be done before the 1642 // memory allocated for the expanded command line is free()d below. 1643 LLVM_DEBUG(dbgs() << "Args: "; 1644 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' '; 1645 dbgs() << '\n';); 1646 1647 // Free all of the memory allocated to the map. Command line options may only 1648 // be processed once! 1649 MoreHelp.clear(); 1650 1651 // If we had an error processing our arguments, don't let the program execute 1652 if (ErrorParsing) { 1653 if (!IgnoreErrors) 1654 exit(1); 1655 return false; 1656 } 1657 return true; 1658 } 1659 1660 //===----------------------------------------------------------------------===// 1661 // Option Base class implementation 1662 // 1663 1664 bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) { 1665 if (!ArgName.data()) 1666 ArgName = ArgStr; 1667 if (ArgName.empty()) 1668 Errs << HelpStr; // Be nice for positional arguments 1669 else 1670 Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0); 1671 1672 Errs << " option: " << Message << "\n"; 1673 return true; 1674 } 1675 1676 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value, 1677 bool MultiArg) { 1678 if (!MultiArg) 1679 NumOccurrences++; // Increment the number of times we have been seen 1680 1681 switch (getNumOccurrencesFlag()) { 1682 case Optional: 1683 if (NumOccurrences > 1) 1684 return error("may only occur zero or one times!", ArgName); 1685 break; 1686 case Required: 1687 if (NumOccurrences > 1) 1688 return error("must occur exactly one time!", ArgName); 1689 LLVM_FALLTHROUGH; 1690 case OneOrMore: 1691 case ZeroOrMore: 1692 case ConsumeAfter: 1693 break; 1694 } 1695 1696 return handleOccurrence(pos, ArgName, Value); 1697 } 1698 1699 // getValueStr - Get the value description string, using "DefaultMsg" if nothing 1700 // has been specified yet. 1701 // 1702 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) { 1703 if (O.ValueStr.empty()) 1704 return DefaultMsg; 1705 return O.ValueStr; 1706 } 1707 1708 //===----------------------------------------------------------------------===// 1709 // cl::alias class implementation 1710 // 1711 1712 // Return the width of the option tag for printing... 1713 size_t alias::getOptionWidth() const { 1714 return argPlusPrefixesSize(ArgStr); 1715 } 1716 1717 void Option::printHelpStr(StringRef HelpStr, size_t Indent, 1718 size_t FirstLineIndentedBy) { 1719 assert(Indent >= FirstLineIndentedBy); 1720 std::pair<StringRef, StringRef> Split = HelpStr.split('\n'); 1721 outs().indent(Indent - FirstLineIndentedBy) 1722 << ArgHelpPrefix << Split.first << "\n"; 1723 while (!Split.second.empty()) { 1724 Split = Split.second.split('\n'); 1725 outs().indent(Indent) << Split.first << "\n"; 1726 } 1727 } 1728 1729 void Option::printEnumValHelpStr(StringRef HelpStr, size_t BaseIndent, 1730 size_t FirstLineIndentedBy) { 1731 const StringRef ValHelpPrefix = " "; 1732 assert(BaseIndent >= FirstLineIndentedBy); 1733 std::pair<StringRef, StringRef> Split = HelpStr.split('\n'); 1734 outs().indent(BaseIndent - FirstLineIndentedBy) 1735 << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n"; 1736 while (!Split.second.empty()) { 1737 Split = Split.second.split('\n'); 1738 outs().indent(BaseIndent + ValHelpPrefix.size()) << Split.first << "\n"; 1739 } 1740 } 1741 1742 // Print out the option for the alias. 1743 void alias::printOptionInfo(size_t GlobalWidth) const { 1744 outs() << PrintArg(ArgStr); 1745 printHelpStr(HelpStr, GlobalWidth, argPlusPrefixesSize(ArgStr)); 1746 } 1747 1748 //===----------------------------------------------------------------------===// 1749 // Parser Implementation code... 1750 // 1751 1752 // basic_parser implementation 1753 // 1754 1755 // Return the width of the option tag for printing... 1756 size_t basic_parser_impl::getOptionWidth(const Option &O) const { 1757 size_t Len = argPlusPrefixesSize(O.ArgStr); 1758 auto ValName = getValueName(); 1759 if (!ValName.empty()) { 1760 size_t FormattingLen = 3; 1761 if (O.getMiscFlags() & PositionalEatsArgs) 1762 FormattingLen = 6; 1763 Len += getValueStr(O, ValName).size() + FormattingLen; 1764 } 1765 1766 return Len; 1767 } 1768 1769 // printOptionInfo - Print out information about this option. The 1770 // to-be-maintained width is specified. 1771 // 1772 void basic_parser_impl::printOptionInfo(const Option &O, 1773 size_t GlobalWidth) const { 1774 outs() << PrintArg(O.ArgStr); 1775 1776 auto ValName = getValueName(); 1777 if (!ValName.empty()) { 1778 if (O.getMiscFlags() & PositionalEatsArgs) { 1779 outs() << " <" << getValueStr(O, ValName) << ">..."; 1780 } else if (O.getValueExpectedFlag() == ValueOptional) 1781 outs() << "[=<" << getValueStr(O, ValName) << ">]"; 1782 else 1783 outs() << "=<" << getValueStr(O, ValName) << '>'; 1784 } 1785 1786 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O)); 1787 } 1788 1789 void basic_parser_impl::printOptionName(const Option &O, 1790 size_t GlobalWidth) const { 1791 outs() << PrintArg(O.ArgStr); 1792 outs().indent(GlobalWidth - O.ArgStr.size()); 1793 } 1794 1795 // parser<bool> implementation 1796 // 1797 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg, 1798 bool &Value) { 1799 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 1800 Arg == "1") { 1801 Value = true; 1802 return false; 1803 } 1804 1805 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 1806 Value = false; 1807 return false; 1808 } 1809 return O.error("'" + Arg + 1810 "' is invalid value for boolean argument! Try 0 or 1"); 1811 } 1812 1813 // parser<boolOrDefault> implementation 1814 // 1815 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg, 1816 boolOrDefault &Value) { 1817 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 1818 Arg == "1") { 1819 Value = BOU_TRUE; 1820 return false; 1821 } 1822 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 1823 Value = BOU_FALSE; 1824 return false; 1825 } 1826 1827 return O.error("'" + Arg + 1828 "' is invalid value for boolean argument! Try 0 or 1"); 1829 } 1830 1831 // parser<int> implementation 1832 // 1833 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg, 1834 int &Value) { 1835 if (Arg.getAsInteger(0, Value)) 1836 return O.error("'" + Arg + "' value invalid for integer argument!"); 1837 return false; 1838 } 1839 1840 // parser<long> implementation 1841 // 1842 bool parser<long>::parse(Option &O, StringRef ArgName, StringRef Arg, 1843 long &Value) { 1844 if (Arg.getAsInteger(0, Value)) 1845 return O.error("'" + Arg + "' value invalid for long argument!"); 1846 return false; 1847 } 1848 1849 // parser<long long> implementation 1850 // 1851 bool parser<long long>::parse(Option &O, StringRef ArgName, StringRef Arg, 1852 long long &Value) { 1853 if (Arg.getAsInteger(0, Value)) 1854 return O.error("'" + Arg + "' value invalid for llong argument!"); 1855 return false; 1856 } 1857 1858 // parser<unsigned> implementation 1859 // 1860 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg, 1861 unsigned &Value) { 1862 1863 if (Arg.getAsInteger(0, Value)) 1864 return O.error("'" + Arg + "' value invalid for uint argument!"); 1865 return false; 1866 } 1867 1868 // parser<unsigned long> implementation 1869 // 1870 bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg, 1871 unsigned long &Value) { 1872 1873 if (Arg.getAsInteger(0, Value)) 1874 return O.error("'" + Arg + "' value invalid for ulong argument!"); 1875 return false; 1876 } 1877 1878 // parser<unsigned long long> implementation 1879 // 1880 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName, 1881 StringRef Arg, 1882 unsigned long long &Value) { 1883 1884 if (Arg.getAsInteger(0, Value)) 1885 return O.error("'" + Arg + "' value invalid for ullong argument!"); 1886 return false; 1887 } 1888 1889 // parser<double>/parser<float> implementation 1890 // 1891 static bool parseDouble(Option &O, StringRef Arg, double &Value) { 1892 if (to_float(Arg, Value)) 1893 return false; 1894 return O.error("'" + Arg + "' value invalid for floating point argument!"); 1895 } 1896 1897 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg, 1898 double &Val) { 1899 return parseDouble(O, Arg, Val); 1900 } 1901 1902 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg, 1903 float &Val) { 1904 double dVal; 1905 if (parseDouble(O, Arg, dVal)) 1906 return true; 1907 Val = (float)dVal; 1908 return false; 1909 } 1910 1911 // generic_parser_base implementation 1912 // 1913 1914 // findOption - Return the option number corresponding to the specified 1915 // argument string. If the option is not found, getNumOptions() is returned. 1916 // 1917 unsigned generic_parser_base::findOption(StringRef Name) { 1918 unsigned e = getNumOptions(); 1919 1920 for (unsigned i = 0; i != e; ++i) { 1921 if (getOption(i) == Name) 1922 return i; 1923 } 1924 return e; 1925 } 1926 1927 static StringRef EqValue = "=<value>"; 1928 static StringRef EmptyOption = "<empty>"; 1929 static StringRef OptionPrefix = " ="; 1930 static size_t OptionPrefixesSize = OptionPrefix.size() + ArgHelpPrefix.size(); 1931 1932 static bool shouldPrintOption(StringRef Name, StringRef Description, 1933 const Option &O) { 1934 return O.getValueExpectedFlag() != ValueOptional || !Name.empty() || 1935 !Description.empty(); 1936 } 1937 1938 // Return the width of the option tag for printing... 1939 size_t generic_parser_base::getOptionWidth(const Option &O) const { 1940 if (O.hasArgStr()) { 1941 size_t Size = 1942 argPlusPrefixesSize(O.ArgStr) + EqValue.size(); 1943 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1944 StringRef Name = getOption(i); 1945 if (!shouldPrintOption(Name, getDescription(i), O)) 1946 continue; 1947 size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size(); 1948 Size = std::max(Size, NameSize + OptionPrefixesSize); 1949 } 1950 return Size; 1951 } else { 1952 size_t BaseSize = 0; 1953 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1954 BaseSize = std::max(BaseSize, getOption(i).size() + 8); 1955 return BaseSize; 1956 } 1957 } 1958 1959 // printOptionInfo - Print out information about this option. The 1960 // to-be-maintained width is specified. 1961 // 1962 void generic_parser_base::printOptionInfo(const Option &O, 1963 size_t GlobalWidth) const { 1964 if (O.hasArgStr()) { 1965 // When the value is optional, first print a line just describing the 1966 // option without values. 1967 if (O.getValueExpectedFlag() == ValueOptional) { 1968 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1969 if (getOption(i).empty()) { 1970 outs() << PrintArg(O.ArgStr); 1971 Option::printHelpStr(O.HelpStr, GlobalWidth, 1972 argPlusPrefixesSize(O.ArgStr)); 1973 break; 1974 } 1975 } 1976 } 1977 1978 outs() << PrintArg(O.ArgStr) << EqValue; 1979 Option::printHelpStr(O.HelpStr, GlobalWidth, 1980 EqValue.size() + 1981 argPlusPrefixesSize(O.ArgStr)); 1982 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1983 StringRef OptionName = getOption(i); 1984 StringRef Description = getDescription(i); 1985 if (!shouldPrintOption(OptionName, Description, O)) 1986 continue; 1987 size_t FirstLineIndent = OptionName.size() + OptionPrefixesSize; 1988 outs() << OptionPrefix << OptionName; 1989 if (OptionName.empty()) { 1990 outs() << EmptyOption; 1991 assert(FirstLineIndent >= EmptyOption.size()); 1992 FirstLineIndent += EmptyOption.size(); 1993 } 1994 if (!Description.empty()) 1995 Option::printEnumValHelpStr(Description, GlobalWidth, FirstLineIndent); 1996 else 1997 outs() << '\n'; 1998 } 1999 } else { 2000 if (!O.HelpStr.empty()) 2001 outs() << " " << O.HelpStr << '\n'; 2002 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 2003 StringRef Option = getOption(i); 2004 outs() << " " << PrintArg(Option); 2005 Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8); 2006 } 2007 } 2008 } 2009 2010 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff 2011 2012 // printGenericOptionDiff - Print the value of this option and it's default. 2013 // 2014 // "Generic" options have each value mapped to a name. 2015 void generic_parser_base::printGenericOptionDiff( 2016 const Option &O, const GenericOptionValue &Value, 2017 const GenericOptionValue &Default, size_t GlobalWidth) const { 2018 outs() << " " << PrintArg(O.ArgStr); 2019 outs().indent(GlobalWidth - O.ArgStr.size()); 2020 2021 unsigned NumOpts = getNumOptions(); 2022 for (unsigned i = 0; i != NumOpts; ++i) { 2023 if (Value.compare(getOptionValue(i))) 2024 continue; 2025 2026 outs() << "= " << getOption(i); 2027 size_t L = getOption(i).size(); 2028 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0; 2029 outs().indent(NumSpaces) << " (default: "; 2030 for (unsigned j = 0; j != NumOpts; ++j) { 2031 if (Default.compare(getOptionValue(j))) 2032 continue; 2033 outs() << getOption(j); 2034 break; 2035 } 2036 outs() << ")\n"; 2037 return; 2038 } 2039 outs() << "= *unknown option value*\n"; 2040 } 2041 2042 // printOptionDiff - Specializations for printing basic value types. 2043 // 2044 #define PRINT_OPT_DIFF(T) \ 2045 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \ 2046 size_t GlobalWidth) const { \ 2047 printOptionName(O, GlobalWidth); \ 2048 std::string Str; \ 2049 { \ 2050 raw_string_ostream SS(Str); \ 2051 SS << V; \ 2052 } \ 2053 outs() << "= " << Str; \ 2054 size_t NumSpaces = \ 2055 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \ 2056 outs().indent(NumSpaces) << " (default: "; \ 2057 if (D.hasValue()) \ 2058 outs() << D.getValue(); \ 2059 else \ 2060 outs() << "*no default*"; \ 2061 outs() << ")\n"; \ 2062 } 2063 2064 PRINT_OPT_DIFF(bool) 2065 PRINT_OPT_DIFF(boolOrDefault) 2066 PRINT_OPT_DIFF(int) 2067 PRINT_OPT_DIFF(long) 2068 PRINT_OPT_DIFF(long long) 2069 PRINT_OPT_DIFF(unsigned) 2070 PRINT_OPT_DIFF(unsigned long) 2071 PRINT_OPT_DIFF(unsigned long long) 2072 PRINT_OPT_DIFF(double) 2073 PRINT_OPT_DIFF(float) 2074 PRINT_OPT_DIFF(char) 2075 2076 void parser<std::string>::printOptionDiff(const Option &O, StringRef V, 2077 const OptionValue<std::string> &D, 2078 size_t GlobalWidth) const { 2079 printOptionName(O, GlobalWidth); 2080 outs() << "= " << V; 2081 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0; 2082 outs().indent(NumSpaces) << " (default: "; 2083 if (D.hasValue()) 2084 outs() << D.getValue(); 2085 else 2086 outs() << "*no default*"; 2087 outs() << ")\n"; 2088 } 2089 2090 // Print a placeholder for options that don't yet support printOptionDiff(). 2091 void basic_parser_impl::printOptionNoValue(const Option &O, 2092 size_t GlobalWidth) const { 2093 printOptionName(O, GlobalWidth); 2094 outs() << "= *cannot print option value*\n"; 2095 } 2096 2097 //===----------------------------------------------------------------------===// 2098 // -help and -help-hidden option implementation 2099 // 2100 2101 static int OptNameCompare(const std::pair<const char *, Option *> *LHS, 2102 const std::pair<const char *, Option *> *RHS) { 2103 return strcmp(LHS->first, RHS->first); 2104 } 2105 2106 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS, 2107 const std::pair<const char *, SubCommand *> *RHS) { 2108 return strcmp(LHS->first, RHS->first); 2109 } 2110 2111 // Copy Options into a vector so we can sort them as we like. 2112 static void sortOpts(StringMap<Option *> &OptMap, 2113 SmallVectorImpl<std::pair<const char *, Option *>> &Opts, 2114 bool ShowHidden) { 2115 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection. 2116 2117 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end(); 2118 I != E; ++I) { 2119 // Ignore really-hidden options. 2120 if (I->second->getOptionHiddenFlag() == ReallyHidden) 2121 continue; 2122 2123 // Unless showhidden is set, ignore hidden flags. 2124 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden) 2125 continue; 2126 2127 // If we've already seen this option, don't add it to the list again. 2128 if (!OptionSet.insert(I->second).second) 2129 continue; 2130 2131 Opts.push_back( 2132 std::pair<const char *, Option *>(I->getKey().data(), I->second)); 2133 } 2134 2135 // Sort the options list alphabetically. 2136 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare); 2137 } 2138 2139 static void 2140 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap, 2141 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) { 2142 for (auto *S : SubMap) { 2143 if (S->getName().empty()) 2144 continue; 2145 Subs.push_back(std::make_pair(S->getName().data(), S)); 2146 } 2147 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare); 2148 } 2149 2150 namespace { 2151 2152 class HelpPrinter { 2153 protected: 2154 const bool ShowHidden; 2155 typedef SmallVector<std::pair<const char *, Option *>, 128> 2156 StrOptionPairVector; 2157 typedef SmallVector<std::pair<const char *, SubCommand *>, 128> 2158 StrSubCommandPairVector; 2159 // Print the options. Opts is assumed to be alphabetically sorted. 2160 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) { 2161 for (size_t i = 0, e = Opts.size(); i != e; ++i) 2162 Opts[i].second->printOptionInfo(MaxArgLen); 2163 } 2164 2165 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) { 2166 for (const auto &S : Subs) { 2167 outs() << " " << S.first; 2168 if (!S.second->getDescription().empty()) { 2169 outs().indent(MaxSubLen - strlen(S.first)); 2170 outs() << " - " << S.second->getDescription(); 2171 } 2172 outs() << "\n"; 2173 } 2174 } 2175 2176 public: 2177 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {} 2178 virtual ~HelpPrinter() {} 2179 2180 // Invoke the printer. 2181 void operator=(bool Value) { 2182 if (!Value) 2183 return; 2184 printHelp(); 2185 2186 // Halt the program since help information was printed 2187 exit(0); 2188 } 2189 2190 void printHelp() { 2191 SubCommand *Sub = GlobalParser->getActiveSubCommand(); 2192 auto &OptionsMap = Sub->OptionsMap; 2193 auto &PositionalOpts = Sub->PositionalOpts; 2194 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt; 2195 2196 StrOptionPairVector Opts; 2197 sortOpts(OptionsMap, Opts, ShowHidden); 2198 2199 StrSubCommandPairVector Subs; 2200 sortSubCommands(GlobalParser->RegisteredSubCommands, Subs); 2201 2202 if (!GlobalParser->ProgramOverview.empty()) 2203 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n"; 2204 2205 if (Sub == &*TopLevelSubCommand) { 2206 outs() << "USAGE: " << GlobalParser->ProgramName; 2207 if (Subs.size() > 2) 2208 outs() << " [subcommand]"; 2209 outs() << " [options]"; 2210 } else { 2211 if (!Sub->getDescription().empty()) { 2212 outs() << "SUBCOMMAND '" << Sub->getName() 2213 << "': " << Sub->getDescription() << "\n\n"; 2214 } 2215 outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName() 2216 << " [options]"; 2217 } 2218 2219 for (auto Opt : PositionalOpts) { 2220 if (Opt->hasArgStr()) 2221 outs() << " --" << Opt->ArgStr; 2222 outs() << " " << Opt->HelpStr; 2223 } 2224 2225 // Print the consume after option info if it exists... 2226 if (ConsumeAfterOpt) 2227 outs() << " " << ConsumeAfterOpt->HelpStr; 2228 2229 if (Sub == &*TopLevelSubCommand && !Subs.empty()) { 2230 // Compute the maximum subcommand length... 2231 size_t MaxSubLen = 0; 2232 for (size_t i = 0, e = Subs.size(); i != e; ++i) 2233 MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first)); 2234 2235 outs() << "\n\n"; 2236 outs() << "SUBCOMMANDS:\n\n"; 2237 printSubCommands(Subs, MaxSubLen); 2238 outs() << "\n"; 2239 outs() << " Type \"" << GlobalParser->ProgramName 2240 << " <subcommand> --help\" to get more help on a specific " 2241 "subcommand"; 2242 } 2243 2244 outs() << "\n\n"; 2245 2246 // Compute the maximum argument length... 2247 size_t MaxArgLen = 0; 2248 for (size_t i = 0, e = Opts.size(); i != e; ++i) 2249 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 2250 2251 outs() << "OPTIONS:\n"; 2252 printOptions(Opts, MaxArgLen); 2253 2254 // Print any extra help the user has declared. 2255 for (auto I : GlobalParser->MoreHelp) 2256 outs() << I; 2257 GlobalParser->MoreHelp.clear(); 2258 } 2259 }; 2260 2261 class CategorizedHelpPrinter : public HelpPrinter { 2262 public: 2263 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {} 2264 2265 // Helper function for printOptions(). 2266 // It shall return a negative value if A's name should be lexicographically 2267 // ordered before B's name. It returns a value greater than zero if B's name 2268 // should be ordered before A's name, and it returns 0 otherwise. 2269 static int OptionCategoryCompare(OptionCategory *const *A, 2270 OptionCategory *const *B) { 2271 return (*A)->getName().compare((*B)->getName()); 2272 } 2273 2274 // Make sure we inherit our base class's operator=() 2275 using HelpPrinter::operator=; 2276 2277 protected: 2278 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override { 2279 std::vector<OptionCategory *> SortedCategories; 2280 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions; 2281 2282 // Collect registered option categories into vector in preparation for 2283 // sorting. 2284 for (auto I = GlobalParser->RegisteredOptionCategories.begin(), 2285 E = GlobalParser->RegisteredOptionCategories.end(); 2286 I != E; ++I) { 2287 SortedCategories.push_back(*I); 2288 } 2289 2290 // Sort the different option categories alphabetically. 2291 assert(SortedCategories.size() > 0 && "No option categories registered!"); 2292 array_pod_sort(SortedCategories.begin(), SortedCategories.end(), 2293 OptionCategoryCompare); 2294 2295 // Create map to empty vectors. 2296 for (std::vector<OptionCategory *>::const_iterator 2297 I = SortedCategories.begin(), 2298 E = SortedCategories.end(); 2299 I != E; ++I) 2300 CategorizedOptions[*I] = std::vector<Option *>(); 2301 2302 // Walk through pre-sorted options and assign into categories. 2303 // Because the options are already alphabetically sorted the 2304 // options within categories will also be alphabetically sorted. 2305 for (size_t I = 0, E = Opts.size(); I != E; ++I) { 2306 Option *Opt = Opts[I].second; 2307 for (auto &Cat : Opt->Categories) { 2308 assert(CategorizedOptions.count(Cat) > 0 && 2309 "Option has an unregistered category"); 2310 CategorizedOptions[Cat].push_back(Opt); 2311 } 2312 } 2313 2314 // Now do printing. 2315 for (std::vector<OptionCategory *>::const_iterator 2316 Category = SortedCategories.begin(), 2317 E = SortedCategories.end(); 2318 Category != E; ++Category) { 2319 // Hide empty categories for --help, but show for --help-hidden. 2320 const auto &CategoryOptions = CategorizedOptions[*Category]; 2321 bool IsEmptyCategory = CategoryOptions.empty(); 2322 if (!ShowHidden && IsEmptyCategory) 2323 continue; 2324 2325 // Print category information. 2326 outs() << "\n"; 2327 outs() << (*Category)->getName() << ":\n"; 2328 2329 // Check if description is set. 2330 if (!(*Category)->getDescription().empty()) 2331 outs() << (*Category)->getDescription() << "\n\n"; 2332 else 2333 outs() << "\n"; 2334 2335 // When using --help-hidden explicitly state if the category has no 2336 // options associated with it. 2337 if (IsEmptyCategory) { 2338 outs() << " This option category has no options.\n"; 2339 continue; 2340 } 2341 // Loop over the options in the category and print. 2342 for (const Option *Opt : CategoryOptions) 2343 Opt->printOptionInfo(MaxArgLen); 2344 } 2345 } 2346 }; 2347 2348 // This wraps the Uncategorizing and Categorizing printers and decides 2349 // at run time which should be invoked. 2350 class HelpPrinterWrapper { 2351 private: 2352 HelpPrinter &UncategorizedPrinter; 2353 CategorizedHelpPrinter &CategorizedPrinter; 2354 2355 public: 2356 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter, 2357 CategorizedHelpPrinter &CategorizedPrinter) 2358 : UncategorizedPrinter(UncategorizedPrinter), 2359 CategorizedPrinter(CategorizedPrinter) {} 2360 2361 // Invoke the printer. 2362 void operator=(bool Value); 2363 }; 2364 2365 } // End anonymous namespace 2366 2367 // Declare the four HelpPrinter instances that are used to print out help, or 2368 // help-hidden as an uncategorized list or in categories. 2369 static HelpPrinter UncategorizedNormalPrinter(false); 2370 static HelpPrinter UncategorizedHiddenPrinter(true); 2371 static CategorizedHelpPrinter CategorizedNormalPrinter(false); 2372 static CategorizedHelpPrinter CategorizedHiddenPrinter(true); 2373 2374 // Declare HelpPrinter wrappers that will decide whether or not to invoke 2375 // a categorizing help printer 2376 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter, 2377 CategorizedNormalPrinter); 2378 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter, 2379 CategorizedHiddenPrinter); 2380 2381 // Define a category for generic options that all tools should have. 2382 static cl::OptionCategory GenericCategory("Generic Options"); 2383 2384 // Define uncategorized help printers. 2385 // --help-list is hidden by default because if Option categories are being used 2386 // then --help behaves the same as --help-list. 2387 static cl::opt<HelpPrinter, true, parser<bool>> HLOp( 2388 "help-list", 2389 cl::desc("Display list of available options (--help-list-hidden for more)"), 2390 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed, 2391 cl::cat(GenericCategory), cl::sub(*AllSubCommands)); 2392 2393 static cl::opt<HelpPrinter, true, parser<bool>> 2394 HLHOp("help-list-hidden", cl::desc("Display list of all available options"), 2395 cl::location(UncategorizedHiddenPrinter), cl::Hidden, 2396 cl::ValueDisallowed, cl::cat(GenericCategory), 2397 cl::sub(*AllSubCommands)); 2398 2399 // Define uncategorized/categorized help printers. These printers change their 2400 // behaviour at runtime depending on whether one or more Option categories have 2401 // been declared. 2402 static cl::opt<HelpPrinterWrapper, true, parser<bool>> 2403 HOp("help", cl::desc("Display available options (--help-hidden for more)"), 2404 cl::location(WrappedNormalPrinter), cl::ValueDisallowed, 2405 cl::cat(GenericCategory), cl::sub(*AllSubCommands)); 2406 2407 static cl::alias HOpA("h", cl::desc("Alias for --help"), cl::aliasopt(HOp), 2408 cl::DefaultOption); 2409 2410 static cl::opt<HelpPrinterWrapper, true, parser<bool>> 2411 HHOp("help-hidden", cl::desc("Display all available options"), 2412 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed, 2413 cl::cat(GenericCategory), cl::sub(*AllSubCommands)); 2414 2415 static cl::opt<bool> PrintOptions( 2416 "print-options", 2417 cl::desc("Print non-default options after command line parsing"), 2418 cl::Hidden, cl::init(false), cl::cat(GenericCategory), 2419 cl::sub(*AllSubCommands)); 2420 2421 static cl::opt<bool> PrintAllOptions( 2422 "print-all-options", 2423 cl::desc("Print all option values after command line parsing"), cl::Hidden, 2424 cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands)); 2425 2426 void HelpPrinterWrapper::operator=(bool Value) { 2427 if (!Value) 2428 return; 2429 2430 // Decide which printer to invoke. If more than one option category is 2431 // registered then it is useful to show the categorized help instead of 2432 // uncategorized help. 2433 if (GlobalParser->RegisteredOptionCategories.size() > 1) { 2434 // unhide --help-list option so user can have uncategorized output if they 2435 // want it. 2436 HLOp.setHiddenFlag(NotHidden); 2437 2438 CategorizedPrinter = true; // Invoke categorized printer 2439 } else 2440 UncategorizedPrinter = true; // Invoke uncategorized printer 2441 } 2442 2443 // Print the value of each option. 2444 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); } 2445 2446 void CommandLineParser::printOptionValues() { 2447 if (!PrintOptions && !PrintAllOptions) 2448 return; 2449 2450 SmallVector<std::pair<const char *, Option *>, 128> Opts; 2451 sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true); 2452 2453 // Compute the maximum argument length... 2454 size_t MaxArgLen = 0; 2455 for (size_t i = 0, e = Opts.size(); i != e; ++i) 2456 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 2457 2458 for (size_t i = 0, e = Opts.size(); i != e; ++i) 2459 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions); 2460 } 2461 2462 static VersionPrinterTy OverrideVersionPrinter = nullptr; 2463 2464 static std::vector<VersionPrinterTy> *ExtraVersionPrinters = nullptr; 2465 2466 #if defined(__GNUC__) 2467 // GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are 2468 // enabled. 2469 # if defined(__OPTIMIZE__) 2470 # define LLVM_IS_DEBUG_BUILD 0 2471 # else 2472 # define LLVM_IS_DEBUG_BUILD 1 2473 # endif 2474 #elif defined(_MSC_VER) 2475 // MSVC doesn't have a predefined macro indicating if optimizations are enabled. 2476 // Use _DEBUG instead. This macro actually corresponds to the choice between 2477 // debug and release CRTs, but it is a reasonable proxy. 2478 # if defined(_DEBUG) 2479 # define LLVM_IS_DEBUG_BUILD 1 2480 # else 2481 # define LLVM_IS_DEBUG_BUILD 0 2482 # endif 2483 #else 2484 // Otherwise, for an unknown compiler, assume this is an optimized build. 2485 # define LLVM_IS_DEBUG_BUILD 0 2486 #endif 2487 2488 namespace { 2489 class VersionPrinter { 2490 public: 2491 void print() { 2492 raw_ostream &OS = outs(); 2493 #ifdef PACKAGE_VENDOR 2494 OS << PACKAGE_VENDOR << " "; 2495 #else 2496 OS << "LLVM (http://llvm.org/):\n "; 2497 #endif 2498 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION; 2499 #ifdef LLVM_VERSION_INFO 2500 OS << " " << LLVM_VERSION_INFO; 2501 #endif 2502 OS << "\n "; 2503 #if LLVM_IS_DEBUG_BUILD 2504 OS << "DEBUG build"; 2505 #else 2506 OS << "Optimized build"; 2507 #endif 2508 #ifndef NDEBUG 2509 OS << " with assertions"; 2510 #endif 2511 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO 2512 std::string CPU = std::string(sys::getHostCPUName()); 2513 if (CPU == "generic") 2514 CPU = "(unknown)"; 2515 OS << ".\n" 2516 << " Default target: " << sys::getDefaultTargetTriple() << '\n' 2517 << " Host CPU: " << CPU; 2518 #endif 2519 OS << '\n'; 2520 } 2521 void operator=(bool OptionWasSpecified) { 2522 if (!OptionWasSpecified) 2523 return; 2524 2525 if (OverrideVersionPrinter != nullptr) { 2526 OverrideVersionPrinter(outs()); 2527 exit(0); 2528 } 2529 print(); 2530 2531 // Iterate over any registered extra printers and call them to add further 2532 // information. 2533 if (ExtraVersionPrinters != nullptr) { 2534 outs() << '\n'; 2535 for (const auto &I : *ExtraVersionPrinters) 2536 I(outs()); 2537 } 2538 2539 exit(0); 2540 } 2541 }; 2542 } // End anonymous namespace 2543 2544 // Define the --version option that prints out the LLVM version for the tool 2545 static VersionPrinter VersionPrinterInstance; 2546 2547 static cl::opt<VersionPrinter, true, parser<bool>> 2548 VersOp("version", cl::desc("Display the version of this program"), 2549 cl::location(VersionPrinterInstance), cl::ValueDisallowed, 2550 cl::cat(GenericCategory)); 2551 2552 // Utility function for printing the help message. 2553 void cl::PrintHelpMessage(bool Hidden, bool Categorized) { 2554 if (!Hidden && !Categorized) 2555 UncategorizedNormalPrinter.printHelp(); 2556 else if (!Hidden && Categorized) 2557 CategorizedNormalPrinter.printHelp(); 2558 else if (Hidden && !Categorized) 2559 UncategorizedHiddenPrinter.printHelp(); 2560 else 2561 CategorizedHiddenPrinter.printHelp(); 2562 } 2563 2564 /// Utility function for printing version number. 2565 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); } 2566 2567 void cl::SetVersionPrinter(VersionPrinterTy func) { OverrideVersionPrinter = func; } 2568 2569 void cl::AddExtraVersionPrinter(VersionPrinterTy func) { 2570 if (!ExtraVersionPrinters) 2571 ExtraVersionPrinters = new std::vector<VersionPrinterTy>; 2572 2573 ExtraVersionPrinters->push_back(func); 2574 } 2575 2576 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) { 2577 auto &Subs = GlobalParser->RegisteredSubCommands; 2578 (void)Subs; 2579 assert(is_contained(Subs, &Sub)); 2580 return Sub.OptionsMap; 2581 } 2582 2583 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator> 2584 cl::getRegisteredSubcommands() { 2585 return GlobalParser->getRegisteredSubcommands(); 2586 } 2587 2588 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) { 2589 for (auto &I : Sub.OptionsMap) { 2590 for (auto &Cat : I.second->Categories) { 2591 if (Cat != &Category && 2592 Cat != &GenericCategory) 2593 I.second->setHiddenFlag(cl::ReallyHidden); 2594 } 2595 } 2596 } 2597 2598 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories, 2599 SubCommand &Sub) { 2600 for (auto &I : Sub.OptionsMap) { 2601 for (auto &Cat : I.second->Categories) { 2602 if (!is_contained(Categories, Cat) && Cat != &GenericCategory) 2603 I.second->setHiddenFlag(cl::ReallyHidden); 2604 } 2605 } 2606 } 2607 2608 void cl::ResetCommandLineParser() { GlobalParser->reset(); } 2609 void cl::ResetAllOptionOccurrences() { 2610 GlobalParser->ResetAllOptionOccurrences(); 2611 } 2612 2613 void LLVMParseCommandLineOptions(int argc, const char *const *argv, 2614 const char *Overview) { 2615 llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview), 2616 &llvm::nulls()); 2617 } 2618