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