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