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