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