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