1 //===- llvm/Support/CommandLine.h - Command line handler --------*- C++ -*-===// 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 should 14 // read the library documentation located in docs/CommandLine.html or looks at 15 // the many example usages in tools/*/*.cpp 16 // 17 //===----------------------------------------------------------------------===// 18 19 #ifndef LLVM_SUPPORT_COMMANDLINE_H 20 #define LLVM_SUPPORT_COMMANDLINE_H 21 22 #include "llvm/ADT/ArrayRef.h" 23 #include "llvm/ADT/None.h" 24 #include "llvm/ADT/Optional.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SmallPtrSet.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/ADT/StringMap.h" 29 #include "llvm/ADT/StringRef.h" 30 #include "llvm/ADT/Twine.h" 31 #include "llvm/ADT/iterator_range.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/ManagedStatic.h" 34 #include "llvm/Support/VirtualFileSystem.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include <cassert> 37 #include <climits> 38 #include <cstddef> 39 #include <functional> 40 #include <initializer_list> 41 #include <string> 42 #include <type_traits> 43 #include <vector> 44 45 namespace llvm { 46 47 class StringSaver; 48 49 /// cl Namespace - This namespace contains all of the command line option 50 /// processing machinery. It is intentionally a short name to make qualified 51 /// usage concise. 52 namespace cl { 53 54 //===----------------------------------------------------------------------===// 55 // ParseCommandLineOptions - Command line option processing entry point. 56 // 57 // Returns true on success. Otherwise, this will print the error message to 58 // stderr and exit if \p Errs is not set (nullptr by default), or print the 59 // error message to \p Errs and return false if \p Errs is provided. 60 // 61 // If EnvVar is not nullptr, command-line options are also parsed from the 62 // environment variable named by EnvVar. Precedence is given to occurrences 63 // from argv. This precedence is currently implemented by parsing argv after 64 // the environment variable, so it is only implemented correctly for options 65 // that give precedence to later occurrences. If your program supports options 66 // that give precedence to earlier occurrences, you will need to extend this 67 // function to support it correctly. 68 bool ParseCommandLineOptions(int argc, const char *const *argv, 69 StringRef Overview = "", 70 raw_ostream *Errs = nullptr, 71 const char *EnvVar = nullptr, 72 bool LongOptionsUseDoubleDash = false); 73 74 //===----------------------------------------------------------------------===// 75 // ParseEnvironmentOptions - Environment variable option processing alternate 76 // entry point. 77 // 78 void ParseEnvironmentOptions(const char *progName, const char *envvar, 79 const char *Overview = ""); 80 81 // Function pointer type for printing version information. 82 using VersionPrinterTy = std::function<void(raw_ostream &)>; 83 84 ///===---------------------------------------------------------------------===// 85 /// SetVersionPrinter - Override the default (LLVM specific) version printer 86 /// used to print out the version when --version is given 87 /// on the command line. This allows other systems using the 88 /// CommandLine utilities to print their own version string. 89 void SetVersionPrinter(VersionPrinterTy func); 90 91 ///===---------------------------------------------------------------------===// 92 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the 93 /// default one. This can be called multiple times, 94 /// and each time it adds a new function to the list 95 /// which will be called after the basic LLVM version 96 /// printing is complete. Each can then add additional 97 /// information specific to the tool. 98 void AddExtraVersionPrinter(VersionPrinterTy func); 99 100 // PrintOptionValues - Print option values. 101 // With -print-options print the difference between option values and defaults. 102 // With -print-all-options print all option values. 103 // (Currently not perfect, but best-effort.) 104 void PrintOptionValues(); 105 106 // Forward declaration - AddLiteralOption needs to be up here to make gcc happy. 107 class Option; 108 109 /// Adds a new option for parsing and provides the option it refers to. 110 /// 111 /// \param O pointer to the option 112 /// \param Name the string name for the option to handle during parsing 113 /// 114 /// Literal options are used by some parsers to register special option values. 115 /// This is how the PassNameParser registers pass names for opt. 116 void AddLiteralOption(Option &O, StringRef Name); 117 118 //===----------------------------------------------------------------------===// 119 // Flags permitted to be passed to command line arguments 120 // 121 122 enum NumOccurrencesFlag { // Flags for the number of occurrences allowed 123 Optional = 0x00, // Zero or One occurrence 124 ZeroOrMore = 0x01, // Zero or more occurrences allowed 125 Required = 0x02, // One occurrence required 126 OneOrMore = 0x03, // One or more occurrences required 127 128 // ConsumeAfter - Indicates that this option is fed anything that follows the 129 // last positional argument required by the application (it is an error if 130 // there are zero positional arguments, and a ConsumeAfter option is used). 131 // Thus, for example, all arguments to LLI are processed until a filename is 132 // found. Once a filename is found, all of the succeeding arguments are 133 // passed, unprocessed, to the ConsumeAfter option. 134 // 135 ConsumeAfter = 0x04 136 }; 137 138 enum ValueExpected { // Is a value required for the option? 139 // zero reserved for the unspecified value 140 ValueOptional = 0x01, // The value can appear... or not 141 ValueRequired = 0x02, // The value is required to appear! 142 ValueDisallowed = 0x03 // A value may not be specified (for flags) 143 }; 144 145 enum OptionHidden { // Control whether -help shows this option 146 NotHidden = 0x00, // Option included in -help & -help-hidden 147 Hidden = 0x01, // -help doesn't, but -help-hidden does 148 ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg 149 }; 150 151 // Formatting flags - This controls special features that the option might have 152 // that cause it to be parsed differently... 153 // 154 // Prefix - This option allows arguments that are otherwise unrecognized to be 155 // matched by options that are a prefix of the actual value. This is useful for 156 // cases like a linker, where options are typically of the form '-lfoo' or 157 // '-L../../include' where -l or -L are the actual flags. When prefix is 158 // enabled, and used, the value for the flag comes from the suffix of the 159 // argument. 160 // 161 // AlwaysPrefix - Only allow the behavior enabled by the Prefix flag and reject 162 // the Option=Value form. 163 // 164 165 enum FormattingFlags { 166 NormalFormatting = 0x00, // Nothing special 167 Positional = 0x01, // Is a positional argument, no '-' required 168 Prefix = 0x02, // Can this option directly prefix its value? 169 AlwaysPrefix = 0x03 // Can this option only directly prefix its value? 170 }; 171 172 enum MiscFlags { // Miscellaneous flags to adjust argument 173 CommaSeparated = 0x01, // Should this cl::list split between commas? 174 PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args? 175 Sink = 0x04, // Should this cl::list eat all unknown options? 176 177 // Grouping - Can this option group with other options? 178 // If this is enabled, multiple letter options are allowed to bunch together 179 // with only a single hyphen for the whole group. This allows emulation 180 // of the behavior that ls uses for example: ls -la === ls -l -a 181 Grouping = 0x08, 182 183 // Default option 184 DefaultOption = 0x10 185 }; 186 187 //===----------------------------------------------------------------------===// 188 // Option Category class 189 // 190 class OptionCategory { 191 private: 192 StringRef const Name; 193 StringRef const Description; 194 195 void registerCategory(); 196 197 public: 198 OptionCategory(StringRef const Name, 199 StringRef const Description = "") 200 : Name(Name), Description(Description) { 201 registerCategory(); 202 } 203 204 StringRef getName() const { return Name; } 205 StringRef getDescription() const { return Description; } 206 }; 207 208 // The general Option Category (used as default category). 209 extern OptionCategory GeneralCategory; 210 211 //===----------------------------------------------------------------------===// 212 // SubCommand class 213 // 214 class SubCommand { 215 private: 216 StringRef Name; 217 StringRef Description; 218 219 protected: 220 void registerSubCommand(); 221 void unregisterSubCommand(); 222 223 public: 224 SubCommand(StringRef Name, StringRef Description = "") 225 : Name(Name), Description(Description) { 226 registerSubCommand(); 227 } 228 SubCommand() = default; 229 230 void reset(); 231 232 explicit operator bool() const; 233 234 StringRef getName() const { return Name; } 235 StringRef getDescription() const { return Description; } 236 237 SmallVector<Option *, 4> PositionalOpts; 238 SmallVector<Option *, 4> SinkOpts; 239 StringMap<Option *> OptionsMap; 240 241 Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists. 242 }; 243 244 // A special subcommand representing no subcommand 245 extern ManagedStatic<SubCommand> TopLevelSubCommand; 246 247 // A special subcommand that can be used to put an option into all subcommands. 248 extern ManagedStatic<SubCommand> AllSubCommands; 249 250 //===----------------------------------------------------------------------===// 251 // Option Base class 252 // 253 class Option { 254 friend class alias; 255 256 // handleOccurrences - Overriden by subclasses to handle the value passed into 257 // an argument. Should return true if there was an error processing the 258 // argument and the program should exit. 259 // 260 virtual bool handleOccurrence(unsigned pos, StringRef ArgName, 261 StringRef Arg) = 0; 262 263 virtual enum ValueExpected getValueExpectedFlagDefault() const { 264 return ValueOptional; 265 } 266 267 // Out of line virtual function to provide home for the class. 268 virtual void anchor(); 269 270 uint16_t NumOccurrences; // The number of times specified 271 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid 272 // problems with signed enums in bitfields. 273 uint16_t Occurrences : 3; // enum NumOccurrencesFlag 274 // not using the enum type for 'Value' because zero is an implementation 275 // detail representing the non-value 276 uint16_t Value : 2; 277 uint16_t HiddenFlag : 2; // enum OptionHidden 278 uint16_t Formatting : 2; // enum FormattingFlags 279 uint16_t Misc : 5; 280 uint16_t FullyInitialized : 1; // Has addArgument been called? 281 uint16_t Position; // Position of last occurrence of the option 282 uint16_t AdditionalVals; // Greater than 0 for multi-valued option. 283 284 public: 285 StringRef ArgStr; // The argument string itself (ex: "help", "o") 286 StringRef HelpStr; // The descriptive text message for -help 287 StringRef ValueStr; // String describing what the value of this option is 288 SmallVector<OptionCategory *, 1> 289 Categories; // The Categories this option belongs to 290 SmallPtrSet<SubCommand *, 1> Subs; // The subcommands this option belongs to. 291 292 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const { 293 return (enum NumOccurrencesFlag)Occurrences; 294 } 295 296 inline enum ValueExpected getValueExpectedFlag() const { 297 return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault(); 298 } 299 300 inline enum OptionHidden getOptionHiddenFlag() const { 301 return (enum OptionHidden)HiddenFlag; 302 } 303 304 inline enum FormattingFlags getFormattingFlag() const { 305 return (enum FormattingFlags)Formatting; 306 } 307 308 inline unsigned getMiscFlags() const { return Misc; } 309 inline unsigned getPosition() const { return Position; } 310 inline unsigned getNumAdditionalVals() const { return AdditionalVals; } 311 312 // hasArgStr - Return true if the argstr != "" 313 bool hasArgStr() const { return !ArgStr.empty(); } 314 bool isPositional() const { return getFormattingFlag() == cl::Positional; } 315 bool isSink() const { return getMiscFlags() & cl::Sink; } 316 bool isDefaultOption() const { return getMiscFlags() & cl::DefaultOption; } 317 318 bool isConsumeAfter() const { 319 return getNumOccurrencesFlag() == cl::ConsumeAfter; 320 } 321 322 bool isInAllSubCommands() const { 323 return any_of(Subs, [](const SubCommand *SC) { 324 return SC == &*AllSubCommands; 325 }); 326 } 327 328 //-------------------------------------------------------------------------=== 329 // Accessor functions set by OptionModifiers 330 // 331 void setArgStr(StringRef S); 332 void setDescription(StringRef S) { HelpStr = S; } 333 void setValueStr(StringRef S) { ValueStr = S; } 334 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; } 335 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; } 336 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; } 337 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; } 338 void setMiscFlag(enum MiscFlags M) { Misc |= M; } 339 void setPosition(unsigned pos) { Position = pos; } 340 void addCategory(OptionCategory &C); 341 void addSubCommand(SubCommand &S) { Subs.insert(&S); } 342 343 protected: 344 explicit Option(enum NumOccurrencesFlag OccurrencesFlag, 345 enum OptionHidden Hidden) 346 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0), 347 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), 348 FullyInitialized(false), Position(0), AdditionalVals(0) { 349 Categories.push_back(&GeneralCategory); 350 } 351 352 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; } 353 354 public: 355 virtual ~Option() = default; 356 357 // addArgument - Register this argument with the commandline system. 358 // 359 void addArgument(); 360 361 /// Unregisters this option from the CommandLine system. 362 /// 363 /// This option must have been the last option registered. 364 /// For testing purposes only. 365 void removeArgument(); 366 367 // Return the width of the option tag for printing... 368 virtual size_t getOptionWidth() const = 0; 369 370 // printOptionInfo - Print out information about this option. The 371 // to-be-maintained width is specified. 372 // 373 virtual void printOptionInfo(size_t GlobalWidth) const = 0; 374 375 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0; 376 377 virtual void setDefault() = 0; 378 379 static void printHelpStr(StringRef HelpStr, size_t Indent, 380 size_t FirstLineIndentedBy); 381 382 virtual void getExtraOptionNames(SmallVectorImpl<StringRef> &) {} 383 384 // addOccurrence - Wrapper around handleOccurrence that enforces Flags. 385 // 386 virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value, 387 bool MultiArg = false); 388 389 // Prints option name followed by message. Always returns true. 390 bool error(const Twine &Message, StringRef ArgName = StringRef(), raw_ostream &Errs = llvm::errs()); 391 bool error(const Twine &Message, raw_ostream &Errs) { 392 return error(Message, StringRef(), Errs); 393 } 394 395 inline int getNumOccurrences() const { return NumOccurrences; } 396 void reset(); 397 }; 398 399 //===----------------------------------------------------------------------===// 400 // Command line option modifiers that can be used to modify the behavior of 401 // command line option parsers... 402 // 403 404 // desc - Modifier to set the description shown in the -help output... 405 struct desc { 406 StringRef Desc; 407 408 desc(StringRef Str) : Desc(Str) {} 409 410 void apply(Option &O) const { O.setDescription(Desc); } 411 }; 412 413 // value_desc - Modifier to set the value description shown in the -help 414 // output... 415 struct value_desc { 416 StringRef Desc; 417 418 value_desc(StringRef Str) : Desc(Str) {} 419 420 void apply(Option &O) const { O.setValueStr(Desc); } 421 }; 422 423 // init - Specify a default (initial) value for the command line argument, if 424 // the default constructor for the argument type does not give you what you 425 // want. This is only valid on "opt" arguments, not on "list" arguments. 426 // 427 template <class Ty> struct initializer { 428 const Ty &Init; 429 initializer(const Ty &Val) : Init(Val) {} 430 431 template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); } 432 }; 433 434 template <class Ty> initializer<Ty> init(const Ty &Val) { 435 return initializer<Ty>(Val); 436 } 437 438 // location - Allow the user to specify which external variable they want to 439 // store the results of the command line argument processing into, if they don't 440 // want to store it in the option itself. 441 // 442 template <class Ty> struct LocationClass { 443 Ty &Loc; 444 445 LocationClass(Ty &L) : Loc(L) {} 446 447 template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); } 448 }; 449 450 template <class Ty> LocationClass<Ty> location(Ty &L) { 451 return LocationClass<Ty>(L); 452 } 453 454 // cat - Specifiy the Option category for the command line argument to belong 455 // to. 456 struct cat { 457 OptionCategory &Category; 458 459 cat(OptionCategory &c) : Category(c) {} 460 461 template <class Opt> void apply(Opt &O) const { O.addCategory(Category); } 462 }; 463 464 // sub - Specify the subcommand that this option belongs to. 465 struct sub { 466 SubCommand ⋐ 467 468 sub(SubCommand &S) : Sub(S) {} 469 470 template <class Opt> void apply(Opt &O) const { O.addSubCommand(Sub); } 471 }; 472 473 // Specify a callback function to be called when an option is seen. 474 // Can be used to set other options automatically. 475 template <typename R, typename Ty> struct cb { 476 std::function<R(Ty)> CB; 477 478 cb(std::function<R(Ty)> CB) : CB(CB) {} 479 480 template <typename Opt> void apply(Opt &O) const { O.setCallback(CB); } 481 }; 482 483 namespace detail { 484 template <typename F> 485 struct callback_traits : public callback_traits<decltype(&F::operator())> {}; 486 487 template <typename R, typename C, typename... Args> 488 struct callback_traits<R (C::*)(Args...) const> { 489 using result_type = R; 490 using arg_type = std::tuple_element_t<0, std::tuple<Args...>>; 491 static_assert(sizeof...(Args) == 1, "callback function must have one and only one parameter"); 492 static_assert(std::is_same<result_type, void>::value, 493 "callback return type must be void"); 494 static_assert(std::is_lvalue_reference<arg_type>::value && 495 std::is_const<std::remove_reference_t<arg_type>>::value, 496 "callback arg_type must be a const lvalue reference"); 497 }; 498 } // namespace detail 499 500 template <typename F> 501 cb<typename detail::callback_traits<F>::result_type, 502 typename detail::callback_traits<F>::arg_type> 503 callback(F CB) { 504 using result_type = typename detail::callback_traits<F>::result_type; 505 using arg_type = typename detail::callback_traits<F>::arg_type; 506 return cb<result_type, arg_type>(CB); 507 } 508 509 //===----------------------------------------------------------------------===// 510 // OptionValue class 511 512 // Support value comparison outside the template. 513 struct GenericOptionValue { 514 virtual bool compare(const GenericOptionValue &V) const = 0; 515 516 protected: 517 GenericOptionValue() = default; 518 GenericOptionValue(const GenericOptionValue&) = default; 519 GenericOptionValue &operator=(const GenericOptionValue &) = default; 520 ~GenericOptionValue() = default; 521 522 private: 523 virtual void anchor(); 524 }; 525 526 template <class DataType> struct OptionValue; 527 528 // The default value safely does nothing. Option value printing is only 529 // best-effort. 530 template <class DataType, bool isClass> 531 struct OptionValueBase : public GenericOptionValue { 532 // Temporary storage for argument passing. 533 using WrapperType = OptionValue<DataType>; 534 535 bool hasValue() const { return false; } 536 537 const DataType &getValue() const { llvm_unreachable("no default value"); } 538 539 // Some options may take their value from a different data type. 540 template <class DT> void setValue(const DT & /*V*/) {} 541 542 bool compare(const DataType & /*V*/) const { return false; } 543 544 bool compare(const GenericOptionValue & /*V*/) const override { 545 return false; 546 } 547 548 protected: 549 ~OptionValueBase() = default; 550 }; 551 552 // Simple copy of the option value. 553 template <class DataType> class OptionValueCopy : public GenericOptionValue { 554 DataType Value; 555 bool Valid = false; 556 557 protected: 558 OptionValueCopy(const OptionValueCopy&) = default; 559 OptionValueCopy &operator=(const OptionValueCopy &) = default; 560 ~OptionValueCopy() = default; 561 562 public: 563 OptionValueCopy() = default; 564 565 bool hasValue() const { return Valid; } 566 567 const DataType &getValue() const { 568 assert(Valid && "invalid option value"); 569 return Value; 570 } 571 572 void setValue(const DataType &V) { 573 Valid = true; 574 Value = V; 575 } 576 577 bool compare(const DataType &V) const { return Valid && (Value != V); } 578 579 bool compare(const GenericOptionValue &V) const override { 580 const OptionValueCopy<DataType> &VC = 581 static_cast<const OptionValueCopy<DataType> &>(V); 582 if (!VC.hasValue()) 583 return false; 584 return compare(VC.getValue()); 585 } 586 }; 587 588 // Non-class option values. 589 template <class DataType> 590 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> { 591 using WrapperType = DataType; 592 593 protected: 594 OptionValueBase() = default; 595 OptionValueBase(const OptionValueBase&) = default; 596 OptionValueBase &operator=(const OptionValueBase &) = default; 597 ~OptionValueBase() = default; 598 }; 599 600 // Top-level option class. 601 template <class DataType> 602 struct OptionValue final 603 : OptionValueBase<DataType, std::is_class<DataType>::value> { 604 OptionValue() = default; 605 606 OptionValue(const DataType &V) { this->setValue(V); } 607 608 // Some options may take their value from a different data type. 609 template <class DT> OptionValue<DataType> &operator=(const DT &V) { 610 this->setValue(V); 611 return *this; 612 } 613 }; 614 615 // Other safe-to-copy-by-value common option types. 616 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE }; 617 template <> 618 struct OptionValue<cl::boolOrDefault> final 619 : OptionValueCopy<cl::boolOrDefault> { 620 using WrapperType = cl::boolOrDefault; 621 622 OptionValue() = default; 623 624 OptionValue(const cl::boolOrDefault &V) { this->setValue(V); } 625 626 OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) { 627 setValue(V); 628 return *this; 629 } 630 631 private: 632 void anchor() override; 633 }; 634 635 template <> 636 struct OptionValue<std::string> final : OptionValueCopy<std::string> { 637 using WrapperType = StringRef; 638 639 OptionValue() = default; 640 641 OptionValue(const std::string &V) { this->setValue(V); } 642 643 OptionValue<std::string> &operator=(const std::string &V) { 644 setValue(V); 645 return *this; 646 } 647 648 private: 649 void anchor() override; 650 }; 651 652 //===----------------------------------------------------------------------===// 653 // Enum valued command line option 654 // 655 656 // This represents a single enum value, using "int" as the underlying type. 657 struct OptionEnumValue { 658 StringRef Name; 659 int Value; 660 StringRef Description; 661 }; 662 663 #define clEnumVal(ENUMVAL, DESC) \ 664 llvm::cl::OptionEnumValue { #ENUMVAL, int(ENUMVAL), DESC } 665 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) \ 666 llvm::cl::OptionEnumValue { FLAGNAME, int(ENUMVAL), DESC } 667 668 // values - For custom data types, allow specifying a group of values together 669 // as the values that go into the mapping that the option handler uses. 670 // 671 class ValuesClass { 672 // Use a vector instead of a map, because the lists should be short, 673 // the overhead is less, and most importantly, it keeps them in the order 674 // inserted so we can print our option out nicely. 675 SmallVector<OptionEnumValue, 4> Values; 676 677 public: 678 ValuesClass(std::initializer_list<OptionEnumValue> Options) 679 : Values(Options) {} 680 681 template <class Opt> void apply(Opt &O) const { 682 for (auto Value : Values) 683 O.getParser().addLiteralOption(Value.Name, Value.Value, 684 Value.Description); 685 } 686 }; 687 688 /// Helper to build a ValuesClass by forwarding a variable number of arguments 689 /// as an initializer list to the ValuesClass constructor. 690 template <typename... OptsTy> ValuesClass values(OptsTy... Options) { 691 return ValuesClass({Options...}); 692 } 693 694 //===----------------------------------------------------------------------===// 695 // parser class - Parameterizable parser for different data types. By default, 696 // known data types (string, int, bool) have specialized parsers, that do what 697 // you would expect. The default parser, used for data types that are not 698 // built-in, uses a mapping table to map specific options to values, which is 699 // used, among other things, to handle enum types. 700 701 //-------------------------------------------------- 702 // generic_parser_base - This class holds all the non-generic code that we do 703 // not need replicated for every instance of the generic parser. This also 704 // allows us to put stuff into CommandLine.cpp 705 // 706 class generic_parser_base { 707 protected: 708 class GenericOptionInfo { 709 public: 710 GenericOptionInfo(StringRef name, StringRef helpStr) 711 : Name(name), HelpStr(helpStr) {} 712 StringRef Name; 713 StringRef HelpStr; 714 }; 715 716 public: 717 generic_parser_base(Option &O) : Owner(O) {} 718 719 virtual ~generic_parser_base() = default; 720 // Base class should have virtual-destructor 721 722 // getNumOptions - Virtual function implemented by generic subclass to 723 // indicate how many entries are in Values. 724 // 725 virtual unsigned getNumOptions() const = 0; 726 727 // getOption - Return option name N. 728 virtual StringRef getOption(unsigned N) const = 0; 729 730 // getDescription - Return description N 731 virtual StringRef getDescription(unsigned N) const = 0; 732 733 // Return the width of the option tag for printing... 734 virtual size_t getOptionWidth(const Option &O) const; 735 736 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0; 737 738 // printOptionInfo - Print out information about this option. The 739 // to-be-maintained width is specified. 740 // 741 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const; 742 743 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V, 744 const GenericOptionValue &Default, 745 size_t GlobalWidth) const; 746 747 // printOptionDiff - print the value of an option and it's default. 748 // 749 // Template definition ensures that the option and default have the same 750 // DataType (via the same AnyOptionValue). 751 template <class AnyOptionValue> 752 void printOptionDiff(const Option &O, const AnyOptionValue &V, 753 const AnyOptionValue &Default, 754 size_t GlobalWidth) const { 755 printGenericOptionDiff(O, V, Default, GlobalWidth); 756 } 757 758 void initialize() {} 759 760 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) { 761 // If there has been no argstr specified, that means that we need to add an 762 // argument for every possible option. This ensures that our options are 763 // vectored to us. 764 if (!Owner.hasArgStr()) 765 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 766 OptionNames.push_back(getOption(i)); 767 } 768 769 enum ValueExpected getValueExpectedFlagDefault() const { 770 // If there is an ArgStr specified, then we are of the form: 771 // 772 // -opt=O2 or -opt O2 or -optO2 773 // 774 // In which case, the value is required. Otherwise if an arg str has not 775 // been specified, we are of the form: 776 // 777 // -O2 or O2 or -la (where -l and -a are separate options) 778 // 779 // If this is the case, we cannot allow a value. 780 // 781 if (Owner.hasArgStr()) 782 return ValueRequired; 783 else 784 return ValueDisallowed; 785 } 786 787 // findOption - Return the option number corresponding to the specified 788 // argument string. If the option is not found, getNumOptions() is returned. 789 // 790 unsigned findOption(StringRef Name); 791 792 protected: 793 Option &Owner; 794 }; 795 796 // Default parser implementation - This implementation depends on having a 797 // mapping of recognized options to values of some sort. In addition to this, 798 // each entry in the mapping also tracks a help message that is printed with the 799 // command line option for -help. Because this is a simple mapping parser, the 800 // data type can be any unsupported type. 801 // 802 template <class DataType> class parser : public generic_parser_base { 803 protected: 804 class OptionInfo : public GenericOptionInfo { 805 public: 806 OptionInfo(StringRef name, DataType v, StringRef helpStr) 807 : GenericOptionInfo(name, helpStr), V(v) {} 808 809 OptionValue<DataType> V; 810 }; 811 SmallVector<OptionInfo, 8> Values; 812 813 public: 814 parser(Option &O) : generic_parser_base(O) {} 815 816 using parser_data_type = DataType; 817 818 // Implement virtual functions needed by generic_parser_base 819 unsigned getNumOptions() const override { return unsigned(Values.size()); } 820 StringRef getOption(unsigned N) const override { return Values[N].Name; } 821 StringRef getDescription(unsigned N) const override { 822 return Values[N].HelpStr; 823 } 824 825 // getOptionValue - Return the value of option name N. 826 const GenericOptionValue &getOptionValue(unsigned N) const override { 827 return Values[N].V; 828 } 829 830 // parse - Return true on error. 831 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) { 832 StringRef ArgVal; 833 if (Owner.hasArgStr()) 834 ArgVal = Arg; 835 else 836 ArgVal = ArgName; 837 838 for (size_t i = 0, e = Values.size(); i != e; ++i) 839 if (Values[i].Name == ArgVal) { 840 V = Values[i].V.getValue(); 841 return false; 842 } 843 844 return O.error("Cannot find option named '" + ArgVal + "'!"); 845 } 846 847 /// addLiteralOption - Add an entry to the mapping table. 848 /// 849 template <class DT> 850 void addLiteralOption(StringRef Name, const DT &V, StringRef HelpStr) { 851 assert(findOption(Name) == Values.size() && "Option already exists!"); 852 OptionInfo X(Name, static_cast<DataType>(V), HelpStr); 853 Values.push_back(X); 854 AddLiteralOption(Owner, Name); 855 } 856 857 /// removeLiteralOption - Remove the specified option. 858 /// 859 void removeLiteralOption(StringRef Name) { 860 unsigned N = findOption(Name); 861 assert(N != Values.size() && "Option not found!"); 862 Values.erase(Values.begin() + N); 863 } 864 }; 865 866 //-------------------------------------------------- 867 // basic_parser - Super class of parsers to provide boilerplate code 868 // 869 class basic_parser_impl { // non-template implementation of basic_parser<t> 870 public: 871 basic_parser_impl(Option &) {} 872 873 virtual ~basic_parser_impl() {} 874 875 enum ValueExpected getValueExpectedFlagDefault() const { 876 return ValueRequired; 877 } 878 879 void getExtraOptionNames(SmallVectorImpl<StringRef> &) {} 880 881 void initialize() {} 882 883 // Return the width of the option tag for printing... 884 size_t getOptionWidth(const Option &O) const; 885 886 // printOptionInfo - Print out information about this option. The 887 // to-be-maintained width is specified. 888 // 889 void printOptionInfo(const Option &O, size_t GlobalWidth) const; 890 891 // printOptionNoValue - Print a placeholder for options that don't yet support 892 // printOptionDiff(). 893 void printOptionNoValue(const Option &O, size_t GlobalWidth) const; 894 895 // getValueName - Overload in subclass to provide a better default value. 896 virtual StringRef getValueName() const { return "value"; } 897 898 // An out-of-line virtual method to provide a 'home' for this class. 899 virtual void anchor(); 900 901 protected: 902 // A helper for basic_parser::printOptionDiff. 903 void printOptionName(const Option &O, size_t GlobalWidth) const; 904 }; 905 906 // basic_parser - The real basic parser is just a template wrapper that provides 907 // a typedef for the provided data type. 908 // 909 template <class DataType> class basic_parser : public basic_parser_impl { 910 public: 911 using parser_data_type = DataType; 912 using OptVal = OptionValue<DataType>; 913 914 basic_parser(Option &O) : basic_parser_impl(O) {} 915 }; 916 917 //-------------------------------------------------- 918 // parser<bool> 919 // 920 template <> class parser<bool> : public basic_parser<bool> { 921 public: 922 parser(Option &O) : basic_parser(O) {} 923 924 // parse - Return true on error. 925 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val); 926 927 void initialize() {} 928 929 enum ValueExpected getValueExpectedFlagDefault() const { 930 return ValueOptional; 931 } 932 933 // getValueName - Do not print =<value> at all. 934 StringRef getValueName() const override { return StringRef(); } 935 936 void printOptionDiff(const Option &O, bool V, OptVal Default, 937 size_t GlobalWidth) const; 938 939 // An out-of-line virtual method to provide a 'home' for this class. 940 void anchor() override; 941 }; 942 943 extern template class basic_parser<bool>; 944 945 //-------------------------------------------------- 946 // parser<boolOrDefault> 947 template <> class parser<boolOrDefault> : public basic_parser<boolOrDefault> { 948 public: 949 parser(Option &O) : basic_parser(O) {} 950 951 // parse - Return true on error. 952 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val); 953 954 enum ValueExpected getValueExpectedFlagDefault() const { 955 return ValueOptional; 956 } 957 958 // getValueName - Do not print =<value> at all. 959 StringRef getValueName() const override { return StringRef(); } 960 961 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default, 962 size_t GlobalWidth) const; 963 964 // An out-of-line virtual method to provide a 'home' for this class. 965 void anchor() override; 966 }; 967 968 extern template class basic_parser<boolOrDefault>; 969 970 //-------------------------------------------------- 971 // parser<int> 972 // 973 template <> class parser<int> : public basic_parser<int> { 974 public: 975 parser(Option &O) : basic_parser(O) {} 976 977 // parse - Return true on error. 978 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val); 979 980 // getValueName - Overload in subclass to provide a better default value. 981 StringRef getValueName() const override { return "int"; } 982 983 void printOptionDiff(const Option &O, int V, OptVal Default, 984 size_t GlobalWidth) const; 985 986 // An out-of-line virtual method to provide a 'home' for this class. 987 void anchor() override; 988 }; 989 990 extern template class basic_parser<int>; 991 992 //-------------------------------------------------- 993 // parser<long> 994 // 995 template <> class parser<long> final : public basic_parser<long> { 996 public: 997 parser(Option &O) : basic_parser(O) {} 998 999 // parse - Return true on error. 1000 bool parse(Option &O, StringRef ArgName, StringRef Arg, long &Val); 1001 1002 // getValueName - Overload in subclass to provide a better default value. 1003 StringRef getValueName() const override { return "long"; } 1004 1005 void printOptionDiff(const Option &O, long V, OptVal Default, 1006 size_t GlobalWidth) const; 1007 1008 // An out-of-line virtual method to provide a 'home' for this class. 1009 void anchor() override; 1010 }; 1011 1012 extern template class basic_parser<long>; 1013 1014 //-------------------------------------------------- 1015 // parser<long long> 1016 // 1017 template <> class parser<long long> : public basic_parser<long long> { 1018 public: 1019 parser(Option &O) : basic_parser(O) {} 1020 1021 // parse - Return true on error. 1022 bool parse(Option &O, StringRef ArgName, StringRef Arg, long long &Val); 1023 1024 // getValueName - Overload in subclass to provide a better default value. 1025 StringRef getValueName() const override { return "long"; } 1026 1027 void printOptionDiff(const Option &O, long long V, OptVal Default, 1028 size_t GlobalWidth) const; 1029 1030 // An out-of-line virtual method to provide a 'home' for this class. 1031 void anchor() override; 1032 }; 1033 1034 extern template class basic_parser<long long>; 1035 1036 //-------------------------------------------------- 1037 // parser<unsigned> 1038 // 1039 template <> class parser<unsigned> : public basic_parser<unsigned> { 1040 public: 1041 parser(Option &O) : basic_parser(O) {} 1042 1043 // parse - Return true on error. 1044 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val); 1045 1046 // getValueName - Overload in subclass to provide a better default value. 1047 StringRef getValueName() const override { return "uint"; } 1048 1049 void printOptionDiff(const Option &O, unsigned V, OptVal Default, 1050 size_t GlobalWidth) const; 1051 1052 // An out-of-line virtual method to provide a 'home' for this class. 1053 void anchor() override; 1054 }; 1055 1056 extern template class basic_parser<unsigned>; 1057 1058 //-------------------------------------------------- 1059 // parser<unsigned long> 1060 // 1061 template <> 1062 class parser<unsigned long> final : public basic_parser<unsigned long> { 1063 public: 1064 parser(Option &O) : basic_parser(O) {} 1065 1066 // parse - Return true on error. 1067 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned long &Val); 1068 1069 // getValueName - Overload in subclass to provide a better default value. 1070 StringRef getValueName() const override { return "ulong"; } 1071 1072 void printOptionDiff(const Option &O, unsigned long V, OptVal Default, 1073 size_t GlobalWidth) const; 1074 1075 // An out-of-line virtual method to provide a 'home' for this class. 1076 void anchor() override; 1077 }; 1078 1079 extern template class basic_parser<unsigned long>; 1080 1081 //-------------------------------------------------- 1082 // parser<unsigned long long> 1083 // 1084 template <> 1085 class parser<unsigned long long> : public basic_parser<unsigned long long> { 1086 public: 1087 parser(Option &O) : basic_parser(O) {} 1088 1089 // parse - Return true on error. 1090 bool parse(Option &O, StringRef ArgName, StringRef Arg, 1091 unsigned long long &Val); 1092 1093 // getValueName - Overload in subclass to provide a better default value. 1094 StringRef getValueName() const override { return "ulong"; } 1095 1096 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default, 1097 size_t GlobalWidth) const; 1098 1099 // An out-of-line virtual method to provide a 'home' for this class. 1100 void anchor() override; 1101 }; 1102 1103 extern template class basic_parser<unsigned long long>; 1104 1105 //-------------------------------------------------- 1106 // parser<double> 1107 // 1108 template <> class parser<double> : public basic_parser<double> { 1109 public: 1110 parser(Option &O) : basic_parser(O) {} 1111 1112 // parse - Return true on error. 1113 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val); 1114 1115 // getValueName - Overload in subclass to provide a better default value. 1116 StringRef getValueName() const override { return "number"; } 1117 1118 void printOptionDiff(const Option &O, double V, OptVal Default, 1119 size_t GlobalWidth) const; 1120 1121 // An out-of-line virtual method to provide a 'home' for this class. 1122 void anchor() override; 1123 }; 1124 1125 extern template class basic_parser<double>; 1126 1127 //-------------------------------------------------- 1128 // parser<float> 1129 // 1130 template <> class parser<float> : public basic_parser<float> { 1131 public: 1132 parser(Option &O) : basic_parser(O) {} 1133 1134 // parse - Return true on error. 1135 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val); 1136 1137 // getValueName - Overload in subclass to provide a better default value. 1138 StringRef getValueName() const override { return "number"; } 1139 1140 void printOptionDiff(const Option &O, float V, OptVal Default, 1141 size_t GlobalWidth) const; 1142 1143 // An out-of-line virtual method to provide a 'home' for this class. 1144 void anchor() override; 1145 }; 1146 1147 extern template class basic_parser<float>; 1148 1149 //-------------------------------------------------- 1150 // parser<std::string> 1151 // 1152 template <> class parser<std::string> : public basic_parser<std::string> { 1153 public: 1154 parser(Option &O) : basic_parser(O) {} 1155 1156 // parse - Return true on error. 1157 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) { 1158 Value = Arg.str(); 1159 return false; 1160 } 1161 1162 // getValueName - Overload in subclass to provide a better default value. 1163 StringRef getValueName() const override { return "string"; } 1164 1165 void printOptionDiff(const Option &O, StringRef V, const OptVal &Default, 1166 size_t GlobalWidth) const; 1167 1168 // An out-of-line virtual method to provide a 'home' for this class. 1169 void anchor() override; 1170 }; 1171 1172 extern template class basic_parser<std::string>; 1173 1174 //-------------------------------------------------- 1175 // parser<char> 1176 // 1177 template <> class parser<char> : public basic_parser<char> { 1178 public: 1179 parser(Option &O) : basic_parser(O) {} 1180 1181 // parse - Return true on error. 1182 bool parse(Option &, StringRef, StringRef Arg, char &Value) { 1183 Value = Arg[0]; 1184 return false; 1185 } 1186 1187 // getValueName - Overload in subclass to provide a better default value. 1188 StringRef getValueName() const override { return "char"; } 1189 1190 void printOptionDiff(const Option &O, char V, OptVal Default, 1191 size_t GlobalWidth) const; 1192 1193 // An out-of-line virtual method to provide a 'home' for this class. 1194 void anchor() override; 1195 }; 1196 1197 extern template class basic_parser<char>; 1198 1199 //-------------------------------------------------- 1200 // PrintOptionDiff 1201 // 1202 // This collection of wrappers is the intermediary between class opt and class 1203 // parser to handle all the template nastiness. 1204 1205 // This overloaded function is selected by the generic parser. 1206 template <class ParserClass, class DT> 1207 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V, 1208 const OptionValue<DT> &Default, size_t GlobalWidth) { 1209 OptionValue<DT> OV = V; 1210 P.printOptionDiff(O, OV, Default, GlobalWidth); 1211 } 1212 1213 // This is instantiated for basic parsers when the parsed value has a different 1214 // type than the option value. e.g. HelpPrinter. 1215 template <class ParserDT, class ValDT> struct OptionDiffPrinter { 1216 void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/, 1217 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) { 1218 P.printOptionNoValue(O, GlobalWidth); 1219 } 1220 }; 1221 1222 // This is instantiated for basic parsers when the parsed value has the same 1223 // type as the option value. 1224 template <class DT> struct OptionDiffPrinter<DT, DT> { 1225 void print(const Option &O, const parser<DT> &P, const DT &V, 1226 const OptionValue<DT> &Default, size_t GlobalWidth) { 1227 P.printOptionDiff(O, V, Default, GlobalWidth); 1228 } 1229 }; 1230 1231 // This overloaded function is selected by the basic parser, which may parse a 1232 // different type than the option type. 1233 template <class ParserClass, class ValDT> 1234 void printOptionDiff( 1235 const Option &O, 1236 const basic_parser<typename ParserClass::parser_data_type> &P, 1237 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) { 1238 1239 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer; 1240 printer.print(O, static_cast<const ParserClass &>(P), V, Default, 1241 GlobalWidth); 1242 } 1243 1244 //===----------------------------------------------------------------------===// 1245 // applicator class - This class is used because we must use partial 1246 // specialization to handle literal string arguments specially (const char* does 1247 // not correctly respond to the apply method). Because the syntax to use this 1248 // is a pain, we have the 'apply' method below to handle the nastiness... 1249 // 1250 template <class Mod> struct applicator { 1251 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); } 1252 }; 1253 1254 // Handle const char* as a special case... 1255 template <unsigned n> struct applicator<char[n]> { 1256 template <class Opt> static void opt(StringRef Str, Opt &O) { 1257 O.setArgStr(Str); 1258 } 1259 }; 1260 template <unsigned n> struct applicator<const char[n]> { 1261 template <class Opt> static void opt(StringRef Str, Opt &O) { 1262 O.setArgStr(Str); 1263 } 1264 }; 1265 template <> struct applicator<StringRef > { 1266 template <class Opt> static void opt(StringRef Str, Opt &O) { 1267 O.setArgStr(Str); 1268 } 1269 }; 1270 1271 template <> struct applicator<NumOccurrencesFlag> { 1272 static void opt(NumOccurrencesFlag N, Option &O) { 1273 O.setNumOccurrencesFlag(N); 1274 } 1275 }; 1276 1277 template <> struct applicator<ValueExpected> { 1278 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); } 1279 }; 1280 1281 template <> struct applicator<OptionHidden> { 1282 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); } 1283 }; 1284 1285 template <> struct applicator<FormattingFlags> { 1286 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); } 1287 }; 1288 1289 template <> struct applicator<MiscFlags> { 1290 static void opt(MiscFlags MF, Option &O) { 1291 assert((MF != Grouping || O.ArgStr.size() == 1) && 1292 "cl::Grouping can only apply to single charater Options."); 1293 O.setMiscFlag(MF); 1294 } 1295 }; 1296 1297 // apply method - Apply modifiers to an option in a type safe way. 1298 template <class Opt, class Mod, class... Mods> 1299 void apply(Opt *O, const Mod &M, const Mods &... Ms) { 1300 applicator<Mod>::opt(M, *O); 1301 apply(O, Ms...); 1302 } 1303 1304 template <class Opt, class Mod> void apply(Opt *O, const Mod &M) { 1305 applicator<Mod>::opt(M, *O); 1306 } 1307 1308 //===----------------------------------------------------------------------===// 1309 // opt_storage class 1310 1311 // Default storage class definition: external storage. This implementation 1312 // assumes the user will specify a variable to store the data into with the 1313 // cl::location(x) modifier. 1314 // 1315 template <class DataType, bool ExternalStorage, bool isClass> 1316 class opt_storage { 1317 DataType *Location = nullptr; // Where to store the object... 1318 OptionValue<DataType> Default; 1319 1320 void check_location() const { 1321 assert(Location && "cl::location(...) not specified for a command " 1322 "line option with external storage, " 1323 "or cl::init specified before cl::location()!!"); 1324 } 1325 1326 public: 1327 opt_storage() = default; 1328 1329 bool setLocation(Option &O, DataType &L) { 1330 if (Location) 1331 return O.error("cl::location(x) specified more than once!"); 1332 Location = &L; 1333 Default = L; 1334 return false; 1335 } 1336 1337 template <class T> void setValue(const T &V, bool initial = false) { 1338 check_location(); 1339 *Location = V; 1340 if (initial) 1341 Default = V; 1342 } 1343 1344 DataType &getValue() { 1345 check_location(); 1346 return *Location; 1347 } 1348 const DataType &getValue() const { 1349 check_location(); 1350 return *Location; 1351 } 1352 1353 operator DataType() const { return this->getValue(); } 1354 1355 const OptionValue<DataType> &getDefault() const { return Default; } 1356 }; 1357 1358 // Define how to hold a class type object, such as a string. Since we can 1359 // inherit from a class, we do so. This makes us exactly compatible with the 1360 // object in all cases that it is used. 1361 // 1362 template <class DataType> 1363 class opt_storage<DataType, false, true> : public DataType { 1364 public: 1365 OptionValue<DataType> Default; 1366 1367 template <class T> void setValue(const T &V, bool initial = false) { 1368 DataType::operator=(V); 1369 if (initial) 1370 Default = V; 1371 } 1372 1373 DataType &getValue() { return *this; } 1374 const DataType &getValue() const { return *this; } 1375 1376 const OptionValue<DataType> &getDefault() const { return Default; } 1377 }; 1378 1379 // Define a partial specialization to handle things we cannot inherit from. In 1380 // this case, we store an instance through containment, and overload operators 1381 // to get at the value. 1382 // 1383 template <class DataType> class opt_storage<DataType, false, false> { 1384 public: 1385 DataType Value; 1386 OptionValue<DataType> Default; 1387 1388 // Make sure we initialize the value with the default constructor for the 1389 // type. 1390 opt_storage() : Value(DataType()), Default(DataType()) {} 1391 1392 template <class T> void setValue(const T &V, bool initial = false) { 1393 Value = V; 1394 if (initial) 1395 Default = V; 1396 } 1397 DataType &getValue() { return Value; } 1398 DataType getValue() const { return Value; } 1399 1400 const OptionValue<DataType> &getDefault() const { return Default; } 1401 1402 operator DataType() const { return getValue(); } 1403 1404 // If the datatype is a pointer, support -> on it. 1405 DataType operator->() const { return Value; } 1406 }; 1407 1408 //===----------------------------------------------------------------------===// 1409 // opt - A scalar command line option. 1410 // 1411 template <class DataType, bool ExternalStorage = false, 1412 class ParserClass = parser<DataType>> 1413 class opt : public Option, 1414 public opt_storage<DataType, ExternalStorage, 1415 std::is_class<DataType>::value> { 1416 ParserClass Parser; 1417 1418 bool handleOccurrence(unsigned pos, StringRef ArgName, 1419 StringRef Arg) override { 1420 typename ParserClass::parser_data_type Val = 1421 typename ParserClass::parser_data_type(); 1422 if (Parser.parse(*this, ArgName, Arg, Val)) 1423 return true; // Parse error! 1424 this->setValue(Val); 1425 this->setPosition(pos); 1426 Callback(Val); 1427 return false; 1428 } 1429 1430 enum ValueExpected getValueExpectedFlagDefault() const override { 1431 return Parser.getValueExpectedFlagDefault(); 1432 } 1433 1434 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override { 1435 return Parser.getExtraOptionNames(OptionNames); 1436 } 1437 1438 // Forward printing stuff to the parser... 1439 size_t getOptionWidth() const override { 1440 return Parser.getOptionWidth(*this); 1441 } 1442 1443 void printOptionInfo(size_t GlobalWidth) const override { 1444 Parser.printOptionInfo(*this, GlobalWidth); 1445 } 1446 1447 void printOptionValue(size_t GlobalWidth, bool Force) const override { 1448 if (Force || this->getDefault().compare(this->getValue())) { 1449 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(), 1450 this->getDefault(), GlobalWidth); 1451 } 1452 } 1453 1454 template <class T, 1455 class = std::enable_if_t<std::is_assignable<T &, T>::value>> 1456 void setDefaultImpl() { 1457 const OptionValue<DataType> &V = this->getDefault(); 1458 if (V.hasValue()) 1459 this->setValue(V.getValue()); 1460 } 1461 1462 template <class T, 1463 class = std::enable_if_t<!std::is_assignable<T &, T>::value>> 1464 void setDefaultImpl(...) {} 1465 1466 void setDefault() override { setDefaultImpl<DataType>(); } 1467 1468 void done() { 1469 addArgument(); 1470 Parser.initialize(); 1471 } 1472 1473 public: 1474 // Command line options should not be copyable 1475 opt(const opt &) = delete; 1476 opt &operator=(const opt &) = delete; 1477 1478 // setInitialValue - Used by the cl::init modifier... 1479 void setInitialValue(const DataType &V) { this->setValue(V, true); } 1480 1481 ParserClass &getParser() { return Parser; } 1482 1483 template <class T> DataType &operator=(const T &Val) { 1484 this->setValue(Val); 1485 Callback(Val); 1486 return this->getValue(); 1487 } 1488 1489 template <class... Mods> 1490 explicit opt(const Mods &... Ms) 1491 : Option(Optional, NotHidden), Parser(*this) { 1492 apply(this, Ms...); 1493 done(); 1494 } 1495 1496 void setCallback( 1497 std::function<void(const typename ParserClass::parser_data_type &)> CB) { 1498 Callback = CB; 1499 } 1500 1501 std::function<void(const typename ParserClass::parser_data_type &)> Callback = 1502 [](const typename ParserClass::parser_data_type &) {}; 1503 }; 1504 1505 extern template class opt<unsigned>; 1506 extern template class opt<int>; 1507 extern template class opt<std::string>; 1508 extern template class opt<char>; 1509 extern template class opt<bool>; 1510 1511 //===----------------------------------------------------------------------===// 1512 // list_storage class 1513 1514 // Default storage class definition: external storage. This implementation 1515 // assumes the user will specify a variable to store the data into with the 1516 // cl::location(x) modifier. 1517 // 1518 template <class DataType, class StorageClass> class list_storage { 1519 StorageClass *Location = nullptr; // Where to store the object... 1520 1521 public: 1522 list_storage() = default; 1523 1524 void clear() {} 1525 1526 bool setLocation(Option &O, StorageClass &L) { 1527 if (Location) 1528 return O.error("cl::location(x) specified more than once!"); 1529 Location = &L; 1530 return false; 1531 } 1532 1533 template <class T> void addValue(const T &V) { 1534 assert(Location != 0 && "cl::location(...) not specified for a command " 1535 "line option with external storage!"); 1536 Location->push_back(V); 1537 } 1538 }; 1539 1540 // Define how to hold a class type object, such as a string. 1541 // Originally this code inherited from std::vector. In transitioning to a new 1542 // API for command line options we should change this. The new implementation 1543 // of this list_storage specialization implements the minimum subset of the 1544 // std::vector API required for all the current clients. 1545 // 1546 // FIXME: Reduce this API to a more narrow subset of std::vector 1547 // 1548 template <class DataType> class list_storage<DataType, bool> { 1549 std::vector<DataType> Storage; 1550 1551 public: 1552 using iterator = typename std::vector<DataType>::iterator; 1553 1554 iterator begin() { return Storage.begin(); } 1555 iterator end() { return Storage.end(); } 1556 1557 using const_iterator = typename std::vector<DataType>::const_iterator; 1558 1559 const_iterator begin() const { return Storage.begin(); } 1560 const_iterator end() const { return Storage.end(); } 1561 1562 using size_type = typename std::vector<DataType>::size_type; 1563 1564 size_type size() const { return Storage.size(); } 1565 1566 bool empty() const { return Storage.empty(); } 1567 1568 void push_back(const DataType &value) { Storage.push_back(value); } 1569 void push_back(DataType &&value) { Storage.push_back(value); } 1570 1571 using reference = typename std::vector<DataType>::reference; 1572 using const_reference = typename std::vector<DataType>::const_reference; 1573 1574 reference operator[](size_type pos) { return Storage[pos]; } 1575 const_reference operator[](size_type pos) const { return Storage[pos]; } 1576 1577 void clear() { 1578 Storage.clear(); 1579 } 1580 1581 iterator erase(const_iterator pos) { return Storage.erase(pos); } 1582 iterator erase(const_iterator first, const_iterator last) { 1583 return Storage.erase(first, last); 1584 } 1585 1586 iterator erase(iterator pos) { return Storage.erase(pos); } 1587 iterator erase(iterator first, iterator last) { 1588 return Storage.erase(first, last); 1589 } 1590 1591 iterator insert(const_iterator pos, const DataType &value) { 1592 return Storage.insert(pos, value); 1593 } 1594 iterator insert(const_iterator pos, DataType &&value) { 1595 return Storage.insert(pos, value); 1596 } 1597 1598 iterator insert(iterator pos, const DataType &value) { 1599 return Storage.insert(pos, value); 1600 } 1601 iterator insert(iterator pos, DataType &&value) { 1602 return Storage.insert(pos, value); 1603 } 1604 1605 reference front() { return Storage.front(); } 1606 const_reference front() const { return Storage.front(); } 1607 1608 operator std::vector<DataType> &() { return Storage; } 1609 operator ArrayRef<DataType>() const { return Storage; } 1610 std::vector<DataType> *operator&() { return &Storage; } 1611 const std::vector<DataType> *operator&() const { return &Storage; } 1612 1613 template <class T> void addValue(const T &V) { Storage.push_back(V); } 1614 }; 1615 1616 //===----------------------------------------------------------------------===// 1617 // list - A list of command line options. 1618 // 1619 template <class DataType, class StorageClass = bool, 1620 class ParserClass = parser<DataType>> 1621 class list : public Option, public list_storage<DataType, StorageClass> { 1622 std::vector<unsigned> Positions; 1623 ParserClass Parser; 1624 1625 enum ValueExpected getValueExpectedFlagDefault() const override { 1626 return Parser.getValueExpectedFlagDefault(); 1627 } 1628 1629 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override { 1630 return Parser.getExtraOptionNames(OptionNames); 1631 } 1632 1633 bool handleOccurrence(unsigned pos, StringRef ArgName, 1634 StringRef Arg) override { 1635 typename ParserClass::parser_data_type Val = 1636 typename ParserClass::parser_data_type(); 1637 if (Parser.parse(*this, ArgName, Arg, Val)) 1638 return true; // Parse Error! 1639 list_storage<DataType, StorageClass>::addValue(Val); 1640 setPosition(pos); 1641 Positions.push_back(pos); 1642 Callback(Val); 1643 return false; 1644 } 1645 1646 // Forward printing stuff to the parser... 1647 size_t getOptionWidth() const override { 1648 return Parser.getOptionWidth(*this); 1649 } 1650 1651 void printOptionInfo(size_t GlobalWidth) const override { 1652 Parser.printOptionInfo(*this, GlobalWidth); 1653 } 1654 1655 // Unimplemented: list options don't currently store their default value. 1656 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override { 1657 } 1658 1659 void setDefault() override { 1660 Positions.clear(); 1661 list_storage<DataType, StorageClass>::clear(); 1662 } 1663 1664 void done() { 1665 addArgument(); 1666 Parser.initialize(); 1667 } 1668 1669 public: 1670 // Command line options should not be copyable 1671 list(const list &) = delete; 1672 list &operator=(const list &) = delete; 1673 1674 ParserClass &getParser() { return Parser; } 1675 1676 unsigned getPosition(unsigned optnum) const { 1677 assert(optnum < this->size() && "Invalid option index"); 1678 return Positions[optnum]; 1679 } 1680 1681 void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); } 1682 1683 template <class... Mods> 1684 explicit list(const Mods &... Ms) 1685 : Option(ZeroOrMore, NotHidden), Parser(*this) { 1686 apply(this, Ms...); 1687 done(); 1688 } 1689 1690 void setCallback( 1691 std::function<void(const typename ParserClass::parser_data_type &)> CB) { 1692 Callback = CB; 1693 } 1694 1695 std::function<void(const typename ParserClass::parser_data_type &)> Callback = 1696 [](const typename ParserClass::parser_data_type &) {}; 1697 }; 1698 1699 // multi_val - Modifier to set the number of additional values. 1700 struct multi_val { 1701 unsigned AdditionalVals; 1702 explicit multi_val(unsigned N) : AdditionalVals(N) {} 1703 1704 template <typename D, typename S, typename P> 1705 void apply(list<D, S, P> &L) const { 1706 L.setNumAdditionalVals(AdditionalVals); 1707 } 1708 }; 1709 1710 //===----------------------------------------------------------------------===// 1711 // bits_storage class 1712 1713 // Default storage class definition: external storage. This implementation 1714 // assumes the user will specify a variable to store the data into with the 1715 // cl::location(x) modifier. 1716 // 1717 template <class DataType, class StorageClass> class bits_storage { 1718 unsigned *Location = nullptr; // Where to store the bits... 1719 1720 template <class T> static unsigned Bit(const T &V) { 1721 unsigned BitPos = reinterpret_cast<unsigned>(V); 1722 assert(BitPos < sizeof(unsigned) * CHAR_BIT && 1723 "enum exceeds width of bit vector!"); 1724 return 1 << BitPos; 1725 } 1726 1727 public: 1728 bits_storage() = default; 1729 1730 bool setLocation(Option &O, unsigned &L) { 1731 if (Location) 1732 return O.error("cl::location(x) specified more than once!"); 1733 Location = &L; 1734 return false; 1735 } 1736 1737 template <class T> void addValue(const T &V) { 1738 assert(Location != 0 && "cl::location(...) not specified for a command " 1739 "line option with external storage!"); 1740 *Location |= Bit(V); 1741 } 1742 1743 unsigned getBits() { return *Location; } 1744 1745 template <class T> bool isSet(const T &V) { 1746 return (*Location & Bit(V)) != 0; 1747 } 1748 }; 1749 1750 // Define how to hold bits. Since we can inherit from a class, we do so. 1751 // This makes us exactly compatible with the bits in all cases that it is used. 1752 // 1753 template <class DataType> class bits_storage<DataType, bool> { 1754 unsigned Bits; // Where to store the bits... 1755 1756 template <class T> static unsigned Bit(const T &V) { 1757 unsigned BitPos = (unsigned)V; 1758 assert(BitPos < sizeof(unsigned) * CHAR_BIT && 1759 "enum exceeds width of bit vector!"); 1760 return 1 << BitPos; 1761 } 1762 1763 public: 1764 template <class T> void addValue(const T &V) { Bits |= Bit(V); } 1765 1766 unsigned getBits() { return Bits; } 1767 1768 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; } 1769 }; 1770 1771 //===----------------------------------------------------------------------===// 1772 // bits - A bit vector of command options. 1773 // 1774 template <class DataType, class Storage = bool, 1775 class ParserClass = parser<DataType>> 1776 class bits : public Option, public bits_storage<DataType, Storage> { 1777 std::vector<unsigned> Positions; 1778 ParserClass Parser; 1779 1780 enum ValueExpected getValueExpectedFlagDefault() const override { 1781 return Parser.getValueExpectedFlagDefault(); 1782 } 1783 1784 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override { 1785 return Parser.getExtraOptionNames(OptionNames); 1786 } 1787 1788 bool handleOccurrence(unsigned pos, StringRef ArgName, 1789 StringRef Arg) override { 1790 typename ParserClass::parser_data_type Val = 1791 typename ParserClass::parser_data_type(); 1792 if (Parser.parse(*this, ArgName, Arg, Val)) 1793 return true; // Parse Error! 1794 this->addValue(Val); 1795 setPosition(pos); 1796 Positions.push_back(pos); 1797 Callback(Val); 1798 return false; 1799 } 1800 1801 // Forward printing stuff to the parser... 1802 size_t getOptionWidth() const override { 1803 return Parser.getOptionWidth(*this); 1804 } 1805 1806 void printOptionInfo(size_t GlobalWidth) const override { 1807 Parser.printOptionInfo(*this, GlobalWidth); 1808 } 1809 1810 // Unimplemented: bits options don't currently store their default values. 1811 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override { 1812 } 1813 1814 void setDefault() override {} 1815 1816 void done() { 1817 addArgument(); 1818 Parser.initialize(); 1819 } 1820 1821 public: 1822 // Command line options should not be copyable 1823 bits(const bits &) = delete; 1824 bits &operator=(const bits &) = delete; 1825 1826 ParserClass &getParser() { return Parser; } 1827 1828 unsigned getPosition(unsigned optnum) const { 1829 assert(optnum < this->size() && "Invalid option index"); 1830 return Positions[optnum]; 1831 } 1832 1833 template <class... Mods> 1834 explicit bits(const Mods &... Ms) 1835 : Option(ZeroOrMore, NotHidden), Parser(*this) { 1836 apply(this, Ms...); 1837 done(); 1838 } 1839 1840 void setCallback( 1841 std::function<void(const typename ParserClass::parser_data_type &)> CB) { 1842 Callback = CB; 1843 } 1844 1845 std::function<void(const typename ParserClass::parser_data_type &)> Callback = 1846 [](const typename ParserClass::parser_data_type &) {}; 1847 }; 1848 1849 //===----------------------------------------------------------------------===// 1850 // Aliased command line option (alias this name to a preexisting name) 1851 // 1852 1853 class alias : public Option { 1854 Option *AliasFor; 1855 1856 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/, 1857 StringRef Arg) override { 1858 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg); 1859 } 1860 1861 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value, 1862 bool MultiArg = false) override { 1863 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg); 1864 } 1865 1866 // Handle printing stuff... 1867 size_t getOptionWidth() const override; 1868 void printOptionInfo(size_t GlobalWidth) const override; 1869 1870 // Aliases do not need to print their values. 1871 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override { 1872 } 1873 1874 void setDefault() override { AliasFor->setDefault(); } 1875 1876 ValueExpected getValueExpectedFlagDefault() const override { 1877 return AliasFor->getValueExpectedFlag(); 1878 } 1879 1880 void done() { 1881 if (!hasArgStr()) 1882 error("cl::alias must have argument name specified!"); 1883 if (!AliasFor) 1884 error("cl::alias must have an cl::aliasopt(option) specified!"); 1885 if (!Subs.empty()) 1886 error("cl::alias must not have cl::sub(), aliased option's cl::sub() will be used!"); 1887 Subs = AliasFor->Subs; 1888 Categories = AliasFor->Categories; 1889 addArgument(); 1890 } 1891 1892 public: 1893 // Command line options should not be copyable 1894 alias(const alias &) = delete; 1895 alias &operator=(const alias &) = delete; 1896 1897 void setAliasFor(Option &O) { 1898 if (AliasFor) 1899 error("cl::alias must only have one cl::aliasopt(...) specified!"); 1900 AliasFor = &O; 1901 } 1902 1903 template <class... Mods> 1904 explicit alias(const Mods &... Ms) 1905 : Option(Optional, Hidden), AliasFor(nullptr) { 1906 apply(this, Ms...); 1907 done(); 1908 } 1909 }; 1910 1911 // aliasfor - Modifier to set the option an alias aliases. 1912 struct aliasopt { 1913 Option &Opt; 1914 1915 explicit aliasopt(Option &O) : Opt(O) {} 1916 1917 void apply(alias &A) const { A.setAliasFor(Opt); } 1918 }; 1919 1920 // extrahelp - provide additional help at the end of the normal help 1921 // output. All occurrences of cl::extrahelp will be accumulated and 1922 // printed to stderr at the end of the regular help, just before 1923 // exit is called. 1924 struct extrahelp { 1925 StringRef morehelp; 1926 1927 explicit extrahelp(StringRef help); 1928 }; 1929 1930 void PrintVersionMessage(); 1931 1932 /// This function just prints the help message, exactly the same way as if the 1933 /// -help or -help-hidden option had been given on the command line. 1934 /// 1935 /// \param Hidden if true will print hidden options 1936 /// \param Categorized if true print options in categories 1937 void PrintHelpMessage(bool Hidden = false, bool Categorized = false); 1938 1939 //===----------------------------------------------------------------------===// 1940 // Public interface for accessing registered options. 1941 // 1942 1943 /// Use this to get a StringMap to all registered named options 1944 /// (e.g. -help). 1945 /// 1946 /// \return A reference to the StringMap used by the cl APIs to parse options. 1947 /// 1948 /// Access to unnamed arguments (i.e. positional) are not provided because 1949 /// it is expected that the client already has access to these. 1950 /// 1951 /// Typical usage: 1952 /// \code 1953 /// main(int argc,char* argv[]) { 1954 /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions(); 1955 /// assert(opts.count("help") == 1) 1956 /// opts["help"]->setDescription("Show alphabetical help information") 1957 /// // More code 1958 /// llvm::cl::ParseCommandLineOptions(argc,argv); 1959 /// //More code 1960 /// } 1961 /// \endcode 1962 /// 1963 /// This interface is useful for modifying options in libraries that are out of 1964 /// the control of the client. The options should be modified before calling 1965 /// llvm::cl::ParseCommandLineOptions(). 1966 /// 1967 /// Hopefully this API can be deprecated soon. Any situation where options need 1968 /// to be modified by tools or libraries should be handled by sane APIs rather 1969 /// than just handing around a global list. 1970 StringMap<Option *> &getRegisteredOptions(SubCommand &Sub = *TopLevelSubCommand); 1971 1972 /// Use this to get all registered SubCommands from the provided parser. 1973 /// 1974 /// \return A range of all SubCommand pointers registered with the parser. 1975 /// 1976 /// Typical usage: 1977 /// \code 1978 /// main(int argc, char* argv[]) { 1979 /// llvm::cl::ParseCommandLineOptions(argc, argv); 1980 /// for (auto* S : llvm::cl::getRegisteredSubcommands()) { 1981 /// if (*S) { 1982 /// std::cout << "Executing subcommand: " << S->getName() << std::endl; 1983 /// // Execute some function based on the name... 1984 /// } 1985 /// } 1986 /// } 1987 /// \endcode 1988 /// 1989 /// This interface is useful for defining subcommands in libraries and 1990 /// the dispatch from a single point (like in the main function). 1991 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator> 1992 getRegisteredSubcommands(); 1993 1994 //===----------------------------------------------------------------------===// 1995 // Standalone command line processing utilities. 1996 // 1997 1998 /// Tokenizes a command line that can contain escapes and quotes. 1999 // 2000 /// The quoting rules match those used by GCC and other tools that use 2001 /// libiberty's buildargv() or expandargv() utilities, and do not match bash. 2002 /// They differ from buildargv() on treatment of backslashes that do not escape 2003 /// a special character to make it possible to accept most Windows file paths. 2004 /// 2005 /// \param [in] Source The string to be split on whitespace with quotes. 2006 /// \param [in] Saver Delegates back to the caller for saving parsed strings. 2007 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of 2008 /// lines and end of the response file to be marked with a nullptr string. 2009 /// \param [out] NewArgv All parsed strings are appended to NewArgv. 2010 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver, 2011 SmallVectorImpl<const char *> &NewArgv, 2012 bool MarkEOLs = false); 2013 2014 /// Tokenizes a Windows command line which may contain quotes and escaped 2015 /// quotes. 2016 /// 2017 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules. 2018 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx 2019 /// 2020 /// \param [in] Source The string to be split on whitespace with quotes. 2021 /// \param [in] Saver Delegates back to the caller for saving parsed strings. 2022 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of 2023 /// lines and end of the response file to be marked with a nullptr string. 2024 /// \param [out] NewArgv All parsed strings are appended to NewArgv. 2025 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver, 2026 SmallVectorImpl<const char *> &NewArgv, 2027 bool MarkEOLs = false); 2028 2029 /// Tokenizes a Windows command line while attempting to avoid copies. If no 2030 /// quoting or escaping was used, this produces substrings of the original 2031 /// string. If a token requires unquoting, it will be allocated with the 2032 /// StringSaver. 2033 void TokenizeWindowsCommandLineNoCopy(StringRef Source, StringSaver &Saver, 2034 SmallVectorImpl<StringRef> &NewArgv); 2035 2036 /// String tokenization function type. Should be compatible with either 2037 /// Windows or Unix command line tokenizers. 2038 using TokenizerCallback = void (*)(StringRef Source, StringSaver &Saver, 2039 SmallVectorImpl<const char *> &NewArgv, 2040 bool MarkEOLs); 2041 2042 /// Tokenizes content of configuration file. 2043 /// 2044 /// \param [in] Source The string representing content of config file. 2045 /// \param [in] Saver Delegates back to the caller for saving parsed strings. 2046 /// \param [out] NewArgv All parsed strings are appended to NewArgv. 2047 /// \param [in] MarkEOLs Added for compatibility with TokenizerCallback. 2048 /// 2049 /// It works like TokenizeGNUCommandLine with ability to skip comment lines. 2050 /// 2051 void tokenizeConfigFile(StringRef Source, StringSaver &Saver, 2052 SmallVectorImpl<const char *> &NewArgv, 2053 bool MarkEOLs = false); 2054 2055 /// Reads command line options from the given configuration file. 2056 /// 2057 /// \param [in] CfgFileName Path to configuration file. 2058 /// \param [in] Saver Objects that saves allocated strings. 2059 /// \param [out] Argv Array to which the read options are added. 2060 /// \return true if the file was successfully read. 2061 /// 2062 /// It reads content of the specified file, tokenizes it and expands "@file" 2063 /// commands resolving file names in them relative to the directory where 2064 /// CfgFilename resides. 2065 /// 2066 bool readConfigFile(StringRef CfgFileName, StringSaver &Saver, 2067 SmallVectorImpl<const char *> &Argv); 2068 2069 /// Expand response files on a command line recursively using the given 2070 /// StringSaver and tokenization strategy. Argv should contain the command line 2071 /// before expansion and will be modified in place. If requested, Argv will 2072 /// also be populated with nullptrs indicating where each response file line 2073 /// ends, which is useful for the "/link" argument that needs to consume all 2074 /// remaining arguments only until the next end of line, when in a response 2075 /// file. 2076 /// 2077 /// \param [in] Saver Delegates back to the caller for saving parsed strings. 2078 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows. 2079 /// \param [in,out] Argv Command line into which to expand response files. 2080 /// \param [in] MarkEOLs Mark end of lines and the end of the response file 2081 /// with nullptrs in the Argv vector. 2082 /// \param [in] RelativeNames true if names of nested response files must be 2083 /// resolved relative to including file. 2084 /// \param [in] FS File system used for all file access when running the tool. 2085 /// \param [in] CurrentDir Path used to resolve relative rsp files. If set to 2086 /// None, process' cwd is used instead. 2087 /// \return true if all @files were expanded successfully or there were none. 2088 bool ExpandResponseFiles( 2089 StringSaver &Saver, TokenizerCallback Tokenizer, 2090 SmallVectorImpl<const char *> &Argv, bool MarkEOLs = false, 2091 bool RelativeNames = false, 2092 llvm::vfs::FileSystem &FS = *llvm::vfs::getRealFileSystem(), 2093 llvm::Optional<llvm::StringRef> CurrentDir = llvm::None); 2094 2095 /// Mark all options not part of this category as cl::ReallyHidden. 2096 /// 2097 /// \param Category the category of options to keep displaying 2098 /// 2099 /// Some tools (like clang-format) like to be able to hide all options that are 2100 /// not specific to the tool. This function allows a tool to specify a single 2101 /// option category to display in the -help output. 2102 void HideUnrelatedOptions(cl::OptionCategory &Category, 2103 SubCommand &Sub = *TopLevelSubCommand); 2104 2105 /// Mark all options not part of the categories as cl::ReallyHidden. 2106 /// 2107 /// \param Categories the categories of options to keep displaying. 2108 /// 2109 /// Some tools (like clang-format) like to be able to hide all options that are 2110 /// not specific to the tool. This function allows a tool to specify a single 2111 /// option category to display in the -help output. 2112 void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories, 2113 SubCommand &Sub = *TopLevelSubCommand); 2114 2115 /// Reset all command line options to a state that looks as if they have 2116 /// never appeared on the command line. This is useful for being able to parse 2117 /// a command line multiple times (especially useful for writing tests). 2118 void ResetAllOptionOccurrences(); 2119 2120 /// Reset the command line parser back to its initial state. This 2121 /// removes 2122 /// all options, categories, and subcommands and returns the parser to a state 2123 /// where no options are supported. 2124 void ResetCommandLineParser(); 2125 2126 /// Parses `Arg` into the option handler `Handler`. 2127 bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i); 2128 2129 } // end namespace cl 2130 2131 } // end namespace llvm 2132 2133 #endif // LLVM_SUPPORT_COMMANDLINE_H 2134