LLVM API Documentation

CommandLine.h
Go to the documentation of this file.
00001 //===- llvm/Support/CommandLine.h - Command line handler --------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This class implements a command line argument processor that is useful when
00011 // creating a tool.  It provides a simple, minimalistic interface that is easily
00012 // extensible and supports nonlocal (library) command line options.
00013 //
00014 // Note that rather than trying to figure out what this code does, you should
00015 // read the library documentation located in docs/CommandLine.html or looks at
00016 // the many example usages in tools/*/*.cpp
00017 //
00018 //===----------------------------------------------------------------------===//
00019 
00020 #ifndef LLVM_SUPPORT_COMMANDLINE_H
00021 #define LLVM_SUPPORT_COMMANDLINE_H
00022 
00023 #include "llvm/ADT/SmallVector.h"
00024 #include "llvm/ADT/StringMap.h"
00025 #include "llvm/ADT/Twine.h"
00026 #include "llvm/Support/Compiler.h"
00027 #include <cassert>
00028 #include <climits>
00029 #include <cstdarg>
00030 #include <utility>
00031 #include <vector>
00032 
00033 namespace llvm {
00034 
00035 /// cl Namespace - This namespace contains all of the command line option
00036 /// processing machinery.  It is intentionally a short name to make qualified
00037 /// usage concise.
00038 namespace cl {
00039 
00040 //===----------------------------------------------------------------------===//
00041 // ParseCommandLineOptions - Command line option processing entry point.
00042 //
00043 void ParseCommandLineOptions(int argc, const char * const *argv,
00044                              const char *Overview = nullptr);
00045 
00046 //===----------------------------------------------------------------------===//
00047 // ParseEnvironmentOptions - Environment variable option processing alternate
00048 //                           entry point.
00049 //
00050 void ParseEnvironmentOptions(const char *progName, const char *envvar,
00051                              const char *Overview = nullptr);
00052 
00053 ///===---------------------------------------------------------------------===//
00054 /// SetVersionPrinter - Override the default (LLVM specific) version printer
00055 ///                     used to print out the version when --version is given
00056 ///                     on the command line. This allows other systems using the
00057 ///                     CommandLine utilities to print their own version string.
00058 void SetVersionPrinter(void (*func)());
00059 
00060 ///===---------------------------------------------------------------------===//
00061 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
00062 ///                          default one. This can be called multiple times,
00063 ///                          and each time it adds a new function to the list
00064 ///                          which will be called after the basic LLVM version
00065 ///                          printing is complete. Each can then add additional
00066 ///                          information specific to the tool.
00067 void AddExtraVersionPrinter(void (*func)());
00068 
00069 
00070 // PrintOptionValues - Print option values.
00071 // With -print-options print the difference between option values and defaults.
00072 // With -print-all-options print all option values.
00073 // (Currently not perfect, but best-effort.)
00074 void PrintOptionValues();
00075 
00076 // MarkOptionsChanged - Internal helper function.
00077 void MarkOptionsChanged();
00078 
00079 //===----------------------------------------------------------------------===//
00080 // Flags permitted to be passed to command line arguments
00081 //
00082 
00083 enum NumOccurrencesFlag {      // Flags for the number of occurrences allowed
00084   Optional        = 0x00,      // Zero or One occurrence
00085   ZeroOrMore      = 0x01,      // Zero or more occurrences allowed
00086   Required        = 0x02,      // One occurrence required
00087   OneOrMore       = 0x03,      // One or more occurrences required
00088 
00089   // ConsumeAfter - Indicates that this option is fed anything that follows the
00090   // last positional argument required by the application (it is an error if
00091   // there are zero positional arguments, and a ConsumeAfter option is used).
00092   // Thus, for example, all arguments to LLI are processed until a filename is
00093   // found.  Once a filename is found, all of the succeeding arguments are
00094   // passed, unprocessed, to the ConsumeAfter option.
00095   //
00096   ConsumeAfter    = 0x04
00097 };
00098 
00099 enum ValueExpected {           // Is a value required for the option?
00100   // zero reserved for the unspecified value
00101   ValueOptional   = 0x01,      // The value can appear... or not
00102   ValueRequired   = 0x02,      // The value is required to appear!
00103   ValueDisallowed = 0x03       // A value may not be specified (for flags)
00104 };
00105 
00106 enum OptionHidden {            // Control whether -help shows this option
00107   NotHidden       = 0x00,      // Option included in -help & -help-hidden
00108   Hidden          = 0x01,      // -help doesn't, but -help-hidden does
00109   ReallyHidden    = 0x02       // Neither -help nor -help-hidden show this arg
00110 };
00111 
00112 // Formatting flags - This controls special features that the option might have
00113 // that cause it to be parsed differently...
00114 //
00115 // Prefix - This option allows arguments that are otherwise unrecognized to be
00116 // matched by options that are a prefix of the actual value.  This is useful for
00117 // cases like a linker, where options are typically of the form '-lfoo' or
00118 // '-L../../include' where -l or -L are the actual flags.  When prefix is
00119 // enabled, and used, the value for the flag comes from the suffix of the
00120 // argument.
00121 //
00122 // Grouping - With this option enabled, multiple letter options are allowed to
00123 // bunch together with only a single hyphen for the whole group.  This allows
00124 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
00125 //
00126 
00127 enum FormattingFlags {
00128   NormalFormatting = 0x00,     // Nothing special
00129   Positional       = 0x01,     // Is a positional argument, no '-' required
00130   Prefix           = 0x02,     // Can this option directly prefix its value?
00131   Grouping         = 0x03      // Can this option group with other options?
00132 };
00133 
00134 enum MiscFlags {               // Miscellaneous flags to adjust argument
00135   CommaSeparated     = 0x01,  // Should this cl::list split between commas?
00136   PositionalEatsArgs = 0x02,  // Should this positional cl::list eat -args?
00137   Sink               = 0x04   // Should this cl::list eat all unknown options?
00138 };
00139 
00140 //===----------------------------------------------------------------------===//
00141 // Option Category class
00142 //
00143 class OptionCategory {
00144 private:
00145   const char *const Name;
00146   const char *const Description;
00147   void registerCategory();
00148 public:
00149   OptionCategory(const char *const Name, const char *const Description = nullptr)
00150       : Name(Name), Description(Description) { registerCategory(); }
00151   const char *getName() const { return Name; }
00152   const char *getDescription() const { return Description; }
00153 };
00154 
00155 // The general Option Category (used as default category).
00156 extern OptionCategory GeneralCategory;
00157 
00158 //===----------------------------------------------------------------------===//
00159 // Option Base class
00160 //
00161 class alias;
00162 class Option {
00163   friend class alias;
00164 
00165   // handleOccurrences - Overriden by subclasses to handle the value passed into
00166   // an argument.  Should return true if there was an error processing the
00167   // argument and the program should exit.
00168   //
00169   virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
00170                                 StringRef Arg) = 0;
00171 
00172   virtual enum ValueExpected getValueExpectedFlagDefault() const {
00173     return ValueOptional;
00174   }
00175 
00176   // Out of line virtual function to provide home for the class.
00177   virtual void anchor();
00178 
00179   int NumOccurrences;     // The number of times specified
00180   // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
00181   // problems with signed enums in bitfields.
00182   unsigned Occurrences : 3; // enum NumOccurrencesFlag
00183   // not using the enum type for 'Value' because zero is an implementation
00184   // detail representing the non-value
00185   unsigned Value : 2;
00186   unsigned HiddenFlag : 2; // enum OptionHidden
00187   unsigned Formatting : 2; // enum FormattingFlags
00188   unsigned Misc : 3;
00189   unsigned Position;      // Position of last occurrence of the option
00190   unsigned AdditionalVals;// Greater than 0 for multi-valued option.
00191   Option *NextRegistered; // Singly linked list of registered options.
00192 
00193 public:
00194   const char *ArgStr;   // The argument string itself (ex: "help", "o")
00195   const char *HelpStr;  // The descriptive text message for -help
00196   const char *ValueStr; // String describing what the value of this option is
00197   OptionCategory *Category; // The Category this option belongs to
00198 
00199   inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
00200     return (enum NumOccurrencesFlag)Occurrences;
00201   }
00202   inline enum ValueExpected getValueExpectedFlag() const {
00203     return Value ? ((enum ValueExpected)Value)
00204               : getValueExpectedFlagDefault();
00205   }
00206   inline enum OptionHidden getOptionHiddenFlag() const {
00207     return (enum OptionHidden)HiddenFlag;
00208   }
00209   inline enum FormattingFlags getFormattingFlag() const {
00210     return (enum FormattingFlags)Formatting;
00211   }
00212   inline unsigned getMiscFlags() const {
00213     return Misc;
00214   }
00215   inline unsigned getPosition() const { return Position; }
00216   inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
00217 
00218   // hasArgStr - Return true if the argstr != ""
00219   bool hasArgStr() const { return ArgStr[0] != 0; }
00220 
00221   //-------------------------------------------------------------------------===
00222   // Accessor functions set by OptionModifiers
00223   //
00224   void setArgStr(const char *S) { ArgStr = S; }
00225   void setDescription(const char *S) { HelpStr = S; }
00226   void setValueStr(const char *S) { ValueStr = S; }
00227   void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) {
00228     Occurrences = Val;
00229   }
00230   void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
00231   void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
00232   void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
00233   void setMiscFlag(enum MiscFlags M) { Misc |= M; }
00234   void setPosition(unsigned pos) { Position = pos; }
00235   void setCategory(OptionCategory &C) { Category = &C; }
00236 protected:
00237   explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
00238                   enum OptionHidden Hidden)
00239     : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
00240       HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0),
00241       Position(0), AdditionalVals(0), NextRegistered(nullptr),
00242       ArgStr(""), HelpStr(""), ValueStr(""), Category(&GeneralCategory) {
00243   }
00244 
00245   inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
00246 public:
00247   // addArgument - Register this argument with the commandline system.
00248   //
00249   void addArgument();
00250 
00251   /// Unregisters this option from the CommandLine system.
00252   ///
00253   /// This option must have been the last option registered.
00254   /// For testing purposes only.
00255   void removeArgument();
00256 
00257   Option *getNextRegisteredOption() const { return NextRegistered; }
00258 
00259   // Return the width of the option tag for printing...
00260   virtual size_t getOptionWidth() const = 0;
00261 
00262   // printOptionInfo - Print out information about this option.  The
00263   // to-be-maintained width is specified.
00264   //
00265   virtual void printOptionInfo(size_t GlobalWidth) const = 0;
00266 
00267   virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
00268 
00269   virtual void getExtraOptionNames(SmallVectorImpl<const char*> &) {}
00270 
00271   // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
00272   //
00273   virtual bool addOccurrence(unsigned pos, StringRef ArgName,
00274                              StringRef Value, bool MultiArg = false);
00275 
00276   // Prints option name followed by message.  Always returns true.
00277   bool error(const Twine &Message, StringRef ArgName = StringRef());
00278 
00279 public:
00280   inline int getNumOccurrences() const { return NumOccurrences; }
00281   virtual ~Option() {}
00282 };
00283 
00284 
00285 //===----------------------------------------------------------------------===//
00286 // Command line option modifiers that can be used to modify the behavior of
00287 // command line option parsers...
00288 //
00289 
00290 // desc - Modifier to set the description shown in the -help output...
00291 struct desc {
00292   const char *Desc;
00293   desc(const char *Str) : Desc(Str) {}
00294   void apply(Option &O) const { O.setDescription(Desc); }
00295 };
00296 
00297 // value_desc - Modifier to set the value description shown in the -help
00298 // output...
00299 struct value_desc {
00300   const char *Desc;
00301   value_desc(const char *Str) : Desc(Str) {}
00302   void apply(Option &O) const { O.setValueStr(Desc); }
00303 };
00304 
00305 // init - Specify a default (initial) value for the command line argument, if
00306 // the default constructor for the argument type does not give you what you
00307 // want.  This is only valid on "opt" arguments, not on "list" arguments.
00308 //
00309 template<class Ty>
00310 struct initializer {
00311   const Ty &Init;
00312   initializer(const Ty &Val) : Init(Val) {}
00313 
00314   template<class Opt>
00315   void apply(Opt &O) const { O.setInitialValue(Init); }
00316 };
00317 
00318 template<class Ty>
00319 initializer<Ty> init(const Ty &Val) {
00320   return initializer<Ty>(Val);
00321 }
00322 
00323 
00324 // location - Allow the user to specify which external variable they want to
00325 // store the results of the command line argument processing into, if they don't
00326 // want to store it in the option itself.
00327 //
00328 template<class Ty>
00329 struct LocationClass {
00330   Ty &Loc;
00331   LocationClass(Ty &L) : Loc(L) {}
00332 
00333   template<class Opt>
00334   void apply(Opt &O) const { O.setLocation(O, Loc); }
00335 };
00336 
00337 template<class Ty>
00338 LocationClass<Ty> location(Ty &L) { return LocationClass<Ty>(L); }
00339 
00340 // cat - Specifiy the Option category for the command line argument to belong
00341 // to.
00342 struct cat {
00343   OptionCategory &Category;
00344   cat(OptionCategory &c) : Category(c) {}
00345 
00346   template<class Opt>
00347   void apply(Opt &O) const { O.setCategory(Category); }
00348 };
00349 
00350 
00351 //===----------------------------------------------------------------------===//
00352 // OptionValue class
00353 
00354 // Support value comparison outside the template.
00355 struct GenericOptionValue {
00356   virtual ~GenericOptionValue() {}
00357   virtual bool compare(const GenericOptionValue &V) const = 0;
00358 
00359 private:
00360   virtual void anchor();
00361 };
00362 
00363 template<class DataType> struct OptionValue;
00364 
00365 // The default value safely does nothing. Option value printing is only
00366 // best-effort.
00367 template<class DataType, bool isClass>
00368 struct OptionValueBase : public GenericOptionValue {
00369   // Temporary storage for argument passing.
00370   typedef OptionValue<DataType> WrapperType;
00371 
00372   bool hasValue() const { return false; }
00373 
00374   const DataType &getValue() const { llvm_unreachable("no default value"); }
00375 
00376   // Some options may take their value from a different data type.
00377   template<class DT>
00378   void setValue(const DT& /*V*/) {}
00379 
00380   bool compare(const DataType &/*V*/) const { return false; }
00381 
00382   bool compare(const GenericOptionValue& /*V*/) const override {
00383     return false;
00384   }
00385 };
00386 
00387 // Simple copy of the option value.
00388 template<class DataType>
00389 class OptionValueCopy : public GenericOptionValue {
00390   DataType Value;
00391   bool Valid;
00392 public:
00393   OptionValueCopy() : Valid(false) {}
00394 
00395   bool hasValue() const { return Valid; }
00396 
00397   const DataType &getValue() const {
00398     assert(Valid && "invalid option value");
00399     return Value;
00400   }
00401 
00402   void setValue(const DataType &V) { Valid = true; Value = V; }
00403 
00404   bool compare(const DataType &V) const {
00405     return Valid && (Value != V);
00406   }
00407 
00408   bool compare(const GenericOptionValue &V) const override {
00409     const OptionValueCopy<DataType> &VC =
00410       static_cast< const OptionValueCopy<DataType>& >(V);
00411     if (!VC.hasValue()) return false;
00412     return compare(VC.getValue());
00413   }
00414 };
00415 
00416 // Non-class option values.
00417 template<class DataType>
00418 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
00419   typedef DataType WrapperType;
00420 };
00421 
00422 // Top-level option class.
00423 template<class DataType>
00424 struct OptionValue : OptionValueBase<DataType, std::is_class<DataType>::value> {
00425   OptionValue() {}
00426 
00427   OptionValue(const DataType& V) {
00428     this->setValue(V);
00429   }
00430   // Some options may take their value from a different data type.
00431   template<class DT>
00432   OptionValue<DataType> &operator=(const DT& V) {
00433     this->setValue(V);
00434     return *this;
00435   }
00436 };
00437 
00438 // Other safe-to-copy-by-value common option types.
00439 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
00440 template<>
00441 struct OptionValue<cl::boolOrDefault> : OptionValueCopy<cl::boolOrDefault> {
00442   typedef cl::boolOrDefault WrapperType;
00443 
00444   OptionValue() {}
00445 
00446   OptionValue(const cl::boolOrDefault& V) {
00447     this->setValue(V);
00448   }
00449   OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault& V) {
00450     setValue(V);
00451     return *this;
00452   }
00453 private:
00454   void anchor() override;
00455 };
00456 
00457 template<>
00458 struct OptionValue<std::string> : OptionValueCopy<std::string> {
00459   typedef StringRef WrapperType;
00460 
00461   OptionValue() {}
00462 
00463   OptionValue(const std::string& V) {
00464     this->setValue(V);
00465   }
00466   OptionValue<std::string> &operator=(const std::string& V) {
00467     setValue(V);
00468     return *this;
00469   }
00470 private:
00471   void anchor() override;
00472 };
00473 
00474 //===----------------------------------------------------------------------===//
00475 // Enum valued command line option
00476 //
00477 #define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
00478 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
00479 #define clEnumValEnd (reinterpret_cast<void*>(0))
00480 
00481 // values - For custom data types, allow specifying a group of values together
00482 // as the values that go into the mapping that the option handler uses.  Note
00483 // that the values list must always have a 0 at the end of the list to indicate
00484 // that the list has ended.
00485 //
00486 template<class DataType>
00487 class ValuesClass {
00488   // Use a vector instead of a map, because the lists should be short,
00489   // the overhead is less, and most importantly, it keeps them in the order
00490   // inserted so we can print our option out nicely.
00491   SmallVector<std::pair<const char *, std::pair<int, const char *> >,4> Values;
00492   void processValues(va_list Vals);
00493 public:
00494   ValuesClass(const char *EnumName, DataType Val, const char *Desc,
00495               va_list ValueArgs) {
00496     // Insert the first value, which is required.
00497     Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
00498 
00499     // Process the varargs portion of the values...
00500     while (const char *enumName = va_arg(ValueArgs, const char *)) {
00501       DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
00502       const char *EnumDesc = va_arg(ValueArgs, const char *);
00503       Values.push_back(std::make_pair(enumName,      // Add value to value map
00504                                       std::make_pair(EnumVal, EnumDesc)));
00505     }
00506   }
00507 
00508   template<class Opt>
00509   void apply(Opt &O) const {
00510     for (size_t i = 0, e = Values.size(); i != e; ++i)
00511       O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
00512                                      Values[i].second.second);
00513   }
00514 };
00515 
00516 template<class DataType>
00517 ValuesClass<DataType> END_WITH_NULL values(const char *Arg, DataType Val,
00518                                            const char *Desc, ...) {
00519     va_list ValueArgs;
00520     va_start(ValueArgs, Desc);
00521     ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
00522     va_end(ValueArgs);
00523     return Vals;
00524 }
00525 
00526 //===----------------------------------------------------------------------===//
00527 // parser class - Parameterizable parser for different data types.  By default,
00528 // known data types (string, int, bool) have specialized parsers, that do what
00529 // you would expect.  The default parser, used for data types that are not
00530 // built-in, uses a mapping table to map specific options to values, which is
00531 // used, among other things, to handle enum types.
00532 
00533 //--------------------------------------------------
00534 // generic_parser_base - This class holds all the non-generic code that we do
00535 // not need replicated for every instance of the generic parser.  This also
00536 // allows us to put stuff into CommandLine.cpp
00537 //
00538 class generic_parser_base {
00539 protected:
00540   class GenericOptionInfo {
00541   public:
00542     GenericOptionInfo(const char *name, const char *helpStr) :
00543       Name(name), HelpStr(helpStr) {}
00544     const char *Name;
00545     const char *HelpStr;
00546   };
00547 public:
00548   virtual ~generic_parser_base() {}  // Base class should have virtual-dtor
00549 
00550   // getNumOptions - Virtual function implemented by generic subclass to
00551   // indicate how many entries are in Values.
00552   //
00553   virtual unsigned getNumOptions() const = 0;
00554 
00555   // getOption - Return option name N.
00556   virtual const char *getOption(unsigned N) const = 0;
00557 
00558   // getDescription - Return description N
00559   virtual const char *getDescription(unsigned N) const = 0;
00560 
00561   // Return the width of the option tag for printing...
00562   virtual size_t getOptionWidth(const Option &O) const;
00563 
00564   virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
00565 
00566   // printOptionInfo - Print out information about this option.  The
00567   // to-be-maintained width is specified.
00568   //
00569   virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
00570 
00571   void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
00572                               const GenericOptionValue &Default,
00573                               size_t GlobalWidth) const;
00574 
00575   // printOptionDiff - print the value of an option and it's default.
00576   //
00577   // Template definition ensures that the option and default have the same
00578   // DataType (via the same AnyOptionValue).
00579   template<class AnyOptionValue>
00580   void printOptionDiff(const Option &O, const AnyOptionValue &V,
00581                        const AnyOptionValue &Default,
00582                        size_t GlobalWidth) const {
00583     printGenericOptionDiff(O, V, Default, GlobalWidth);
00584   }
00585 
00586   void initialize(Option &O) {
00587     // All of the modifiers for the option have been processed by now, so the
00588     // argstr field should be stable, copy it down now.
00589     //
00590     hasArgStr = O.hasArgStr();
00591   }
00592 
00593   void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) {
00594     // If there has been no argstr specified, that means that we need to add an
00595     // argument for every possible option.  This ensures that our options are
00596     // vectored to us.
00597     if (!hasArgStr)
00598       for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
00599         OptionNames.push_back(getOption(i));
00600   }
00601 
00602 
00603   enum ValueExpected getValueExpectedFlagDefault() const {
00604     // If there is an ArgStr specified, then we are of the form:
00605     //
00606     //    -opt=O2   or   -opt O2  or  -optO2
00607     //
00608     // In which case, the value is required.  Otherwise if an arg str has not
00609     // been specified, we are of the form:
00610     //
00611     //    -O2 or O2 or -la (where -l and -a are separate options)
00612     //
00613     // If this is the case, we cannot allow a value.
00614     //
00615     if (hasArgStr)
00616       return ValueRequired;
00617     else
00618       return ValueDisallowed;
00619   }
00620 
00621   // findOption - Return the option number corresponding to the specified
00622   // argument string.  If the option is not found, getNumOptions() is returned.
00623   //
00624   unsigned findOption(const char *Name);
00625 
00626 protected:
00627   bool hasArgStr;
00628 };
00629 
00630 // Default parser implementation - This implementation depends on having a
00631 // mapping of recognized options to values of some sort.  In addition to this,
00632 // each entry in the mapping also tracks a help message that is printed with the
00633 // command line option for -help.  Because this is a simple mapping parser, the
00634 // data type can be any unsupported type.
00635 //
00636 template <class DataType>
00637 class parser : public generic_parser_base {
00638 protected:
00639   class OptionInfo : public GenericOptionInfo {
00640   public:
00641     OptionInfo(const char *name, DataType v, const char *helpStr) :
00642       GenericOptionInfo(name, helpStr), V(v) {}
00643     OptionValue<DataType> V;
00644   };
00645   SmallVector<OptionInfo, 8> Values;
00646 public:
00647   typedef DataType parser_data_type;
00648 
00649   // Implement virtual functions needed by generic_parser_base
00650   unsigned getNumOptions() const override { return unsigned(Values.size()); }
00651   const char *getOption(unsigned N) const override { return Values[N].Name; }
00652   const char *getDescription(unsigned N) const override {
00653     return Values[N].HelpStr;
00654   }
00655 
00656   // getOptionValue - Return the value of option name N.
00657   const GenericOptionValue &getOptionValue(unsigned N) const override {
00658     return Values[N].V;
00659   }
00660 
00661   // parse - Return true on error.
00662   bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
00663     StringRef ArgVal;
00664     if (hasArgStr)
00665       ArgVal = Arg;
00666     else
00667       ArgVal = ArgName;
00668 
00669     for (size_t i = 0, e = Values.size(); i != e; ++i)
00670       if (Values[i].Name == ArgVal) {
00671         V = Values[i].V.getValue();
00672         return false;
00673       }
00674 
00675     return O.error("Cannot find option named '" + ArgVal + "'!");
00676   }
00677 
00678   /// addLiteralOption - Add an entry to the mapping table.
00679   ///
00680   template <class DT>
00681   void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
00682     assert(findOption(Name) == Values.size() && "Option already exists!");
00683     OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
00684     Values.push_back(X);
00685     MarkOptionsChanged();
00686   }
00687 
00688   /// removeLiteralOption - Remove the specified option.
00689   ///
00690   void removeLiteralOption(const char *Name) {
00691     unsigned N = findOption(Name);
00692     assert(N != Values.size() && "Option not found!");
00693     Values.erase(Values.begin()+N);
00694   }
00695 };
00696 
00697 //--------------------------------------------------
00698 // basic_parser - Super class of parsers to provide boilerplate code
00699 //
00700 class basic_parser_impl {  // non-template implementation of basic_parser<t>
00701 public:
00702   virtual ~basic_parser_impl() {}
00703 
00704   enum ValueExpected getValueExpectedFlagDefault() const {
00705     return ValueRequired;
00706   }
00707 
00708   void getExtraOptionNames(SmallVectorImpl<const char*> &) {}
00709 
00710   void initialize(Option &) {}
00711 
00712   // Return the width of the option tag for printing...
00713   size_t getOptionWidth(const Option &O) const;
00714 
00715   // printOptionInfo - Print out information about this option.  The
00716   // to-be-maintained width is specified.
00717   //
00718   void printOptionInfo(const Option &O, size_t GlobalWidth) const;
00719 
00720   // printOptionNoValue - Print a placeholder for options that don't yet support
00721   // printOptionDiff().
00722   void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
00723 
00724   // getValueName - Overload in subclass to provide a better default value.
00725   virtual const char *getValueName() const { return "value"; }
00726 
00727   // An out-of-line virtual method to provide a 'home' for this class.
00728   virtual void anchor();
00729 
00730 protected:
00731   // A helper for basic_parser::printOptionDiff.
00732   void printOptionName(const Option &O, size_t GlobalWidth) const;
00733 };
00734 
00735 // basic_parser - The real basic parser is just a template wrapper that provides
00736 // a typedef for the provided data type.
00737 //
00738 template<class DataType>
00739 class basic_parser : public basic_parser_impl {
00740 public:
00741   typedef DataType parser_data_type;
00742   typedef OptionValue<DataType> OptVal;
00743 };
00744 
00745 //--------------------------------------------------
00746 // parser<bool>
00747 //
00748 template<>
00749 class parser<bool> : public basic_parser<bool> {
00750   const char *ArgStr;
00751 public:
00752 
00753   // parse - Return true on error.
00754   bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
00755 
00756   template <class Opt>
00757   void initialize(Opt &O) {
00758     ArgStr = O.ArgStr;
00759   }
00760 
00761   enum ValueExpected getValueExpectedFlagDefault() const {
00762     return ValueOptional;
00763   }
00764 
00765   // getValueName - Do not print =<value> at all.
00766   const char *getValueName() const override { return nullptr; }
00767 
00768   void printOptionDiff(const Option &O, bool V, OptVal Default,
00769                        size_t GlobalWidth) const;
00770 
00771   // An out-of-line virtual method to provide a 'home' for this class.
00772   void anchor() override;
00773 };
00774 
00775 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<bool>);
00776 
00777 //--------------------------------------------------
00778 // parser<boolOrDefault>
00779 template<>
00780 class parser<boolOrDefault> : public basic_parser<boolOrDefault> {
00781 public:
00782   // parse - Return true on error.
00783   bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
00784 
00785   enum ValueExpected getValueExpectedFlagDefault() const {
00786     return ValueOptional;
00787   }
00788 
00789   // getValueName - Do not print =<value> at all.
00790   const char *getValueName() const override { return nullptr; }
00791 
00792   void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
00793                        size_t GlobalWidth) const;
00794 
00795   // An out-of-line virtual method to provide a 'home' for this class.
00796   void anchor() override;
00797 };
00798 
00799 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
00800 
00801 //--------------------------------------------------
00802 // parser<int>
00803 //
00804 template<>
00805 class parser<int> : public basic_parser<int> {
00806 public:
00807   // parse - Return true on error.
00808   bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
00809 
00810   // getValueName - Overload in subclass to provide a better default value.
00811   const char *getValueName() const override { return "int"; }
00812 
00813   void printOptionDiff(const Option &O, int V, OptVal Default,
00814                        size_t GlobalWidth) const;
00815 
00816   // An out-of-line virtual method to provide a 'home' for this class.
00817   void anchor() override;
00818 };
00819 
00820 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<int>);
00821 
00822 
00823 //--------------------------------------------------
00824 // parser<unsigned>
00825 //
00826 template<>
00827 class parser<unsigned> : public basic_parser<unsigned> {
00828 public:
00829   // parse - Return true on error.
00830   bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
00831 
00832   // getValueName - Overload in subclass to provide a better default value.
00833   const char *getValueName() const override { return "uint"; }
00834 
00835   void printOptionDiff(const Option &O, unsigned V, OptVal Default,
00836                        size_t GlobalWidth) const;
00837 
00838   // An out-of-line virtual method to provide a 'home' for this class.
00839   void anchor() override;
00840 };
00841 
00842 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
00843 
00844 //--------------------------------------------------
00845 // parser<unsigned long long>
00846 //
00847 template<>
00848 class parser<unsigned long long> : public basic_parser<unsigned long long> {
00849 public:
00850   // parse - Return true on error.
00851   bool parse(Option &O, StringRef ArgName, StringRef Arg,
00852              unsigned long long &Val);
00853 
00854   // getValueName - Overload in subclass to provide a better default value.
00855   const char *getValueName() const override { return "uint"; }
00856 
00857   void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
00858                        size_t GlobalWidth) const;
00859 
00860   // An out-of-line virtual method to provide a 'home' for this class.
00861   void anchor() override;
00862 };
00863 
00864 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
00865 
00866 //--------------------------------------------------
00867 // parser<double>
00868 //
00869 template<>
00870 class parser<double> : public basic_parser<double> {
00871 public:
00872   // parse - Return true on error.
00873   bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
00874 
00875   // getValueName - Overload in subclass to provide a better default value.
00876   const char *getValueName() const override { return "number"; }
00877 
00878   void printOptionDiff(const Option &O, double V, OptVal Default,
00879                        size_t GlobalWidth) const;
00880 
00881   // An out-of-line virtual method to provide a 'home' for this class.
00882   void anchor() override;
00883 };
00884 
00885 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<double>);
00886 
00887 //--------------------------------------------------
00888 // parser<float>
00889 //
00890 template<>
00891 class parser<float> : public basic_parser<float> {
00892 public:
00893   // parse - Return true on error.
00894   bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
00895 
00896   // getValueName - Overload in subclass to provide a better default value.
00897   const char *getValueName() const override { return "number"; }
00898 
00899   void printOptionDiff(const Option &O, float V, OptVal Default,
00900                        size_t GlobalWidth) const;
00901 
00902   // An out-of-line virtual method to provide a 'home' for this class.
00903   void anchor() override;
00904 };
00905 
00906 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<float>);
00907 
00908 //--------------------------------------------------
00909 // parser<std::string>
00910 //
00911 template<>
00912 class parser<std::string> : public basic_parser<std::string> {
00913 public:
00914   // parse - Return true on error.
00915   bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
00916     Value = Arg.str();
00917     return false;
00918   }
00919 
00920   // getValueName - Overload in subclass to provide a better default value.
00921   const char *getValueName() const override { return "string"; }
00922 
00923   void printOptionDiff(const Option &O, StringRef V, OptVal Default,
00924                        size_t GlobalWidth) const;
00925 
00926   // An out-of-line virtual method to provide a 'home' for this class.
00927   void anchor() override;
00928 };
00929 
00930 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
00931 
00932 //--------------------------------------------------
00933 // parser<char>
00934 //
00935 template<>
00936 class parser<char> : public basic_parser<char> {
00937 public:
00938   // parse - Return true on error.
00939   bool parse(Option &, StringRef, StringRef Arg, char &Value) {
00940     Value = Arg[0];
00941     return false;
00942   }
00943 
00944   // getValueName - Overload in subclass to provide a better default value.
00945   const char *getValueName() const override { return "char"; }
00946 
00947   void printOptionDiff(const Option &O, char V, OptVal Default,
00948                        size_t GlobalWidth) const;
00949 
00950   // An out-of-line virtual method to provide a 'home' for this class.
00951   void anchor() override;
00952 };
00953 
00954 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<char>);
00955 
00956 //--------------------------------------------------
00957 // PrintOptionDiff
00958 //
00959 // This collection of wrappers is the intermediary between class opt and class
00960 // parser to handle all the template nastiness.
00961 
00962 // This overloaded function is selected by the generic parser.
00963 template<class ParserClass, class DT>
00964 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
00965                      const OptionValue<DT> &Default, size_t GlobalWidth) {
00966   OptionValue<DT> OV = V;
00967   P.printOptionDiff(O, OV, Default, GlobalWidth);
00968 }
00969 
00970 // This is instantiated for basic parsers when the parsed value has a different
00971 // type than the option value. e.g. HelpPrinter.
00972 template<class ParserDT, class ValDT>
00973 struct OptionDiffPrinter {
00974   void print(const Option &O, const parser<ParserDT> P, const ValDT &/*V*/,
00975              const OptionValue<ValDT> &/*Default*/, size_t GlobalWidth) {
00976     P.printOptionNoValue(O, GlobalWidth);
00977   }
00978 };
00979 
00980 // This is instantiated for basic parsers when the parsed value has the same
00981 // type as the option value.
00982 template<class DT>
00983 struct OptionDiffPrinter<DT, DT> {
00984   void print(const Option &O, const parser<DT> P, const DT &V,
00985              const OptionValue<DT> &Default, size_t GlobalWidth) {
00986     P.printOptionDiff(O, V, Default, GlobalWidth);
00987   }
00988 };
00989 
00990 // This overloaded function is selected by the basic parser, which may parse a
00991 // different type than the option type.
00992 template<class ParserClass, class ValDT>
00993 void printOptionDiff(
00994   const Option &O,
00995   const basic_parser<typename ParserClass::parser_data_type> &P,
00996   const ValDT &V, const OptionValue<ValDT> &Default,
00997   size_t GlobalWidth) {
00998 
00999   OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
01000   printer.print(O, static_cast<const ParserClass&>(P), V, Default,
01001                 GlobalWidth);
01002 }
01003 
01004 //===----------------------------------------------------------------------===//
01005 // applicator class - This class is used because we must use partial
01006 // specialization to handle literal string arguments specially (const char* does
01007 // not correctly respond to the apply method).  Because the syntax to use this
01008 // is a pain, we have the 'apply' method below to handle the nastiness...
01009 //
01010 template<class Mod> struct applicator {
01011   template<class Opt>
01012   static void opt(const Mod &M, Opt &O) { M.apply(O); }
01013 };
01014 
01015 // Handle const char* as a special case...
01016 template<unsigned n> struct applicator<char[n]> {
01017   template<class Opt>
01018   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
01019 };
01020 template<unsigned n> struct applicator<const char[n]> {
01021   template<class Opt>
01022   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
01023 };
01024 template<> struct applicator<const char*> {
01025   template<class Opt>
01026   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
01027 };
01028 
01029 template<> struct applicator<NumOccurrencesFlag> {
01030   static void opt(NumOccurrencesFlag N, Option &O) {
01031     O.setNumOccurrencesFlag(N);
01032   }
01033 };
01034 template<> struct applicator<ValueExpected> {
01035   static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
01036 };
01037 template<> struct applicator<OptionHidden> {
01038   static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
01039 };
01040 template<> struct applicator<FormattingFlags> {
01041   static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
01042 };
01043 template<> struct applicator<MiscFlags> {
01044   static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
01045 };
01046 
01047 // apply method - Apply a modifier to an option in a type safe way.
01048 template<class Mod, class Opt>
01049 void apply(const Mod &M, Opt *O) {
01050   applicator<Mod>::opt(M, *O);
01051 }
01052 
01053 //===----------------------------------------------------------------------===//
01054 // opt_storage class
01055 
01056 // Default storage class definition: external storage.  This implementation
01057 // assumes the user will specify a variable to store the data into with the
01058 // cl::location(x) modifier.
01059 //
01060 template<class DataType, bool ExternalStorage, bool isClass>
01061 class opt_storage {
01062   DataType *Location;   // Where to store the object...
01063   OptionValue<DataType> Default;
01064 
01065   void check_location() const {
01066     assert(Location && "cl::location(...) not specified for a command "
01067            "line option with external storage, "
01068            "or cl::init specified before cl::location()!!");
01069   }
01070 public:
01071   opt_storage() : Location(nullptr) {}
01072 
01073   bool setLocation(Option &O, DataType &L) {
01074     if (Location)
01075       return O.error("cl::location(x) specified more than once!");
01076     Location = &L;
01077     Default = L;
01078     return false;
01079   }
01080 
01081   template<class T>
01082   void setValue(const T &V, bool initial = false) {
01083     check_location();
01084     *Location = V;
01085     if (initial)
01086       Default = V;
01087   }
01088 
01089   DataType &getValue() { check_location(); return *Location; }
01090   const DataType &getValue() const { check_location(); return *Location; }
01091 
01092   operator DataType() const { return this->getValue(); }
01093 
01094   const OptionValue<DataType> &getDefault() const { return Default; }
01095 };
01096 
01097 // Define how to hold a class type object, such as a string.  Since we can
01098 // inherit from a class, we do so.  This makes us exactly compatible with the
01099 // object in all cases that it is used.
01100 //
01101 template<class DataType>
01102 class opt_storage<DataType,false,true> : public DataType {
01103 public:
01104   OptionValue<DataType> Default;
01105 
01106   template<class T>
01107   void setValue(const T &V, bool initial = false) {
01108     DataType::operator=(V);
01109     if (initial)
01110       Default = V;
01111   }
01112 
01113   DataType &getValue() { return *this; }
01114   const DataType &getValue() const { return *this; }
01115 
01116   const OptionValue<DataType> &getDefault() const { return Default; }
01117 };
01118 
01119 // Define a partial specialization to handle things we cannot inherit from.  In
01120 // this case, we store an instance through containment, and overload operators
01121 // to get at the value.
01122 //
01123 template<class DataType>
01124 class opt_storage<DataType, false, false> {
01125 public:
01126   DataType Value;
01127   OptionValue<DataType> Default;
01128 
01129   // Make sure we initialize the value with the default constructor for the
01130   // type.
01131   opt_storage() : Value(DataType()), Default(DataType()) {}
01132 
01133   template<class T>
01134   void setValue(const T &V, bool initial = false) {
01135     Value = V;
01136     if (initial)
01137       Default = V;
01138   }
01139   DataType &getValue() { return Value; }
01140   DataType getValue() const { return Value; }
01141 
01142   const OptionValue<DataType> &getDefault() const { return Default; }
01143 
01144   operator DataType() const { return getValue(); }
01145 
01146   // If the datatype is a pointer, support -> on it.
01147   DataType operator->() const { return Value; }
01148 };
01149 
01150 
01151 //===----------------------------------------------------------------------===//
01152 // opt - A scalar command line option.
01153 //
01154 template <class DataType, bool ExternalStorage = false,
01155           class ParserClass = parser<DataType> >
01156 class opt : public Option,
01157             public opt_storage<DataType, ExternalStorage,
01158                                std::is_class<DataType>::value> {
01159   ParserClass Parser;
01160 
01161   bool handleOccurrence(unsigned pos, StringRef ArgName,
01162                         StringRef Arg) override {
01163     typename ParserClass::parser_data_type Val =
01164        typename ParserClass::parser_data_type();
01165     if (Parser.parse(*this, ArgName, Arg, Val))
01166       return true;                            // Parse error!
01167     this->setValue(Val);
01168     this->setPosition(pos);
01169     return false;
01170   }
01171 
01172   enum ValueExpected getValueExpectedFlagDefault() const override {
01173     return Parser.getValueExpectedFlagDefault();
01174   }
01175   void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) override {
01176     return Parser.getExtraOptionNames(OptionNames);
01177   }
01178 
01179   // Forward printing stuff to the parser...
01180   size_t getOptionWidth() const override {return Parser.getOptionWidth(*this);}
01181   void printOptionInfo(size_t GlobalWidth) const override {
01182     Parser.printOptionInfo(*this, GlobalWidth);
01183   }
01184 
01185   void printOptionValue(size_t GlobalWidth, bool Force) const override {
01186     if (Force || this->getDefault().compare(this->getValue())) {
01187       cl::printOptionDiff<ParserClass>(
01188         *this, Parser, this->getValue(), this->getDefault(), GlobalWidth);
01189     }
01190   }
01191 
01192   void done() {
01193     addArgument();
01194     Parser.initialize(*this);
01195   }
01196 public:
01197   // setInitialValue - Used by the cl::init modifier...
01198   void setInitialValue(const DataType &V) { this->setValue(V, true); }
01199 
01200   ParserClass &getParser() { return Parser; }
01201 
01202   template<class T>
01203   DataType &operator=(const T &Val) {
01204     this->setValue(Val);
01205     return this->getValue();
01206   }
01207 
01208   // One option...
01209   template<class M0t>
01210   explicit opt(const M0t &M0) : Option(Optional, NotHidden) {
01211     apply(M0, this);
01212     done();
01213   }
01214 
01215   // Two options...
01216   template<class M0t, class M1t>
01217   opt(const M0t &M0, const M1t &M1) : Option(Optional, NotHidden) {
01218     apply(M0, this); apply(M1, this);
01219     done();
01220   }
01221 
01222   // Three options...
01223   template<class M0t, class M1t, class M2t>
01224   opt(const M0t &M0, const M1t &M1,
01225       const M2t &M2) : Option(Optional, NotHidden) {
01226     apply(M0, this); apply(M1, this); apply(M2, this);
01227     done();
01228   }
01229   // Four options...
01230   template<class M0t, class M1t, class M2t, class M3t>
01231   opt(const M0t &M0, const M1t &M1, const M2t &M2,
01232       const M3t &M3) : Option(Optional, NotHidden) {
01233     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01234     done();
01235   }
01236   // Five options...
01237   template<class M0t, class M1t, class M2t, class M3t, class M4t>
01238   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
01239       const M4t &M4) : Option(Optional, NotHidden) {
01240     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01241     apply(M4, this);
01242     done();
01243   }
01244   // Six options...
01245   template<class M0t, class M1t, class M2t, class M3t,
01246            class M4t, class M5t>
01247   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
01248       const M4t &M4, const M5t &M5) : Option(Optional, NotHidden) {
01249     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01250     apply(M4, this); apply(M5, this);
01251     done();
01252   }
01253   // Seven options...
01254   template<class M0t, class M1t, class M2t, class M3t,
01255            class M4t, class M5t, class M6t>
01256   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
01257       const M4t &M4, const M5t &M5,
01258       const M6t &M6) : Option(Optional, NotHidden) {
01259     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01260     apply(M4, this); apply(M5, this); apply(M6, this);
01261     done();
01262   }
01263   // Eight options...
01264   template<class M0t, class M1t, class M2t, class M3t,
01265            class M4t, class M5t, class M6t, class M7t>
01266   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
01267       const M4t &M4, const M5t &M5, const M6t &M6,
01268       const M7t &M7) : Option(Optional, NotHidden) {
01269     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01270     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
01271     done();
01272   }
01273 };
01274 
01275 EXTERN_TEMPLATE_INSTANTIATION(class opt<unsigned>);
01276 EXTERN_TEMPLATE_INSTANTIATION(class opt<int>);
01277 EXTERN_TEMPLATE_INSTANTIATION(class opt<std::string>);
01278 EXTERN_TEMPLATE_INSTANTIATION(class opt<char>);
01279 EXTERN_TEMPLATE_INSTANTIATION(class opt<bool>);
01280 
01281 //===----------------------------------------------------------------------===//
01282 // list_storage class
01283 
01284 // Default storage class definition: external storage.  This implementation
01285 // assumes the user will specify a variable to store the data into with the
01286 // cl::location(x) modifier.
01287 //
01288 template<class DataType, class StorageClass>
01289 class list_storage {
01290   StorageClass *Location;   // Where to store the object...
01291 
01292 public:
01293   list_storage() : Location(0) {}
01294 
01295   bool setLocation(Option &O, StorageClass &L) {
01296     if (Location)
01297       return O.error("cl::location(x) specified more than once!");
01298     Location = &L;
01299     return false;
01300   }
01301 
01302   template<class T>
01303   void addValue(const T &V) {
01304     assert(Location != 0 && "cl::location(...) not specified for a command "
01305            "line option with external storage!");
01306     Location->push_back(V);
01307   }
01308 };
01309 
01310 
01311 // Define how to hold a class type object, such as a string.  Since we can
01312 // inherit from a class, we do so.  This makes us exactly compatible with the
01313 // object in all cases that it is used.
01314 //
01315 template<class DataType>
01316 class list_storage<DataType, bool> : public std::vector<DataType> {
01317 public:
01318   template<class T>
01319   void addValue(const T &V) { std::vector<DataType>::push_back(V); }
01320 };
01321 
01322 
01323 //===----------------------------------------------------------------------===//
01324 // list - A list of command line options.
01325 //
01326 template <class DataType, class Storage = bool,
01327           class ParserClass = parser<DataType> >
01328 class list : public Option, public list_storage<DataType, Storage> {
01329   std::vector<unsigned> Positions;
01330   ParserClass Parser;
01331 
01332   enum ValueExpected getValueExpectedFlagDefault() const override {
01333     return Parser.getValueExpectedFlagDefault();
01334   }
01335   void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) override {
01336     return Parser.getExtraOptionNames(OptionNames);
01337   }
01338 
01339   bool handleOccurrence(unsigned pos, StringRef ArgName,
01340                         StringRef Arg) override {
01341     typename ParserClass::parser_data_type Val =
01342       typename ParserClass::parser_data_type();
01343     if (Parser.parse(*this, ArgName, Arg, Val))
01344       return true;  // Parse Error!
01345     list_storage<DataType, Storage>::addValue(Val);
01346     setPosition(pos);
01347     Positions.push_back(pos);
01348     return false;
01349   }
01350 
01351   // Forward printing stuff to the parser...
01352   size_t getOptionWidth() const override {return Parser.getOptionWidth(*this);}
01353   void printOptionInfo(size_t GlobalWidth) const override {
01354     Parser.printOptionInfo(*this, GlobalWidth);
01355   }
01356 
01357   // Unimplemented: list options don't currently store their default value.
01358   void printOptionValue(size_t /*GlobalWidth*/,
01359                         bool /*Force*/) const override {}
01360 
01361   void done() {
01362     addArgument();
01363     Parser.initialize(*this);
01364   }
01365 public:
01366   ParserClass &getParser() { return Parser; }
01367 
01368   unsigned getPosition(unsigned optnum) const {
01369     assert(optnum < this->size() && "Invalid option index");
01370     return Positions[optnum];
01371   }
01372 
01373   void setNumAdditionalVals(unsigned n) {
01374     Option::setNumAdditionalVals(n);
01375   }
01376 
01377   // One option...
01378   template<class M0t>
01379   explicit list(const M0t &M0) : Option(ZeroOrMore, NotHidden) {
01380     apply(M0, this);
01381     done();
01382   }
01383   // Two options...
01384   template<class M0t, class M1t>
01385   list(const M0t &M0, const M1t &M1) : Option(ZeroOrMore, NotHidden) {
01386     apply(M0, this); apply(M1, this);
01387     done();
01388   }
01389   // Three options...
01390   template<class M0t, class M1t, class M2t>
01391   list(const M0t &M0, const M1t &M1, const M2t &M2)
01392     : Option(ZeroOrMore, NotHidden) {
01393     apply(M0, this); apply(M1, this); apply(M2, this);
01394     done();
01395   }
01396   // Four options...
01397   template<class M0t, class M1t, class M2t, class M3t>
01398   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
01399     : Option(ZeroOrMore, NotHidden) {
01400     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01401     done();
01402   }
01403   // Five options...
01404   template<class M0t, class M1t, class M2t, class M3t, class M4t>
01405   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
01406        const M4t &M4) : Option(ZeroOrMore, NotHidden) {
01407     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01408     apply(M4, this);
01409     done();
01410   }
01411   // Six options...
01412   template<class M0t, class M1t, class M2t, class M3t,
01413            class M4t, class M5t>
01414   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
01415        const M4t &M4, const M5t &M5) : Option(ZeroOrMore, NotHidden) {
01416     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01417     apply(M4, this); apply(M5, this);
01418     done();
01419   }
01420   // Seven options...
01421   template<class M0t, class M1t, class M2t, class M3t,
01422            class M4t, class M5t, class M6t>
01423   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
01424        const M4t &M4, const M5t &M5, const M6t &M6)
01425     : Option(ZeroOrMore, NotHidden) {
01426     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01427     apply(M4, this); apply(M5, this); apply(M6, this);
01428     done();
01429   }
01430   // Eight options...
01431   template<class M0t, class M1t, class M2t, class M3t,
01432            class M4t, class M5t, class M6t, class M7t>
01433   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
01434        const M4t &M4, const M5t &M5, const M6t &M6,
01435        const M7t &M7) : Option(ZeroOrMore, NotHidden) {
01436     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01437     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
01438     done();
01439   }
01440 };
01441 
01442 // multi_val - Modifier to set the number of additional values.
01443 struct multi_val {
01444   unsigned AdditionalVals;
01445   explicit multi_val(unsigned N) : AdditionalVals(N) {}
01446 
01447   template <typename D, typename S, typename P>
01448   void apply(list<D, S, P> &L) const { L.setNumAdditionalVals(AdditionalVals); }
01449 };
01450 
01451 
01452 //===----------------------------------------------------------------------===//
01453 // bits_storage class
01454 
01455 // Default storage class definition: external storage.  This implementation
01456 // assumes the user will specify a variable to store the data into with the
01457 // cl::location(x) modifier.
01458 //
01459 template<class DataType, class StorageClass>
01460 class bits_storage {
01461   unsigned *Location;   // Where to store the bits...
01462 
01463   template<class T>
01464   static unsigned Bit(const T &V) {
01465     unsigned BitPos = reinterpret_cast<unsigned>(V);
01466     assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
01467           "enum exceeds width of bit vector!");
01468     return 1 << BitPos;
01469   }
01470 
01471 public:
01472   bits_storage() : Location(nullptr) {}
01473 
01474   bool setLocation(Option &O, unsigned &L) {
01475     if (Location)
01476       return O.error("cl::location(x) specified more than once!");
01477     Location = &L;
01478     return false;
01479   }
01480 
01481   template<class T>
01482   void addValue(const T &V) {
01483     assert(Location != 0 && "cl::location(...) not specified for a command "
01484            "line option with external storage!");
01485     *Location |= Bit(V);
01486   }
01487 
01488   unsigned getBits() { return *Location; }
01489 
01490   template<class T>
01491   bool isSet(const T &V) {
01492     return (*Location & Bit(V)) != 0;
01493   }
01494 };
01495 
01496 
01497 // Define how to hold bits.  Since we can inherit from a class, we do so.
01498 // This makes us exactly compatible with the bits in all cases that it is used.
01499 //
01500 template<class DataType>
01501 class bits_storage<DataType, bool> {
01502   unsigned Bits;   // Where to store the bits...
01503 
01504   template<class T>
01505   static unsigned Bit(const T &V) {
01506     unsigned BitPos = (unsigned)V;
01507     assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
01508           "enum exceeds width of bit vector!");
01509     return 1 << BitPos;
01510   }
01511 
01512 public:
01513   template<class T>
01514   void addValue(const T &V) {
01515     Bits |=  Bit(V);
01516   }
01517 
01518   unsigned getBits() { return Bits; }
01519 
01520   template<class T>
01521   bool isSet(const T &V) {
01522     return (Bits & Bit(V)) != 0;
01523   }
01524 };
01525 
01526 
01527 //===----------------------------------------------------------------------===//
01528 // bits - A bit vector of command options.
01529 //
01530 template <class DataType, class Storage = bool,
01531           class ParserClass = parser<DataType> >
01532 class bits : public Option, public bits_storage<DataType, Storage> {
01533   std::vector<unsigned> Positions;
01534   ParserClass Parser;
01535 
01536   enum ValueExpected getValueExpectedFlagDefault() const override {
01537     return Parser.getValueExpectedFlagDefault();
01538   }
01539   void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) override {
01540     return Parser.getExtraOptionNames(OptionNames);
01541   }
01542 
01543   bool handleOccurrence(unsigned pos, StringRef ArgName,
01544                         StringRef Arg) override {
01545     typename ParserClass::parser_data_type Val =
01546       typename ParserClass::parser_data_type();
01547     if (Parser.parse(*this, ArgName, Arg, Val))
01548       return true;  // Parse Error!
01549     this->addValue(Val);
01550     setPosition(pos);
01551     Positions.push_back(pos);
01552     return false;
01553   }
01554 
01555   // Forward printing stuff to the parser...
01556   size_t getOptionWidth() const override {return Parser.getOptionWidth(*this);}
01557   void printOptionInfo(size_t GlobalWidth) const override {
01558     Parser.printOptionInfo(*this, GlobalWidth);
01559   }
01560 
01561   // Unimplemented: bits options don't currently store their default values.
01562   void printOptionValue(size_t /*GlobalWidth*/,
01563                         bool /*Force*/) const override {}
01564 
01565   void done() {
01566     addArgument();
01567     Parser.initialize(*this);
01568   }
01569 public:
01570   ParserClass &getParser() { return Parser; }
01571 
01572   unsigned getPosition(unsigned optnum) const {
01573     assert(optnum < this->size() && "Invalid option index");
01574     return Positions[optnum];
01575   }
01576 
01577   // One option...
01578   template<class M0t>
01579   explicit bits(const M0t &M0) : Option(ZeroOrMore, NotHidden) {
01580     apply(M0, this);
01581     done();
01582   }
01583   // Two options...
01584   template<class M0t, class M1t>
01585   bits(const M0t &M0, const M1t &M1) : Option(ZeroOrMore, NotHidden) {
01586     apply(M0, this); apply(M1, this);
01587     done();
01588   }
01589   // Three options...
01590   template<class M0t, class M1t, class M2t>
01591   bits(const M0t &M0, const M1t &M1, const M2t &M2)
01592     : Option(ZeroOrMore, NotHidden) {
01593     apply(M0, this); apply(M1, this); apply(M2, this);
01594     done();
01595   }
01596   // Four options...
01597   template<class M0t, class M1t, class M2t, class M3t>
01598   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
01599     : Option(ZeroOrMore, NotHidden) {
01600     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01601     done();
01602   }
01603   // Five options...
01604   template<class M0t, class M1t, class M2t, class M3t, class M4t>
01605   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
01606        const M4t &M4) : Option(ZeroOrMore, NotHidden) {
01607     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01608     apply(M4, this);
01609     done();
01610   }
01611   // Six options...
01612   template<class M0t, class M1t, class M2t, class M3t,
01613            class M4t, class M5t>
01614   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
01615        const M4t &M4, const M5t &M5) : Option(ZeroOrMore, NotHidden) {
01616     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01617     apply(M4, this); apply(M5, this);
01618     done();
01619   }
01620   // Seven options...
01621   template<class M0t, class M1t, class M2t, class M3t,
01622            class M4t, class M5t, class M6t>
01623   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
01624        const M4t &M4, const M5t &M5, const M6t &M6)
01625     : Option(ZeroOrMore, NotHidden) {
01626     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01627     apply(M4, this); apply(M5, this); apply(M6, this);
01628     done();
01629   }
01630   // Eight options...
01631   template<class M0t, class M1t, class M2t, class M3t,
01632            class M4t, class M5t, class M6t, class M7t>
01633   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
01634        const M4t &M4, const M5t &M5, const M6t &M6,
01635        const M7t &M7) : Option(ZeroOrMore, NotHidden) {
01636     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01637     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
01638     done();
01639   }
01640 };
01641 
01642 //===----------------------------------------------------------------------===//
01643 // Aliased command line option (alias this name to a preexisting name)
01644 //
01645 
01646 class alias : public Option {
01647   Option *AliasFor;
01648   bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
01649                                 StringRef Arg) override {
01650     return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
01651   }
01652   bool addOccurrence(unsigned pos, StringRef /*ArgName*/,
01653                      StringRef Value, bool MultiArg = false) override {
01654     return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
01655   }
01656   // Handle printing stuff...
01657   size_t getOptionWidth() const override;
01658   void printOptionInfo(size_t GlobalWidth) const override;
01659 
01660   // Aliases do not need to print their values.
01661   void printOptionValue(size_t /*GlobalWidth*/,
01662                         bool /*Force*/) const override {}
01663 
01664   ValueExpected getValueExpectedFlagDefault() const override {
01665     return AliasFor->getValueExpectedFlag();
01666   }
01667 
01668   void done() {
01669     if (!hasArgStr())
01670       error("cl::alias must have argument name specified!");
01671     if (!AliasFor)
01672       error("cl::alias must have an cl::aliasopt(option) specified!");
01673       addArgument();
01674   }
01675 public:
01676   void setAliasFor(Option &O) {
01677     if (AliasFor)
01678       error("cl::alias must only have one cl::aliasopt(...) specified!");
01679     AliasFor = &O;
01680   }
01681 
01682   // One option...
01683   template<class M0t>
01684   explicit alias(const M0t &M0) : Option(Optional, Hidden), AliasFor(nullptr) {
01685     apply(M0, this);
01686     done();
01687   }
01688   // Two options...
01689   template<class M0t, class M1t>
01690   alias(const M0t &M0, const M1t &M1)
01691     : Option(Optional, Hidden), AliasFor(nullptr) {
01692     apply(M0, this); apply(M1, this);
01693     done();
01694   }
01695   // Three options...
01696   template<class M0t, class M1t, class M2t>
01697   alias(const M0t &M0, const M1t &M1, const M2t &M2)
01698     : Option(Optional, Hidden), AliasFor(nullptr) {
01699     apply(M0, this); apply(M1, this); apply(M2, this);
01700     done();
01701   }
01702   // Four options...
01703   template<class M0t, class M1t, class M2t, class M3t>
01704   alias(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
01705     : Option(Optional, Hidden), AliasFor(nullptr) {
01706     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
01707     done();
01708   }
01709 };
01710 
01711 // aliasfor - Modifier to set the option an alias aliases.
01712 struct aliasopt {
01713   Option &Opt;
01714   explicit aliasopt(Option &O) : Opt(O) {}
01715   void apply(alias &A) const { A.setAliasFor(Opt); }
01716 };
01717 
01718 // extrahelp - provide additional help at the end of the normal help
01719 // output. All occurrences of cl::extrahelp will be accumulated and
01720 // printed to stderr at the end of the regular help, just before
01721 // exit is called.
01722 struct extrahelp {
01723   const char * morehelp;
01724   explicit extrahelp(const char* help);
01725 };
01726 
01727 void PrintVersionMessage();
01728 
01729 /// This function just prints the help message, exactly the same way as if the
01730 /// -help or -help-hidden option had been given on the command line.
01731 ///
01732 /// NOTE: THIS FUNCTION TERMINATES THE PROGRAM!
01733 ///
01734 /// \param Hidden if true will print hidden options
01735 /// \param Categorized if true print options in categories
01736 void PrintHelpMessage(bool Hidden=false, bool Categorized=false);
01737 
01738 
01739 //===----------------------------------------------------------------------===//
01740 // Public interface for accessing registered options.
01741 //
01742 
01743 /// \brief Use this to get a StringMap to all registered named options
01744 /// (e.g. -help). Note \p Map Should be an empty StringMap.
01745 ///
01746 /// \param [out] Map will be filled with mappings where the key is the
01747 /// Option argument string (e.g. "help") and value is the corresponding
01748 /// Option*.
01749 ///
01750 /// Access to unnamed arguments (i.e. positional) are not provided because
01751 /// it is expected that the client already has access to these.
01752 ///
01753 /// Typical usage:
01754 /// \code
01755 /// main(int argc,char* argv[]) {
01756 /// StringMap<llvm::cl::Option*> opts;
01757 /// llvm::cl::getRegisteredOptions(opts);
01758 /// assert(opts.count("help") == 1)
01759 /// opts["help"]->setDescription("Show alphabetical help information")
01760 /// // More code
01761 /// llvm::cl::ParseCommandLineOptions(argc,argv);
01762 /// //More code
01763 /// }
01764 /// \endcode
01765 ///
01766 /// This interface is useful for modifying options in libraries that are out of
01767 /// the control of the client. The options should be modified before calling
01768 /// llvm::cl::ParseCommandLineOptions().
01769 void getRegisteredOptions(StringMap<Option*> &Map);
01770 
01771 //===----------------------------------------------------------------------===//
01772 // Standalone command line processing utilities.
01773 //
01774 
01775 /// \brief Saves strings in the inheritor's stable storage and returns a stable
01776 /// raw character pointer.
01777 class StringSaver {
01778   virtual void anchor();
01779 public:
01780   virtual const char *SaveString(const char *Str) = 0;
01781   virtual ~StringSaver() {};  // Pacify -Wnon-virtual-dtor.
01782 };
01783 
01784 /// \brief Tokenizes a command line that can contain escapes and quotes.
01785 //
01786 /// The quoting rules match those used by GCC and other tools that use
01787 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
01788 /// They differ from buildargv() on treatment of backslashes that do not escape
01789 /// a special character to make it possible to accept most Windows file paths.
01790 ///
01791 /// \param [in] Source The string to be split on whitespace with quotes.
01792 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
01793 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
01794 /// lines and end of the response file to be marked with a nullptr string.
01795 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
01796 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
01797                             SmallVectorImpl<const char *> &NewArgv,
01798                             bool MarkEOLs = false);
01799 
01800 /// \brief Tokenizes a Windows command line which may contain quotes and escaped
01801 /// quotes.
01802 ///
01803 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
01804 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
01805 ///
01806 /// \param [in] Source The string to be split on whitespace with quotes.
01807 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
01808 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
01809 /// lines and end of the response file to be marked with a nullptr string.
01810 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
01811 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
01812                                 SmallVectorImpl<const char *> &NewArgv,
01813                                 bool MarkEOLs = false);
01814 
01815 /// \brief String tokenization function type.  Should be compatible with either
01816 /// Windows or Unix command line tokenizers.
01817 typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
01818                                   SmallVectorImpl<const char *> &NewArgv,
01819                                   bool MarkEOLs);
01820 
01821 /// \brief Expand response files on a command line recursively using the given
01822 /// StringSaver and tokenization strategy.  Argv should contain the command line
01823 /// before expansion and will be modified in place. If requested, Argv will
01824 /// also be populated with nullptrs indicating where each response file line
01825 /// ends, which is useful for the "/link" argument that needs to consume all
01826 /// remaining arguments only until the next end of line, when in a response
01827 /// file.
01828 ///
01829 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
01830 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
01831 /// \param [in,out] Argv Command line into which to expand response files.
01832 /// \param [in] MarkEOLs Mark end of lines and the end of the response file
01833 /// with nullptrs in the Argv vector.
01834 /// \return true if all @files were expanded successfully or there were none.
01835 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
01836                          SmallVectorImpl<const char *> &Argv,
01837                          bool MarkEOLs = false);
01838 
01839 } // End namespace cl
01840 
01841 } // End namespace llvm
01842 
01843 #endif