1 //===- llvm/Support/CommandLine.h - Command line handler --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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
18 //===----------------------------------------------------------------------===//
20 #ifndef LLVM_SUPPORT_COMMANDLINE_H
21 #define LLVM_SUPPORT_COMMANDLINE_H
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Support/Compiler.h"
36 /// cl Namespace - This namespace contains all of the command line option
37 /// processing machinery. It is intentionally a short name to make qualified
41 //===----------------------------------------------------------------------===//
42 // ParseCommandLineOptions - Command line option processing entry point.
44 void ParseCommandLineOptions(int argc, const char *const *argv,
45 const char *Overview = nullptr);
47 //===----------------------------------------------------------------------===//
48 // ParseEnvironmentOptions - Environment variable option processing alternate
51 void ParseEnvironmentOptions(const char *progName, const char *envvar,
52 const char *Overview = nullptr);
54 ///===---------------------------------------------------------------------===//
55 /// SetVersionPrinter - Override the default (LLVM specific) version printer
56 /// used to print out the version when --version is given
57 /// on the command line. This allows other systems using the
58 /// CommandLine utilities to print their own version string.
59 void SetVersionPrinter(void (*func)());
61 ///===---------------------------------------------------------------------===//
62 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
63 /// default one. This can be called multiple times,
64 /// and each time it adds a new function to the list
65 /// which will be called after the basic LLVM version
66 /// printing is complete. Each can then add additional
67 /// information specific to the tool.
68 void AddExtraVersionPrinter(void (*func)());
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();
76 // MarkOptionsChanged - Internal helper function.
77 void MarkOptionsChanged();
79 //===----------------------------------------------------------------------===//
80 // Flags permitted to be passed to command line arguments
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
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.
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)
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
112 // Formatting flags - This controls special features that the option might have
113 // that cause it to be parsed differently...
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
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
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?
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?
140 //===----------------------------------------------------------------------===//
141 // Option Category class
143 class OptionCategory {
145 const char *const Name;
146 const char *const Description;
147 void registerCategory();
150 OptionCategory(const char *const Name,
151 const char *const Description = nullptr)
152 : Name(Name), Description(Description) {
155 const char *getName() const { return Name; }
156 const char *getDescription() const { return Description; }
159 // The general Option Category (used as default category).
160 extern OptionCategory GeneralCategory;
162 //===----------------------------------------------------------------------===//
169 // handleOccurrences - Overriden by subclasses to handle the value passed into
170 // an argument. Should return true if there was an error processing the
171 // argument and the program should exit.
173 virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
176 virtual enum ValueExpected getValueExpectedFlagDefault() const {
177 return ValueOptional;
180 // Out of line virtual function to provide home for the class.
181 virtual void anchor();
183 int NumOccurrences; // The number of times specified
184 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
185 // problems with signed enums in bitfields.
186 unsigned Occurrences : 3; // enum NumOccurrencesFlag
187 // not using the enum type for 'Value' because zero is an implementation
188 // detail representing the non-value
190 unsigned HiddenFlag : 2; // enum OptionHidden
191 unsigned Formatting : 2; // enum FormattingFlags
193 unsigned Position; // Position of last occurrence of the option
194 unsigned AdditionalVals; // Greater than 0 for multi-valued option.
195 Option *NextRegistered; // Singly linked list of registered options.
198 const char *ArgStr; // The argument string itself (ex: "help", "o")
199 const char *HelpStr; // The descriptive text message for -help
200 const char *ValueStr; // String describing what the value of this option is
201 OptionCategory *Category; // The Category this option belongs to
203 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
204 return (enum NumOccurrencesFlag)Occurrences;
206 inline enum ValueExpected getValueExpectedFlag() const {
207 return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
209 inline enum OptionHidden getOptionHiddenFlag() const {
210 return (enum OptionHidden)HiddenFlag;
212 inline enum FormattingFlags getFormattingFlag() const {
213 return (enum FormattingFlags)Formatting;
215 inline unsigned getMiscFlags() const { return Misc; }
216 inline unsigned getPosition() const { return Position; }
217 inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
219 // hasArgStr - Return true if the argstr != ""
220 bool hasArgStr() const { return ArgStr[0] != 0; }
222 //-------------------------------------------------------------------------===
223 // Accessor functions set by OptionModifiers
225 void setArgStr(const char *S) { ArgStr = S; }
226 void setDescription(const char *S) { HelpStr = S; }
227 void setValueStr(const char *S) { ValueStr = S; }
228 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
229 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
230 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
231 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
232 void setMiscFlag(enum MiscFlags M) { Misc |= M; }
233 void setPosition(unsigned pos) { Position = pos; }
234 void setCategory(OptionCategory &C) { Category = &C; }
237 explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
238 enum OptionHidden Hidden)
239 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
240 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0),
241 AdditionalVals(0), NextRegistered(nullptr), ArgStr(""), HelpStr(""),
242 ValueStr(""), Category(&GeneralCategory) {}
244 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
247 // addArgument - Register this argument with the commandline system.
251 /// Unregisters this option from the CommandLine system.
253 /// This option must have been the last option registered.
254 /// For testing purposes only.
255 void removeArgument();
257 Option *getNextRegisteredOption() const { return NextRegistered; }
259 // Return the width of the option tag for printing...
260 virtual size_t getOptionWidth() const = 0;
262 // printOptionInfo - Print out information about this option. The
263 // to-be-maintained width is specified.
265 virtual void printOptionInfo(size_t GlobalWidth) const = 0;
267 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
269 virtual void getExtraOptionNames(SmallVectorImpl<const char *> &) {}
271 // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
273 virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
274 bool MultiArg = false);
276 // Prints option name followed by message. Always returns true.
277 bool error(const Twine &Message, StringRef ArgName = StringRef());
280 inline int getNumOccurrences() const { return NumOccurrences; }
284 //===----------------------------------------------------------------------===//
285 // Command line option modifiers that can be used to modify the behavior of
286 // command line option parsers...
289 // desc - Modifier to set the description shown in the -help output...
292 desc(const char *Str) : Desc(Str) {}
293 void apply(Option &O) const { O.setDescription(Desc); }
296 // value_desc - Modifier to set the value description shown in the -help
300 value_desc(const char *Str) : Desc(Str) {}
301 void apply(Option &O) const { O.setValueStr(Desc); }
304 // init - Specify a default (initial) value for the command line argument, if
305 // the default constructor for the argument type does not give you what you
306 // want. This is only valid on "opt" arguments, not on "list" arguments.
308 template <class Ty> struct initializer {
310 initializer(const Ty &Val) : Init(Val) {}
312 template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
315 template <class Ty> initializer<Ty> init(const Ty &Val) {
316 return initializer<Ty>(Val);
319 // location - Allow the user to specify which external variable they want to
320 // store the results of the command line argument processing into, if they don't
321 // want to store it in the option itself.
323 template <class Ty> struct LocationClass {
325 LocationClass(Ty &L) : Loc(L) {}
327 template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
330 template <class Ty> LocationClass<Ty> location(Ty &L) {
331 return LocationClass<Ty>(L);
334 // cat - Specifiy the Option category for the command line argument to belong
337 OptionCategory &Category;
338 cat(OptionCategory &c) : Category(c) {}
340 template <class Opt> void apply(Opt &O) const { O.setCategory(Category); }
343 //===----------------------------------------------------------------------===//
346 // Support value comparison outside the template.
347 struct GenericOptionValue {
348 virtual ~GenericOptionValue() {}
349 virtual bool compare(const GenericOptionValue &V) const = 0;
352 virtual void anchor();
355 template <class DataType> struct OptionValue;
357 // The default value safely does nothing. Option value printing is only
359 template <class DataType, bool isClass>
360 struct OptionValueBase : public GenericOptionValue {
361 // Temporary storage for argument passing.
362 typedef OptionValue<DataType> WrapperType;
364 bool hasValue() const { return false; }
366 const DataType &getValue() const { llvm_unreachable("no default value"); }
368 // Some options may take their value from a different data type.
369 template <class DT> void setValue(const DT & /*V*/) {}
371 bool compare(const DataType & /*V*/) const { return false; }
373 bool compare(const GenericOptionValue & /*V*/) const override {
378 // Simple copy of the option value.
379 template <class DataType> class OptionValueCopy : public GenericOptionValue {
384 OptionValueCopy() : Valid(false) {}
386 bool hasValue() const { return Valid; }
388 const DataType &getValue() const {
389 assert(Valid && "invalid option value");
393 void setValue(const DataType &V) {
398 bool compare(const DataType &V) const { return Valid && (Value != V); }
400 bool compare(const GenericOptionValue &V) const override {
401 const OptionValueCopy<DataType> &VC =
402 static_cast<const OptionValueCopy<DataType> &>(V);
405 return compare(VC.getValue());
409 // Non-class option values.
410 template <class DataType>
411 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
412 typedef DataType WrapperType;
415 // Top-level option class.
416 template <class DataType>
417 struct OptionValue : OptionValueBase<DataType, std::is_class<DataType>::value> {
420 OptionValue(const DataType &V) { this->setValue(V); }
421 // Some options may take their value from a different data type.
422 template <class DT> OptionValue<DataType> &operator=(const DT &V) {
428 // Other safe-to-copy-by-value common option types.
429 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
431 struct OptionValue<cl::boolOrDefault> : OptionValueCopy<cl::boolOrDefault> {
432 typedef cl::boolOrDefault WrapperType;
436 OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
437 OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
443 void anchor() override;
446 template <> struct OptionValue<std::string> : OptionValueCopy<std::string> {
447 typedef StringRef WrapperType;
451 OptionValue(const std::string &V) { this->setValue(V); }
452 OptionValue<std::string> &operator=(const std::string &V) {
458 void anchor() override;
461 //===----------------------------------------------------------------------===//
462 // Enum valued command line option
464 #define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
465 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
466 #define clEnumValEnd (reinterpret_cast<void *>(0))
468 // values - For custom data types, allow specifying a group of values together
469 // as the values that go into the mapping that the option handler uses. Note
470 // that the values list must always have a 0 at the end of the list to indicate
471 // that the list has ended.
473 template <class DataType> class ValuesClass {
474 // Use a vector instead of a map, because the lists should be short,
475 // the overhead is less, and most importantly, it keeps them in the order
476 // inserted so we can print our option out nicely.
477 SmallVector<std::pair<const char *, std::pair<int, const char *>>, 4> Values;
478 void processValues(va_list Vals);
481 ValuesClass(const char *EnumName, DataType Val, const char *Desc,
483 // Insert the first value, which is required.
484 Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
486 // Process the varargs portion of the values...
487 while (const char *enumName = va_arg(ValueArgs, const char *)) {
488 DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
489 const char *EnumDesc = va_arg(ValueArgs, const char *);
490 Values.push_back(std::make_pair(enumName, // Add value to value map
491 std::make_pair(EnumVal, EnumDesc)));
495 template <class Opt> void apply(Opt &O) const {
496 for (size_t i = 0, e = Values.size(); i != e; ++i)
497 O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
498 Values[i].second.second);
502 template <class DataType>
503 ValuesClass<DataType> LLVM_END_WITH_NULL
504 values(const char *Arg, DataType Val, const char *Desc, ...) {
506 va_start(ValueArgs, Desc);
507 ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
512 //===----------------------------------------------------------------------===//
513 // parser class - Parameterizable parser for different data types. By default,
514 // known data types (string, int, bool) have specialized parsers, that do what
515 // you would expect. The default parser, used for data types that are not
516 // built-in, uses a mapping table to map specific options to values, which is
517 // used, among other things, to handle enum types.
519 //--------------------------------------------------
520 // generic_parser_base - This class holds all the non-generic code that we do
521 // not need replicated for every instance of the generic parser. This also
522 // allows us to put stuff into CommandLine.cpp
524 class generic_parser_base {
526 class GenericOptionInfo {
528 GenericOptionInfo(const char *name, const char *helpStr)
529 : Name(name), HelpStr(helpStr) {}
535 generic_parser_base(Option &O) : Owner(O) {}
537 virtual ~generic_parser_base() {} // Base class should have virtual-dtor
539 // getNumOptions - Virtual function implemented by generic subclass to
540 // indicate how many entries are in Values.
542 virtual unsigned getNumOptions() const = 0;
544 // getOption - Return option name N.
545 virtual const char *getOption(unsigned N) const = 0;
547 // getDescription - Return description N
548 virtual const char *getDescription(unsigned N) const = 0;
550 // Return the width of the option tag for printing...
551 virtual size_t getOptionWidth(const Option &O) const;
553 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
555 // printOptionInfo - Print out information about this option. The
556 // to-be-maintained width is specified.
558 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
560 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
561 const GenericOptionValue &Default,
562 size_t GlobalWidth) const;
564 // printOptionDiff - print the value of an option and it's default.
566 // Template definition ensures that the option and default have the same
567 // DataType (via the same AnyOptionValue).
568 template <class AnyOptionValue>
569 void printOptionDiff(const Option &O, const AnyOptionValue &V,
570 const AnyOptionValue &Default,
571 size_t GlobalWidth) const {
572 printGenericOptionDiff(O, V, Default, GlobalWidth);
577 void getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) {
578 // If there has been no argstr specified, that means that we need to add an
579 // argument for every possible option. This ensures that our options are
581 if (!Owner.hasArgStr())
582 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
583 OptionNames.push_back(getOption(i));
586 enum ValueExpected getValueExpectedFlagDefault() const {
587 // If there is an ArgStr specified, then we are of the form:
589 // -opt=O2 or -opt O2 or -optO2
591 // In which case, the value is required. Otherwise if an arg str has not
592 // been specified, we are of the form:
594 // -O2 or O2 or -la (where -l and -a are separate options)
596 // If this is the case, we cannot allow a value.
598 if (Owner.hasArgStr())
599 return ValueRequired;
601 return ValueDisallowed;
604 // findOption - Return the option number corresponding to the specified
605 // argument string. If the option is not found, getNumOptions() is returned.
607 unsigned findOption(const char *Name);
613 // Default parser implementation - This implementation depends on having a
614 // mapping of recognized options to values of some sort. In addition to this,
615 // each entry in the mapping also tracks a help message that is printed with the
616 // command line option for -help. Because this is a simple mapping parser, the
617 // data type can be any unsupported type.
619 template <class DataType> class parser : public generic_parser_base {
621 class OptionInfo : public GenericOptionInfo {
623 OptionInfo(const char *name, DataType v, const char *helpStr)
624 : GenericOptionInfo(name, helpStr), V(v) {}
625 OptionValue<DataType> V;
627 SmallVector<OptionInfo, 8> Values;
630 parser(Option &O) : generic_parser_base(O) {}
631 typedef DataType parser_data_type;
633 // Implement virtual functions needed by generic_parser_base
634 unsigned getNumOptions() const override { return unsigned(Values.size()); }
635 const char *getOption(unsigned N) const override { return Values[N].Name; }
636 const char *getDescription(unsigned N) const override {
637 return Values[N].HelpStr;
640 // getOptionValue - Return the value of option name N.
641 const GenericOptionValue &getOptionValue(unsigned N) const override {
645 // parse - Return true on error.
646 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
648 if (Owner.hasArgStr())
653 for (size_t i = 0, e = Values.size(); i != e; ++i)
654 if (Values[i].Name == ArgVal) {
655 V = Values[i].V.getValue();
659 return O.error("Cannot find option named '" + ArgVal + "'!");
662 /// addLiteralOption - Add an entry to the mapping table.
665 void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
666 assert(findOption(Name) == Values.size() && "Option already exists!");
667 OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
669 MarkOptionsChanged();
672 /// removeLiteralOption - Remove the specified option.
674 void removeLiteralOption(const char *Name) {
675 unsigned N = findOption(Name);
676 assert(N != Values.size() && "Option not found!");
677 Values.erase(Values.begin() + N);
681 //--------------------------------------------------
682 // basic_parser - Super class of parsers to provide boilerplate code
684 class basic_parser_impl { // non-template implementation of basic_parser<t>
686 basic_parser_impl(Option &O) {}
688 virtual ~basic_parser_impl() {}
690 enum ValueExpected getValueExpectedFlagDefault() const {
691 return ValueRequired;
694 void getExtraOptionNames(SmallVectorImpl<const char *> &) {}
698 // Return the width of the option tag for printing...
699 size_t getOptionWidth(const Option &O) const;
701 // printOptionInfo - Print out information about this option. The
702 // to-be-maintained width is specified.
704 void printOptionInfo(const Option &O, size_t GlobalWidth) const;
706 // printOptionNoValue - Print a placeholder for options that don't yet support
707 // printOptionDiff().
708 void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
710 // getValueName - Overload in subclass to provide a better default value.
711 virtual const char *getValueName() const { return "value"; }
713 // An out-of-line virtual method to provide a 'home' for this class.
714 virtual void anchor();
717 // A helper for basic_parser::printOptionDiff.
718 void printOptionName(const Option &O, size_t GlobalWidth) const;
721 // basic_parser - The real basic parser is just a template wrapper that provides
722 // a typedef for the provided data type.
724 template <class DataType> class basic_parser : public basic_parser_impl {
726 basic_parser(Option &O) : basic_parser_impl(O) {}
727 typedef DataType parser_data_type;
728 typedef OptionValue<DataType> OptVal;
731 //--------------------------------------------------
734 template <> class parser<bool> : public basic_parser<bool> {
736 parser(Option &O) : basic_parser(O) {}
738 // parse - Return true on error.
739 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
743 enum ValueExpected getValueExpectedFlagDefault() const {
744 return ValueOptional;
747 // getValueName - Do not print =<value> at all.
748 const char *getValueName() const override { return nullptr; }
750 void printOptionDiff(const Option &O, bool V, OptVal Default,
751 size_t GlobalWidth) const;
753 // An out-of-line virtual method to provide a 'home' for this class.
754 void anchor() override;
757 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<bool>);
759 //--------------------------------------------------
760 // parser<boolOrDefault>
761 template <> class parser<boolOrDefault> : public basic_parser<boolOrDefault> {
763 parser(Option &O) : basic_parser(O) {}
765 // parse - Return true on error.
766 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
768 enum ValueExpected getValueExpectedFlagDefault() const {
769 return ValueOptional;
772 // getValueName - Do not print =<value> at all.
773 const char *getValueName() const override { return nullptr; }
775 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
776 size_t GlobalWidth) const;
778 // An out-of-line virtual method to provide a 'home' for this class.
779 void anchor() override;
782 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
784 //--------------------------------------------------
787 template <> class parser<int> : public basic_parser<int> {
789 parser(Option &O) : basic_parser(O) {}
791 // parse - Return true on error.
792 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
794 // getValueName - Overload in subclass to provide a better default value.
795 const char *getValueName() const override { return "int"; }
797 void printOptionDiff(const Option &O, int V, OptVal Default,
798 size_t GlobalWidth) const;
800 // An out-of-line virtual method to provide a 'home' for this class.
801 void anchor() override;
804 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<int>);
806 //--------------------------------------------------
809 template <> class parser<unsigned> : public basic_parser<unsigned> {
811 parser(Option &O) : basic_parser(O) {}
813 // parse - Return true on error.
814 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
816 // getValueName - Overload in subclass to provide a better default value.
817 const char *getValueName() const override { return "uint"; }
819 void printOptionDiff(const Option &O, unsigned V, OptVal Default,
820 size_t GlobalWidth) const;
822 // An out-of-line virtual method to provide a 'home' for this class.
823 void anchor() override;
826 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
828 //--------------------------------------------------
829 // parser<unsigned long long>
832 class parser<unsigned long long> : public basic_parser<unsigned long long> {
834 parser(Option &O) : basic_parser(O) {}
836 // parse - Return true on error.
837 bool parse(Option &O, StringRef ArgName, StringRef Arg,
838 unsigned long long &Val);
840 // getValueName - Overload in subclass to provide a better default value.
841 const char *getValueName() const override { return "uint"; }
843 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
844 size_t GlobalWidth) const;
846 // An out-of-line virtual method to provide a 'home' for this class.
847 void anchor() override;
850 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
852 //--------------------------------------------------
855 template <> class parser<double> : public basic_parser<double> {
857 parser(Option &O) : basic_parser(O) {}
859 // parse - Return true on error.
860 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
862 // getValueName - Overload in subclass to provide a better default value.
863 const char *getValueName() const override { return "number"; }
865 void printOptionDiff(const Option &O, double V, OptVal Default,
866 size_t GlobalWidth) const;
868 // An out-of-line virtual method to provide a 'home' for this class.
869 void anchor() override;
872 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<double>);
874 //--------------------------------------------------
877 template <> class parser<float> : public basic_parser<float> {
879 parser(Option &O) : basic_parser(O) {}
881 // parse - Return true on error.
882 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
884 // getValueName - Overload in subclass to provide a better default value.
885 const char *getValueName() const override { return "number"; }
887 void printOptionDiff(const Option &O, float V, OptVal Default,
888 size_t GlobalWidth) const;
890 // An out-of-line virtual method to provide a 'home' for this class.
891 void anchor() override;
894 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<float>);
896 //--------------------------------------------------
897 // parser<std::string>
899 template <> class parser<std::string> : public basic_parser<std::string> {
901 parser(Option &O) : basic_parser(O) {}
903 // parse - Return true on error.
904 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
909 // getValueName - Overload in subclass to provide a better default value.
910 const char *getValueName() const override { return "string"; }
912 void printOptionDiff(const Option &O, StringRef V, OptVal Default,
913 size_t GlobalWidth) const;
915 // An out-of-line virtual method to provide a 'home' for this class.
916 void anchor() override;
919 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
921 //--------------------------------------------------
924 template <> class parser<char> : public basic_parser<char> {
926 parser(Option &O) : basic_parser(O) {}
928 // parse - Return true on error.
929 bool parse(Option &, StringRef, StringRef Arg, char &Value) {
934 // getValueName - Overload in subclass to provide a better default value.
935 const char *getValueName() const override { return "char"; }
937 void printOptionDiff(const Option &O, char V, OptVal Default,
938 size_t GlobalWidth) const;
940 // An out-of-line virtual method to provide a 'home' for this class.
941 void anchor() override;
944 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<char>);
946 //--------------------------------------------------
949 // This collection of wrappers is the intermediary between class opt and class
950 // parser to handle all the template nastiness.
952 // This overloaded function is selected by the generic parser.
953 template <class ParserClass, class DT>
954 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
955 const OptionValue<DT> &Default, size_t GlobalWidth) {
956 OptionValue<DT> OV = V;
957 P.printOptionDiff(O, OV, Default, GlobalWidth);
960 // This is instantiated for basic parsers when the parsed value has a different
961 // type than the option value. e.g. HelpPrinter.
962 template <class ParserDT, class ValDT> struct OptionDiffPrinter {
963 void print(const Option &O, const parser<ParserDT> P, const ValDT & /*V*/,
964 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
965 P.printOptionNoValue(O, GlobalWidth);
969 // This is instantiated for basic parsers when the parsed value has the same
970 // type as the option value.
971 template <class DT> struct OptionDiffPrinter<DT, DT> {
972 void print(const Option &O, const parser<DT> P, const DT &V,
973 const OptionValue<DT> &Default, size_t GlobalWidth) {
974 P.printOptionDiff(O, V, Default, GlobalWidth);
978 // This overloaded function is selected by the basic parser, which may parse a
979 // different type than the option type.
980 template <class ParserClass, class ValDT>
981 void printOptionDiff(
983 const basic_parser<typename ParserClass::parser_data_type> &P,
984 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
986 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
987 printer.print(O, static_cast<const ParserClass &>(P), V, Default,
991 //===----------------------------------------------------------------------===//
992 // applicator class - This class is used because we must use partial
993 // specialization to handle literal string arguments specially (const char* does
994 // not correctly respond to the apply method). Because the syntax to use this
995 // is a pain, we have the 'apply' method below to handle the nastiness...
997 template <class Mod> struct applicator {
998 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1001 // Handle const char* as a special case...
1002 template <unsigned n> struct applicator<char[n]> {
1003 template <class Opt> static void opt(const char *Str, Opt &O) {
1007 template <unsigned n> struct applicator<const char[n]> {
1008 template <class Opt> static void opt(const char *Str, Opt &O) {
1012 template <> struct applicator<const char *> {
1013 template <class Opt> static void opt(const char *Str, Opt &O) {
1018 template <> struct applicator<NumOccurrencesFlag> {
1019 static void opt(NumOccurrencesFlag N, Option &O) {
1020 O.setNumOccurrencesFlag(N);
1023 template <> struct applicator<ValueExpected> {
1024 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1026 template <> struct applicator<OptionHidden> {
1027 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1029 template <> struct applicator<FormattingFlags> {
1030 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1032 template <> struct applicator<MiscFlags> {
1033 static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1036 // apply method - Apply a modifier to an option in a type safe way.
1037 template <class Mod, class Opt> void apply(const Mod &M, Opt *O) {
1038 applicator<Mod>::opt(M, *O);
1041 //===----------------------------------------------------------------------===//
1042 // opt_storage class
1044 // Default storage class definition: external storage. This implementation
1045 // assumes the user will specify a variable to store the data into with the
1046 // cl::location(x) modifier.
1048 template <class DataType, bool ExternalStorage, bool isClass>
1050 DataType *Location; // Where to store the object...
1051 OptionValue<DataType> Default;
1053 void check_location() const {
1054 assert(Location && "cl::location(...) not specified for a command "
1055 "line option with external storage, "
1056 "or cl::init specified before cl::location()!!");
1060 opt_storage() : Location(nullptr) {}
1062 bool setLocation(Option &O, DataType &L) {
1064 return O.error("cl::location(x) specified more than once!");
1070 template <class T> void setValue(const T &V, bool initial = false) {
1077 DataType &getValue() {
1081 const DataType &getValue() const {
1086 operator DataType() const { return this->getValue(); }
1088 const OptionValue<DataType> &getDefault() const { return Default; }
1091 // Define how to hold a class type object, such as a string. Since we can
1092 // inherit from a class, we do so. This makes us exactly compatible with the
1093 // object in all cases that it is used.
1095 template <class DataType>
1096 class opt_storage<DataType, false, true> : public DataType {
1098 OptionValue<DataType> Default;
1100 template <class T> void setValue(const T &V, bool initial = false) {
1101 DataType::operator=(V);
1106 DataType &getValue() { return *this; }
1107 const DataType &getValue() const { return *this; }
1109 const OptionValue<DataType> &getDefault() const { return Default; }
1112 // Define a partial specialization to handle things we cannot inherit from. In
1113 // this case, we store an instance through containment, and overload operators
1114 // to get at the value.
1116 template <class DataType> class opt_storage<DataType, false, false> {
1119 OptionValue<DataType> Default;
1121 // Make sure we initialize the value with the default constructor for the
1123 opt_storage() : Value(DataType()), Default(DataType()) {}
1125 template <class T> void setValue(const T &V, bool initial = false) {
1130 DataType &getValue() { return Value; }
1131 DataType getValue() const { return Value; }
1133 const OptionValue<DataType> &getDefault() const { return Default; }
1135 operator DataType() const { return getValue(); }
1137 // If the datatype is a pointer, support -> on it.
1138 DataType operator->() const { return Value; }
1141 //===----------------------------------------------------------------------===//
1142 // opt - A scalar command line option.
1144 template <class DataType, bool ExternalStorage = false,
1145 class ParserClass = parser<DataType>>
1146 class opt : public Option,
1147 public opt_storage<DataType, ExternalStorage,
1148 std::is_class<DataType>::value> {
1151 bool handleOccurrence(unsigned pos, StringRef ArgName,
1152 StringRef Arg) override {
1153 typename ParserClass::parser_data_type Val =
1154 typename ParserClass::parser_data_type();
1155 if (Parser.parse(*this, ArgName, Arg, Val))
1156 return true; // Parse error!
1157 this->setValue(Val);
1158 this->setPosition(pos);
1162 enum ValueExpected getValueExpectedFlagDefault() const override {
1163 return Parser.getValueExpectedFlagDefault();
1166 getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
1167 return Parser.getExtraOptionNames(OptionNames);
1170 // Forward printing stuff to the parser...
1171 size_t getOptionWidth() const override {
1172 return Parser.getOptionWidth(*this);
1174 void printOptionInfo(size_t GlobalWidth) const override {
1175 Parser.printOptionInfo(*this, GlobalWidth);
1178 void printOptionValue(size_t GlobalWidth, bool Force) const override {
1179 if (Force || this->getDefault().compare(this->getValue())) {
1180 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1181 this->getDefault(), GlobalWidth);
1187 Parser.initialize();
1190 // Command line options should not be copyable
1191 opt(const opt &) LLVM_DELETED_FUNCTION;
1192 opt &operator=(const opt &) LLVM_DELETED_FUNCTION;
1195 // setInitialValue - Used by the cl::init modifier...
1196 void setInitialValue(const DataType &V) { this->setValue(V, true); }
1198 ParserClass &getParser() { return Parser; }
1200 template <class T> DataType &operator=(const T &Val) {
1201 this->setValue(Val);
1202 return this->getValue();
1206 template <class M0t>
1207 explicit opt(const M0t &M0)
1208 : Option(Optional, NotHidden), Parser(*this) {
1214 template <class M0t, class M1t>
1215 opt(const M0t &M0, const M1t &M1)
1216 : Option(Optional, NotHidden), Parser(*this) {
1223 template <class M0t, class M1t, class M2t>
1224 opt(const M0t &M0, const M1t &M1, const M2t &M2)
1225 : Option(Optional, NotHidden), Parser(*this) {
1232 template <class M0t, class M1t, class M2t, class M3t>
1233 opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1234 : Option(Optional, NotHidden), Parser(*this) {
1242 template <class M0t, class M1t, class M2t, class M3t, class M4t>
1243 opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3, const M4t &M4)
1244 : Option(Optional, NotHidden), Parser(*this) {
1253 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t>
1254 opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3, const M4t &M4,
1256 : Option(Optional, NotHidden), Parser(*this) {
1266 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
1268 opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3, const M4t &M4,
1269 const M5t &M5, const M6t &M6)
1270 : Option(Optional, NotHidden), Parser(*this) {
1281 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
1282 class M6t, class M7t>
1283 opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3, const M4t &M4,
1284 const M5t &M5, const M6t &M6, const M7t &M7)
1285 : Option(Optional, NotHidden), Parser(*this) {
1298 EXTERN_TEMPLATE_INSTANTIATION(class opt<unsigned>);
1299 EXTERN_TEMPLATE_INSTANTIATION(class opt<int>);
1300 EXTERN_TEMPLATE_INSTANTIATION(class opt<std::string>);
1301 EXTERN_TEMPLATE_INSTANTIATION(class opt<char>);
1302 EXTERN_TEMPLATE_INSTANTIATION(class opt<bool>);
1304 //===----------------------------------------------------------------------===//
1305 // list_storage class
1307 // Default storage class definition: external storage. This implementation
1308 // assumes the user will specify a variable to store the data into with the
1309 // cl::location(x) modifier.
1311 template <class DataType, class StorageClass> class list_storage {
1312 StorageClass *Location; // Where to store the object...
1315 list_storage() : Location(0) {}
1317 bool setLocation(Option &O, StorageClass &L) {
1319 return O.error("cl::location(x) specified more than once!");
1324 template <class T> void addValue(const T &V) {
1325 assert(Location != 0 && "cl::location(...) not specified for a command "
1326 "line option with external storage!");
1327 Location->push_back(V);
1331 // Define how to hold a class type object, such as a string. Since we can
1332 // inherit from a class, we do so. This makes us exactly compatible with the
1333 // object in all cases that it is used.
1335 template <class DataType>
1336 class list_storage<DataType, bool> : public std::vector<DataType> {
1338 template <class T> void addValue(const T &V) {
1339 std::vector<DataType>::push_back(V);
1343 //===----------------------------------------------------------------------===//
1344 // list - A list of command line options.
1346 template <class DataType, class Storage = bool,
1347 class ParserClass = parser<DataType>>
1348 class list : public Option, public list_storage<DataType, Storage> {
1349 std::vector<unsigned> Positions;
1352 enum ValueExpected getValueExpectedFlagDefault() const override {
1353 return Parser.getValueExpectedFlagDefault();
1356 getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
1357 return Parser.getExtraOptionNames(OptionNames);
1360 bool handleOccurrence(unsigned pos, StringRef ArgName,
1361 StringRef Arg) override {
1362 typename ParserClass::parser_data_type Val =
1363 typename ParserClass::parser_data_type();
1364 if (Parser.parse(*this, ArgName, Arg, Val))
1365 return true; // Parse Error!
1366 list_storage<DataType, Storage>::addValue(Val);
1368 Positions.push_back(pos);
1372 // Forward printing stuff to the parser...
1373 size_t getOptionWidth() const override {
1374 return Parser.getOptionWidth(*this);
1376 void printOptionInfo(size_t GlobalWidth) const override {
1377 Parser.printOptionInfo(*this, GlobalWidth);
1380 // Unimplemented: list options don't currently store their default value.
1381 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1386 Parser.initialize();
1389 // Command line options should not be copyable
1390 list(const list &) LLVM_DELETED_FUNCTION;
1391 list &operator=(const list &) LLVM_DELETED_FUNCTION;
1394 ParserClass &getParser() { return Parser; }
1396 unsigned getPosition(unsigned optnum) const {
1397 assert(optnum < this->size() && "Invalid option index");
1398 return Positions[optnum];
1401 void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
1404 template <class M0t>
1405 explicit list(const M0t &M0)
1406 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1411 template <class M0t, class M1t>
1412 list(const M0t &M0, const M1t &M1)
1413 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1419 template <class M0t, class M1t, class M2t>
1420 list(const M0t &M0, const M1t &M1, const M2t &M2)
1421 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1428 template <class M0t, class M1t, class M2t, class M3t>
1429 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1430 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1438 template <class M0t, class M1t, class M2t, class M3t, class M4t>
1439 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1441 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1450 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t>
1451 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1452 const M4t &M4, const M5t &M5)
1453 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1463 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
1465 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1466 const M4t &M4, const M5t &M5, const M6t &M6)
1467 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1478 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
1479 class M6t, class M7t>
1480 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1481 const M4t &M4, const M5t &M5, const M6t &M6, const M7t &M7)
1482 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1495 // multi_val - Modifier to set the number of additional values.
1497 unsigned AdditionalVals;
1498 explicit multi_val(unsigned N) : AdditionalVals(N) {}
1500 template <typename D, typename S, typename P>
1501 void apply(list<D, S, P> &L) const {
1502 L.setNumAdditionalVals(AdditionalVals);
1506 //===----------------------------------------------------------------------===//
1507 // bits_storage class
1509 // Default storage class definition: external storage. This implementation
1510 // assumes the user will specify a variable to store the data into with the
1511 // cl::location(x) modifier.
1513 template <class DataType, class StorageClass> class bits_storage {
1514 unsigned *Location; // Where to store the bits...
1516 template <class T> static unsigned Bit(const T &V) {
1517 unsigned BitPos = reinterpret_cast<unsigned>(V);
1518 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1519 "enum exceeds width of bit vector!");
1524 bits_storage() : Location(nullptr) {}
1526 bool setLocation(Option &O, unsigned &L) {
1528 return O.error("cl::location(x) specified more than once!");
1533 template <class T> void addValue(const T &V) {
1534 assert(Location != 0 && "cl::location(...) not specified for a command "
1535 "line option with external storage!");
1536 *Location |= Bit(V);
1539 unsigned getBits() { return *Location; }
1541 template <class T> bool isSet(const T &V) {
1542 return (*Location & Bit(V)) != 0;
1546 // Define how to hold bits. Since we can inherit from a class, we do so.
1547 // This makes us exactly compatible with the bits in all cases that it is used.
1549 template <class DataType> class bits_storage<DataType, bool> {
1550 unsigned Bits; // Where to store the bits...
1552 template <class T> static unsigned Bit(const T &V) {
1553 unsigned BitPos = (unsigned)V;
1554 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1555 "enum exceeds width of bit vector!");
1560 template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1562 unsigned getBits() { return Bits; }
1564 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1567 //===----------------------------------------------------------------------===//
1568 // bits - A bit vector of command options.
1570 template <class DataType, class Storage = bool,
1571 class ParserClass = parser<DataType>>
1572 class bits : public Option, public bits_storage<DataType, Storage> {
1573 std::vector<unsigned> Positions;
1576 enum ValueExpected getValueExpectedFlagDefault() const override {
1577 return Parser.getValueExpectedFlagDefault();
1580 getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
1581 return Parser.getExtraOptionNames(OptionNames);
1584 bool handleOccurrence(unsigned pos, StringRef ArgName,
1585 StringRef Arg) override {
1586 typename ParserClass::parser_data_type Val =
1587 typename ParserClass::parser_data_type();
1588 if (Parser.parse(*this, ArgName, Arg, Val))
1589 return true; // Parse Error!
1590 this->addValue(Val);
1592 Positions.push_back(pos);
1596 // Forward printing stuff to the parser...
1597 size_t getOptionWidth() const override {
1598 return Parser.getOptionWidth(*this);
1600 void printOptionInfo(size_t GlobalWidth) const override {
1601 Parser.printOptionInfo(*this, GlobalWidth);
1604 // Unimplemented: bits options don't currently store their default values.
1605 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1610 Parser.initialize();
1613 // Command line options should not be copyable
1614 bits(const bits &) LLVM_DELETED_FUNCTION;
1615 bits &operator=(const bits &) LLVM_DELETED_FUNCTION;
1618 ParserClass &getParser() { return Parser; }
1620 unsigned getPosition(unsigned optnum) const {
1621 assert(optnum < this->size() && "Invalid option index");
1622 return Positions[optnum];
1626 template <class M0t>
1627 explicit bits(const M0t &M0)
1628 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1633 template <class M0t, class M1t>
1634 bits(const M0t &M0, const M1t &M1)
1635 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1641 template <class M0t, class M1t, class M2t>
1642 bits(const M0t &M0, const M1t &M1, const M2t &M2)
1643 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1650 template <class M0t, class M1t, class M2t, class M3t>
1651 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1652 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1660 template <class M0t, class M1t, class M2t, class M3t, class M4t>
1661 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1663 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1672 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t>
1673 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1674 const M4t &M4, const M5t &M5)
1675 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1685 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
1687 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1688 const M4t &M4, const M5t &M5, const M6t &M6)
1689 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1700 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
1701 class M6t, class M7t>
1702 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1703 const M4t &M4, const M5t &M5, const M6t &M6, const M7t &M7)
1704 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1717 //===----------------------------------------------------------------------===//
1718 // Aliased command line option (alias this name to a preexisting name)
1721 class alias : public Option {
1723 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1724 StringRef Arg) override {
1725 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1727 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1728 bool MultiArg = false) override {
1729 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1731 // Handle printing stuff...
1732 size_t getOptionWidth() const override;
1733 void printOptionInfo(size_t GlobalWidth) const override;
1735 // Aliases do not need to print their values.
1736 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1739 ValueExpected getValueExpectedFlagDefault() const override {
1740 return AliasFor->getValueExpectedFlag();
1745 error("cl::alias must have argument name specified!");
1747 error("cl::alias must have an cl::aliasopt(option) specified!");
1751 // Command line options should not be copyable
1752 alias(const alias &) LLVM_DELETED_FUNCTION;
1753 alias &operator=(const alias &) LLVM_DELETED_FUNCTION;
1756 void setAliasFor(Option &O) {
1758 error("cl::alias must only have one cl::aliasopt(...) specified!");
1763 template <class M0t>
1764 explicit alias(const M0t &M0)
1765 : Option(Optional, Hidden), AliasFor(nullptr) {
1770 template <class M0t, class M1t>
1771 alias(const M0t &M0, const M1t &M1)
1772 : Option(Optional, Hidden), AliasFor(nullptr) {
1778 template <class M0t, class M1t, class M2t>
1779 alias(const M0t &M0, const M1t &M1, const M2t &M2)
1780 : Option(Optional, Hidden), AliasFor(nullptr) {
1787 template <class M0t, class M1t, class M2t, class M3t>
1788 alias(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1789 : Option(Optional, Hidden), AliasFor(nullptr) {
1798 // aliasfor - Modifier to set the option an alias aliases.
1801 explicit aliasopt(Option &O) : Opt(O) {}
1802 void apply(alias &A) const { A.setAliasFor(Opt); }
1805 // extrahelp - provide additional help at the end of the normal help
1806 // output. All occurrences of cl::extrahelp will be accumulated and
1807 // printed to stderr at the end of the regular help, just before
1810 const char *morehelp;
1811 explicit extrahelp(const char *help);
1814 void PrintVersionMessage();
1816 /// This function just prints the help message, exactly the same way as if the
1817 /// -help or -help-hidden option had been given on the command line.
1819 /// NOTE: THIS FUNCTION TERMINATES THE PROGRAM!
1821 /// \param Hidden if true will print hidden options
1822 /// \param Categorized if true print options in categories
1823 void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
1825 //===----------------------------------------------------------------------===//
1826 // Public interface for accessing registered options.
1829 /// \brief Use this to get a StringMap to all registered named options
1830 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1832 /// \param [out] Map will be filled with mappings where the key is the
1833 /// Option argument string (e.g. "help") and value is the corresponding
1836 /// Access to unnamed arguments (i.e. positional) are not provided because
1837 /// it is expected that the client already has access to these.
1841 /// main(int argc,char* argv[]) {
1842 /// StringMap<llvm::cl::Option*> opts;
1843 /// llvm::cl::getRegisteredOptions(opts);
1844 /// assert(opts.count("help") == 1)
1845 /// opts["help"]->setDescription("Show alphabetical help information")
1847 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1852 /// This interface is useful for modifying options in libraries that are out of
1853 /// the control of the client. The options should be modified before calling
1854 /// llvm::cl::ParseCommandLineOptions().
1855 void getRegisteredOptions(StringMap<Option *> &Map);
1857 //===----------------------------------------------------------------------===//
1858 // Standalone command line processing utilities.
1861 /// \brief Saves strings in the inheritor's stable storage and returns a stable
1862 /// raw character pointer.
1864 virtual void anchor();
1867 virtual const char *SaveString(const char *Str) = 0;
1868 virtual ~StringSaver(){}; // Pacify -Wnon-virtual-dtor.
1871 /// \brief Tokenizes a command line that can contain escapes and quotes.
1873 /// The quoting rules match those used by GCC and other tools that use
1874 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1875 /// They differ from buildargv() on treatment of backslashes that do not escape
1876 /// a special character to make it possible to accept most Windows file paths.
1878 /// \param [in] Source The string to be split on whitespace with quotes.
1879 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1880 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1881 /// lines and end of the response file to be marked with a nullptr string.
1882 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1883 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
1884 SmallVectorImpl<const char *> &NewArgv,
1885 bool MarkEOLs = false);
1887 /// \brief Tokenizes a Windows command line which may contain quotes and escaped
1890 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1891 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1893 /// \param [in] Source The string to be split on whitespace with quotes.
1894 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1895 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1896 /// lines and end of the response file to be marked with a nullptr string.
1897 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1898 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
1899 SmallVectorImpl<const char *> &NewArgv,
1900 bool MarkEOLs = false);
1902 /// \brief String tokenization function type. Should be compatible with either
1903 /// Windows or Unix command line tokenizers.
1904 typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
1905 SmallVectorImpl<const char *> &NewArgv,
1908 /// \brief Expand response files on a command line recursively using the given
1909 /// StringSaver and tokenization strategy. Argv should contain the command line
1910 /// before expansion and will be modified in place. If requested, Argv will
1911 /// also be populated with nullptrs indicating where each response file line
1912 /// ends, which is useful for the "/link" argument that needs to consume all
1913 /// remaining arguments only until the next end of line, when in a response
1916 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1917 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1918 /// \param [in,out] Argv Command line into which to expand response files.
1919 /// \param [in] MarkEOLs Mark end of lines and the end of the response file
1920 /// with nullptrs in the Argv vector.
1921 /// \return true if all @files were expanded successfully or there were none.
1922 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1923 SmallVectorImpl<const char *> &Argv,
1924 bool MarkEOLs = false);
1926 /// \brief Mark all options not part of this category as cl::ReallyHidden.
1928 /// \param Category the category of options to keep displaying
1930 /// Some tools (like clang-format) like to be able to hide all options that are
1931 /// not specific to the tool. This function allows a tool to specify a single
1932 /// option category to display in the -help output.
1933 void HideUnrelatedOptions(cl::OptionCategory &Category);
1935 /// \brief Mark all options not part of the categories as cl::ReallyHidden.
1937 /// \param Categories the categories of options to keep displaying.
1939 /// Some tools (like clang-format) like to be able to hide all options that are
1940 /// not specific to the tool. This function allows a tool to specify a single
1941 /// option category to display in the -help output.
1942 void HideUnrelatedOptions(ArrayRef<cl::OptionCategory *> Categories);
1944 } // End namespace cl
1946 } // End namespace llvm