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