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