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