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