Be a bit more efficient when processing the active and inactive
[oota-llvm.git] / include / llvm / Support / CommandLine.h
1 //===- Support/CommandLine.h - Flexible Command line parser -----*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This class implements a command line argument processor that is useful when
11 // creating a tool.  It provides a simple, minimalistic interface that is easily
12 // extensible and supports nonlocal (library) command line options.
13 //
14 // Note that rather than trying to figure out what this code does, you should
15 // read the library documentation located in docs/CommandLine.html or looks at
16 // the many example usages in tools/*/*.cpp
17 //
18 //===----------------------------------------------------------------------===//
19
20 #ifndef SUPPORT_COMMANDLINE_H
21 #define SUPPORT_COMMANDLINE_H
22
23 #include "Support/type_traits.h"
24 #include <string>
25 #include <vector>
26 #include <utility>
27 #include <cstdarg>
28 #include <cassert>
29
30 namespace llvm {
31
32 /// cl Namespace - This namespace contains all of the command line option
33 /// processing machinery.  It is intentionally a short name to make qualified
34 /// usage concise.
35 namespace cl {
36
37 //===----------------------------------------------------------------------===//
38 // ParseCommandLineOptions - Command line option processing entry point.
39 //
40 void ParseCommandLineOptions(int &argc, char **argv,
41                              const char *Overview = 0);
42
43 //===----------------------------------------------------------------------===//
44 // ParseEnvironmentOptions - Environment variable option processing alternate
45 //                           entry point.
46 //
47 void ParseEnvironmentOptions(const char *progName, const char *envvar,
48                              const char *Overview = 0);
49
50 //===----------------------------------------------------------------------===//
51 // Flags permitted to be passed to command line arguments
52 //
53
54 enum NumOccurrences {          // Flags for the number of occurrences allowed
55   Optional        = 0x01,      // Zero or One occurrence
56   ZeroOrMore      = 0x02,      // Zero or more occurrences allowed
57   Required        = 0x03,      // One occurrence required
58   OneOrMore       = 0x04,      // One or more occurrences required
59
60   // ConsumeAfter - Indicates that this option is fed anything that follows the
61   // last positional argument required by the application (it is an error if
62   // there are zero positional arguments, and a ConsumeAfter option is used).
63   // Thus, for example, all arguments to LLI are processed until a filename is
64   // found.  Once a filename is found, all of the succeeding arguments are
65   // passed, unprocessed, to the ConsumeAfter option.
66   //
67   ConsumeAfter    = 0x05,
68
69   OccurrencesMask  = 0x07,
70 };
71
72 enum ValueExpected {           // Is a value required for the option?
73   ValueOptional   = 0x08,      // The value can appear... or not
74   ValueRequired   = 0x10,      // The value is required to appear!
75   ValueDisallowed = 0x18,      // A value may not be specified (for flags)
76   ValueMask       = 0x18,
77 };
78
79 enum OptionHidden {            // Control whether -help shows this option
80   NotHidden       = 0x20,      // Option included in --help & --help-hidden
81   Hidden          = 0x40,      // -help doesn't, but --help-hidden does
82   ReallyHidden    = 0x60,      // Neither --help nor --help-hidden show this arg
83   HiddenMask      = 0x60,
84 };
85
86 // Formatting flags - This controls special features that the option might have
87 // that cause it to be parsed differently...
88 //
89 // Prefix - This option allows arguments that are otherwise unrecognized to be
90 // matched by options that are a prefix of the actual value.  This is useful for
91 // cases like a linker, where options are typically of the form '-lfoo' or
92 // '-L../../include' where -l or -L are the actual flags.  When prefix is
93 // enabled, and used, the value for the flag comes from the suffix of the
94 // argument.
95 //
96 // Grouping - With this option enabled, multiple letter options are allowed to
97 // bunch together with only a single hyphen for the whole group.  This allows
98 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
99 //
100
101 enum FormattingFlags {
102   NormalFormatting = 0x000,     // Nothing special
103   Positional       = 0x080,     // Is a positional argument, no '-' required
104   Prefix           = 0x100,     // Can this option directly prefix its value?
105   Grouping         = 0x180,     // Can this option group with other options?
106   FormattingMask   = 0x180,     // Union of the above flags.
107 };
108
109 enum MiscFlags {               // Miscellaneous flags to adjust argument
110   CommaSeparated     = 0x200,  // Should this cl::list split between commas?
111   PositionalEatsArgs = 0x400,  // Should this positional cl::list eat -args?
112   MiscMask           = 0x600,  // Union of the above flags.
113 };
114
115
116
117 //===----------------------------------------------------------------------===//
118 // Option Base class
119 //
120 class alias;
121 class Option {
122   friend void cl::ParseCommandLineOptions(int &, char **, const char *);
123   friend class alias;
124
125   // handleOccurrences - Overriden by subclasses to handle the value passed into
126   // an argument.  Should return true if there was an error processing the
127   // argument and the program should exit.
128   //
129   virtual bool handleOccurrence(unsigned pos, const char *ArgName, 
130                                 const std::string &Arg) = 0;
131
132   virtual enum NumOccurrences getNumOccurrencesFlagDefault() const { 
133     return Optional;
134   }
135   virtual enum ValueExpected getValueExpectedFlagDefault() const {
136     return ValueOptional; 
137   }
138   virtual enum OptionHidden getOptionHiddenFlagDefault() const {
139     return NotHidden;
140   }
141   virtual enum FormattingFlags getFormattingFlagDefault() const {
142     return NormalFormatting;
143   }
144
145   int NumOccurrences;   // The number of times specified
146   int Flags;            // Flags for the argument
147   unsigned Position;    // Position of last occurrence of the option
148 public:
149   const char *ArgStr;   // The argument string itself (ex: "help", "o")
150   const char *HelpStr;  // The descriptive text message for --help
151   const char *ValueStr; // String describing what the value of this option is
152
153   inline enum NumOccurrences getNumOccurrencesFlag() const {
154     int NO = Flags & OccurrencesMask;
155     return NO ? static_cast<enum NumOccurrences>(NO)
156               : getNumOccurrencesFlagDefault();
157   }
158   inline enum ValueExpected getValueExpectedFlag() const {
159     int VE = Flags & ValueMask;
160     return VE ? static_cast<enum ValueExpected>(VE)
161               : getValueExpectedFlagDefault();
162   }
163   inline enum OptionHidden getOptionHiddenFlag() const {
164     int OH = Flags & HiddenMask;
165     return OH ? static_cast<enum OptionHidden>(OH)
166               : getOptionHiddenFlagDefault();
167   }
168   inline enum FormattingFlags getFormattingFlag() const {
169     int OH = Flags & FormattingMask;
170     return OH ? static_cast<enum FormattingFlags>(OH)
171               : getFormattingFlagDefault();
172   }
173   inline unsigned getMiscFlags() const {
174     return Flags & MiscMask;
175   }
176   inline unsigned getPosition() const { return Position; }
177
178   // hasArgStr - Return true if the argstr != ""
179   bool hasArgStr() const { return ArgStr[0] != 0; }
180
181   //-------------------------------------------------------------------------===
182   // Accessor functions set by OptionModifiers
183   //
184   void setArgStr(const char *S) { ArgStr = S; }
185   void setDescription(const char *S) { HelpStr = S; }
186   void setValueStr(const char *S) { ValueStr = S; }
187
188   void setFlag(unsigned Flag, unsigned FlagMask) {
189     if (Flags & FlagMask) {
190       error(": Specified two settings for the same option!");
191       exit(1);
192     }
193
194     Flags |= Flag;
195   }
196
197   void setNumOccurrencesFlag(enum NumOccurrences Val) {
198     setFlag(Val, OccurrencesMask);
199   }
200   void setValueExpectedFlag(enum ValueExpected Val) { setFlag(Val, ValueMask); }
201   void setHiddenFlag(enum OptionHidden Val) { setFlag(Val, HiddenMask); }
202   void setFormattingFlag(enum FormattingFlags V) { setFlag(V, FormattingMask); }
203   void setMiscFlag(enum MiscFlags M) { setFlag(M, M); }
204   void setPosition(unsigned pos) { Position = pos; }
205 protected:
206   Option() : NumOccurrences(0), Flags(0), Position(0),
207              ArgStr(""), HelpStr(""), ValueStr("") {}
208
209 public:
210   // addArgument - Tell the system that this Option subclass will handle all
211   // occurrences of -ArgStr on the command line.
212   //
213   void addArgument(const char *ArgStr);
214   void removeArgument(const char *ArgStr);
215
216   // Return the width of the option tag for printing...
217   virtual unsigned getOptionWidth() const = 0;
218
219   // printOptionInfo - Print out information about this option.  The 
220   // to-be-maintained width is specified.
221   //
222   virtual void printOptionInfo(unsigned GlobalWidth) const = 0;
223
224   // addOccurrence - Wrapper around handleOccurrence that enforces Flags
225   //
226   bool addOccurrence(unsigned pos, const char *ArgName, 
227                      const std::string &Value);
228
229   // Prints option name followed by message.  Always returns true.
230   bool error(std::string Message, const char *ArgName = 0);
231
232 public:
233   inline int getNumOccurrences() const { return NumOccurrences; }
234   virtual ~Option() {}
235 };
236
237
238 //===----------------------------------------------------------------------===//
239 // Command line option modifiers that can be used to modify the behavior of
240 // command line option parsers...
241 //
242
243 // desc - Modifier to set the description shown in the --help output...
244 struct desc {
245   const char *Desc;
246   desc(const char *Str) : Desc(Str) {}
247   void apply(Option &O) const { O.setDescription(Desc); }
248 };
249
250 // value_desc - Modifier to set the value description shown in the --help
251 // output...
252 struct value_desc {
253   const char *Desc;
254   value_desc(const char *Str) : Desc(Str) {}
255   void apply(Option &O) const { O.setValueStr(Desc); }
256 };
257
258 // init - Specify a default (initial) value for the command line argument, if
259 // the default constructor for the argument type does not give you what you
260 // want.  This is only valid on "opt" arguments, not on "list" arguments.
261 //
262 template<class Ty>
263 struct initializer {
264   const Ty &Init;
265   initializer(const Ty &Val) : Init(Val) {}
266
267   template<class Opt>
268   void apply(Opt &O) const { O.setInitialValue(Init); }
269 };
270
271 template<class Ty>
272 initializer<Ty> init(const Ty &Val) {
273   return initializer<Ty>(Val);
274 }
275
276
277 // location - Allow the user to specify which external variable they want to
278 // store the results of the command line argument processing into, if they don't
279 // want to store it in the option itself.
280 //
281 template<class Ty>
282 struct LocationClass {
283   Ty &Loc;
284   LocationClass(Ty &L) : Loc(L) {}
285
286   template<class Opt>
287   void apply(Opt &O) const { O.setLocation(O, Loc); }
288 };
289
290 template<class Ty>
291 LocationClass<Ty> location(Ty &L) { return LocationClass<Ty>(L); }
292
293
294 //===----------------------------------------------------------------------===//
295 // Enum valued command line option
296 //
297 #define clEnumVal(ENUMVAL, DESC) #ENUMVAL, (int)ENUMVAL, DESC
298 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, (int)ENUMVAL, DESC
299 #define clEnumValEnd ((void*)0)
300
301 // values - For custom data types, allow specifying a group of values together
302 // as the values that go into the mapping that the option handler uses.  Note
303 // that the values list must always have a 0 at the end of the list to indicate
304 // that the list has ended.
305 //
306 template<class DataType>
307 class ValuesClass {
308   // Use a vector instead of a map, because the lists should be short,
309   // the overhead is less, and most importantly, it keeps them in the order
310   // inserted so we can print our option out nicely.
311   std::vector<std::pair<const char *, std::pair<int, const char *> > > Values;
312   void processValues(va_list Vals);
313 public:
314   ValuesClass(const char *EnumName, DataType Val, const char *Desc, 
315               va_list ValueArgs) {
316     // Insert the first value, which is required.
317     Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
318
319     // Process the varargs portion of the values...
320     while (const char *EnumName = va_arg(ValueArgs, const char *)) {
321       DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
322       const char *EnumDesc = va_arg(ValueArgs, const char *);
323       Values.push_back(std::make_pair(EnumName,      // Add value to value map
324                                       std::make_pair(EnumVal, EnumDesc)));
325     }
326   }
327
328   template<class Opt>
329   void apply(Opt &O) const {
330     for (unsigned i = 0, e = Values.size(); i != e; ++i)
331       O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
332                                      Values[i].second.second);
333   }
334 };
335
336 template<class DataType>
337 ValuesClass<DataType> values(const char *Arg, DataType Val, const char *Desc,
338                              ...) {
339     va_list ValueArgs;
340     va_start(ValueArgs, Desc);
341     ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
342     va_end(ValueArgs);
343     return Vals;
344 }
345
346
347 //===----------------------------------------------------------------------===//
348 // parser class - Parameterizable parser for different data types.  By default,
349 // known data types (string, int, bool) have specialized parsers, that do what
350 // you would expect.  The default parser, used for data types that are not
351 // built-in, uses a mapping table to map specific options to values, which is
352 // used, among other things, to handle enum types.
353
354 //--------------------------------------------------
355 // generic_parser_base - This class holds all the non-generic code that we do
356 // not need replicated for every instance of the generic parser.  This also
357 // allows us to put stuff into CommandLine.cpp
358 //
359 struct generic_parser_base {
360   virtual ~generic_parser_base() {}  // Base class should have virtual-dtor
361
362   // getNumOptions - Virtual function implemented by generic subclass to
363   // indicate how many entries are in Values.
364   //
365   virtual unsigned getNumOptions() const = 0;
366
367   // getOption - Return option name N.
368   virtual const char *getOption(unsigned N) const = 0;
369   
370   // getDescription - Return description N
371   virtual const char *getDescription(unsigned N) const = 0;
372
373   // Return the width of the option tag for printing...
374   virtual unsigned getOptionWidth(const Option &O) const;
375
376   // printOptionInfo - Print out information about this option.  The 
377   // to-be-maintained width is specified.
378   //
379   virtual void printOptionInfo(const Option &O, unsigned GlobalWidth) const;
380
381   void initialize(Option &O) {
382     // All of the modifiers for the option have been processed by now, so the
383     // argstr field should be stable, copy it down now.
384     //
385     hasArgStr = O.hasArgStr();
386
387     // If there has been no argstr specified, that means that we need to add an
388     // argument for every possible option.  This ensures that our options are
389     // vectored to us.
390     //
391     if (!hasArgStr)
392       for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
393         O.addArgument(getOption(i));
394   }
395
396   enum ValueExpected getValueExpectedFlagDefault() const {
397     // If there is an ArgStr specified, then we are of the form:
398     //
399     //    -opt=O2   or   -opt O2  or  -optO2
400     //
401     // In which case, the value is required.  Otherwise if an arg str has not
402     // been specified, we are of the form:
403     //
404     //    -O2 or O2 or -la (where -l and -a are separate options)
405     //
406     // If this is the case, we cannot allow a value.
407     //
408     if (hasArgStr)
409       return ValueRequired;
410     else
411       return ValueDisallowed;
412   }
413
414   // findOption - Return the option number corresponding to the specified
415   // argument string.  If the option is not found, getNumOptions() is returned.
416   //
417   unsigned findOption(const char *Name);
418
419 protected:
420   bool hasArgStr;
421 };
422
423 // Default parser implementation - This implementation depends on having a
424 // mapping of recognized options to values of some sort.  In addition to this,
425 // each entry in the mapping also tracks a help message that is printed with the
426 // command line option for --help.  Because this is a simple mapping parser, the
427 // data type can be any unsupported type.
428 //
429 template <class DataType>
430 class parser : public generic_parser_base {
431 protected:
432   std::vector<std::pair<const char *,
433                         std::pair<DataType, const char *> > > Values;
434 public:
435   typedef DataType parser_data_type;
436
437   // Implement virtual functions needed by generic_parser_base
438   unsigned getNumOptions() const { return Values.size(); }
439   const char *getOption(unsigned N) const { return Values[N].first; }
440   const char *getDescription(unsigned N) const {
441     return Values[N].second.second;
442   }
443
444   // parse - Return true on error.
445   bool parse(Option &O, const char *ArgName, const std::string &Arg, 
446              DataType &V) {
447     std::string ArgVal;
448     if (hasArgStr)
449       ArgVal = Arg;
450     else
451       ArgVal = ArgName;
452
453     for (unsigned i = 0, e = Values.size(); i != e; ++i)
454       if (ArgVal == Values[i].first) {
455         V = Values[i].second.first;
456         return false;
457       }
458
459     return O.error(": Cannot find option named '" + ArgVal + "'!");
460   }
461
462   // addLiteralOption - Add an entry to the mapping table...
463   template <class DT>
464   void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
465     assert(findOption(Name) == Values.size() && "Option already exists!");
466     Values.push_back(std::make_pair(Name,
467                              std::make_pair(static_cast<DataType>(V),HelpStr)));
468   }
469
470   // removeLiteralOption - Remove the specified option.
471   //
472   void removeLiteralOption(const char *Name) {
473     unsigned N = findOption(Name);
474     assert(N != Values.size() && "Option not found!");
475     Values.erase(Values.begin()+N);
476   }
477 };
478
479 //--------------------------------------------------
480 // basic_parser - Super class of parsers to provide boilerplate code
481 //
482 struct basic_parser_impl {  // non-template implementation of basic_parser<t>
483   virtual ~basic_parser_impl() {}
484
485   enum ValueExpected getValueExpectedFlagDefault() const {
486     return ValueRequired;
487   }
488   
489   void initialize(Option &O) {}
490   
491   // Return the width of the option tag for printing...
492   unsigned getOptionWidth(const Option &O) const;
493   
494   // printOptionInfo - Print out information about this option.  The
495   // to-be-maintained width is specified.
496   //
497   void printOptionInfo(const Option &O, unsigned GlobalWidth) const;
498
499   // getValueName - Overload in subclass to provide a better default value.
500   virtual const char *getValueName() const { return "value"; }
501 };
502
503 // basic_parser - The real basic parser is just a template wrapper that provides
504 // a typedef for the provided data type.
505 //
506 template<class DataType>
507 struct basic_parser : public basic_parser_impl {
508   typedef DataType parser_data_type;
509 };
510
511
512 //--------------------------------------------------
513 // parser<bool>
514 //
515 template<>
516 struct parser<bool> : public basic_parser<bool> {
517
518   // parse - Return true on error.
519   bool parse(Option &O, const char *ArgName, const std::string &Arg, bool &Val);
520
521   enum ValueExpected getValueExpectedFlagDefault() const {
522     return ValueOptional; 
523   }
524
525   // getValueName - Do not print =<value> at all
526   virtual const char *getValueName() const { return 0; }
527 };
528
529
530 //--------------------------------------------------
531 // parser<int>
532 //
533 template<>
534 struct parser<int> : public basic_parser<int> {
535   
536   // parse - Return true on error.
537   bool parse(Option &O, const char *ArgName, const std::string &Arg, int &Val);
538
539   // getValueName - Overload in subclass to provide a better default value.
540   virtual const char *getValueName() const { return "int"; }
541 };
542
543
544 //--------------------------------------------------
545 // parser<unsigned>
546 //
547 template<>
548 struct parser<unsigned> : public basic_parser<unsigned> {
549   
550   // parse - Return true on error.
551   bool parse(Option &O, const char *AN, const std::string &Arg, unsigned &Val);
552
553   // getValueName - Overload in subclass to provide a better default value.
554   virtual const char *getValueName() const { return "uint"; }
555 };
556
557
558 //--------------------------------------------------
559 // parser<double>
560 //
561 template<>
562 struct parser<double> : public basic_parser<double> {
563   // parse - Return true on error.
564   bool parse(Option &O, const char *AN, const std::string &Arg, double &Val);
565
566   // getValueName - Overload in subclass to provide a better default value.
567   virtual const char *getValueName() const { return "number"; }
568 };
569
570
571 //--------------------------------------------------
572 // parser<float>
573 //
574 template<>
575 struct parser<float> : public basic_parser<float> {
576   // parse - Return true on error.
577   bool parse(Option &O, const char *AN, const std::string &Arg, float &Val);
578
579   // getValueName - Overload in subclass to provide a better default value.
580   virtual const char *getValueName() const { return "number"; }
581 };
582
583
584 //--------------------------------------------------
585 // parser<std::string>
586 //
587 template<>
588 struct parser<std::string> : public basic_parser<std::string> {
589   // parse - Return true on error.
590   bool parse(Option &O, const char *AN, const std::string &Arg, 
591              std::string &Value) {
592     Value = Arg;
593     return false;
594   }
595
596   // getValueName - Overload in subclass to provide a better default value.
597   virtual const char *getValueName() const { return "string"; }
598 };
599
600 //===----------------------------------------------------------------------===//
601 // applicator class - This class is used because we must use partial
602 // specialization to handle literal string arguments specially (const char* does
603 // not correctly respond to the apply method).  Because the syntax to use this
604 // is a pain, we have the 'apply' method below to handle the nastiness...
605 //
606 template<class Mod> struct applicator {
607   template<class Opt>
608   static void opt(const Mod &M, Opt &O) { M.apply(O); }
609 };
610
611 // Handle const char* as a special case...
612 template<unsigned n> struct applicator<char[n]> {
613   template<class Opt>
614   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
615 };
616 template<unsigned n> struct applicator<const char[n]> {
617   template<class Opt>
618   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
619 };
620 template<> struct applicator<const char*> {
621   template<class Opt>
622   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
623 };
624
625 template<> struct applicator<NumOccurrences> {
626   static void opt(NumOccurrences NO, Option &O) { O.setNumOccurrencesFlag(NO); }
627 };
628 template<> struct applicator<ValueExpected> {
629   static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
630 };
631 template<> struct applicator<OptionHidden> {
632   static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
633 };
634 template<> struct applicator<FormattingFlags> {
635   static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
636 };
637 template<> struct applicator<MiscFlags> {
638   static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
639 };
640
641 // apply method - Apply a modifier to an option in a type safe way.
642 template<class Mod, class Opt>
643 void apply(const Mod &M, Opt *O) {
644   applicator<Mod>::opt(M, *O);
645 }
646
647
648 //===----------------------------------------------------------------------===//
649 // opt_storage class
650
651 // Default storage class definition: external storage.  This implementation
652 // assumes the user will specify a variable to store the data into with the
653 // cl::location(x) modifier.
654 //
655 template<class DataType, bool ExternalStorage, bool isClass>
656 class opt_storage {
657   DataType *Location;   // Where to store the object...
658
659   void check() {
660     assert(Location != 0 && "cl::location(...) not specified for a command "
661            "line option with external storage, "
662            "or cl::init specified before cl::location()!!");
663   }
664 public:
665   opt_storage() : Location(0) {}
666
667   bool setLocation(Option &O, DataType &L) {
668     if (Location)
669       return O.error(": cl::location(x) specified more than once!");
670     Location = &L;
671     return false;
672   }
673
674   template<class T>
675   void setValue(const T &V) {
676     check();
677     *Location = V;
678   }
679
680   DataType &getValue() { check(); return *Location; }
681   const DataType &getValue() const { check(); return *Location; }
682 };
683
684
685 // Define how to hold a class type object, such as a string.  Since we can
686 // inherit from a class, we do so.  This makes us exactly compatible with the
687 // object in all cases that it is used.
688 //
689 template<class DataType>
690 struct opt_storage<DataType,false,true> : public DataType {
691
692   template<class T>
693   void setValue(const T &V) { DataType::operator=(V); }
694
695   DataType &getValue() { return *this; }
696   const DataType &getValue() const { return *this; }
697 };
698
699 // Define a partial specialization to handle things we cannot inherit from.  In
700 // this case, we store an instance through containment, and overload operators
701 // to get at the value.
702 //
703 template<class DataType>
704 struct opt_storage<DataType, false, false> {
705   DataType Value;
706
707   // Make sure we initialize the value with the default constructor for the
708   // type.
709   opt_storage() : Value(DataType()) {}
710
711   template<class T>
712   void setValue(const T &V) { Value = V; }
713   DataType &getValue() { return Value; }
714   DataType getValue() const { return Value; }
715
716   // If the datatype is a pointer, support -> on it.
717   DataType operator->() const { return Value; }
718 };
719
720
721 //===----------------------------------------------------------------------===//
722 // opt - A scalar command line option.
723 //
724 template <class DataType, bool ExternalStorage = false,
725           class ParserClass = parser<DataType> >
726 class opt : public Option, 
727             public opt_storage<DataType, ExternalStorage,
728                                is_class<DataType>::value> {
729   ParserClass Parser;
730
731   virtual bool handleOccurrence(unsigned pos, const char *ArgName, 
732                                 const std::string &Arg) {
733     typename ParserClass::parser_data_type Val;
734     if (Parser.parse(*this, ArgName, Arg, Val))
735       return true;                            // Parse error!
736     setValue(Val);
737     setPosition(pos);
738     return false;
739   }
740
741   virtual enum ValueExpected getValueExpectedFlagDefault() const {
742     return Parser.getValueExpectedFlagDefault();
743   }
744
745   // Forward printing stuff to the parser...
746   virtual unsigned getOptionWidth() const {return Parser.getOptionWidth(*this);}
747   virtual void printOptionInfo(unsigned GlobalWidth) const {
748     Parser.printOptionInfo(*this, GlobalWidth);
749   }
750
751   void done() {
752     addArgument(ArgStr);
753     Parser.initialize(*this);
754   }
755 public:
756   // setInitialValue - Used by the cl::init modifier...
757   void setInitialValue(const DataType &V) { this->setValue(V); }
758
759   ParserClass &getParser() { return Parser; }
760
761   operator DataType() const { return this->getValue(); }
762
763   template<class T>
764   DataType &operator=(const T &Val) {
765     this->setValue(Val);
766     return this->getValue();
767   }
768
769   // One option...
770   template<class M0t>
771   opt(const M0t &M0) {
772     apply(M0, this);
773     done();
774   }
775
776   // Two options...
777   template<class M0t, class M1t>
778   opt(const M0t &M0, const M1t &M1) {
779     apply(M0, this); apply(M1, this);
780     done();
781   }
782
783   // Three options...
784   template<class M0t, class M1t, class M2t>
785   opt(const M0t &M0, const M1t &M1, const M2t &M2) {
786     apply(M0, this); apply(M1, this); apply(M2, this);
787     done();
788   }
789   // Four options...
790   template<class M0t, class M1t, class M2t, class M3t>
791   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3) {
792     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
793     done();
794   }
795   // Five options...
796   template<class M0t, class M1t, class M2t, class M3t, class M4t>
797   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
798       const M4t &M4) {
799     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
800     apply(M4, this);
801     done();
802   }
803   // Six options...
804   template<class M0t, class M1t, class M2t, class M3t,
805            class M4t, class M5t>
806   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
807       const M4t &M4, const M5t &M5) {
808     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
809     apply(M4, this); apply(M5, this);
810     done();
811   }
812   // Seven options...
813   template<class M0t, class M1t, class M2t, class M3t,
814            class M4t, class M5t, class M6t>
815   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
816       const M4t &M4, const M5t &M5, const M6t &M6) {
817     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
818     apply(M4, this); apply(M5, this); apply(M6, this);
819     done();
820   }
821   // Eight options...
822   template<class M0t, class M1t, class M2t, class M3t,
823            class M4t, class M5t, class M6t, class M7t>
824   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
825       const M4t &M4, const M5t &M5, const M6t &M6, const M7t &M7) {
826     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
827     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
828     done();
829   }
830 };
831
832 //===----------------------------------------------------------------------===//
833 // list_storage class
834
835 // Default storage class definition: external storage.  This implementation
836 // assumes the user will specify a variable to store the data into with the
837 // cl::location(x) modifier.
838 //
839 template<class DataType, class StorageClass>
840 class list_storage {
841   StorageClass *Location;   // Where to store the object...
842
843 public:
844   list_storage() : Location(0) {}
845
846   bool setLocation(Option &O, StorageClass &L) {
847     if (Location)
848       return O.error(": cl::location(x) specified more than once!");
849     Location = &L;
850     return false;
851   }
852
853   template<class T>
854   void addValue(const T &V) {
855     assert(Location != 0 && "cl::location(...) not specified for a command "
856            "line option with external storage!");
857     Location->push_back(V);
858   }
859 };
860
861
862 // Define how to hold a class type object, such as a string.  Since we can
863 // inherit from a class, we do so.  This makes us exactly compatible with the
864 // object in all cases that it is used.
865 //
866 template<class DataType>
867 struct list_storage<DataType, bool> : public std::vector<DataType> {
868
869   template<class T>
870   void addValue(const T &V) { push_back(V); }
871 };
872
873
874 //===----------------------------------------------------------------------===//
875 // list - A list of command line options.
876 //
877 template <class DataType, class Storage = bool,
878           class ParserClass = parser<DataType> >
879 class list : public Option, public list_storage<DataType, Storage> {
880   std::vector<unsigned> Positions;
881   ParserClass Parser;
882
883   virtual enum NumOccurrences getNumOccurrencesFlagDefault() const { 
884     return ZeroOrMore;
885   }
886   virtual enum ValueExpected getValueExpectedFlagDefault() const {
887     return Parser.getValueExpectedFlagDefault();
888   }
889
890   virtual bool handleOccurrence(unsigned pos, const char *ArgName, 
891                                 const std::string &Arg) {
892     typename ParserClass::parser_data_type Val;
893     if (Parser.parse(*this, ArgName, Arg, Val))
894       return true;  // Parse Error!
895     addValue(Val);
896     setPosition(pos);
897     Positions.push_back(pos);
898     return false;
899   }
900
901   // Forward printing stuff to the parser...
902   virtual unsigned getOptionWidth() const {return Parser.getOptionWidth(*this);}
903   virtual void printOptionInfo(unsigned GlobalWidth) const {
904     Parser.printOptionInfo(*this, GlobalWidth);
905   }
906
907   void done() {
908     addArgument(ArgStr);
909     Parser.initialize(*this);
910   }
911 public:
912   ParserClass &getParser() { return Parser; }
913
914   unsigned getPosition(unsigned optnum) { 
915     assert(optnum < this->size() && "Invalid option index");
916     return Positions[optnum]; 
917   }
918
919   // One option...
920   template<class M0t>
921   list(const M0t &M0) {
922     apply(M0, this);
923     done();
924   }
925   // Two options...
926   template<class M0t, class M1t>
927   list(const M0t &M0, const M1t &M1) {
928     apply(M0, this); apply(M1, this);
929     done();
930   }
931   // Three options...
932   template<class M0t, class M1t, class M2t>
933   list(const M0t &M0, const M1t &M1, const M2t &M2) {
934     apply(M0, this); apply(M1, this); apply(M2, this);
935     done();
936   }
937   // Four options...
938   template<class M0t, class M1t, class M2t, class M3t>
939   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3) {
940     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
941     done();
942   }
943   // Five options...
944   template<class M0t, class M1t, class M2t, class M3t, class M4t>
945   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
946        const M4t &M4) {
947     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
948     apply(M4, this);
949     done();
950   }
951   // Six options...
952   template<class M0t, class M1t, class M2t, class M3t,
953            class M4t, class M5t>
954   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
955        const M4t &M4, const M5t &M5) {
956     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
957     apply(M4, this); apply(M5, this);
958     done();
959   }
960   // Seven options...
961   template<class M0t, class M1t, class M2t, class M3t,
962            class M4t, class M5t, class M6t>
963   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
964       const M4t &M4, const M5t &M5, const M6t &M6) {
965     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
966     apply(M4, this); apply(M5, this); apply(M6, this);
967     done();
968   }
969   // Eight options...
970   template<class M0t, class M1t, class M2t, class M3t,
971            class M4t, class M5t, class M6t, class M7t>
972   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
973       const M4t &M4, const M5t &M5, const M6t &M6, const M7t &M7) {
974     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
975     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
976     done();
977   }
978 };
979
980 //===----------------------------------------------------------------------===//
981 // Aliased command line option (alias this name to a preexisting name)
982 //
983
984 class alias : public Option {
985   Option *AliasFor;
986   virtual bool handleOccurrence(unsigned pos, const char *ArgName, 
987                                 const std::string &Arg) {
988     return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
989   }
990   // Aliases default to be hidden...
991   virtual enum OptionHidden getOptionHiddenFlagDefault() const {return Hidden;}
992
993   // Handle printing stuff...
994   virtual unsigned getOptionWidth() const;
995   virtual void printOptionInfo(unsigned GlobalWidth) const;
996
997   void done() {
998     if (!hasArgStr())
999       error(": cl::alias must have argument name specified!");
1000     if (AliasFor == 0)
1001       error(": cl::alias must have an cl::aliasopt(option) specified!");
1002     addArgument(ArgStr);
1003   }
1004 public:
1005   void setAliasFor(Option &O) {
1006     if (AliasFor)
1007       error(": cl::alias must only have one cl::aliasopt(...) specified!");
1008     AliasFor = &O;
1009   }
1010
1011   // One option...
1012   template<class M0t>
1013   alias(const M0t &M0) : AliasFor(0) {
1014     apply(M0, this);
1015     done();
1016   }
1017   // Two options...
1018   template<class M0t, class M1t>
1019   alias(const M0t &M0, const M1t &M1) : AliasFor(0) {
1020     apply(M0, this); apply(M1, this);
1021     done();
1022   }
1023   // Three options...
1024   template<class M0t, class M1t, class M2t>
1025   alias(const M0t &M0, const M1t &M1, const M2t &M2) : AliasFor(0) {
1026     apply(M0, this); apply(M1, this); apply(M2, this);
1027     done();
1028   }
1029   // Four options...
1030   template<class M0t, class M1t, class M2t, class M3t>
1031   alias(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1032     : AliasFor(0) {
1033     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1034     done();
1035   }
1036 };
1037
1038 // aliasfor - Modifier to set the option an alias aliases.
1039 struct aliasopt {
1040   Option &Opt;
1041   aliasopt(Option &O) : Opt(O) {}
1042   void apply(alias &A) const { A.setAliasFor(Opt); }
1043 };
1044
1045 } // End namespace cl
1046
1047 } // End namespace llvm
1048
1049 #endif