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