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