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