add new function
[oota-llvm.git] / include / Support / CommandLine.h
index e8a4250a894206fc97390cb8f14d7dcb9a386bef..0a3cb6f320b7cac125beabdd433097a9c3b34652 100644 (file)
@@ -1,4 +1,11 @@
-//===- Support/CommandLine.h - Flexible Command line parser ------*- C++ -*--=//
+//===- Support/CommandLine.h - Flexible Command line parser -----*- C++ -*-===//
+// 
+//                     The LLVM Compiler Infrastructure
+//
+// This file was developed by the LLVM research group and is distributed under
+// the University of Illinois Open Source License. See LICENSE.TXT for details.
+// 
+//===----------------------------------------------------------------------===//
 //
 // This class implements a command line argument processor that is useful when
 // creating a tool.  It provides a simple, minimalistic interface that is easily
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_SUPPORT_COMMANDLINE_H
-#define LLVM_SUPPORT_COMMANDLINE_H
+#ifndef SUPPORT_COMMANDLINE_H
+#define SUPPORT_COMMANDLINE_H
 
 #include <string>
 #include <vector>
 #include <utility>
-#include <stdarg.h>
+#include <cstdarg>
+#include <cassert>
 #include "boost/type_traits/object_traits.hpp"
 
-namespace cl {   // Short namespace to make usage concise
+namespace llvm {
+/// cl Namespace - This namespace contains all of the command line option
+/// processing machinery.  It is intentionally a short name to make qualified
+/// usage concise.
+namespace cl {
 
 //===----------------------------------------------------------------------===//
 // ParseCommandLineOptions - Command line option processing entry point.
 //
-void cl::ParseCommandLineOptions(int &argc, char **argv,
-                                const char *Overview = 0);
+void ParseCommandLineOptions(int &argc, char **argv,
+                             const char *Overview = 0);
+
+//===----------------------------------------------------------------------===//
+// ParseEnvironmentOptions - Environment variable option processing alternate
+//                           entry point.
+//
+void ParseEnvironmentOptions(const char *progName, const char *envvar,
+                             const char *Overview = 0);
 
 //===----------------------------------------------------------------------===//
 // Flags permitted to be passed to command line arguments
 //
 
-enum NumOccurances {           // Flags for the number of occurances allowed...
-  Optional        = 0x01,      // Zero or One occurance
-  ZeroOrMore      = 0x02,      // Zero or more occurances allowed
-  Required        = 0x03,      // One occurance required
-  OneOrMore       = 0x04,      // One or more occurances required
+enum NumOccurrences {           // Flags for the number of occurrences allowed
+  Optional        = 0x01,      // Zero or One occurrence
+  ZeroOrMore      = 0x02,      // Zero or more occurrences allowed
+  Required        = 0x03,      // One occurrence required
+  OneOrMore       = 0x04,      // One or more occurrences required
 
   // ConsumeAfter - Indicates that this option is fed anything that follows the
   // last positional argument required by the application (it is an error if
@@ -46,11 +65,11 @@ enum NumOccurances {           // Flags for the number of occurances allowed...
   //
   ConsumeAfter    = 0x05,
 
-  OccurancesMask  = 0x07,
+  OccurrencesMask  = 0x07,
 };
 
 enum ValueExpected {           // Is a value required for the option?
-  ValueOptional   = 0x08,      // The value can oppear... or not
+  ValueOptional   = 0x08,      // The value can appear... or not
   ValueRequired   = 0x10,      // The value is required to appear!
   ValueDisallowed = 0x18,      // A value may not be specified (for flags)
   ValueMask       = 0x18,
@@ -86,6 +105,12 @@ enum FormattingFlags {
   FormattingMask   = 0x180,
 };
 
+enum MiscFlags {                // Miscellaneous flags to adjust argument
+  CommaSeparated   = 0x200,     // Should this cl::list split between commas?
+  MiscMask         = 0x200,
+};
+
+
 
 //===----------------------------------------------------------------------===//
 // Option Base class
@@ -95,13 +120,13 @@ class Option {
   friend void cl::ParseCommandLineOptions(int &, char **, const char *, int);
   friend class alias;
 
-  // handleOccurances - Overriden by subclasses to handle the value passed into
+  // handleOccurrences - Overriden by subclasses to handle the value passed into
   // an argument.  Should return true if there was an error processing the
   // argument and the program should exit.
   //
-  virtual bool handleOccurance(const char *ArgName, const std::string &Arg) = 0;
+  virtual bool handleOccurrence(const char *ArgName, const std::string &Arg) = 0;
 
-  virtual enum NumOccurances getNumOccurancesFlagDefault() const { 
+  virtual enum NumOccurrences getNumOccurrencesFlagDefault() const { 
     return Optional;
   }
   virtual enum ValueExpected getValueExpectedFlagDefault() const {
@@ -114,28 +139,35 @@ class Option {
     return NormalFormatting;
   }
 
-  int NumOccurances;    // The number of times specified
+  int NumOccurrences;    // The number of times specified
   int Flags;            // Flags for the argument
 public:
   const char *ArgStr;   // The argument string itself (ex: "help", "o")
   const char *HelpStr;  // The descriptive text message for --help
   const char *ValueStr; // String describing what the value of this option is
 
-  inline enum NumOccurances getNumOccurancesFlag() const {
-    int NO = Flags & OccurancesMask;
-    return NO ? (enum NumOccurances)NO : getNumOccurancesFlagDefault();
+  inline enum NumOccurrences getNumOccurrencesFlag() const {
+    int NO = Flags & OccurrencesMask;
+    return NO ? static_cast<enum NumOccurrences>(NO)
+              : getNumOccurrencesFlagDefault();
   }
   inline enum ValueExpected getValueExpectedFlag() const {
     int VE = Flags & ValueMask;
-    return VE ? (enum ValueExpected)VE : getValueExpectedFlagDefault();
+    return VE ? static_cast<enum ValueExpected>(VE)
+              : getValueExpectedFlagDefault();
   }
   inline enum OptionHidden getOptionHiddenFlag() const {
     int OH = Flags & HiddenMask;
-    return OH ? (enum OptionHidden)OH : getOptionHiddenFlagDefault();
+    return OH ? static_cast<enum OptionHidden>(OH)
+              : getOptionHiddenFlagDefault();
   }
   inline enum FormattingFlags getFormattingFlag() const {
     int OH = Flags & FormattingMask;
-    return OH ? (enum FormattingFlags)OH : getFormattingFlagDefault();
+    return OH ? static_cast<enum FormattingFlags>(OH)
+              : getFormattingFlagDefault();
+  }
+  inline unsigned getMiscFlags() const {
+    return Flags & MiscMask;
   }
 
   // hasArgStr - Return true if the argstr != ""
@@ -157,22 +189,23 @@ public:
     Flags |= Flag;
   }
 
-  void setNumOccurancesFlag(enum NumOccurances Val) {
-    setFlag(Val, OccurancesMask);
+  void setNumOccurrencesFlag(enum NumOccurrences Val) {
+    setFlag(Val, OccurrencesMask);
   }
   void setValueExpectedFlag(enum ValueExpected Val) { setFlag(Val, ValueMask); }
   void setHiddenFlag(enum OptionHidden Val) { setFlag(Val, HiddenMask); }
   void setFormattingFlag(enum FormattingFlags V) { setFlag(V, FormattingMask); }
-
+  void setMiscFlag(enum MiscFlags M) { setFlag(M, M); }
 protected:
-  Option() : NumOccurances(0), Flags(0),
+  Option() : NumOccurrences(0), Flags(0),
              ArgStr(""), HelpStr(""), ValueStr("") {}
 
 public:
   // addArgument - Tell the system that this Option subclass will handle all
-  // occurances of -ArgStr on the command line.
+  // occurrences of -ArgStr on the command line.
   //
   void addArgument(const char *ArgStr);
+  void removeArgument(const char *ArgStr);
 
   // Return the width of the option tag for printing...
   virtual unsigned getOptionWidth() const = 0;
@@ -182,15 +215,15 @@ public:
   //
   virtual void printOptionInfo(unsigned GlobalWidth) const = 0;
 
-  // addOccurance - Wrapper around handleOccurance that enforces Flags
+  // addOccurrence - Wrapper around handleOccurrence that enforces Flags
   //
-  bool addOccurance(const char *ArgName, const std::string &Value);
+  bool addOccurrence(const char *ArgName, const std::string &Value);
 
   // Prints option name followed by message.  Always returns true.
   bool error(std::string Message, const char *ArgName = 0);
 
 public:
-  inline int getNumOccurances() const { return NumOccurances; }
+  inline int getNumOccurrences() const { return NumOccurrences; }
   virtual ~Option() {}
 };
 
@@ -255,8 +288,8 @@ LocationClass<Ty> location(Ty &L) { return LocationClass<Ty>(L); }
 //===----------------------------------------------------------------------===//
 // Enum valued command line option
 //
-#define clEnumVal(ENUMVAL, DESC) #ENUMVAL, ENUMVAL, DESC
-#define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, ENUMVAL, DESC
+#define clEnumVal(ENUMVAL, DESC) #ENUMVAL, (int)ENUMVAL, DESC
+#define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, (int)ENUMVAL, DESC
 
 // values - For custom data types, allow specifying a group of values together
 // as the values that go into the mapping that the option handler uses.  Note
@@ -278,7 +311,7 @@ public:
 
     // Process the varargs portion of the values...
     while (const char *EnumName = va_arg(ValueArgs, const char *)) {
-      DataType EnumVal = va_arg(ValueArgs, DataType);
+      DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
       const char *EnumDesc = va_arg(ValueArgs, const char *);
       Values.push_back(std::make_pair(EnumName,      // Add value to value map
                                       std::make_pair(EnumVal, EnumDesc)));
@@ -361,7 +394,7 @@ struct generic_parser_base {
     // In which case, the value is required.  Otherwise if an arg str has not
     // been specified, we are of the form:
     //
-    //    -O2 or O2 or -la (where -l and -a are seperate options)
+    //    -O2 or O2 or -la (where -l and -a are separate options)
     //
     // If this is the case, we cannot allow a value.
     //
@@ -371,6 +404,11 @@ struct generic_parser_base {
       return ValueDisallowed;
   }
 
+  // findOption - Return the option number corresponding to the specified
+  // argument string.  If the option is not found, getNumOptions() is returned.
+  //
+  unsigned findOption(const char *Name);
+
 protected:
   bool hasArgStr;
 };
@@ -383,8 +421,11 @@ protected:
 //
 template <class DataType>
 class parser : public generic_parser_base {
+protected:
   std::vector<std::pair<const char *,
                         std::pair<DataType, const char *> > > Values;
+public:
+  typedef DataType parser_data_type;
 
   // Implement virtual functions needed by generic_parser_base
   unsigned getNumOptions() const { return Values.size(); }
@@ -393,11 +434,10 @@ class parser : public generic_parser_base {
     return Values[N].second.second;
   }
 
-public:
-  // Default implementation, requires user to populate it with values somehow.
-  template<class Opt>   // parse - Return true on error.
-  bool parse(Opt &O, const char *ArgName, const string &Arg) {
-    string ArgVal;
+  // parse - Return true on error.
+  bool parse(Option &O, const char *ArgName, const std::string &Arg,
+             DataType &V) {
+    std::string ArgVal;
     if (hasArgStr)
       ArgVal = Arg;
     else
@@ -405,7 +445,7 @@ public:
 
     for (unsigned i = 0, e = Values.size(); i != e; ++i)
       if (ArgVal == Values[i].first) {
-        O.addValue(Values[i].second.first);
+        V = Values[i].second.first;
         return false;
       }
 
@@ -415,137 +455,141 @@ public:
   // addLiteralOption - Add an entry to the mapping table...
   template <class DT>
   void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
-    Values.push_back(std::make_pair(Name, std::make_pair((DataType)V,HelpStr)));
+    assert(findOption(Name) == Values.size() && "Option already exists!");
+    Values.push_back(std::make_pair(Name,
+                             std::make_pair(static_cast<DataType>(V),HelpStr)));
   }
-};
 
+  // removeLiteralOption - Remove the specified option.
+  //
+  void removeLiteralOption(const char *Name) {
+    unsigned N = findOption(Name);
+    assert(N != Values.size() && "Option not found!");
+    Values.erase(Values.begin()+N);
+  }
+};
 
 //--------------------------------------------------
-// parser<bool>
+// basic_parser - Super class of parsers to provide boilerplate code
 //
-template<>
-class parser<bool> {
-  static bool parseImpl(Option &O, const string &Arg, bool &Val);
-public:
-  
-  template<class Opt>     // parse - Return true on error.
-  bool parse(Opt &O, const char *ArgName, const string &Arg) {
-    bool Val;
-    bool Error = parseImpl(O, Arg, Val);
-    if (!Error) O.addValue(Val);
-    return Error;
-  }
+struct basic_parser_impl {  // non-template implementation of basic_parser<t>
+  virtual ~basic_parser_impl() {}
 
   enum ValueExpected getValueExpectedFlagDefault() const {
-    return ValueOptional; 
+    return ValueRequired;
   }
-
+  
   void initialize(Option &O) {}
-
+  
   // Return the width of the option tag for printing...
-  virtual unsigned getOptionWidth(const Option &O) const;
-
-  // printOptionInfo - Print out information about this option.  The 
+  unsigned getOptionWidth(const Option &O) const;
+  
+  // printOptionInfo - Print out information about this option.  The
   // to-be-maintained width is specified.
   //
-  virtual void printOptionInfo(const Option &O, unsigned GlobalWidth) const;
+  void printOptionInfo(const Option &O, unsigned GlobalWidth) const;
+
+
+  // getValueName - Overload in subclass to provide a better default value.
+  virtual const char *getValueName() const { return "value"; }
+};
+
+// basic_parser - The real basic parser is just a template wrapper that provides
+// a typedef for the provided data type.
+//
+template<class DataType>
+struct basic_parser : public basic_parser_impl {
+  typedef DataType parser_data_type;
 };
 
 
 //--------------------------------------------------
-// parser<int>
+// parser<bool>
 //
 template<>
-class parser<int> {
-  static bool parseImpl(Option &O, const string &Arg, int &Val);
-public:
-  
+struct parser<bool> : public basic_parser<bool> {
+
   // parse - Return true on error.
-  template<class Opt>
-  bool parse(Opt &O, const char *ArgName, const string &Arg) {
-    int Val;
-    bool Error = parseImpl(O, Arg, Val);
-    if (!Error) O.addValue(Val);
-    return Error;
-  }
+  bool parse(Option &O, const char *ArgName, const std::string &Arg, bool &Val);
 
   enum ValueExpected getValueExpectedFlagDefault() const {
-    return ValueRequired
+    return ValueOptional
   }
 
-  void initialize(Option &O) {}
+  // getValueName - Do not print =<value> at all
+  virtual const char *getValueName() const { return 0; }
+};
 
-  // Return the width of the option tag for printing...
-  virtual unsigned getOptionWidth(const Option &O) const;
 
-  // printOptionInfo - Print out information about this option.  The 
-  // to-be-maintained width is specified.
-  //
-  virtual void printOptionInfo(const Option &O, unsigned GlobalWidth) const;
+//--------------------------------------------------
+// parser<int>
+//
+template<>
+struct parser<int> : public basic_parser<int> {
+  
+  // parse - Return true on error.
+  bool parse(Option &O, const char *ArgName, const std::string &Arg, int &Val);
+
+  // getValueName - Overload in subclass to provide a better default value.
+  virtual const char *getValueName() const { return "int"; }
 };
 
 
 //--------------------------------------------------
-// parser<double>
+// parser<unsigned>
 //
 template<>
-class parser<double> {
-  static bool parseImpl(Option &O, const string &Arg, double &Val);
-public:
+struct parser<unsigned> : public basic_parser<unsigned> {
   
   // parse - Return true on error.
-  template<class Opt>
-  bool parse(Opt &O, const char *ArgName, const string &Arg) {
-    double Val;
-    bool Error = parseImpl(O, Arg, Val);
-    if (!Error) O.addValue(Val);
-    return Error;
-  }
+  bool parse(Option &O, const char *ArgName, const std::string &Arg,
+             unsigned &Val);
 
-  enum ValueExpected getValueExpectedFlagDefault() const {
-    return ValueRequired; 
-  }
+  // getValueName - Overload in subclass to provide a better default value.
+  virtual const char *getValueName() const { return "uint"; }
+};
 
-  void initialize(Option &O) {}
 
-  // Return the width of the option tag for printing...
-  virtual unsigned getOptionWidth(const Option &O) const;
+//--------------------------------------------------
+// parser<double>
+//
+template<>
+struct parser<double> : public basic_parser<double> {
+  // parse - Return true on error.
+  bool parse(Option &O, const char *AN, const std::string &Arg, double &Val);
 
-  // printOptionInfo - Print out information about this option.  The 
-  // to-be-maintained width is specified.
-  //
-  virtual void printOptionInfo(const Option &O, unsigned GlobalWidth) const;
+  // getValueName - Overload in subclass to provide a better default value.
+  virtual const char *getValueName() const { return "number"; }
 };
 
-// Parser<float> is the same as parser<double>
-template<> struct parser<float> : public parser<double> {};
 
+//--------------------------------------------------
+// parser<float>
+//
+template<>
+struct parser<float> : public basic_parser<float> {
+  // parse - Return true on error.
+  bool parse(Option &O, const char *AN, const std::string &Arg, float &Val);
+
+  // getValueName - Overload in subclass to provide a better default value.
+  virtual const char *getValueName() const { return "number"; }
+};
 
 
 //--------------------------------------------------
-// parser<string>
+// parser<std::string>
 //
 template<>
-struct parser<string> {
+struct parser<std::string> : public basic_parser<std::string> {
   // parse - Return true on error.
-  template<class Opt>
-  bool parse(Opt &O, const char *ArgName, const string &Arg) {
-    O.addValue(Arg);
+  bool parse(Option &O, const char *ArgName, const std::string &Arg,
+             std::string &Value) {
+    Value = Arg;
     return false;
   }
-  enum ValueExpected getValueExpectedFlagDefault() const {
-    return ValueRequired;
-  }
-
-  void initialize(Option &O) {}
-
-  // Return the width of the option tag for printing...
-  virtual unsigned getOptionWidth(const Option &O) const;
 
-  // printOptionInfo - Print out information about this option.  The 
-  // to-be-maintained width is specified.
-  //
-  virtual void printOptionInfo(const Option &O, unsigned GlobalWidth) const;
+  // getValueName - Overload in subclass to provide a better default value.
+  virtual const char *getValueName() const { return "string"; }
 };
 
 
@@ -566,13 +610,17 @@ template<unsigned n> struct applicator<char[n]> {
   template<class Opt>
   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
 };
+template<unsigned n> struct applicator<const char[n]> {
+  template<class Opt>
+  static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
+};
 template<> struct applicator<const char*> {
   template<class Opt>
   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
 };
 
-template<> struct applicator<NumOccurances> {
-  static void opt(NumOccurances NO, Option &O) { O.setNumOccurancesFlag(NO); }
+template<> struct applicator<NumOccurrences> {
+  static void opt(NumOccurrences NO, Option &O) { O.setNumOccurrencesFlag(NO); }
 };
 template<> struct applicator<ValueExpected> {
   static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
@@ -583,6 +631,9 @@ template<> struct applicator<OptionHidden> {
 template<> struct applicator<FormattingFlags> {
   static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
 };
+template<> struct applicator<MiscFlags> {
+  static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
+};
 
 // apply method - Apply a modifier to an option in a type safe way.
 template<class Mod, class Opt>
@@ -604,7 +655,8 @@ class opt_storage {
 
   void check() {
     assert(Location != 0 && "cl::location(...) not specified for a command "
-           "line option with external storage!");
+           "line option with external storage, "
+           "or cl::init specified before cl::location()!!");
   }
 public:
   opt_storage() : Location(0) {}
@@ -667,11 +719,15 @@ template <class DataType, bool ExternalStorage = false,
           class ParserClass = parser<DataType> >
 class opt : public Option, 
             public opt_storage<DataType, ExternalStorage,
-                               ::boost::is_class<DataType>::value>{
+                               ::boost::is_class<DataType>::value> {
   ParserClass Parser;
 
-  virtual bool handleOccurance(const char *ArgName, const std::string &Arg) {
-    return Parser.parse(*this, ArgName, Arg);
+  virtual bool handleOccurrence(const char *ArgName, const std::string &Arg) {
+    typename ParserClass::parser_data_type Val;
+    if (Parser.parse(*this, ArgName, Arg, Val))
+      return true;                            // Parse error!
+    setValue(Val);
+    return false;
   }
 
   virtual enum ValueExpected getValueExpectedFlagDefault() const {
@@ -690,17 +746,17 @@ class opt : public Option,
   }
 public:
   // setInitialValue - Used by the cl::init modifier...
-  void setInitialValue(const DataType &V) { setValue(V); }
+  void setInitialValue(const DataType &V) { this->setValue(V); }
 
-  // addValue - Used by the parser to add a value to the option
-  template<class T>
-  void addValue(const T &V) { setValue(V); }
   ParserClass &getParser() { return Parser; }
 
-  operator DataType() const { return getValue(); }
+  operator DataType() const { return this->getValue(); }
 
   template<class T>
-  DataType &operator=(const T &Val) { setValue(Val); return getValue(); }
+  DataType &operator=(const T &Val) {
+    this->setValue(Val);
+    return this->getValue();
+  }
 
   // One option...
   template<class M0t>
@@ -815,15 +871,19 @@ template <class DataType, class Storage = bool,
 class list : public Option, public list_storage<DataType, Storage> {
   ParserClass Parser;
 
-  virtual enum NumOccurances getNumOccurancesFlagDefault() const { 
+  virtual enum NumOccurrences getNumOccurrencesFlagDefault() const { 
     return ZeroOrMore;
   }
   virtual enum ValueExpected getValueExpectedFlagDefault() const {
     return Parser.getValueExpectedFlagDefault();
   }
 
-  virtual bool handleOccurance(const char *ArgName, const std::string &Arg) {
-    return Parser.parse(*this, ArgName, Arg);
+  virtual bool handleOccurrence(const char *ArgName, const std::string &Arg) {
+    typename ParserClass::parser_data_type Val;
+    if (Parser.parse(*this, ArgName, Arg, Val))
+      return true;  // Parse Error!
+    addValue(Val);
+    return false;
   }
 
   // Forward printing stuff to the parser...
@@ -908,8 +968,8 @@ public:
 
 class alias : public Option {
   Option *AliasFor;
-  virtual bool handleOccurance(const char *ArgName, const std::string &Arg) {
-    return AliasFor->handleOccurance(AliasFor->ArgStr, Arg);
+  virtual bool handleOccurrence(const char *ArgName, const std::string &Arg) {
+    return AliasFor->handleOccurrence(AliasFor->ArgStr, Arg);
   }
   // Aliases default to be hidden...
   virtual enum OptionHidden getOptionHiddenFlagDefault() const {return Hidden;}
@@ -968,4 +1028,6 @@ struct aliasopt {
 
 } // End namespace cl
 
+} // End namespace llvm
+
 #endif