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