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