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