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