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/ADT/SmallVector.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Support/Compiler.h"
27 #include <cassert>
28 #include <climits>
29 #include <cstdarg>
30 #include <utility>
31 #include <vector>
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, const char * const *argv,
44 const char *Overview = nullptr);
45
46 //===----------------------------------------------------------------------===//
47 // ParseEnvironmentOptions - Environment variable option processing alternate
48 // entry point.
49 //
50 void ParseEnvironmentOptions(const char *progName, const char *envvar,
51 const char *Overview = nullptr);
52
53 ///===---------------------------------------------------------------------===//
54 /// SetVersionPrinter - Override the default (LLVM specific) version printer
55 /// used to print out the version when --version is given
56 /// on the command line. This allows other systems using the
57 /// CommandLine utilities to print their own version string.
58 void SetVersionPrinter(void (*func)());
59
60 ///===---------------------------------------------------------------------===//
61 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
62 /// default one. This can be called multiple times,
63 /// and each time it adds a new function to the list
64 /// which will be called after the basic LLVM version
65 /// printing is complete. Each can then add additional
66 /// information specific to the tool.
67 void AddExtraVersionPrinter(void (*func)());
68
69
70 // PrintOptionValues - Print option values.
71 // With -print-options print the difference between option values and defaults.
72 // With -print-all-options print all option values.
73 // (Currently not perfect, but best-effort.)
74 void PrintOptionValues();
75
76 // MarkOptionsChanged - Internal helper function.
77 void MarkOptionsChanged();
78
79 //===----------------------------------------------------------------------===//
80 // Flags permitted to be passed to command line arguments
81 //
82
83 enum NumOccurrencesFlag { // Flags for the number of occurrences allowed
84 Optional = 0x00, // Zero or One occurrence
85 ZeroOrMore = 0x01, // Zero or more occurrences allowed
86 Required = 0x02, // One occurrence required
87 OneOrMore = 0x03, // One or more occurrences required
88
89 // ConsumeAfter - Indicates that this option is fed anything that follows the
90 // last positional argument required by the application (it is an error if
91 // there are zero positional arguments, and a ConsumeAfter option is used).
92 // Thus, for example, all arguments to LLI are processed until a filename is
93 // found. Once a filename is found, all of the succeeding arguments are
94 // passed, unprocessed, to the ConsumeAfter option.
95 //
96 ConsumeAfter = 0x04
97 };
98
99 enum ValueExpected { // Is a value required for the option?
100 // zero reserved for the unspecified value
101 ValueOptional = 0x01, // The value can appear... or not
102 ValueRequired = 0x02, // The value is required to appear!
103 ValueDisallowed = 0x03 // A value may not be specified (for flags)
104 };
105
106 enum OptionHidden { // Control whether -help shows this option
107 NotHidden = 0x00, // Option included in -help & -help-hidden
108 Hidden = 0x01, // -help doesn't, but -help-hidden does
109 ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg
110 };
111
112 // Formatting flags - This controls special features that the option might have
113 // that cause it to be parsed differently...
114 //
115 // Prefix - This option allows arguments that are otherwise unrecognized to be
116 // matched by options that are a prefix of the actual value. This is useful for
117 // cases like a linker, where options are typically of the form '-lfoo' or
118 // '-L../../include' where -l or -L are the actual flags. When prefix is
119 // enabled, and used, the value for the flag comes from the suffix of the
120 // argument.
121 //
122 // Grouping - With this option enabled, multiple letter options are allowed to
123 // bunch together with only a single hyphen for the whole group. This allows
124 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
125 //
126
127 enum FormattingFlags {
128 NormalFormatting = 0x00, // Nothing special
129 Positional = 0x01, // Is a positional argument, no '-' required
130 Prefix = 0x02, // Can this option directly prefix its value?
131 Grouping = 0x03 // Can this option group with other options?
132 };
133
134 enum MiscFlags { // Miscellaneous flags to adjust argument
135 CommaSeparated = 0x01, // Should this cl::list split between commas?
136 PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args?
137 Sink = 0x04 // Should this cl::list eat all unknown options?
138 };
139
140 //===----------------------------------------------------------------------===//
141 // Option Category class
142 //
143 class OptionCategory {
144 private:
145 const char *const Name;
146 const char *const Description;
147 void registerCategory();
148 public:
149 OptionCategory(const char *const Name, const char *const Description = nullptr)
Name(Name)150 : Name(Name), Description(Description) { registerCategory(); }
getName()151 const char *getName() const { return Name; }
getDescription()152 const char *getDescription() const { return Description; }
153 };
154
155 // The general Option Category (used as default category).
156 extern OptionCategory GeneralCategory;
157
158 //===----------------------------------------------------------------------===//
159 // Option Base class
160 //
161 class alias;
162 class Option {
163 friend class alias;
164
165 // handleOccurrences - Overriden by subclasses to handle the value passed into
166 // an argument. Should return true if there was an error processing the
167 // argument and the program should exit.
168 //
169 virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
170 StringRef Arg) = 0;
171
getValueExpectedFlagDefault()172 virtual enum ValueExpected getValueExpectedFlagDefault() const {
173 return ValueOptional;
174 }
175
176 // Out of line virtual function to provide home for the class.
177 virtual void anchor();
178
179 int NumOccurrences; // The number of times specified
180 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
181 // problems with signed enums in bitfields.
182 unsigned Occurrences : 3; // enum NumOccurrencesFlag
183 // not using the enum type for 'Value' because zero is an implementation
184 // detail representing the non-value
185 unsigned Value : 2;
186 unsigned HiddenFlag : 2; // enum OptionHidden
187 unsigned Formatting : 2; // enum FormattingFlags
188 unsigned Misc : 3;
189 unsigned Position; // Position of last occurrence of the option
190 unsigned AdditionalVals;// Greater than 0 for multi-valued option.
191 Option *NextRegistered; // Singly linked list of registered options.
192
193 public:
194 const char *ArgStr; // The argument string itself (ex: "help", "o")
195 const char *HelpStr; // The descriptive text message for -help
196 const char *ValueStr; // String describing what the value of this option is
197 OptionCategory *Category; // The Category this option belongs to
198
getNumOccurrencesFlag()199 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
200 return (enum NumOccurrencesFlag)Occurrences;
201 }
getValueExpectedFlag()202 inline enum ValueExpected getValueExpectedFlag() const {
203 return Value ? ((enum ValueExpected)Value)
204 : getValueExpectedFlagDefault();
205 }
getOptionHiddenFlag()206 inline enum OptionHidden getOptionHiddenFlag() const {
207 return (enum OptionHidden)HiddenFlag;
208 }
getFormattingFlag()209 inline enum FormattingFlags getFormattingFlag() const {
210 return (enum FormattingFlags)Formatting;
211 }
getMiscFlags()212 inline unsigned getMiscFlags() const {
213 return Misc;
214 }
getPosition()215 inline unsigned getPosition() const { return Position; }
getNumAdditionalVals()216 inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
217
218 // hasArgStr - Return true if the argstr != ""
hasArgStr()219 bool hasArgStr() const { return ArgStr[0] != 0; }
220
221 //-------------------------------------------------------------------------===
222 // Accessor functions set by OptionModifiers
223 //
setArgStr(const char * S)224 void setArgStr(const char *S) { ArgStr = S; }
setDescription(const char * S)225 void setDescription(const char *S) { HelpStr = S; }
setValueStr(const char * S)226 void setValueStr(const char *S) { ValueStr = S; }
setNumOccurrencesFlag(enum NumOccurrencesFlag Val)227 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) {
228 Occurrences = Val;
229 }
setValueExpectedFlag(enum ValueExpected Val)230 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
setHiddenFlag(enum OptionHidden Val)231 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
setFormattingFlag(enum FormattingFlags V)232 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
setMiscFlag(enum MiscFlags M)233 void setMiscFlag(enum MiscFlags M) { Misc |= M; }
setPosition(unsigned pos)234 void setPosition(unsigned pos) { Position = pos; }
setCategory(OptionCategory & C)235 void setCategory(OptionCategory &C) { Category = &C; }
236 protected:
Option(enum NumOccurrencesFlag OccurrencesFlag,enum OptionHidden Hidden)237 explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
238 enum OptionHidden Hidden)
239 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
240 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0),
241 Position(0), AdditionalVals(0), NextRegistered(nullptr),
242 ArgStr(""), HelpStr(""), ValueStr(""), Category(&GeneralCategory) {
243 }
244
setNumAdditionalVals(unsigned n)245 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
246 public:
247 // addArgument - Register this argument with the commandline system.
248 //
249 void addArgument();
250
251 /// Unregisters this option from the CommandLine system.
252 ///
253 /// This option must have been the last option registered.
254 /// For testing purposes only.
255 void removeArgument();
256
getNextRegisteredOption()257 Option *getNextRegisteredOption() const { return NextRegistered; }
258
259 // Return the width of the option tag for printing...
260 virtual size_t getOptionWidth() const = 0;
261
262 // printOptionInfo - Print out information about this option. The
263 // to-be-maintained width is specified.
264 //
265 virtual void printOptionInfo(size_t GlobalWidth) const = 0;
266
267 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
268
getExtraOptionNames(SmallVectorImpl<const char * > &)269 virtual void getExtraOptionNames(SmallVectorImpl<const char*> &) {}
270
271 // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
272 //
273 bool addOccurrence(unsigned pos, StringRef ArgName,
274 StringRef Value, bool MultiArg = false);
275
276 // Prints option name followed by message. Always returns true.
277 bool error(const Twine &Message, StringRef ArgName = StringRef());
278
279 public:
getNumOccurrences()280 inline int getNumOccurrences() const { return NumOccurrences; }
~Option()281 virtual ~Option() {}
282 };
283
284
285 //===----------------------------------------------------------------------===//
286 // Command line option modifiers that can be used to modify the behavior of
287 // command line option parsers...
288 //
289
290 // desc - Modifier to set the description shown in the -help output...
291 struct desc {
292 const char *Desc;
descdesc293 desc(const char *Str) : Desc(Str) {}
applydesc294 void apply(Option &O) const { O.setDescription(Desc); }
295 };
296
297 // value_desc - Modifier to set the value description shown in the -help
298 // output...
299 struct value_desc {
300 const char *Desc;
value_descvalue_desc301 value_desc(const char *Str) : Desc(Str) {}
applyvalue_desc302 void apply(Option &O) const { O.setValueStr(Desc); }
303 };
304
305 // init - Specify a default (initial) value for the command line argument, if
306 // the default constructor for the argument type does not give you what you
307 // want. This is only valid on "opt" arguments, not on "list" arguments.
308 //
309 template<class Ty>
310 struct initializer {
311 const Ty &Init;
initializerinitializer312 initializer(const Ty &Val) : Init(Val) {}
313
314 template<class Opt>
applyinitializer315 void apply(Opt &O) const { O.setInitialValue(Init); }
316 };
317
318 template<class Ty>
init(const Ty & Val)319 initializer<Ty> init(const Ty &Val) {
320 return initializer<Ty>(Val);
321 }
322
323
324 // location - Allow the user to specify which external variable they want to
325 // store the results of the command line argument processing into, if they don't
326 // want to store it in the option itself.
327 //
328 template<class Ty>
329 struct LocationClass {
330 Ty &Loc;
LocationClassLocationClass331 LocationClass(Ty &L) : Loc(L) {}
332
333 template<class Opt>
applyLocationClass334 void apply(Opt &O) const { O.setLocation(O, Loc); }
335 };
336
337 template<class Ty>
location(Ty & L)338 LocationClass<Ty> location(Ty &L) { return LocationClass<Ty>(L); }
339
340 // cat - Specifiy the Option category for the command line argument to belong
341 // to.
342 struct cat {
343 OptionCategory &Category;
catcat344 cat(OptionCategory &c) : Category(c) {}
345
346 template<class Opt>
applycat347 void apply(Opt &O) const { O.setCategory(Category); }
348 };
349
350
351 //===----------------------------------------------------------------------===//
352 // OptionValue class
353
354 // Support value comparison outside the template.
355 struct GenericOptionValue {
~GenericOptionValueGenericOptionValue356 virtual ~GenericOptionValue() {}
357 virtual bool compare(const GenericOptionValue &V) const = 0;
358
359 private:
360 virtual void anchor();
361 };
362
363 template<class DataType> struct OptionValue;
364
365 // The default value safely does nothing. Option value printing is only
366 // best-effort.
367 template<class DataType, bool isClass>
368 struct OptionValueBase : public GenericOptionValue {
369 // Temporary storage for argument passing.
370 typedef OptionValue<DataType> WrapperType;
371
hasValueOptionValueBase372 bool hasValue() const { return false; }
373
getValueOptionValueBase374 const DataType &getValue() const { llvm_unreachable("no default value"); }
375
376 // Some options may take their value from a different data type.
377 template<class DT>
setValueOptionValueBase378 void setValue(const DT& /*V*/) {}
379
compareOptionValueBase380 bool compare(const DataType &/*V*/) const { return false; }
381
compareOptionValueBase382 bool compare(const GenericOptionValue& /*V*/) const override {
383 return false;
384 }
385 };
386
387 // Simple copy of the option value.
388 template<class DataType>
389 class OptionValueCopy : public GenericOptionValue {
390 DataType Value;
391 bool Valid;
392 public:
OptionValueCopy()393 OptionValueCopy() : Valid(false) {}
394
hasValue()395 bool hasValue() const { return Valid; }
396
getValue()397 const DataType &getValue() const {
398 assert(Valid && "invalid option value");
399 return Value;
400 }
401
setValue(const DataType & V)402 void setValue(const DataType &V) { Valid = true; Value = V; }
403
compare(const DataType & V)404 bool compare(const DataType &V) const {
405 return Valid && (Value != V);
406 }
407
compare(const GenericOptionValue & V)408 bool compare(const GenericOptionValue &V) const override {
409 const OptionValueCopy<DataType> &VC =
410 static_cast< const OptionValueCopy<DataType>& >(V);
411 if (!VC.hasValue()) return false;
412 return compare(VC.getValue());
413 }
414 };
415
416 // Non-class option values.
417 template<class DataType>
418 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
419 typedef DataType WrapperType;
420 };
421
422 // Top-level option class.
423 template<class DataType>
424 struct OptionValue : OptionValueBase<DataType, std::is_class<DataType>::value> {
425 OptionValue() {}
426
427 OptionValue(const DataType& V) {
428 this->setValue(V);
429 }
430 // Some options may take their value from a different data type.
431 template<class DT>
432 OptionValue<DataType> &operator=(const DT& V) {
433 this->setValue(V);
434 return *this;
435 }
436 };
437
438 // Other safe-to-copy-by-value common option types.
439 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
440 template<>
441 struct OptionValue<cl::boolOrDefault> : OptionValueCopy<cl::boolOrDefault> {
442 typedef cl::boolOrDefault WrapperType;
443
444 OptionValue() {}
445
446 OptionValue(const cl::boolOrDefault& V) {
447 this->setValue(V);
448 }
449 OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault& V) {
450 setValue(V);
451 return *this;
452 }
453 private:
454 void anchor() override;
455 };
456
457 template<>
458 struct OptionValue<std::string> : OptionValueCopy<std::string> {
459 typedef StringRef WrapperType;
460
461 OptionValue() {}
462
463 OptionValue(const std::string& V) {
464 this->setValue(V);
465 }
466 OptionValue<std::string> &operator=(const std::string& V) {
467 setValue(V);
468 return *this;
469 }
470 private:
471 void anchor() override;
472 };
473
474 //===----------------------------------------------------------------------===//
475 // Enum valued command line option
476 //
477 #define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
478 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
479 #define clEnumValEnd (reinterpret_cast<void*>(0))
480
481 // values - For custom data types, allow specifying a group of values together
482 // as the values that go into the mapping that the option handler uses. Note
483 // that the values list must always have a 0 at the end of the list to indicate
484 // that the list has ended.
485 //
486 template<class DataType>
487 class ValuesClass {
488 // Use a vector instead of a map, because the lists should be short,
489 // the overhead is less, and most importantly, it keeps them in the order
490 // inserted so we can print our option out nicely.
491 SmallVector<std::pair<const char *, std::pair<int, const char *> >,4> Values;
492 void processValues(va_list Vals);
493 public:
494 ValuesClass(const char *EnumName, DataType Val, const char *Desc,
495 va_list ValueArgs) {
496 // Insert the first value, which is required.
497 Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
498
499 // Process the varargs portion of the values...
500 while (const char *enumName = va_arg(ValueArgs, const char *)) {
501 DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
502 const char *EnumDesc = va_arg(ValueArgs, const char *);
503 Values.push_back(std::make_pair(enumName, // Add value to value map
504 std::make_pair(EnumVal, EnumDesc)));
505 }
506 }
507
508 template<class Opt>
509 void apply(Opt &O) const {
510 for (size_t i = 0, e = Values.size(); i != e; ++i)
511 O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
512 Values[i].second.second);
513 }
514 };
515
516 template<class DataType>
517 ValuesClass<DataType> END_WITH_NULL values(const char *Arg, DataType Val,
518 const char *Desc, ...) {
519 va_list ValueArgs;
520 va_start(ValueArgs, Desc);
521 ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
522 va_end(ValueArgs);
523 return Vals;
524 }
525
526 //===----------------------------------------------------------------------===//
527 // parser class - Parameterizable parser for different data types. By default,
528 // known data types (string, int, bool) have specialized parsers, that do what
529 // you would expect. The default parser, used for data types that are not
530 // built-in, uses a mapping table to map specific options to values, which is
531 // used, among other things, to handle enum types.
532
533 //--------------------------------------------------
534 // generic_parser_base - This class holds all the non-generic code that we do
535 // not need replicated for every instance of the generic parser. This also
536 // allows us to put stuff into CommandLine.cpp
537 //
538 class generic_parser_base {
539 protected:
540 class GenericOptionInfo {
541 public:
542 GenericOptionInfo(const char *name, const char *helpStr) :
543 Name(name), HelpStr(helpStr) {}
544 const char *Name;
545 const char *HelpStr;
546 };
547 public:
548 virtual ~generic_parser_base() {} // Base class should have virtual-dtor
549
550 // getNumOptions - Virtual function implemented by generic subclass to
551 // indicate how many entries are in Values.
552 //
553 virtual unsigned getNumOptions() const = 0;
554
555 // getOption - Return option name N.
556 virtual const char *getOption(unsigned N) const = 0;
557
558 // getDescription - Return description N
559 virtual const char *getDescription(unsigned N) const = 0;
560
561 // Return the width of the option tag for printing...
562 virtual size_t getOptionWidth(const Option &O) const;
563
564 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
565
566 // printOptionInfo - Print out information about this option. The
567 // to-be-maintained width is specified.
568 //
569 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
570
571 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
572 const GenericOptionValue &Default,
573 size_t GlobalWidth) const;
574
575 // printOptionDiff - print the value of an option and it's default.
576 //
577 // Template definition ensures that the option and default have the same
578 // DataType (via the same AnyOptionValue).
579 template<class AnyOptionValue>
580 void printOptionDiff(const Option &O, const AnyOptionValue &V,
581 const AnyOptionValue &Default,
582 size_t GlobalWidth) const {
583 printGenericOptionDiff(O, V, Default, GlobalWidth);
584 }
585
586 void initialize(Option &O) {
587 // All of the modifiers for the option have been processed by now, so the
588 // argstr field should be stable, copy it down now.
589 //
590 hasArgStr = O.hasArgStr();
591 }
592
593 void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) {
594 // If there has been no argstr specified, that means that we need to add an
595 // argument for every possible option. This ensures that our options are
596 // vectored to us.
597 if (!hasArgStr)
598 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
599 OptionNames.push_back(getOption(i));
600 }
601
602
603 enum ValueExpected getValueExpectedFlagDefault() const {
604 // If there is an ArgStr specified, then we are of the form:
605 //
606 // -opt=O2 or -opt O2 or -optO2
607 //
608 // In which case, the value is required. Otherwise if an arg str has not
609 // been specified, we are of the form:
610 //
611 // -O2 or O2 or -la (where -l and -a are separate options)
612 //
613 // If this is the case, we cannot allow a value.
614 //
615 if (hasArgStr)
616 return ValueRequired;
617 else
618 return ValueDisallowed;
619 }
620
621 // findOption - Return the option number corresponding to the specified
622 // argument string. If the option is not found, getNumOptions() is returned.
623 //
624 unsigned findOption(const char *Name);
625
626 protected:
627 bool hasArgStr;
628 };
629
630 // Default parser implementation - This implementation depends on having a
631 // mapping of recognized options to values of some sort. In addition to this,
632 // each entry in the mapping also tracks a help message that is printed with the
633 // command line option for -help. Because this is a simple mapping parser, the
634 // data type can be any unsupported type.
635 //
636 template <class DataType>
637 class parser : public generic_parser_base {
638 protected:
639 class OptionInfo : public GenericOptionInfo {
640 public:
641 OptionInfo(const char *name, DataType v, const char *helpStr) :
642 GenericOptionInfo(name, helpStr), V(v) {}
643 OptionValue<DataType> V;
644 };
645 SmallVector<OptionInfo, 8> Values;
646 public:
647 typedef DataType parser_data_type;
648
649 // Implement virtual functions needed by generic_parser_base
650 unsigned getNumOptions() const override { return unsigned(Values.size()); }
651 const char *getOption(unsigned N) const override { return Values[N].Name; }
652 const char *getDescription(unsigned N) const override {
653 return Values[N].HelpStr;
654 }
655
656 // getOptionValue - Return the value of option name N.
657 const GenericOptionValue &getOptionValue(unsigned N) const override {
658 return Values[N].V;
659 }
660
661 // parse - Return true on error.
662 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
663 StringRef ArgVal;
664 if (hasArgStr)
665 ArgVal = Arg;
666 else
667 ArgVal = ArgName;
668
669 for (size_t i = 0, e = Values.size(); i != e; ++i)
670 if (Values[i].Name == ArgVal) {
671 V = Values[i].V.getValue();
672 return false;
673 }
674
675 return O.error("Cannot find option named '" + ArgVal + "'!");
676 }
677
678 /// addLiteralOption - Add an entry to the mapping table.
679 ///
680 template <class DT>
681 void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
682 assert(findOption(Name) == Values.size() && "Option already exists!");
683 OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
684 Values.push_back(X);
685 MarkOptionsChanged();
686 }
687
688 /// removeLiteralOption - Remove the specified option.
689 ///
690 void removeLiteralOption(const char *Name) {
691 unsigned N = findOption(Name);
692 assert(N != Values.size() && "Option not found!");
693 Values.erase(Values.begin()+N);
694 }
695 };
696
697 //--------------------------------------------------
698 // basic_parser - Super class of parsers to provide boilerplate code
699 //
700 class basic_parser_impl { // non-template implementation of basic_parser<t>
701 public:
702 virtual ~basic_parser_impl() {}
703
704 enum ValueExpected getValueExpectedFlagDefault() const {
705 return ValueRequired;
706 }
707
708 void getExtraOptionNames(SmallVectorImpl<const char*> &) {}
709
710 void initialize(Option &) {}
711
712 // Return the width of the option tag for printing...
713 size_t getOptionWidth(const Option &O) const;
714
715 // printOptionInfo - Print out information about this option. The
716 // to-be-maintained width is specified.
717 //
718 void printOptionInfo(const Option &O, size_t GlobalWidth) const;
719
720 // printOptionNoValue - Print a placeholder for options that don't yet support
721 // printOptionDiff().
722 void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
723
724 // getValueName - Overload in subclass to provide a better default value.
725 virtual const char *getValueName() const { return "value"; }
726
727 // An out-of-line virtual method to provide a 'home' for this class.
728 virtual void anchor();
729
730 protected:
731 // A helper for basic_parser::printOptionDiff.
732 void printOptionName(const Option &O, size_t GlobalWidth) const;
733 };
734
735 // basic_parser - The real basic parser is just a template wrapper that provides
736 // a typedef for the provided data type.
737 //
738 template<class DataType>
739 class basic_parser : public basic_parser_impl {
740 public:
741 typedef DataType parser_data_type;
742 typedef OptionValue<DataType> OptVal;
743 };
744
745 //--------------------------------------------------
746 // parser<bool>
747 //
748 template<>
749 class parser<bool> : public basic_parser<bool> {
750 const char *ArgStr;
751 public:
752
753 // parse - Return true on error.
754 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
755
756 template <class Opt>
757 void initialize(Opt &O) {
758 ArgStr = O.ArgStr;
759 }
760
761 enum ValueExpected getValueExpectedFlagDefault() const {
762 return ValueOptional;
763 }
764
765 // getValueName - Do not print =<value> at all.
766 const char *getValueName() const override { return nullptr; }
767
768 void printOptionDiff(const Option &O, bool V, OptVal Default,
769 size_t GlobalWidth) const;
770
771 // An out-of-line virtual method to provide a 'home' for this class.
772 void anchor() override;
773 };
774
775 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<bool>);
776
777 //--------------------------------------------------
778 // parser<boolOrDefault>
779 template<>
780 class parser<boolOrDefault> : public basic_parser<boolOrDefault> {
781 public:
782 // parse - Return true on error.
783 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
784
785 enum ValueExpected getValueExpectedFlagDefault() const {
786 return ValueOptional;
787 }
788
789 // getValueName - Do not print =<value> at all.
790 const char *getValueName() const override { return nullptr; }
791
792 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
793 size_t GlobalWidth) const;
794
795 // An out-of-line virtual method to provide a 'home' for this class.
796 void anchor() override;
797 };
798
799 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
800
801 //--------------------------------------------------
802 // parser<int>
803 //
804 template<>
805 class parser<int> : public basic_parser<int> {
806 public:
807 // parse - Return true on error.
808 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
809
810 // getValueName - Overload in subclass to provide a better default value.
811 const char *getValueName() const override { return "int"; }
812
813 void printOptionDiff(const Option &O, int V, OptVal Default,
814 size_t GlobalWidth) const;
815
816 // An out-of-line virtual method to provide a 'home' for this class.
817 void anchor() override;
818 };
819
820 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<int>);
821
822
823 //--------------------------------------------------
824 // parser<unsigned>
825 //
826 template<>
827 class parser<unsigned> : public basic_parser<unsigned> {
828 public:
829 // parse - Return true on error.
830 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
831
832 // getValueName - Overload in subclass to provide a better default value.
833 const char *getValueName() const override { return "uint"; }
834
835 void printOptionDiff(const Option &O, unsigned V, OptVal Default,
836 size_t GlobalWidth) const;
837
838 // An out-of-line virtual method to provide a 'home' for this class.
839 void anchor() override;
840 };
841
842 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
843
844 //--------------------------------------------------
845 // parser<unsigned long long>
846 //
847 template<>
848 class parser<unsigned long long> : public basic_parser<unsigned long long> {
849 public:
850 // parse - Return true on error.
851 bool parse(Option &O, StringRef ArgName, StringRef Arg,
852 unsigned long long &Val);
853
854 // getValueName - Overload in subclass to provide a better default value.
855 const char *getValueName() const override { return "uint"; }
856
857 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
858 size_t GlobalWidth) const;
859
860 // An out-of-line virtual method to provide a 'home' for this class.
861 void anchor() override;
862 };
863
864 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
865
866 //--------------------------------------------------
867 // parser<double>
868 //
869 template<>
870 class parser<double> : public basic_parser<double> {
871 public:
872 // parse - Return true on error.
873 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
874
875 // getValueName - Overload in subclass to provide a better default value.
876 const char *getValueName() const override { return "number"; }
877
878 void printOptionDiff(const Option &O, double V, OptVal Default,
879 size_t GlobalWidth) const;
880
881 // An out-of-line virtual method to provide a 'home' for this class.
882 void anchor() override;
883 };
884
885 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<double>);
886
887 //--------------------------------------------------
888 // parser<float>
889 //
890 template<>
891 class parser<float> : public basic_parser<float> {
892 public:
893 // parse - Return true on error.
894 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
895
896 // getValueName - Overload in subclass to provide a better default value.
897 const char *getValueName() const override { return "number"; }
898
899 void printOptionDiff(const Option &O, float V, OptVal Default,
900 size_t GlobalWidth) const;
901
902 // An out-of-line virtual method to provide a 'home' for this class.
903 void anchor() override;
904 };
905
906 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<float>);
907
908 //--------------------------------------------------
909 // parser<std::string>
910 //
911 template<>
912 class parser<std::string> : public basic_parser<std::string> {
913 public:
914 // parse - Return true on error.
915 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
916 Value = Arg.str();
917 return false;
918 }
919
920 // getValueName - Overload in subclass to provide a better default value.
921 const char *getValueName() const override { return "string"; }
922
923 void printOptionDiff(const Option &O, StringRef V, OptVal Default,
924 size_t GlobalWidth) const;
925
926 // An out-of-line virtual method to provide a 'home' for this class.
927 void anchor() override;
928 };
929
930 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
931
932 //--------------------------------------------------
933 // parser<char>
934 //
935 template<>
936 class parser<char> : public basic_parser<char> {
937 public:
938 // parse - Return true on error.
939 bool parse(Option &, StringRef, StringRef Arg, char &Value) {
940 Value = Arg[0];
941 return false;
942 }
943
944 // getValueName - Overload in subclass to provide a better default value.
945 const char *getValueName() const override { return "char"; }
946
947 void printOptionDiff(const Option &O, char V, OptVal Default,
948 size_t GlobalWidth) const;
949
950 // An out-of-line virtual method to provide a 'home' for this class.
951 void anchor() override;
952 };
953
954 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<char>);
955
956 //--------------------------------------------------
957 // PrintOptionDiff
958 //
959 // This collection of wrappers is the intermediary between class opt and class
960 // parser to handle all the template nastiness.
961
962 // This overloaded function is selected by the generic parser.
963 template<class ParserClass, class DT>
964 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
965 const OptionValue<DT> &Default, size_t GlobalWidth) {
966 OptionValue<DT> OV = V;
967 P.printOptionDiff(O, OV, Default, GlobalWidth);
968 }
969
970 // This is instantiated for basic parsers when the parsed value has a different
971 // type than the option value. e.g. HelpPrinter.
972 template<class ParserDT, class ValDT>
973 struct OptionDiffPrinter {
974 void print(const Option &O, const parser<ParserDT> P, const ValDT &/*V*/,
975 const OptionValue<ValDT> &/*Default*/, size_t GlobalWidth) {
976 P.printOptionNoValue(O, GlobalWidth);
977 }
978 };
979
980 // This is instantiated for basic parsers when the parsed value has the same
981 // type as the option value.
982 template<class DT>
983 struct OptionDiffPrinter<DT, DT> {
984 void print(const Option &O, const parser<DT> P, const DT &V,
985 const OptionValue<DT> &Default, size_t GlobalWidth) {
986 P.printOptionDiff(O, V, Default, GlobalWidth);
987 }
988 };
989
990 // This overloaded function is selected by the basic parser, which may parse a
991 // different type than the option type.
992 template<class ParserClass, class ValDT>
993 void printOptionDiff(
994 const Option &O,
995 const basic_parser<typename ParserClass::parser_data_type> &P,
996 const ValDT &V, const OptionValue<ValDT> &Default,
997 size_t GlobalWidth) {
998
999 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
1000 printer.print(O, static_cast<const ParserClass&>(P), V, Default,
1001 GlobalWidth);
1002 }
1003
1004 //===----------------------------------------------------------------------===//
1005 // applicator class - This class is used because we must use partial
1006 // specialization to handle literal string arguments specially (const char* does
1007 // not correctly respond to the apply method). Because the syntax to use this
1008 // is a pain, we have the 'apply' method below to handle the nastiness...
1009 //
1010 template<class Mod> struct applicator {
1011 template<class Opt>
1012 static void opt(const Mod &M, Opt &O) { M.apply(O); }
1013 };
1014
1015 // Handle const char* as a special case...
1016 template<unsigned n> struct applicator<char[n]> {
1017 template<class Opt>
1018 static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
1019 };
1020 template<unsigned n> struct applicator<const char[n]> {
1021 template<class Opt>
1022 static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
1023 };
1024 template<> struct applicator<const char*> {
1025 template<class Opt>
1026 static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
1027 };
1028
1029 template<> struct applicator<NumOccurrencesFlag> {
1030 static void opt(NumOccurrencesFlag N, Option &O) {
1031 O.setNumOccurrencesFlag(N);
1032 }
1033 };
1034 template<> struct applicator<ValueExpected> {
1035 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1036 };
1037 template<> struct applicator<OptionHidden> {
1038 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1039 };
1040 template<> struct applicator<FormattingFlags> {
1041 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1042 };
1043 template<> struct applicator<MiscFlags> {
1044 static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1045 };
1046
1047 // apply method - Apply a modifier to an option in a type safe way.
1048 template<class Mod, class Opt>
1049 void apply(const Mod &M, Opt *O) {
1050 applicator<Mod>::opt(M, *O);
1051 }
1052
1053 //===----------------------------------------------------------------------===//
1054 // opt_storage class
1055
1056 // Default storage class definition: external storage. This implementation
1057 // assumes the user will specify a variable to store the data into with the
1058 // cl::location(x) modifier.
1059 //
1060 template<class DataType, bool ExternalStorage, bool isClass>
1061 class opt_storage {
1062 DataType *Location; // Where to store the object...
1063 OptionValue<DataType> Default;
1064
1065 void check_location() const {
1066 assert(Location && "cl::location(...) not specified for a command "
1067 "line option with external storage, "
1068 "or cl::init specified before cl::location()!!");
1069 }
1070 public:
1071 opt_storage() : Location(nullptr) {}
1072
1073 bool setLocation(Option &O, DataType &L) {
1074 if (Location)
1075 return O.error("cl::location(x) specified more than once!");
1076 Location = &L;
1077 Default = L;
1078 return false;
1079 }
1080
1081 template<class T>
1082 void setValue(const T &V, bool initial = false) {
1083 check_location();
1084 *Location = V;
1085 if (initial)
1086 Default = V;
1087 }
1088
1089 DataType &getValue() { check_location(); return *Location; }
1090 const DataType &getValue() const { check_location(); return *Location; }
1091
1092 operator DataType() const { return this->getValue(); }
1093
1094 const OptionValue<DataType> &getDefault() const { return Default; }
1095 };
1096
1097 // Define how to hold a class type object, such as a string. Since we can
1098 // inherit from a class, we do so. This makes us exactly compatible with the
1099 // object in all cases that it is used.
1100 //
1101 template<class DataType>
1102 class opt_storage<DataType,false,true> : public DataType {
1103 public:
1104 OptionValue<DataType> Default;
1105
1106 template<class T>
1107 void setValue(const T &V, bool initial = false) {
1108 DataType::operator=(V);
1109 if (initial)
1110 Default = V;
1111 }
1112
1113 DataType &getValue() { return *this; }
1114 const DataType &getValue() const { return *this; }
1115
1116 const OptionValue<DataType> &getDefault() const { return Default; }
1117 };
1118
1119 // Define a partial specialization to handle things we cannot inherit from. In
1120 // this case, we store an instance through containment, and overload operators
1121 // to get at the value.
1122 //
1123 template<class DataType>
1124 class opt_storage<DataType, false, false> {
1125 public:
1126 DataType Value;
1127 OptionValue<DataType> Default;
1128
1129 // Make sure we initialize the value with the default constructor for the
1130 // type.
1131 opt_storage() : Value(DataType()), Default(DataType()) {}
1132
1133 template<class T>
1134 void setValue(const T &V, bool initial = false) {
1135 Value = V;
1136 if (initial)
1137 Default = V;
1138 }
1139 DataType &getValue() { return Value; }
1140 DataType getValue() const { return Value; }
1141
1142 const OptionValue<DataType> &getDefault() const { return Default; }
1143
1144 operator DataType() const { return getValue(); }
1145
1146 // If the datatype is a pointer, support -> on it.
1147 DataType operator->() const { return Value; }
1148 };
1149
1150
1151 //===----------------------------------------------------------------------===//
1152 // opt - A scalar command line option.
1153 //
1154 template <class DataType, bool ExternalStorage = false,
1155 class ParserClass = parser<DataType> >
1156 class opt : public Option,
1157 public opt_storage<DataType, ExternalStorage,
1158 std::is_class<DataType>::value> {
1159 ParserClass Parser;
1160
1161 bool handleOccurrence(unsigned pos, StringRef ArgName,
1162 StringRef Arg) override {
1163 typename ParserClass::parser_data_type Val =
1164 typename ParserClass::parser_data_type();
1165 if (Parser.parse(*this, ArgName, Arg, Val))
1166 return true; // Parse error!
1167 this->setValue(Val);
1168 this->setPosition(pos);
1169 return false;
1170 }
1171
1172 enum ValueExpected getValueExpectedFlagDefault() const override {
1173 return Parser.getValueExpectedFlagDefault();
1174 }
1175 void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) override {
1176 return Parser.getExtraOptionNames(OptionNames);
1177 }
1178
1179 // Forward printing stuff to the parser...
1180 size_t getOptionWidth() const override {return Parser.getOptionWidth(*this);}
1181 void printOptionInfo(size_t GlobalWidth) const override {
1182 Parser.printOptionInfo(*this, GlobalWidth);
1183 }
1184
1185 void printOptionValue(size_t GlobalWidth, bool Force) const override {
1186 if (Force || this->getDefault().compare(this->getValue())) {
1187 cl::printOptionDiff<ParserClass>(
1188 *this, Parser, this->getValue(), this->getDefault(), GlobalWidth);
1189 }
1190 }
1191
1192 void done() {
1193 addArgument();
1194 Parser.initialize(*this);
1195 }
1196 public:
1197 // setInitialValue - Used by the cl::init modifier...
1198 void setInitialValue(const DataType &V) { this->setValue(V, true); }
1199
1200 ParserClass &getParser() { return Parser; }
1201
1202 template<class T>
1203 DataType &operator=(const T &Val) {
1204 this->setValue(Val);
1205 return this->getValue();
1206 }
1207
1208 // One option...
1209 template<class M0t>
1210 explicit opt(const M0t &M0) : Option(Optional, NotHidden) {
1211 apply(M0, this);
1212 done();
1213 }
1214
1215 // Two options...
1216 template<class M0t, class M1t>
1217 opt(const M0t &M0, const M1t &M1) : Option(Optional, NotHidden) {
1218 apply(M0, this); apply(M1, this);
1219 done();
1220 }
1221
1222 // Three options...
1223 template<class M0t, class M1t, class M2t>
1224 opt(const M0t &M0, const M1t &M1,
1225 const M2t &M2) : Option(Optional, NotHidden) {
1226 apply(M0, this); apply(M1, this); apply(M2, this);
1227 done();
1228 }
1229 // Four options...
1230 template<class M0t, class M1t, class M2t, class M3t>
1231 opt(const M0t &M0, const M1t &M1, const M2t &M2,
1232 const M3t &M3) : Option(Optional, NotHidden) {
1233 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1234 done();
1235 }
1236 // Five options...
1237 template<class M0t, class M1t, class M2t, class M3t, class M4t>
1238 opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1239 const M4t &M4) : Option(Optional, NotHidden) {
1240 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1241 apply(M4, this);
1242 done();
1243 }
1244 // Six options...
1245 template<class M0t, class M1t, class M2t, class M3t,
1246 class M4t, class M5t>
1247 opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1248 const M4t &M4, const M5t &M5) : Option(Optional, NotHidden) {
1249 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1250 apply(M4, this); apply(M5, this);
1251 done();
1252 }
1253 // Seven options...
1254 template<class M0t, class M1t, class M2t, class M3t,
1255 class M4t, class M5t, class M6t>
1256 opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1257 const M4t &M4, const M5t &M5,
1258 const M6t &M6) : Option(Optional, NotHidden) {
1259 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1260 apply(M4, this); apply(M5, this); apply(M6, this);
1261 done();
1262 }
1263 // Eight options...
1264 template<class M0t, class M1t, class M2t, class M3t,
1265 class M4t, class M5t, class M6t, class M7t>
1266 opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1267 const M4t &M4, const M5t &M5, const M6t &M6,
1268 const M7t &M7) : Option(Optional, NotHidden) {
1269 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1270 apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
1271 done();
1272 }
1273 };
1274
1275 EXTERN_TEMPLATE_INSTANTIATION(class opt<unsigned>);
1276 EXTERN_TEMPLATE_INSTANTIATION(class opt<int>);
1277 EXTERN_TEMPLATE_INSTANTIATION(class opt<std::string>);
1278 EXTERN_TEMPLATE_INSTANTIATION(class opt<char>);
1279 EXTERN_TEMPLATE_INSTANTIATION(class opt<bool>);
1280
1281 //===----------------------------------------------------------------------===//
1282 // list_storage class
1283
1284 // Default storage class definition: external storage. This implementation
1285 // assumes the user will specify a variable to store the data into with the
1286 // cl::location(x) modifier.
1287 //
1288 template<class DataType, class StorageClass>
1289 class list_storage {
1290 StorageClass *Location; // Where to store the object...
1291
1292 public:
1293 list_storage() : Location(0) {}
1294
1295 bool setLocation(Option &O, StorageClass &L) {
1296 if (Location)
1297 return O.error("cl::location(x) specified more than once!");
1298 Location = &L;
1299 return false;
1300 }
1301
1302 template<class T>
1303 void addValue(const T &V) {
1304 assert(Location != 0 && "cl::location(...) not specified for a command "
1305 "line option with external storage!");
1306 Location->push_back(V);
1307 }
1308 };
1309
1310
1311 // Define how to hold a class type object, such as a string. Since we can
1312 // inherit from a class, we do so. This makes us exactly compatible with the
1313 // object in all cases that it is used.
1314 //
1315 template<class DataType>
1316 class list_storage<DataType, bool> : public std::vector<DataType> {
1317 public:
1318 template<class T>
1319 void addValue(const T &V) { std::vector<DataType>::push_back(V); }
1320 };
1321
1322
1323 //===----------------------------------------------------------------------===//
1324 // list - A list of command line options.
1325 //
1326 template <class DataType, class Storage = bool,
1327 class ParserClass = parser<DataType> >
1328 class list : public Option, public list_storage<DataType, Storage> {
1329 std::vector<unsigned> Positions;
1330 ParserClass Parser;
1331
1332 enum ValueExpected getValueExpectedFlagDefault() const override {
1333 return Parser.getValueExpectedFlagDefault();
1334 }
1335 void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) override {
1336 return Parser.getExtraOptionNames(OptionNames);
1337 }
1338
1339 bool handleOccurrence(unsigned pos, StringRef ArgName,
1340 StringRef Arg) override {
1341 typename ParserClass::parser_data_type Val =
1342 typename ParserClass::parser_data_type();
1343 if (Parser.parse(*this, ArgName, Arg, Val))
1344 return true; // Parse Error!
1345 list_storage<DataType, Storage>::addValue(Val);
1346 setPosition(pos);
1347 Positions.push_back(pos);
1348 return false;
1349 }
1350
1351 // Forward printing stuff to the parser...
1352 size_t getOptionWidth() const override {return Parser.getOptionWidth(*this);}
1353 void printOptionInfo(size_t GlobalWidth) const override {
1354 Parser.printOptionInfo(*this, GlobalWidth);
1355 }
1356
1357 // Unimplemented: list options don't currently store their default value.
1358 void printOptionValue(size_t /*GlobalWidth*/,
1359 bool /*Force*/) const override {}
1360
1361 void done() {
1362 addArgument();
1363 Parser.initialize(*this);
1364 }
1365 public:
1366 ParserClass &getParser() { return Parser; }
1367
1368 unsigned getPosition(unsigned optnum) const {
1369 assert(optnum < this->size() && "Invalid option index");
1370 return Positions[optnum];
1371 }
1372
1373 void setNumAdditionalVals(unsigned n) {
1374 Option::setNumAdditionalVals(n);
1375 }
1376
1377 // One option...
1378 template<class M0t>
1379 explicit list(const M0t &M0) : Option(ZeroOrMore, NotHidden) {
1380 apply(M0, this);
1381 done();
1382 }
1383 // Two options...
1384 template<class M0t, class M1t>
1385 list(const M0t &M0, const M1t &M1) : Option(ZeroOrMore, NotHidden) {
1386 apply(M0, this); apply(M1, this);
1387 done();
1388 }
1389 // Three options...
1390 template<class M0t, class M1t, class M2t>
1391 list(const M0t &M0, const M1t &M1, const M2t &M2)
1392 : Option(ZeroOrMore, NotHidden) {
1393 apply(M0, this); apply(M1, this); apply(M2, this);
1394 done();
1395 }
1396 // Four options...
1397 template<class M0t, class M1t, class M2t, class M3t>
1398 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1399 : Option(ZeroOrMore, NotHidden) {
1400 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1401 done();
1402 }
1403 // Five options...
1404 template<class M0t, class M1t, class M2t, class M3t, class M4t>
1405 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1406 const M4t &M4) : Option(ZeroOrMore, NotHidden) {
1407 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1408 apply(M4, this);
1409 done();
1410 }
1411 // Six options...
1412 template<class M0t, class M1t, class M2t, class M3t,
1413 class M4t, class M5t>
1414 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1415 const M4t &M4, const M5t &M5) : Option(ZeroOrMore, NotHidden) {
1416 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1417 apply(M4, this); apply(M5, this);
1418 done();
1419 }
1420 // Seven options...
1421 template<class M0t, class M1t, class M2t, class M3t,
1422 class M4t, class M5t, class M6t>
1423 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1424 const M4t &M4, const M5t &M5, const M6t &M6)
1425 : Option(ZeroOrMore, NotHidden) {
1426 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1427 apply(M4, this); apply(M5, this); apply(M6, this);
1428 done();
1429 }
1430 // Eight options...
1431 template<class M0t, class M1t, class M2t, class M3t,
1432 class M4t, class M5t, class M6t, class M7t>
1433 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1434 const M4t &M4, const M5t &M5, const M6t &M6,
1435 const M7t &M7) : Option(ZeroOrMore, NotHidden) {
1436 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1437 apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
1438 done();
1439 }
1440 };
1441
1442 // multi_val - Modifier to set the number of additional values.
1443 struct multi_val {
1444 unsigned AdditionalVals;
1445 explicit multi_val(unsigned N) : AdditionalVals(N) {}
1446
1447 template <typename D, typename S, typename P>
1448 void apply(list<D, S, P> &L) const { L.setNumAdditionalVals(AdditionalVals); }
1449 };
1450
1451
1452 //===----------------------------------------------------------------------===//
1453 // bits_storage class
1454
1455 // Default storage class definition: external storage. This implementation
1456 // assumes the user will specify a variable to store the data into with the
1457 // cl::location(x) modifier.
1458 //
1459 template<class DataType, class StorageClass>
1460 class bits_storage {
1461 unsigned *Location; // Where to store the bits...
1462
1463 template<class T>
1464 static unsigned Bit(const T &V) {
1465 unsigned BitPos = reinterpret_cast<unsigned>(V);
1466 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1467 "enum exceeds width of bit vector!");
1468 return 1 << BitPos;
1469 }
1470
1471 public:
1472 bits_storage() : Location(nullptr) {}
1473
1474 bool setLocation(Option &O, unsigned &L) {
1475 if (Location)
1476 return O.error("cl::location(x) specified more than once!");
1477 Location = &L;
1478 return false;
1479 }
1480
1481 template<class T>
1482 void addValue(const T &V) {
1483 assert(Location != 0 && "cl::location(...) not specified for a command "
1484 "line option with external storage!");
1485 *Location |= Bit(V);
1486 }
1487
1488 unsigned getBits() { return *Location; }
1489
1490 template<class T>
1491 bool isSet(const T &V) {
1492 return (*Location & Bit(V)) != 0;
1493 }
1494 };
1495
1496
1497 // Define how to hold bits. Since we can inherit from a class, we do so.
1498 // This makes us exactly compatible with the bits in all cases that it is used.
1499 //
1500 template<class DataType>
1501 class bits_storage<DataType, bool> {
1502 unsigned Bits; // Where to store the bits...
1503
1504 template<class T>
1505 static unsigned Bit(const T &V) {
1506 unsigned BitPos = (unsigned)V;
1507 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1508 "enum exceeds width of bit vector!");
1509 return 1 << BitPos;
1510 }
1511
1512 public:
1513 template<class T>
1514 void addValue(const T &V) {
1515 Bits |= Bit(V);
1516 }
1517
1518 unsigned getBits() { return Bits; }
1519
1520 template<class T>
1521 bool isSet(const T &V) {
1522 return (Bits & Bit(V)) != 0;
1523 }
1524 };
1525
1526
1527 //===----------------------------------------------------------------------===//
1528 // bits - A bit vector of command options.
1529 //
1530 template <class DataType, class Storage = bool,
1531 class ParserClass = parser<DataType> >
1532 class bits : public Option, public bits_storage<DataType, Storage> {
1533 std::vector<unsigned> Positions;
1534 ParserClass Parser;
1535
1536 enum ValueExpected getValueExpectedFlagDefault() const override {
1537 return Parser.getValueExpectedFlagDefault();
1538 }
1539 void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) override {
1540 return Parser.getExtraOptionNames(OptionNames);
1541 }
1542
1543 bool handleOccurrence(unsigned pos, StringRef ArgName,
1544 StringRef Arg) override {
1545 typename ParserClass::parser_data_type Val =
1546 typename ParserClass::parser_data_type();
1547 if (Parser.parse(*this, ArgName, Arg, Val))
1548 return true; // Parse Error!
1549 this->addValue(Val);
1550 setPosition(pos);
1551 Positions.push_back(pos);
1552 return false;
1553 }
1554
1555 // Forward printing stuff to the parser...
1556 size_t getOptionWidth() const override {return Parser.getOptionWidth(*this);}
1557 void printOptionInfo(size_t GlobalWidth) const override {
1558 Parser.printOptionInfo(*this, GlobalWidth);
1559 }
1560
1561 // Unimplemented: bits options don't currently store their default values.
1562 void printOptionValue(size_t /*GlobalWidth*/,
1563 bool /*Force*/) const override {}
1564
1565 void done() {
1566 addArgument();
1567 Parser.initialize(*this);
1568 }
1569 public:
1570 ParserClass &getParser() { return Parser; }
1571
1572 unsigned getPosition(unsigned optnum) const {
1573 assert(optnum < this->size() && "Invalid option index");
1574 return Positions[optnum];
1575 }
1576
1577 // One option...
1578 template<class M0t>
1579 explicit bits(const M0t &M0) : Option(ZeroOrMore, NotHidden) {
1580 apply(M0, this);
1581 done();
1582 }
1583 // Two options...
1584 template<class M0t, class M1t>
1585 bits(const M0t &M0, const M1t &M1) : Option(ZeroOrMore, NotHidden) {
1586 apply(M0, this); apply(M1, this);
1587 done();
1588 }
1589 // Three options...
1590 template<class M0t, class M1t, class M2t>
1591 bits(const M0t &M0, const M1t &M1, const M2t &M2)
1592 : Option(ZeroOrMore, NotHidden) {
1593 apply(M0, this); apply(M1, this); apply(M2, this);
1594 done();
1595 }
1596 // Four options...
1597 template<class M0t, class M1t, class M2t, class M3t>
1598 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1599 : Option(ZeroOrMore, NotHidden) {
1600 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1601 done();
1602 }
1603 // Five options...
1604 template<class M0t, class M1t, class M2t, class M3t, class M4t>
1605 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1606 const M4t &M4) : Option(ZeroOrMore, NotHidden) {
1607 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1608 apply(M4, this);
1609 done();
1610 }
1611 // Six options...
1612 template<class M0t, class M1t, class M2t, class M3t,
1613 class M4t, class M5t>
1614 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1615 const M4t &M4, const M5t &M5) : Option(ZeroOrMore, NotHidden) {
1616 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1617 apply(M4, this); apply(M5, this);
1618 done();
1619 }
1620 // Seven options...
1621 template<class M0t, class M1t, class M2t, class M3t,
1622 class M4t, class M5t, class M6t>
1623 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1624 const M4t &M4, const M5t &M5, const M6t &M6)
1625 : Option(ZeroOrMore, NotHidden) {
1626 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1627 apply(M4, this); apply(M5, this); apply(M6, this);
1628 done();
1629 }
1630 // Eight options...
1631 template<class M0t, class M1t, class M2t, class M3t,
1632 class M4t, class M5t, class M6t, class M7t>
1633 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1634 const M4t &M4, const M5t &M5, const M6t &M6,
1635 const M7t &M7) : Option(ZeroOrMore, NotHidden) {
1636 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1637 apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
1638 done();
1639 }
1640 };
1641
1642 //===----------------------------------------------------------------------===//
1643 // Aliased command line option (alias this name to a preexisting name)
1644 //
1645
1646 class alias : public Option {
1647 Option *AliasFor;
1648 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1649 StringRef Arg) override {
1650 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1651 }
1652 // Handle printing stuff...
1653 size_t getOptionWidth() const override;
1654 void printOptionInfo(size_t GlobalWidth) const override;
1655
1656 // Aliases do not need to print their values.
1657 void printOptionValue(size_t /*GlobalWidth*/,
1658 bool /*Force*/) const override {}
1659
1660 ValueExpected getValueExpectedFlagDefault() const override {
1661 return AliasFor->getValueExpectedFlag();
1662 }
1663
1664 void done() {
1665 if (!hasArgStr())
1666 error("cl::alias must have argument name specified!");
1667 if (!AliasFor)
1668 error("cl::alias must have an cl::aliasopt(option) specified!");
1669 addArgument();
1670 }
1671 public:
1672 void setAliasFor(Option &O) {
1673 if (AliasFor)
1674 error("cl::alias must only have one cl::aliasopt(...) specified!");
1675 AliasFor = &O;
1676 }
1677
1678 // One option...
1679 template<class M0t>
1680 explicit alias(const M0t &M0) : Option(Optional, Hidden), AliasFor(nullptr) {
1681 apply(M0, this);
1682 done();
1683 }
1684 // Two options...
1685 template<class M0t, class M1t>
1686 alias(const M0t &M0, const M1t &M1)
1687 : Option(Optional, Hidden), AliasFor(nullptr) {
1688 apply(M0, this); apply(M1, this);
1689 done();
1690 }
1691 // Three options...
1692 template<class M0t, class M1t, class M2t>
1693 alias(const M0t &M0, const M1t &M1, const M2t &M2)
1694 : Option(Optional, Hidden), AliasFor(nullptr) {
1695 apply(M0, this); apply(M1, this); apply(M2, this);
1696 done();
1697 }
1698 // Four options...
1699 template<class M0t, class M1t, class M2t, class M3t>
1700 alias(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1701 : Option(Optional, Hidden), AliasFor(nullptr) {
1702 apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1703 done();
1704 }
1705 };
1706
1707 // aliasfor - Modifier to set the option an alias aliases.
1708 struct aliasopt {
1709 Option &Opt;
1710 explicit aliasopt(Option &O) : Opt(O) {}
1711 void apply(alias &A) const { A.setAliasFor(Opt); }
1712 };
1713
1714 // extrahelp - provide additional help at the end of the normal help
1715 // output. All occurrences of cl::extrahelp will be accumulated and
1716 // printed to stderr at the end of the regular help, just before
1717 // exit is called.
1718 struct extrahelp {
1719 const char * morehelp;
1720 explicit extrahelp(const char* help);
1721 };
1722
1723 void PrintVersionMessage();
1724
1725 /// This function just prints the help message, exactly the same way as if the
1726 /// -help or -help-hidden option had been given on the command line.
1727 ///
1728 /// NOTE: THIS FUNCTION TERMINATES THE PROGRAM!
1729 ///
1730 /// \param Hidden if true will print hidden options
1731 /// \param Categorized if true print options in categories
1732 void PrintHelpMessage(bool Hidden=false, bool Categorized=false);
1733
1734
1735 //===----------------------------------------------------------------------===//
1736 // Public interface for accessing registered options.
1737 //
1738
1739 /// \brief Use this to get a StringMap to all registered named options
1740 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1741 ///
1742 /// \param [out] Map will be filled with mappings where the key is the
1743 /// Option argument string (e.g. "help") and value is the corresponding
1744 /// Option*.
1745 ///
1746 /// Access to unnamed arguments (i.e. positional) are not provided because
1747 /// it is expected that the client already has access to these.
1748 ///
1749 /// Typical usage:
1750 /// \code
1751 /// main(int argc,char* argv[]) {
1752 /// StringMap<llvm::cl::Option*> opts;
1753 /// llvm::cl::getRegisteredOptions(opts);
1754 /// assert(opts.count("help") == 1)
1755 /// opts["help"]->setDescription("Show alphabetical help information")
1756 /// // More code
1757 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1758 /// //More code
1759 /// }
1760 /// \endcode
1761 ///
1762 /// This interface is useful for modifying options in libraries that are out of
1763 /// the control of the client. The options should be modified before calling
1764 /// llvm::cl::ParseCommandLineOptions().
1765 void getRegisteredOptions(StringMap<Option*> &Map);
1766
1767 //===----------------------------------------------------------------------===//
1768 // Standalone command line processing utilities.
1769 //
1770
1771 /// \brief Saves strings in the inheritor's stable storage and returns a stable
1772 /// raw character pointer.
1773 class StringSaver {
1774 virtual void anchor();
1775 public:
1776 virtual const char *SaveString(const char *Str) = 0;
1777 virtual ~StringSaver() {}; // Pacify -Wnon-virtual-dtor.
1778 };
1779
1780 /// \brief Tokenizes a command line that can contain escapes and quotes.
1781 //
1782 /// The quoting rules match those used by GCC and other tools that use
1783 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1784 /// They differ from buildargv() on treatment of backslashes that do not escape
1785 /// a special character to make it possible to accept most Windows file paths.
1786 ///
1787 /// \param [in] Source The string to be split on whitespace with quotes.
1788 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1789 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1790 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
1791 SmallVectorImpl<const char *> &NewArgv);
1792
1793 /// \brief Tokenizes a Windows command line which may contain quotes and escaped
1794 /// quotes.
1795 ///
1796 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1797 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1798 ///
1799 /// \param [in] Source The string to be split on whitespace with quotes.
1800 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1801 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1802 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
1803 SmallVectorImpl<const char *> &NewArgv);
1804
1805 /// \brief String tokenization function type. Should be compatible with either
1806 /// Windows or Unix command line tokenizers.
1807 typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
1808 SmallVectorImpl<const char *> &NewArgv);
1809
1810 /// \brief Expand response files on a command line recursively using the given
1811 /// StringSaver and tokenization strategy. Argv should contain the command line
1812 /// before expansion and will be modified in place.
1813 ///
1814 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1815 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1816 /// \param [in,out] Argv Command line into which to expand response files.
1817 /// \return true if all @files were expanded successfully or there were none.
1818 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1819 SmallVectorImpl<const char *> &Argv);
1820
1821 } // End namespace cl
1822
1823 } // End namespace llvm
1824
1825 #endif
1826