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/iterator_range.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/ManagedStatic.h"
36 #include <initializer_list>
38 #include <type_traits>
45 /// cl Namespace - This namespace contains all of the command line option
46 /// processing machinery. It is intentionally a short name to make qualified
50 //===----------------------------------------------------------------------===//
51 // ParseCommandLineOptions - Command line option processing entry point.
53 // Returns true on success. Otherwise, this will print the error message to
54 // stderr and exit if \p Errs is not set (nullptr by default), or print the
55 // error message to \p Errs and return false if \p Errs is provided.
56 bool ParseCommandLineOptions(int argc, const char *const *argv,
57 StringRef Overview = "",
58 raw_ostream *Errs = nullptr);
60 //===----------------------------------------------------------------------===//
61 // ParseEnvironmentOptions - Environment variable option processing alternate
64 void ParseEnvironmentOptions(const char *progName, const char *envvar,
65 const char *Overview = "");
67 ///===---------------------------------------------------------------------===//
68 /// SetVersionPrinter - Override the default (LLVM specific) version printer
69 /// used to print out the version when --version is given
70 /// on the command line. This allows other systems using the
71 /// CommandLine utilities to print their own version string.
72 void SetVersionPrinter(void (*func)());
74 ///===---------------------------------------------------------------------===//
75 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
76 /// default one. This can be called multiple times,
77 /// and each time it adds a new function to the list
78 /// which will be called after the basic LLVM version
79 /// printing is complete. Each can then add additional
80 /// information specific to the tool.
81 void AddExtraVersionPrinter(void (*func)());
83 // PrintOptionValues - Print option values.
84 // With -print-options print the difference between option values and defaults.
85 // With -print-all-options print all option values.
86 // (Currently not perfect, but best-effort.)
87 void PrintOptionValues();
89 // Forward declaration - AddLiteralOption needs to be up here to make gcc happy.
92 /// \brief Adds a new option for parsing and provides the option it refers to.
94 /// \param O pointer to the option
95 /// \param Name the string name for the option to handle during parsing
97 /// Literal options are used by some parsers to register special option values.
98 /// This is how the PassNameParser registers pass names for opt.
99 void AddLiteralOption(Option &O, StringRef Name);
101 //===----------------------------------------------------------------------===//
102 // Flags permitted to be passed to command line arguments
105 enum NumOccurrencesFlag { // Flags for the number of occurrences allowed
106 Optional = 0x00, // Zero or One occurrence
107 ZeroOrMore = 0x01, // Zero or more occurrences allowed
108 Required = 0x02, // One occurrence required
109 OneOrMore = 0x03, // One or more occurrences required
111 // ConsumeAfter - Indicates that this option is fed anything that follows the
112 // last positional argument required by the application (it is an error if
113 // there are zero positional arguments, and a ConsumeAfter option is used).
114 // Thus, for example, all arguments to LLI are processed until a filename is
115 // found. Once a filename is found, all of the succeeding arguments are
116 // passed, unprocessed, to the ConsumeAfter option.
121 enum ValueExpected { // Is a value required for the option?
122 // zero reserved for the unspecified value
123 ValueOptional = 0x01, // The value can appear... or not
124 ValueRequired = 0x02, // The value is required to appear!
125 ValueDisallowed = 0x03 // A value may not be specified (for flags)
128 enum OptionHidden { // Control whether -help shows this option
129 NotHidden = 0x00, // Option included in -help & -help-hidden
130 Hidden = 0x01, // -help doesn't, but -help-hidden does
131 ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg
134 // Formatting flags - This controls special features that the option might have
135 // that cause it to be parsed differently...
137 // Prefix - This option allows arguments that are otherwise unrecognized to be
138 // matched by options that are a prefix of the actual value. This is useful for
139 // cases like a linker, where options are typically of the form '-lfoo' or
140 // '-L../../include' where -l or -L are the actual flags. When prefix is
141 // enabled, and used, the value for the flag comes from the suffix of the
144 // Grouping - With this option enabled, multiple letter options are allowed to
145 // bunch together with only a single hyphen for the whole group. This allows
146 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
149 enum FormattingFlags {
150 NormalFormatting = 0x00, // Nothing special
151 Positional = 0x01, // Is a positional argument, no '-' required
152 Prefix = 0x02, // Can this option directly prefix its value?
153 Grouping = 0x03 // Can this option group with other options?
156 enum MiscFlags { // Miscellaneous flags to adjust argument
157 CommaSeparated = 0x01, // Should this cl::list split between commas?
158 PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args?
159 Sink = 0x04 // Should this cl::list eat all unknown options?
162 //===----------------------------------------------------------------------===//
163 // Option Category class
165 class OptionCategory {
167 StringRef const Name;
168 StringRef const Description;
170 void registerCategory();
173 OptionCategory(StringRef const Name,
174 StringRef const Description = "")
175 : Name(Name), Description(Description) {
179 StringRef getName() const { return Name; }
180 StringRef getDescription() const { return Description; }
183 // The general Option Category (used as default category).
184 extern OptionCategory GeneralCategory;
186 //===----------------------------------------------------------------------===//
192 StringRef Description;
195 void registerSubCommand();
196 void unregisterSubCommand();
199 SubCommand(StringRef Name, StringRef Description = "")
200 : Name(Name), Description(Description) {
201 registerSubCommand();
203 SubCommand() = default;
207 explicit operator bool() const;
209 StringRef getName() const { return Name; }
210 StringRef getDescription() const { return Description; }
212 SmallVector<Option *, 4> PositionalOpts;
213 SmallVector<Option *, 4> SinkOpts;
214 StringMap<Option *> OptionsMap;
216 Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists.
219 // A special subcommand representing no subcommand
220 extern ManagedStatic<SubCommand> TopLevelSubCommand;
222 // A special subcommand that can be used to put an option into all subcommands.
223 extern ManagedStatic<SubCommand> AllSubCommands;
225 //===----------------------------------------------------------------------===//
231 // handleOccurrences - Overriden by subclasses to handle the value passed into
232 // an argument. Should return true if there was an error processing the
233 // argument and the program should exit.
235 virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
238 virtual enum ValueExpected getValueExpectedFlagDefault() const {
239 return ValueOptional;
242 // Out of line virtual function to provide home for the class.
243 virtual void anchor();
245 int NumOccurrences; // The number of times specified
246 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
247 // problems with signed enums in bitfields.
248 unsigned Occurrences : 3; // enum NumOccurrencesFlag
249 // not using the enum type for 'Value' because zero is an implementation
250 // detail representing the non-value
252 unsigned HiddenFlag : 2; // enum OptionHidden
253 unsigned Formatting : 2; // enum FormattingFlags
255 unsigned Position; // Position of last occurrence of the option
256 unsigned AdditionalVals; // Greater than 0 for multi-valued option.
259 StringRef ArgStr; // The argument string itself (ex: "help", "o")
260 StringRef HelpStr; // The descriptive text message for -help
261 StringRef ValueStr; // String describing what the value of this option is
262 OptionCategory *Category; // The Category this option belongs to
263 SmallPtrSet<SubCommand *, 4> Subs; // The subcommands this option belongs to.
264 bool FullyInitialized; // Has addArguemnt been called?
266 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
267 return (enum NumOccurrencesFlag)Occurrences;
270 inline enum ValueExpected getValueExpectedFlag() const {
271 return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
274 inline enum OptionHidden getOptionHiddenFlag() const {
275 return (enum OptionHidden)HiddenFlag;
278 inline enum FormattingFlags getFormattingFlag() const {
279 return (enum FormattingFlags)Formatting;
282 inline unsigned getMiscFlags() const { return Misc; }
283 inline unsigned getPosition() const { return Position; }
284 inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
286 // hasArgStr - Return true if the argstr != ""
287 bool hasArgStr() const { return !ArgStr.empty(); }
288 bool isPositional() const { return getFormattingFlag() == cl::Positional; }
289 bool isSink() const { return getMiscFlags() & cl::Sink; }
291 bool isConsumeAfter() const {
292 return getNumOccurrencesFlag() == cl::ConsumeAfter;
295 bool isInAllSubCommands() const {
296 return any_of(Subs, [](const SubCommand *SC) {
297 return SC == &*AllSubCommands;
301 //-------------------------------------------------------------------------===
302 // Accessor functions set by OptionModifiers
304 void setArgStr(StringRef S);
305 void setDescription(StringRef S) { HelpStr = S; }
306 void setValueStr(StringRef S) { ValueStr = S; }
307 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
308 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
309 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
310 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
311 void setMiscFlag(enum MiscFlags M) { Misc |= M; }
312 void setPosition(unsigned pos) { Position = pos; }
313 void setCategory(OptionCategory &C) { Category = &C; }
314 void addSubCommand(SubCommand &S) { Subs.insert(&S); }
317 explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
318 enum OptionHidden Hidden)
319 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
320 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0),
321 AdditionalVals(0), Category(&GeneralCategory), FullyInitialized(false) {
324 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
327 virtual ~Option() = default;
329 // addArgument - Register this argument with the commandline system.
333 /// Unregisters this option from the CommandLine system.
335 /// This option must have been the last option registered.
336 /// For testing purposes only.
337 void removeArgument();
339 // Return the width of the option tag for printing...
340 virtual size_t getOptionWidth() const = 0;
342 // printOptionInfo - Print out information about this option. The
343 // to-be-maintained width is specified.
345 virtual void printOptionInfo(size_t GlobalWidth) const = 0;
347 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
349 static void printHelpStr(StringRef HelpStr, size_t Indent,
350 size_t FirstLineIndentedBy);
352 virtual void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
354 // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
356 virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
357 bool MultiArg = false);
359 // Prints option name followed by message. Always returns true.
360 bool error(const Twine &Message, StringRef ArgName = StringRef());
362 inline int getNumOccurrences() const { return NumOccurrences; }
363 inline void reset() { NumOccurrences = 0; }
366 //===----------------------------------------------------------------------===//
367 // Command line option modifiers that can be used to modify the behavior of
368 // command line option parsers...
371 // desc - Modifier to set the description shown in the -help output...
375 desc(StringRef Str) : Desc(Str) {}
377 void apply(Option &O) const { O.setDescription(Desc); }
380 // value_desc - Modifier to set the value description shown in the -help
385 value_desc(StringRef Str) : Desc(Str) {}
387 void apply(Option &O) const { O.setValueStr(Desc); }
390 // init - Specify a default (initial) value for the command line argument, if
391 // the default constructor for the argument type does not give you what you
392 // want. This is only valid on "opt" arguments, not on "list" arguments.
394 template <class Ty> struct initializer {
396 initializer(const Ty &Val) : Init(Val) {}
398 template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
401 template <class Ty> initializer<Ty> init(const Ty &Val) {
402 return initializer<Ty>(Val);
405 // location - Allow the user to specify which external variable they want to
406 // store the results of the command line argument processing into, if they don't
407 // want to store it in the option itself.
409 template <class Ty> struct LocationClass {
412 LocationClass(Ty &L) : Loc(L) {}
414 template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
417 template <class Ty> LocationClass<Ty> location(Ty &L) {
418 return LocationClass<Ty>(L);
421 // cat - Specifiy the Option category for the command line argument to belong
424 OptionCategory &Category;
426 cat(OptionCategory &c) : Category(c) {}
428 template <class Opt> void apply(Opt &O) const { O.setCategory(Category); }
431 // sub - Specify the subcommand that this option belongs to.
435 sub(SubCommand &S) : Sub(S) {}
437 template <class Opt> void apply(Opt &O) const { O.addSubCommand(Sub); }
440 //===----------------------------------------------------------------------===//
443 // Support value comparison outside the template.
444 struct GenericOptionValue {
445 virtual bool compare(const GenericOptionValue &V) const = 0;
448 GenericOptionValue() = default;
449 GenericOptionValue(const GenericOptionValue&) = default;
450 ~GenericOptionValue() = default;
451 GenericOptionValue &operator=(const GenericOptionValue &) = default;
454 virtual void anchor();
457 template <class DataType> struct OptionValue;
459 // The default value safely does nothing. Option value printing is only
461 template <class DataType, bool isClass>
462 struct OptionValueBase : public GenericOptionValue {
463 // Temporary storage for argument passing.
464 typedef OptionValue<DataType> WrapperType;
466 bool hasValue() const { return false; }
468 const DataType &getValue() const { llvm_unreachable("no default value"); }
470 // Some options may take their value from a different data type.
471 template <class DT> void setValue(const DT & /*V*/) {}
473 bool compare(const DataType & /*V*/) const { return false; }
475 bool compare(const GenericOptionValue & /*V*/) const override {
480 ~OptionValueBase() = default;
483 // Simple copy of the option value.
484 template <class DataType> class OptionValueCopy : public GenericOptionValue {
489 OptionValueCopy(const OptionValueCopy&) = default;
490 ~OptionValueCopy() = default;
491 OptionValueCopy &operator=(const OptionValueCopy&) = default;
494 OptionValueCopy() = default;
496 bool hasValue() const { return Valid; }
498 const DataType &getValue() const {
499 assert(Valid && "invalid option value");
503 void setValue(const DataType &V) {
508 bool compare(const DataType &V) const { return Valid && (Value != V); }
510 bool compare(const GenericOptionValue &V) const override {
511 const OptionValueCopy<DataType> &VC =
512 static_cast<const OptionValueCopy<DataType> &>(V);
515 return compare(VC.getValue());
519 // Non-class option values.
520 template <class DataType>
521 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
522 typedef DataType WrapperType;
525 OptionValueBase() = default;
526 OptionValueBase(const OptionValueBase&) = default;
527 ~OptionValueBase() = default;
528 OptionValueBase &operator=(const OptionValueBase&) = default;
531 // Top-level option class.
532 template <class DataType>
533 struct OptionValue final
534 : OptionValueBase<DataType, std::is_class<DataType>::value> {
535 OptionValue() = default;
537 OptionValue(const DataType &V) { this->setValue(V); }
539 // Some options may take their value from a different data type.
540 template <class DT> OptionValue<DataType> &operator=(const DT &V) {
546 // Other safe-to-copy-by-value common option types.
547 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
549 struct OptionValue<cl::boolOrDefault> final
550 : OptionValueCopy<cl::boolOrDefault> {
551 typedef cl::boolOrDefault WrapperType;
553 OptionValue() = default;
555 OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
557 OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
563 void anchor() override;
567 struct OptionValue<std::string> final : OptionValueCopy<std::string> {
568 typedef StringRef WrapperType;
570 OptionValue() = default;
572 OptionValue(const std::string &V) { this->setValue(V); }
574 OptionValue<std::string> &operator=(const std::string &V) {
580 void anchor() override;
583 //===----------------------------------------------------------------------===//
584 // Enum valued command line option
587 // This represents a single enum value, using "int" as the underlying type.
588 struct OptionEnumValue {
591 StringRef Description;
594 #define clEnumVal(ENUMVAL, DESC) \
595 llvm::cl::OptionEnumValue { #ENUMVAL, int(ENUMVAL), DESC }
596 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) \
597 llvm::cl::OptionEnumValue { FLAGNAME, int(ENUMVAL), DESC }
599 // values - For custom data types, allow specifying a group of values together
600 // as the values that go into the mapping that the option handler uses.
603 // Use a vector instead of a map, because the lists should be short,
604 // the overhead is less, and most importantly, it keeps them in the order
605 // inserted so we can print our option out nicely.
606 SmallVector<OptionEnumValue, 4> Values;
609 ValuesClass(std::initializer_list<OptionEnumValue> Options)
612 template <class Opt> void apply(Opt &O) const {
613 for (auto Value : Values)
614 O.getParser().addLiteralOption(Value.Name, Value.Value,
619 /// Helper to build a ValuesClass by forwarding a variable number of arguments
620 /// as an initializer list to the ValuesClass constructor.
621 template <typename... OptsTy> ValuesClass values(OptsTy... Options) {
622 return ValuesClass({Options...});
625 //===----------------------------------------------------------------------===//
626 // parser class - Parameterizable parser for different data types. By default,
627 // known data types (string, int, bool) have specialized parsers, that do what
628 // you would expect. The default parser, used for data types that are not
629 // built-in, uses a mapping table to map specific options to values, which is
630 // used, among other things, to handle enum types.
632 //--------------------------------------------------
633 // generic_parser_base - This class holds all the non-generic code that we do
634 // not need replicated for every instance of the generic parser. This also
635 // allows us to put stuff into CommandLine.cpp
637 class generic_parser_base {
639 class GenericOptionInfo {
641 GenericOptionInfo(StringRef name, StringRef helpStr)
642 : Name(name), HelpStr(helpStr) {}
648 generic_parser_base(Option &O) : Owner(O) {}
650 virtual ~generic_parser_base() = default;
651 // Base class should have virtual-destructor
653 // getNumOptions - Virtual function implemented by generic subclass to
654 // indicate how many entries are in Values.
656 virtual unsigned getNumOptions() const = 0;
658 // getOption - Return option name N.
659 virtual StringRef getOption(unsigned N) const = 0;
661 // getDescription - Return description N
662 virtual StringRef getDescription(unsigned N) const = 0;
664 // Return the width of the option tag for printing...
665 virtual size_t getOptionWidth(const Option &O) const;
667 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
669 // printOptionInfo - Print out information about this option. The
670 // to-be-maintained width is specified.
672 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
674 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
675 const GenericOptionValue &Default,
676 size_t GlobalWidth) const;
678 // printOptionDiff - print the value of an option and it's default.
680 // Template definition ensures that the option and default have the same
681 // DataType (via the same AnyOptionValue).
682 template <class AnyOptionValue>
683 void printOptionDiff(const Option &O, const AnyOptionValue &V,
684 const AnyOptionValue &Default,
685 size_t GlobalWidth) const {
686 printGenericOptionDiff(O, V, Default, GlobalWidth);
691 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) {
692 // If there has been no argstr specified, that means that we need to add an
693 // argument for every possible option. This ensures that our options are
695 if (!Owner.hasArgStr())
696 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
697 OptionNames.push_back(getOption(i));
700 enum ValueExpected getValueExpectedFlagDefault() const {
701 // If there is an ArgStr specified, then we are of the form:
703 // -opt=O2 or -opt O2 or -optO2
705 // In which case, the value is required. Otherwise if an arg str has not
706 // been specified, we are of the form:
708 // -O2 or O2 or -la (where -l and -a are separate options)
710 // If this is the case, we cannot allow a value.
712 if (Owner.hasArgStr())
713 return ValueRequired;
715 return ValueDisallowed;
718 // findOption - Return the option number corresponding to the specified
719 // argument string. If the option is not found, getNumOptions() is returned.
721 unsigned findOption(StringRef Name);
727 // Default parser implementation - This implementation depends on having a
728 // mapping of recognized options to values of some sort. In addition to this,
729 // each entry in the mapping also tracks a help message that is printed with the
730 // command line option for -help. Because this is a simple mapping parser, the
731 // data type can be any unsupported type.
733 template <class DataType> class parser : public generic_parser_base {
735 class OptionInfo : public GenericOptionInfo {
737 OptionInfo(StringRef name, DataType v, StringRef helpStr)
738 : GenericOptionInfo(name, helpStr), V(v) {}
739 OptionValue<DataType> V;
741 SmallVector<OptionInfo, 8> Values;
744 parser(Option &O) : generic_parser_base(O) {}
745 typedef DataType parser_data_type;
747 // Implement virtual functions needed by generic_parser_base
748 unsigned getNumOptions() const override { return unsigned(Values.size()); }
749 StringRef getOption(unsigned N) const override { return Values[N].Name; }
750 StringRef getDescription(unsigned N) const override {
751 return Values[N].HelpStr;
754 // getOptionValue - Return the value of option name N.
755 const GenericOptionValue &getOptionValue(unsigned N) const override {
759 // parse - Return true on error.
760 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
762 if (Owner.hasArgStr())
767 for (size_t i = 0, e = Values.size(); i != e; ++i)
768 if (Values[i].Name == ArgVal) {
769 V = Values[i].V.getValue();
773 return O.error("Cannot find option named '" + ArgVal + "'!");
776 /// addLiteralOption - Add an entry to the mapping table.
779 void addLiteralOption(StringRef Name, const DT &V, StringRef HelpStr) {
780 assert(findOption(Name) == Values.size() && "Option already exists!");
781 OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
783 AddLiteralOption(Owner, Name);
786 /// removeLiteralOption - Remove the specified option.
788 void removeLiteralOption(StringRef Name) {
789 unsigned N = findOption(Name);
790 assert(N != Values.size() && "Option not found!");
791 Values.erase(Values.begin() + N);
795 //--------------------------------------------------
796 // basic_parser - Super class of parsers to provide boilerplate code
798 class basic_parser_impl { // non-template implementation of basic_parser<t>
800 basic_parser_impl(Option &) {}
802 enum ValueExpected getValueExpectedFlagDefault() const {
803 return ValueRequired;
806 void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
810 // Return the width of the option tag for printing...
811 size_t getOptionWidth(const Option &O) const;
813 // printOptionInfo - Print out information about this option. The
814 // to-be-maintained width is specified.
816 void printOptionInfo(const Option &O, size_t GlobalWidth) const;
818 // printOptionNoValue - Print a placeholder for options that don't yet support
819 // printOptionDiff().
820 void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
822 // getValueName - Overload in subclass to provide a better default value.
823 virtual StringRef getValueName() const { return "value"; }
825 // An out-of-line virtual method to provide a 'home' for this class.
826 virtual void anchor();
829 ~basic_parser_impl() = default;
831 // A helper for basic_parser::printOptionDiff.
832 void printOptionName(const Option &O, size_t GlobalWidth) const;
835 // basic_parser - The real basic parser is just a template wrapper that provides
836 // a typedef for the provided data type.
838 template <class DataType> class basic_parser : public basic_parser_impl {
840 basic_parser(Option &O) : basic_parser_impl(O) {}
842 typedef DataType parser_data_type;
843 typedef OptionValue<DataType> OptVal;
846 ~basic_parser() = default;
849 //--------------------------------------------------
852 template <> class parser<bool> final : public basic_parser<bool> {
854 parser(Option &O) : basic_parser(O) {}
856 // parse - Return true on error.
857 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
861 enum ValueExpected getValueExpectedFlagDefault() const {
862 return ValueOptional;
865 // getValueName - Do not print =<value> at all.
866 StringRef getValueName() const override { return StringRef(); }
868 void printOptionDiff(const Option &O, bool V, OptVal Default,
869 size_t GlobalWidth) const;
871 // An out-of-line virtual method to provide a 'home' for this class.
872 void anchor() override;
875 extern template class basic_parser<bool>;
877 //--------------------------------------------------
878 // parser<boolOrDefault>
880 class parser<boolOrDefault> final : public basic_parser<boolOrDefault> {
882 parser(Option &O) : basic_parser(O) {}
884 // parse - Return true on error.
885 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
887 enum ValueExpected getValueExpectedFlagDefault() const {
888 return ValueOptional;
891 // getValueName - Do not print =<value> at all.
892 StringRef getValueName() const override { return StringRef(); }
894 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
895 size_t GlobalWidth) const;
897 // An out-of-line virtual method to provide a 'home' for this class.
898 void anchor() override;
901 extern template class basic_parser<boolOrDefault>;
903 //--------------------------------------------------
906 template <> class parser<int> final : public basic_parser<int> {
908 parser(Option &O) : basic_parser(O) {}
910 // parse - Return true on error.
911 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
913 // getValueName - Overload in subclass to provide a better default value.
914 StringRef getValueName() const override { return "int"; }
916 void printOptionDiff(const Option &O, int V, OptVal Default,
917 size_t GlobalWidth) const;
919 // An out-of-line virtual method to provide a 'home' for this class.
920 void anchor() override;
923 extern template class basic_parser<int>;
925 //--------------------------------------------------
928 template <> class parser<unsigned> final : public basic_parser<unsigned> {
930 parser(Option &O) : basic_parser(O) {}
932 // parse - Return true on error.
933 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
935 // getValueName - Overload in subclass to provide a better default value.
936 StringRef getValueName() const override { return "uint"; }
938 void printOptionDiff(const Option &O, unsigned V, OptVal Default,
939 size_t GlobalWidth) const;
941 // An out-of-line virtual method to provide a 'home' for this class.
942 void anchor() override;
945 extern template class basic_parser<unsigned>;
947 //--------------------------------------------------
948 // parser<unsigned long long>
951 class parser<unsigned long long> final
952 : public basic_parser<unsigned long long> {
954 parser(Option &O) : basic_parser(O) {}
956 // parse - Return true on error.
957 bool parse(Option &O, StringRef ArgName, StringRef Arg,
958 unsigned long long &Val);
960 // getValueName - Overload in subclass to provide a better default value.
961 StringRef getValueName() const override { return "uint"; }
963 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
964 size_t GlobalWidth) const;
966 // An out-of-line virtual method to provide a 'home' for this class.
967 void anchor() override;
970 extern template class basic_parser<unsigned long long>;
972 //--------------------------------------------------
975 template <> class parser<double> final : public basic_parser<double> {
977 parser(Option &O) : basic_parser(O) {}
979 // parse - Return true on error.
980 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
982 // getValueName - Overload in subclass to provide a better default value.
983 StringRef getValueName() const override { return "number"; }
985 void printOptionDiff(const Option &O, double V, OptVal Default,
986 size_t GlobalWidth) const;
988 // An out-of-line virtual method to provide a 'home' for this class.
989 void anchor() override;
992 extern template class basic_parser<double>;
994 //--------------------------------------------------
997 template <> class parser<float> final : public basic_parser<float> {
999 parser(Option &O) : basic_parser(O) {}
1001 // parse - Return true on error.
1002 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
1004 // getValueName - Overload in subclass to provide a better default value.
1005 StringRef getValueName() const override { return "number"; }
1007 void printOptionDiff(const Option &O, float V, OptVal Default,
1008 size_t GlobalWidth) const;
1010 // An out-of-line virtual method to provide a 'home' for this class.
1011 void anchor() override;
1014 extern template class basic_parser<float>;
1016 //--------------------------------------------------
1017 // parser<std::string>
1019 template <> class parser<std::string> final : public basic_parser<std::string> {
1021 parser(Option &O) : basic_parser(O) {}
1023 // parse - Return true on error.
1024 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
1029 // getValueName - Overload in subclass to provide a better default value.
1030 StringRef getValueName() const override { return "string"; }
1032 void printOptionDiff(const Option &O, StringRef V, const OptVal &Default,
1033 size_t GlobalWidth) const;
1035 // An out-of-line virtual method to provide a 'home' for this class.
1036 void anchor() override;
1039 extern template class basic_parser<std::string>;
1041 //--------------------------------------------------
1044 template <> class parser<char> final : public basic_parser<char> {
1046 parser(Option &O) : basic_parser(O) {}
1048 // parse - Return true on error.
1049 bool parse(Option &, StringRef, StringRef Arg, char &Value) {
1054 // getValueName - Overload in subclass to provide a better default value.
1055 StringRef getValueName() const override { return "char"; }
1057 void printOptionDiff(const Option &O, char V, OptVal Default,
1058 size_t GlobalWidth) const;
1060 // An out-of-line virtual method to provide a 'home' for this class.
1061 void anchor() override;
1064 extern template class basic_parser<char>;
1066 //--------------------------------------------------
1069 // This collection of wrappers is the intermediary between class opt and class
1070 // parser to handle all the template nastiness.
1072 // This overloaded function is selected by the generic parser.
1073 template <class ParserClass, class DT>
1074 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
1075 const OptionValue<DT> &Default, size_t GlobalWidth) {
1076 OptionValue<DT> OV = V;
1077 P.printOptionDiff(O, OV, Default, GlobalWidth);
1080 // This is instantiated for basic parsers when the parsed value has a different
1081 // type than the option value. e.g. HelpPrinter.
1082 template <class ParserDT, class ValDT> struct OptionDiffPrinter {
1083 void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/,
1084 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
1085 P.printOptionNoValue(O, GlobalWidth);
1089 // This is instantiated for basic parsers when the parsed value has the same
1090 // type as the option value.
1091 template <class DT> struct OptionDiffPrinter<DT, DT> {
1092 void print(const Option &O, const parser<DT> &P, const DT &V,
1093 const OptionValue<DT> &Default, size_t GlobalWidth) {
1094 P.printOptionDiff(O, V, Default, GlobalWidth);
1098 // This overloaded function is selected by the basic parser, which may parse a
1099 // different type than the option type.
1100 template <class ParserClass, class ValDT>
1101 void printOptionDiff(
1103 const basic_parser<typename ParserClass::parser_data_type> &P,
1104 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
1106 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
1107 printer.print(O, static_cast<const ParserClass &>(P), V, Default,
1111 //===----------------------------------------------------------------------===//
1112 // applicator class - This class is used because we must use partial
1113 // specialization to handle literal string arguments specially (const char* does
1114 // not correctly respond to the apply method). Because the syntax to use this
1115 // is a pain, we have the 'apply' method below to handle the nastiness...
1117 template <class Mod> struct applicator {
1118 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1121 // Handle const char* as a special case...
1122 template <unsigned n> struct applicator<char[n]> {
1123 template <class Opt> static void opt(StringRef Str, Opt &O) {
1127 template <unsigned n> struct applicator<const char[n]> {
1128 template <class Opt> static void opt(StringRef Str, Opt &O) {
1132 template <> struct applicator<StringRef > {
1133 template <class Opt> static void opt(StringRef Str, Opt &O) {
1138 template <> struct applicator<NumOccurrencesFlag> {
1139 static void opt(NumOccurrencesFlag N, Option &O) {
1140 O.setNumOccurrencesFlag(N);
1144 template <> struct applicator<ValueExpected> {
1145 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1148 template <> struct applicator<OptionHidden> {
1149 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1152 template <> struct applicator<FormattingFlags> {
1153 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1156 template <> struct applicator<MiscFlags> {
1157 static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1160 // apply method - Apply modifiers to an option in a type safe way.
1161 template <class Opt, class Mod, class... Mods>
1162 void apply(Opt *O, const Mod &M, const Mods &... Ms) {
1163 applicator<Mod>::opt(M, *O);
1167 template <class Opt, class Mod> void apply(Opt *O, const Mod &M) {
1168 applicator<Mod>::opt(M, *O);
1171 //===----------------------------------------------------------------------===//
1172 // opt_storage class
1174 // Default storage class definition: external storage. This implementation
1175 // assumes the user will specify a variable to store the data into with the
1176 // cl::location(x) modifier.
1178 template <class DataType, bool ExternalStorage, bool isClass>
1180 DataType *Location = nullptr; // Where to store the object...
1181 OptionValue<DataType> Default;
1183 void check_location() const {
1184 assert(Location && "cl::location(...) not specified for a command "
1185 "line option with external storage, "
1186 "or cl::init specified before cl::location()!!");
1190 opt_storage() = default;
1192 bool setLocation(Option &O, DataType &L) {
1194 return O.error("cl::location(x) specified more than once!");
1200 template <class T> void setValue(const T &V, bool initial = false) {
1207 DataType &getValue() {
1211 const DataType &getValue() const {
1216 operator DataType() const { return this->getValue(); }
1218 const OptionValue<DataType> &getDefault() const { return Default; }
1221 // Define how to hold a class type object, such as a string. Since we can
1222 // inherit from a class, we do so. This makes us exactly compatible with the
1223 // object in all cases that it is used.
1225 template <class DataType>
1226 class opt_storage<DataType, false, true> : public DataType {
1228 OptionValue<DataType> Default;
1230 template <class T> void setValue(const T &V, bool initial = false) {
1231 DataType::operator=(V);
1236 DataType &getValue() { return *this; }
1237 const DataType &getValue() const { return *this; }
1239 const OptionValue<DataType> &getDefault() const { return Default; }
1242 // Define a partial specialization to handle things we cannot inherit from. In
1243 // this case, we store an instance through containment, and overload operators
1244 // to get at the value.
1246 template <class DataType> class opt_storage<DataType, false, false> {
1249 OptionValue<DataType> Default;
1251 // Make sure we initialize the value with the default constructor for the
1253 opt_storage() : Value(DataType()), Default(DataType()) {}
1255 template <class T> void setValue(const T &V, bool initial = false) {
1260 DataType &getValue() { return Value; }
1261 DataType getValue() const { return Value; }
1263 const OptionValue<DataType> &getDefault() const { return Default; }
1265 operator DataType() const { return getValue(); }
1267 // If the datatype is a pointer, support -> on it.
1268 DataType operator->() const { return Value; }
1271 //===----------------------------------------------------------------------===//
1272 // opt - A scalar command line option.
1274 template <class DataType, bool ExternalStorage = false,
1275 class ParserClass = parser<DataType>>
1276 class opt : public Option,
1277 public opt_storage<DataType, ExternalStorage,
1278 std::is_class<DataType>::value> {
1281 bool handleOccurrence(unsigned pos, StringRef ArgName,
1282 StringRef Arg) override {
1283 typename ParserClass::parser_data_type Val =
1284 typename ParserClass::parser_data_type();
1285 if (Parser.parse(*this, ArgName, Arg, Val))
1286 return true; // Parse error!
1287 this->setValue(Val);
1288 this->setPosition(pos);
1292 enum ValueExpected getValueExpectedFlagDefault() const override {
1293 return Parser.getValueExpectedFlagDefault();
1295 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1296 return Parser.getExtraOptionNames(OptionNames);
1299 // Forward printing stuff to the parser...
1300 size_t getOptionWidth() const override {
1301 return Parser.getOptionWidth(*this);
1303 void printOptionInfo(size_t GlobalWidth) const override {
1304 Parser.printOptionInfo(*this, GlobalWidth);
1307 void printOptionValue(size_t GlobalWidth, bool Force) const override {
1308 if (Force || this->getDefault().compare(this->getValue())) {
1309 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1310 this->getDefault(), GlobalWidth);
1316 Parser.initialize();
1320 // Command line options should not be copyable
1321 opt(const opt &) = delete;
1322 opt &operator=(const opt &) = delete;
1324 // setInitialValue - Used by the cl::init modifier...
1325 void setInitialValue(const DataType &V) { this->setValue(V, true); }
1327 ParserClass &getParser() { return Parser; }
1329 template <class T> DataType &operator=(const T &Val) {
1330 this->setValue(Val);
1331 return this->getValue();
1334 template <class... Mods>
1335 explicit opt(const Mods &... Ms)
1336 : Option(Optional, NotHidden), Parser(*this) {
1342 extern template class opt<unsigned>;
1343 extern template class opt<int>;
1344 extern template class opt<std::string>;
1345 extern template class opt<char>;
1346 extern template class opt<bool>;
1348 //===----------------------------------------------------------------------===//
1349 // list_storage class
1351 // Default storage class definition: external storage. This implementation
1352 // assumes the user will specify a variable to store the data into with the
1353 // cl::location(x) modifier.
1355 template <class DataType, class StorageClass> class list_storage {
1356 StorageClass *Location = nullptr; // Where to store the object...
1359 list_storage() = default;
1361 bool setLocation(Option &O, StorageClass &L) {
1363 return O.error("cl::location(x) specified more than once!");
1368 template <class T> void addValue(const T &V) {
1369 assert(Location != 0 && "cl::location(...) not specified for a command "
1370 "line option with external storage!");
1371 Location->push_back(V);
1375 // Define how to hold a class type object, such as a string.
1376 // Originally this code inherited from std::vector. In transitioning to a new
1377 // API for command line options we should change this. The new implementation
1378 // of this list_storage specialization implements the minimum subset of the
1379 // std::vector API required for all the current clients.
1381 // FIXME: Reduce this API to a more narrow subset of std::vector
1383 template <class DataType> class list_storage<DataType, bool> {
1384 std::vector<DataType> Storage;
1387 typedef typename std::vector<DataType>::iterator iterator;
1389 iterator begin() { return Storage.begin(); }
1390 iterator end() { return Storage.end(); }
1392 typedef typename std::vector<DataType>::const_iterator const_iterator;
1393 const_iterator begin() const { return Storage.begin(); }
1394 const_iterator end() const { return Storage.end(); }
1396 typedef typename std::vector<DataType>::size_type size_type;
1397 size_type size() const { return Storage.size(); }
1399 bool empty() const { return Storage.empty(); }
1401 void push_back(const DataType &value) { Storage.push_back(value); }
1402 void push_back(DataType &&value) { Storage.push_back(value); }
1404 typedef typename std::vector<DataType>::reference reference;
1405 typedef typename std::vector<DataType>::const_reference const_reference;
1406 reference operator[](size_type pos) { return Storage[pos]; }
1407 const_reference operator[](size_type pos) const { return Storage[pos]; }
1409 iterator erase(const_iterator pos) { return Storage.erase(pos); }
1410 iterator erase(const_iterator first, const_iterator last) {
1411 return Storage.erase(first, last);
1414 iterator erase(iterator pos) { return Storage.erase(pos); }
1415 iterator erase(iterator first, iterator last) {
1416 return Storage.erase(first, last);
1419 iterator insert(const_iterator pos, const DataType &value) {
1420 return Storage.insert(pos, value);
1422 iterator insert(const_iterator pos, DataType &&value) {
1423 return Storage.insert(pos, value);
1426 iterator insert(iterator pos, const DataType &value) {
1427 return Storage.insert(pos, value);
1429 iterator insert(iterator pos, DataType &&value) {
1430 return Storage.insert(pos, value);
1433 reference front() { return Storage.front(); }
1434 const_reference front() const { return Storage.front(); }
1436 operator std::vector<DataType>&() { return Storage; }
1437 operator ArrayRef<DataType>() { return Storage; }
1438 std::vector<DataType> *operator&() { return &Storage; }
1439 const std::vector<DataType> *operator&() const { return &Storage; }
1441 template <class T> void addValue(const T &V) { Storage.push_back(V); }
1444 //===----------------------------------------------------------------------===//
1445 // list - A list of command line options.
1447 template <class DataType, class StorageClass = bool,
1448 class ParserClass = parser<DataType>>
1449 class list : public Option, public list_storage<DataType, StorageClass> {
1450 std::vector<unsigned> Positions;
1453 enum ValueExpected getValueExpectedFlagDefault() const override {
1454 return Parser.getValueExpectedFlagDefault();
1456 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1457 return Parser.getExtraOptionNames(OptionNames);
1460 bool handleOccurrence(unsigned pos, StringRef ArgName,
1461 StringRef Arg) override {
1462 typename ParserClass::parser_data_type Val =
1463 typename ParserClass::parser_data_type();
1464 if (Parser.parse(*this, ArgName, Arg, Val))
1465 return true; // Parse Error!
1466 list_storage<DataType, StorageClass>::addValue(Val);
1468 Positions.push_back(pos);
1472 // Forward printing stuff to the parser...
1473 size_t getOptionWidth() const override {
1474 return Parser.getOptionWidth(*this);
1476 void printOptionInfo(size_t GlobalWidth) const override {
1477 Parser.printOptionInfo(*this, GlobalWidth);
1480 // Unimplemented: list options don't currently store their default value.
1481 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1486 Parser.initialize();
1490 // Command line options should not be copyable
1491 list(const list &) = delete;
1492 list &operator=(const list &) = delete;
1494 ParserClass &getParser() { return Parser; }
1496 unsigned getPosition(unsigned optnum) const {
1497 assert(optnum < this->size() && "Invalid option index");
1498 return Positions[optnum];
1501 void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
1503 template <class... Mods>
1504 explicit list(const Mods &... Ms)
1505 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1511 // multi_val - Modifier to set the number of additional values.
1513 unsigned AdditionalVals;
1514 explicit multi_val(unsigned N) : AdditionalVals(N) {}
1516 template <typename D, typename S, typename P>
1517 void apply(list<D, S, P> &L) const {
1518 L.setNumAdditionalVals(AdditionalVals);
1522 //===----------------------------------------------------------------------===//
1523 // bits_storage class
1525 // Default storage class definition: external storage. This implementation
1526 // assumes the user will specify a variable to store the data into with the
1527 // cl::location(x) modifier.
1529 template <class DataType, class StorageClass> class bits_storage {
1530 unsigned *Location = nullptr; // Where to store the bits...
1532 template <class T> static unsigned Bit(const T &V) {
1533 unsigned BitPos = reinterpret_cast<unsigned>(V);
1534 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1535 "enum exceeds width of bit vector!");
1540 bits_storage() = default;
1542 bool setLocation(Option &O, unsigned &L) {
1544 return O.error("cl::location(x) specified more than once!");
1549 template <class T> void addValue(const T &V) {
1550 assert(Location != 0 && "cl::location(...) not specified for a command "
1551 "line option with external storage!");
1552 *Location |= Bit(V);
1555 unsigned getBits() { return *Location; }
1557 template <class T> bool isSet(const T &V) {
1558 return (*Location & Bit(V)) != 0;
1562 // Define how to hold bits. Since we can inherit from a class, we do so.
1563 // This makes us exactly compatible with the bits in all cases that it is used.
1565 template <class DataType> class bits_storage<DataType, bool> {
1566 unsigned Bits; // Where to store the bits...
1568 template <class T> static unsigned Bit(const T &V) {
1569 unsigned BitPos = (unsigned)V;
1570 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1571 "enum exceeds width of bit vector!");
1576 template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1578 unsigned getBits() { return Bits; }
1580 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1583 //===----------------------------------------------------------------------===//
1584 // bits - A bit vector of command options.
1586 template <class DataType, class Storage = bool,
1587 class ParserClass = parser<DataType>>
1588 class bits : public Option, public bits_storage<DataType, Storage> {
1589 std::vector<unsigned> Positions;
1592 enum ValueExpected getValueExpectedFlagDefault() const override {
1593 return Parser.getValueExpectedFlagDefault();
1595 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1596 return Parser.getExtraOptionNames(OptionNames);
1599 bool handleOccurrence(unsigned pos, StringRef ArgName,
1600 StringRef Arg) override {
1601 typename ParserClass::parser_data_type Val =
1602 typename ParserClass::parser_data_type();
1603 if (Parser.parse(*this, ArgName, Arg, Val))
1604 return true; // Parse Error!
1605 this->addValue(Val);
1607 Positions.push_back(pos);
1611 // Forward printing stuff to the parser...
1612 size_t getOptionWidth() const override {
1613 return Parser.getOptionWidth(*this);
1615 void printOptionInfo(size_t GlobalWidth) const override {
1616 Parser.printOptionInfo(*this, GlobalWidth);
1619 // Unimplemented: bits options don't currently store their default values.
1620 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1625 Parser.initialize();
1629 // Command line options should not be copyable
1630 bits(const bits &) = delete;
1631 bits &operator=(const bits &) = delete;
1633 ParserClass &getParser() { return Parser; }
1635 unsigned getPosition(unsigned optnum) const {
1636 assert(optnum < this->size() && "Invalid option index");
1637 return Positions[optnum];
1640 template <class... Mods>
1641 explicit bits(const Mods &... Ms)
1642 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1648 //===----------------------------------------------------------------------===//
1649 // Aliased command line option (alias this name to a preexisting name)
1652 class alias : public Option {
1655 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1656 StringRef Arg) override {
1657 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1660 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1661 bool MultiArg = false) override {
1662 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1665 // Handle printing stuff...
1666 size_t getOptionWidth() const override;
1667 void printOptionInfo(size_t GlobalWidth) const override;
1669 // Aliases do not need to print their values.
1670 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1673 ValueExpected getValueExpectedFlagDefault() const override {
1674 return AliasFor->getValueExpectedFlag();
1679 error("cl::alias must have argument name specified!");
1681 error("cl::alias must have an cl::aliasopt(option) specified!");
1682 Subs = AliasFor->Subs;
1687 // Command line options should not be copyable
1688 alias(const alias &) = delete;
1689 alias &operator=(const alias &) = delete;
1691 void setAliasFor(Option &O) {
1693 error("cl::alias must only have one cl::aliasopt(...) specified!");
1697 template <class... Mods>
1698 explicit alias(const Mods &... Ms)
1699 : Option(Optional, Hidden), AliasFor(nullptr) {
1705 // aliasfor - Modifier to set the option an alias aliases.
1709 explicit aliasopt(Option &O) : Opt(O) {}
1711 void apply(alias &A) const { A.setAliasFor(Opt); }
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
1721 explicit extrahelp(StringRef help);
1724 void PrintVersionMessage();
1726 /// This function just prints the help message, exactly the same way as if the
1727 /// -help or -help-hidden option had been given on the command line.
1729 /// NOTE: THIS FUNCTION TERMINATES THE PROGRAM!
1731 /// \param Hidden if true will print hidden options
1732 /// \param Categorized if true print options in categories
1733 void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
1735 //===----------------------------------------------------------------------===//
1736 // Public interface for accessing registered options.
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.
1742 /// \return A reference to the StringMap used by the cl APIs to parse options.
1744 /// Access to unnamed arguments (i.e. positional) are not provided because
1745 /// it is expected that the client already has access to these.
1749 /// main(int argc,char* argv[]) {
1750 /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions();
1751 /// assert(opts.count("help") == 1)
1752 /// opts["help"]->setDescription("Show alphabetical help information")
1754 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1759 /// This interface is useful for modifying options in libraries that are out of
1760 /// the control of the client. The options should be modified before calling
1761 /// llvm::cl::ParseCommandLineOptions().
1763 /// Hopefully this API can be deprecated soon. Any situation where options need
1764 /// to be modified by tools or libraries should be handled by sane APIs rather
1765 /// than just handing around a global list.
1766 StringMap<Option *> &getRegisteredOptions(SubCommand &Sub = *TopLevelSubCommand);
1768 /// \brief Use this to get all registered SubCommands from the provided parser.
1770 /// \return A range of all SubCommand pointers registered with the parser.
1774 /// main(int argc, char* argv[]) {
1775 /// llvm::cl::ParseCommandLineOptions(argc, argv);
1776 /// for (auto* S : llvm::cl::getRegisteredSubcommands()) {
1778 /// std::cout << "Executing subcommand: " << S->getName() << std::endl;
1779 /// // Execute some function based on the name...
1785 /// This interface is useful for defining subcommands in libraries and
1786 /// the dispatch from a single point (like in the main function).
1787 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
1788 getRegisteredSubcommands();
1790 //===----------------------------------------------------------------------===//
1791 // Standalone command line processing utilities.
1794 /// \brief Tokenizes a command line that can contain escapes and quotes.
1796 /// The quoting rules match those used by GCC and other tools that use
1797 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1798 /// They differ from buildargv() on treatment of backslashes that do not escape
1799 /// a special character to make it possible to accept most Windows file paths.
1801 /// \param [in] Source The string to be split on whitespace with quotes.
1802 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1803 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1804 /// lines and end of the response file to be marked with a nullptr string.
1805 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1806 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
1807 SmallVectorImpl<const char *> &NewArgv,
1808 bool MarkEOLs = false);
1810 /// \brief Tokenizes a Windows command line which may contain quotes and escaped
1813 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1814 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1816 /// \param [in] Source The string to be split on whitespace with quotes.
1817 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1818 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1819 /// lines and end of the response file to be marked with a nullptr string.
1820 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1821 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
1822 SmallVectorImpl<const char *> &NewArgv,
1823 bool MarkEOLs = false);
1825 /// \brief String tokenization function type. Should be compatible with either
1826 /// Windows or Unix command line tokenizers.
1827 typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
1828 SmallVectorImpl<const char *> &NewArgv,
1831 /// \brief Expand response files on a command line recursively using the given
1832 /// StringSaver and tokenization strategy. Argv should contain the command line
1833 /// before expansion and will be modified in place. If requested, Argv will
1834 /// also be populated with nullptrs indicating where each response file line
1835 /// ends, which is useful for the "/link" argument that needs to consume all
1836 /// remaining arguments only until the next end of line, when in a response
1839 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1840 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1841 /// \param [in,out] Argv Command line into which to expand response files.
1842 /// \param [in] MarkEOLs Mark end of lines and the end of the response file
1843 /// with nullptrs in the Argv vector.
1844 /// \param [in] RelativeNames true if names of nested response files must be
1845 /// resolved relative to including file.
1846 /// \return true if all @files were expanded successfully or there were none.
1847 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1848 SmallVectorImpl<const char *> &Argv,
1849 bool MarkEOLs = false, bool RelativeNames = false);
1851 /// \brief Mark all options not part of this category as cl::ReallyHidden.
1853 /// \param Category the category of options to keep displaying
1855 /// Some tools (like clang-format) like to be able to hide all options that are
1856 /// not specific to the tool. This function allows a tool to specify a single
1857 /// option category to display in the -help output.
1858 void HideUnrelatedOptions(cl::OptionCategory &Category,
1859 SubCommand &Sub = *TopLevelSubCommand);
1861 /// \brief Mark all options not part of the categories as cl::ReallyHidden.
1863 /// \param Categories the categories of options to keep displaying.
1865 /// Some tools (like clang-format) like to be able to hide all options that are
1866 /// not specific to the tool. This function allows a tool to specify a single
1867 /// option category to display in the -help output.
1868 void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
1869 SubCommand &Sub = *TopLevelSubCommand);
1871 /// \brief Reset all command line options to a state that looks as if they have
1872 /// never appeared on the command line. This is useful for being able to parse
1873 /// a command line multiple times (especially useful for writing tests).
1874 void ResetAllOptionOccurrences();
1876 /// \brief Reset the command line parser back to its initial state. This
1878 /// all options, categories, and subcommands and returns the parser to a state
1879 /// where no options are supported.
1880 void ResetCommandLineParser();
1882 } // end namespace cl
1883 } // end namespace llvm
1885 #endif // LLVM_SUPPORT_COMMANDLINE_H