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