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