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/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/ADT/iterator_range.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/ManagedStatic.h"
37 #include <initializer_list>
39 #include <type_traits>
47 /// cl Namespace - This namespace contains all of the command line option
48 /// processing machinery. It is intentionally a short name to make qualified
52 //===----------------------------------------------------------------------===//
53 // ParseCommandLineOptions - Command line option processing entry point.
55 // Returns true on success. Otherwise, this will print the error message to
56 // stderr and exit if \p Errs is not set (nullptr by default), or print the
57 // error message to \p Errs and return false if \p Errs is provided.
58 bool ParseCommandLineOptions(int argc, const char *const *argv,
59 StringRef Overview = "",
60 raw_ostream *Errs = nullptr);
62 //===----------------------------------------------------------------------===//
63 // ParseEnvironmentOptions - Environment variable option processing alternate
66 void ParseEnvironmentOptions(const char *progName, const char *envvar,
67 const char *Overview = "");
69 ///===---------------------------------------------------------------------===//
70 /// SetVersionPrinter - Override the default (LLVM specific) version printer
71 /// used to print out the version when --version is given
72 /// on the command line. This allows other systems using the
73 /// CommandLine utilities to print their own version string.
74 void SetVersionPrinter(void (*func)());
76 ///===---------------------------------------------------------------------===//
77 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
78 /// default one. This can be called multiple times,
79 /// and each time it adds a new function to the list
80 /// which will be called after the basic LLVM version
81 /// printing is complete. Each can then add additional
82 /// information specific to the tool.
83 void AddExtraVersionPrinter(void (*func)());
85 // PrintOptionValues - Print option values.
86 // With -print-options print the difference between option values and defaults.
87 // With -print-all-options print all option values.
88 // (Currently not perfect, but best-effort.)
89 void PrintOptionValues();
91 // Forward declaration - AddLiteralOption needs to be up here to make gcc happy.
94 /// \brief Adds a new option for parsing and provides the option it refers to.
96 /// \param O pointer to the option
97 /// \param Name the string name for the option to handle during parsing
99 /// Literal options are used by some parsers to register special option values.
100 /// This is how the PassNameParser registers pass names for opt.
101 void AddLiteralOption(Option &O, StringRef Name);
103 //===----------------------------------------------------------------------===//
104 // Flags permitted to be passed to command line arguments
107 enum NumOccurrencesFlag { // Flags for the number of occurrences allowed
108 Optional = 0x00, // Zero or One occurrence
109 ZeroOrMore = 0x01, // Zero or more occurrences allowed
110 Required = 0x02, // One occurrence required
111 OneOrMore = 0x03, // One or more occurrences required
113 // ConsumeAfter - Indicates that this option is fed anything that follows the
114 // last positional argument required by the application (it is an error if
115 // there are zero positional arguments, and a ConsumeAfter option is used).
116 // Thus, for example, all arguments to LLI are processed until a filename is
117 // found. Once a filename is found, all of the succeeding arguments are
118 // passed, unprocessed, to the ConsumeAfter option.
123 enum ValueExpected { // Is a value required for the option?
124 // zero reserved for the unspecified value
125 ValueOptional = 0x01, // The value can appear... or not
126 ValueRequired = 0x02, // The value is required to appear!
127 ValueDisallowed = 0x03 // A value may not be specified (for flags)
130 enum OptionHidden { // Control whether -help shows this option
131 NotHidden = 0x00, // Option included in -help & -help-hidden
132 Hidden = 0x01, // -help doesn't, but -help-hidden does
133 ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg
136 // Formatting flags - This controls special features that the option might have
137 // that cause it to be parsed differently...
139 // Prefix - This option allows arguments that are otherwise unrecognized to be
140 // matched by options that are a prefix of the actual value. This is useful for
141 // cases like a linker, where options are typically of the form '-lfoo' or
142 // '-L../../include' where -l or -L are the actual flags. When prefix is
143 // enabled, and used, the value for the flag comes from the suffix of the
146 // Grouping - With this option enabled, multiple letter options are allowed to
147 // bunch together with only a single hyphen for the whole group. This allows
148 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
151 enum FormattingFlags {
152 NormalFormatting = 0x00, // Nothing special
153 Positional = 0x01, // Is a positional argument, no '-' required
154 Prefix = 0x02, // Can this option directly prefix its value?
155 Grouping = 0x03 // Can this option group with other options?
158 enum MiscFlags { // Miscellaneous flags to adjust argument
159 CommaSeparated = 0x01, // Should this cl::list split between commas?
160 PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args?
161 Sink = 0x04 // Should this cl::list eat all unknown options?
164 //===----------------------------------------------------------------------===//
165 // Option Category class
167 class OptionCategory {
169 StringRef const Name;
170 StringRef const Description;
172 void registerCategory();
175 OptionCategory(StringRef const Name,
176 StringRef const Description = "")
177 : Name(Name), Description(Description) {
181 StringRef getName() const { return Name; }
182 StringRef getDescription() const { return Description; }
185 // The general Option Category (used as default category).
186 extern OptionCategory GeneralCategory;
188 //===----------------------------------------------------------------------===//
194 StringRef Description;
197 void registerSubCommand();
198 void unregisterSubCommand();
201 SubCommand(StringRef Name, StringRef Description = "")
202 : Name(Name), Description(Description) {
203 registerSubCommand();
205 SubCommand() = default;
209 explicit operator bool() const;
211 StringRef getName() const { return Name; }
212 StringRef getDescription() const { return Description; }
214 SmallVector<Option *, 4> PositionalOpts;
215 SmallVector<Option *, 4> SinkOpts;
216 StringMap<Option *> OptionsMap;
218 Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists.
221 // A special subcommand representing no subcommand
222 extern ManagedStatic<SubCommand> TopLevelSubCommand;
224 // A special subcommand that can be used to put an option into all subcommands.
225 extern ManagedStatic<SubCommand> AllSubCommands;
227 //===----------------------------------------------------------------------===//
233 // handleOccurrences - Overriden by subclasses to handle the value passed into
234 // an argument. Should return true if there was an error processing the
235 // argument and the program should exit.
237 virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
240 virtual enum ValueExpected getValueExpectedFlagDefault() const {
241 return ValueOptional;
244 // Out of line virtual function to provide home for the class.
245 virtual void anchor();
247 int NumOccurrences = 0; // The number of times specified
248 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
249 // problems with signed enums in bitfields.
250 unsigned Occurrences : 3; // enum NumOccurrencesFlag
251 // not using the enum type for 'Value' because zero is an implementation
252 // detail representing the non-value
254 unsigned HiddenFlag : 2; // enum OptionHidden
255 unsigned Formatting : 2; // enum FormattingFlags
257 unsigned Position = 0; // Position of last occurrence of the option
258 unsigned AdditionalVals = 0; // Greater than 0 for multi-valued option.
261 StringRef ArgStr; // The argument string itself (ex: "help", "o")
262 StringRef HelpStr; // The descriptive text message for -help
263 StringRef ValueStr; // String describing what the value of this option is
264 OptionCategory *Category; // The Category this option belongs to
265 SmallPtrSet<SubCommand *, 4> Subs; // The subcommands this option belongs to.
266 bool FullyInitialized = false; // Has addArguemnt been called?
268 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
269 return (enum NumOccurrencesFlag)Occurrences;
272 inline enum ValueExpected getValueExpectedFlag() const {
273 return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
276 inline enum OptionHidden getOptionHiddenFlag() const {
277 return (enum OptionHidden)HiddenFlag;
280 inline enum FormattingFlags getFormattingFlag() const {
281 return (enum FormattingFlags)Formatting;
284 inline unsigned getMiscFlags() const { return Misc; }
285 inline unsigned getPosition() const { return Position; }
286 inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
288 // hasArgStr - Return true if the argstr != ""
289 bool hasArgStr() const { return !ArgStr.empty(); }
290 bool isPositional() const { return getFormattingFlag() == cl::Positional; }
291 bool isSink() const { return getMiscFlags() & cl::Sink; }
293 bool isConsumeAfter() const {
294 return getNumOccurrencesFlag() == cl::ConsumeAfter;
297 bool isInAllSubCommands() const {
298 return any_of(Subs, [](const SubCommand *SC) {
299 return SC == &*AllSubCommands;
303 //-------------------------------------------------------------------------===
304 // Accessor functions set by OptionModifiers
306 void setArgStr(StringRef S);
307 void setDescription(StringRef S) { HelpStr = S; }
308 void setValueStr(StringRef S) { ValueStr = S; }
309 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
310 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
311 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
312 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
313 void setMiscFlag(enum MiscFlags M) { Misc |= M; }
314 void setPosition(unsigned pos) { Position = pos; }
315 void setCategory(OptionCategory &C) { Category = &C; }
316 void addSubCommand(SubCommand &S) { Subs.insert(&S); }
319 explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
320 enum OptionHidden Hidden)
321 : Occurrences(OccurrencesFlag), Value(0), HiddenFlag(Hidden),
322 Formatting(NormalFormatting), Misc(0), Category(&GeneralCategory) {}
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 &operator=(const GenericOptionValue &) = default;
451 ~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 using WrapperType = OptionValue<DataType>;
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 &operator=(const OptionValueCopy &) = default;
491 ~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 using WrapperType = DataType;
525 OptionValueBase() = default;
526 OptionValueBase(const OptionValueBase&) = default;
527 OptionValueBase &operator=(const OptionValueBase &) = default;
528 ~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 using WrapperType = cl::boolOrDefault;
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 using WrapperType = StringRef;
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) {}
740 OptionValue<DataType> V;
742 SmallVector<OptionInfo, 8> Values;
745 parser(Option &O) : generic_parser_base(O) {}
747 using parser_data_type = DataType;
749 // Implement virtual functions needed by generic_parser_base
750 unsigned getNumOptions() const override { return unsigned(Values.size()); }
751 StringRef getOption(unsigned N) const override { return Values[N].Name; }
752 StringRef getDescription(unsigned N) const override {
753 return Values[N].HelpStr;
756 // getOptionValue - Return the value of option name N.
757 const GenericOptionValue &getOptionValue(unsigned N) const override {
761 // parse - Return true on error.
762 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
764 if (Owner.hasArgStr())
769 for (size_t i = 0, e = Values.size(); i != e; ++i)
770 if (Values[i].Name == ArgVal) {
771 V = Values[i].V.getValue();
775 return O.error("Cannot find option named '" + ArgVal + "'!");
778 /// addLiteralOption - Add an entry to the mapping table.
781 void addLiteralOption(StringRef Name, const DT &V, StringRef HelpStr) {
782 assert(findOption(Name) == Values.size() && "Option already exists!");
783 OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
785 AddLiteralOption(Owner, Name);
788 /// removeLiteralOption - Remove the specified option.
790 void removeLiteralOption(StringRef Name) {
791 unsigned N = findOption(Name);
792 assert(N != Values.size() && "Option not found!");
793 Values.erase(Values.begin() + N);
797 //--------------------------------------------------
798 // basic_parser - Super class of parsers to provide boilerplate code
800 class basic_parser_impl { // non-template implementation of basic_parser<t>
802 basic_parser_impl(Option &) {}
804 enum ValueExpected getValueExpectedFlagDefault() const {
805 return ValueRequired;
808 void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
812 // Return the width of the option tag for printing...
813 size_t getOptionWidth(const Option &O) const;
815 // printOptionInfo - Print out information about this option. The
816 // to-be-maintained width is specified.
818 void printOptionInfo(const Option &O, size_t GlobalWidth) const;
820 // printOptionNoValue - Print a placeholder for options that don't yet support
821 // printOptionDiff().
822 void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
824 // getValueName - Overload in subclass to provide a better default value.
825 virtual StringRef getValueName() const { return "value"; }
827 // An out-of-line virtual method to provide a 'home' for this class.
828 virtual void anchor();
831 ~basic_parser_impl() = default;
833 // A helper for basic_parser::printOptionDiff.
834 void printOptionName(const Option &O, size_t GlobalWidth) const;
837 // basic_parser - The real basic parser is just a template wrapper that provides
838 // a typedef for the provided data type.
840 template <class DataType> class basic_parser : public basic_parser_impl {
842 using parser_data_type = DataType;
843 using OptVal = OptionValue<DataType>;
845 basic_parser(Option &O) : basic_parser_impl(O) {}
848 ~basic_parser() = default;
851 //--------------------------------------------------
854 template <> class parser<bool> final : public basic_parser<bool> {
856 parser(Option &O) : basic_parser(O) {}
858 // parse - Return true on error.
859 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
863 enum ValueExpected getValueExpectedFlagDefault() const {
864 return ValueOptional;
867 // getValueName - Do not print =<value> at all.
868 StringRef getValueName() const override { return StringRef(); }
870 void printOptionDiff(const Option &O, bool V, OptVal Default,
871 size_t GlobalWidth) const;
873 // An out-of-line virtual method to provide a 'home' for this class.
874 void anchor() override;
877 extern template class basic_parser<bool>;
879 //--------------------------------------------------
880 // parser<boolOrDefault>
882 class parser<boolOrDefault> final : public basic_parser<boolOrDefault> {
884 parser(Option &O) : basic_parser(O) {}
886 // parse - Return true on error.
887 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
889 enum ValueExpected getValueExpectedFlagDefault() const {
890 return ValueOptional;
893 // getValueName - Do not print =<value> at all.
894 StringRef getValueName() const override { return StringRef(); }
896 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
897 size_t GlobalWidth) const;
899 // An out-of-line virtual method to provide a 'home' for this class.
900 void anchor() override;
903 extern template class basic_parser<boolOrDefault>;
905 //--------------------------------------------------
908 template <> class parser<int> final : public basic_parser<int> {
910 parser(Option &O) : basic_parser(O) {}
912 // parse - Return true on error.
913 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
915 // getValueName - Overload in subclass to provide a better default value.
916 StringRef getValueName() const override { return "int"; }
918 void printOptionDiff(const Option &O, int V, OptVal Default,
919 size_t GlobalWidth) const;
921 // An out-of-line virtual method to provide a 'home' for this class.
922 void anchor() override;
925 extern template class basic_parser<int>;
927 //--------------------------------------------------
930 template <> class parser<unsigned> final : public basic_parser<unsigned> {
932 parser(Option &O) : basic_parser(O) {}
934 // parse - Return true on error.
935 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
937 // getValueName - Overload in subclass to provide a better default value.
938 StringRef getValueName() const override { return "uint"; }
940 void printOptionDiff(const Option &O, unsigned V, OptVal Default,
941 size_t GlobalWidth) const;
943 // An out-of-line virtual method to provide a 'home' for this class.
944 void anchor() override;
947 extern template class basic_parser<unsigned>;
949 //--------------------------------------------------
950 // parser<unsigned long long>
953 class parser<unsigned long long> final
954 : public basic_parser<unsigned long long> {
956 parser(Option &O) : basic_parser(O) {}
958 // parse - Return true on error.
959 bool parse(Option &O, StringRef ArgName, StringRef Arg,
960 unsigned long long &Val);
962 // getValueName - Overload in subclass to provide a better default value.
963 StringRef getValueName() const override { return "uint"; }
965 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
966 size_t GlobalWidth) const;
968 // An out-of-line virtual method to provide a 'home' for this class.
969 void anchor() override;
972 extern template class basic_parser<unsigned long long>;
974 //--------------------------------------------------
977 template <> class parser<double> final : public basic_parser<double> {
979 parser(Option &O) : basic_parser(O) {}
981 // parse - Return true on error.
982 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
984 // getValueName - Overload in subclass to provide a better default value.
985 StringRef getValueName() const override { return "number"; }
987 void printOptionDiff(const Option &O, double V, OptVal Default,
988 size_t GlobalWidth) const;
990 // An out-of-line virtual method to provide a 'home' for this class.
991 void anchor() override;
994 extern template class basic_parser<double>;
996 //--------------------------------------------------
999 template <> class parser<float> final : public basic_parser<float> {
1001 parser(Option &O) : basic_parser(O) {}
1003 // parse - Return true on error.
1004 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
1006 // getValueName - Overload in subclass to provide a better default value.
1007 StringRef getValueName() const override { return "number"; }
1009 void printOptionDiff(const Option &O, float V, OptVal Default,
1010 size_t GlobalWidth) const;
1012 // An out-of-line virtual method to provide a 'home' for this class.
1013 void anchor() override;
1016 extern template class basic_parser<float>;
1018 //--------------------------------------------------
1019 // parser<std::string>
1021 template <> class parser<std::string> final : public basic_parser<std::string> {
1023 parser(Option &O) : basic_parser(O) {}
1025 // parse - Return true on error.
1026 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
1031 // getValueName - Overload in subclass to provide a better default value.
1032 StringRef getValueName() const override { return "string"; }
1034 void printOptionDiff(const Option &O, StringRef V, const OptVal &Default,
1035 size_t GlobalWidth) const;
1037 // An out-of-line virtual method to provide a 'home' for this class.
1038 void anchor() override;
1041 extern template class basic_parser<std::string>;
1043 //--------------------------------------------------
1046 template <> class parser<char> final : public basic_parser<char> {
1048 parser(Option &O) : basic_parser(O) {}
1050 // parse - Return true on error.
1051 bool parse(Option &, StringRef, StringRef Arg, char &Value) {
1056 // getValueName - Overload in subclass to provide a better default value.
1057 StringRef getValueName() const override { return "char"; }
1059 void printOptionDiff(const Option &O, char V, OptVal Default,
1060 size_t GlobalWidth) const;
1062 // An out-of-line virtual method to provide a 'home' for this class.
1063 void anchor() override;
1066 extern template class basic_parser<char>;
1068 //--------------------------------------------------
1071 // This collection of wrappers is the intermediary between class opt and class
1072 // parser to handle all the template nastiness.
1074 // This overloaded function is selected by the generic parser.
1075 template <class ParserClass, class DT>
1076 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
1077 const OptionValue<DT> &Default, size_t GlobalWidth) {
1078 OptionValue<DT> OV = V;
1079 P.printOptionDiff(O, OV, Default, GlobalWidth);
1082 // This is instantiated for basic parsers when the parsed value has a different
1083 // type than the option value. e.g. HelpPrinter.
1084 template <class ParserDT, class ValDT> struct OptionDiffPrinter {
1085 void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/,
1086 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
1087 P.printOptionNoValue(O, GlobalWidth);
1091 // This is instantiated for basic parsers when the parsed value has the same
1092 // type as the option value.
1093 template <class DT> struct OptionDiffPrinter<DT, DT> {
1094 void print(const Option &O, const parser<DT> &P, const DT &V,
1095 const OptionValue<DT> &Default, size_t GlobalWidth) {
1096 P.printOptionDiff(O, V, Default, GlobalWidth);
1100 // This overloaded function is selected by the basic parser, which may parse a
1101 // different type than the option type.
1102 template <class ParserClass, class ValDT>
1103 void printOptionDiff(
1105 const basic_parser<typename ParserClass::parser_data_type> &P,
1106 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
1108 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
1109 printer.print(O, static_cast<const ParserClass &>(P), V, Default,
1113 //===----------------------------------------------------------------------===//
1114 // applicator class - This class is used because we must use partial
1115 // specialization to handle literal string arguments specially (const char* does
1116 // not correctly respond to the apply method). Because the syntax to use this
1117 // is a pain, we have the 'apply' method below to handle the nastiness...
1119 template <class Mod> struct applicator {
1120 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1123 // Handle const char* as a special case...
1124 template <unsigned n> struct applicator<char[n]> {
1125 template <class Opt> static void opt(StringRef Str, Opt &O) {
1129 template <unsigned n> struct applicator<const char[n]> {
1130 template <class Opt> static void opt(StringRef Str, Opt &O) {
1134 template <> struct applicator<StringRef > {
1135 template <class Opt> static void opt(StringRef Str, Opt &O) {
1140 template <> struct applicator<NumOccurrencesFlag> {
1141 static void opt(NumOccurrencesFlag N, Option &O) {
1142 O.setNumOccurrencesFlag(N);
1146 template <> struct applicator<ValueExpected> {
1147 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1150 template <> struct applicator<OptionHidden> {
1151 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1154 template <> struct applicator<FormattingFlags> {
1155 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1158 template <> struct applicator<MiscFlags> {
1159 static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1162 // apply method - Apply modifiers to an option in a type safe way.
1163 template <class Opt, class Mod, class... Mods>
1164 void apply(Opt *O, const Mod &M, const Mods &... Ms) {
1165 applicator<Mod>::opt(M, *O);
1169 template <class Opt, class Mod> void apply(Opt *O, const Mod &M) {
1170 applicator<Mod>::opt(M, *O);
1173 //===----------------------------------------------------------------------===//
1174 // opt_storage class
1176 // Default storage class definition: external storage. This implementation
1177 // assumes the user will specify a variable to store the data into with the
1178 // cl::location(x) modifier.
1180 template <class DataType, bool ExternalStorage, bool isClass>
1182 DataType *Location = nullptr; // Where to store the object...
1183 OptionValue<DataType> Default;
1185 void check_location() const {
1186 assert(Location && "cl::location(...) not specified for a command "
1187 "line option with external storage, "
1188 "or cl::init specified before cl::location()!!");
1192 opt_storage() = default;
1194 bool setLocation(Option &O, DataType &L) {
1196 return O.error("cl::location(x) specified more than once!");
1202 template <class T> void setValue(const T &V, bool initial = false) {
1209 DataType &getValue() {
1213 const DataType &getValue() const {
1218 operator DataType() const { return this->getValue(); }
1220 const OptionValue<DataType> &getDefault() const { return Default; }
1223 // Define how to hold a class type object, such as a string. Since we can
1224 // inherit from a class, we do so. This makes us exactly compatible with the
1225 // object in all cases that it is used.
1227 template <class DataType>
1228 class opt_storage<DataType, false, true> : public DataType {
1230 OptionValue<DataType> Default;
1232 template <class T> void setValue(const T &V, bool initial = false) {
1233 DataType::operator=(V);
1238 DataType &getValue() { return *this; }
1239 const DataType &getValue() const { return *this; }
1241 const OptionValue<DataType> &getDefault() const { return Default; }
1244 // Define a partial specialization to handle things we cannot inherit from. In
1245 // this case, we store an instance through containment, and overload operators
1246 // to get at the value.
1248 template <class DataType> class opt_storage<DataType, false, false> {
1251 OptionValue<DataType> Default;
1253 // Make sure we initialize the value with the default constructor for the
1255 opt_storage() : Value(DataType()), Default(DataType()) {}
1257 template <class T> void setValue(const T &V, bool initial = false) {
1262 DataType &getValue() { return Value; }
1263 DataType getValue() const { return Value; }
1265 const OptionValue<DataType> &getDefault() const { return Default; }
1267 operator DataType() const { return getValue(); }
1269 // If the datatype is a pointer, support -> on it.
1270 DataType operator->() const { return Value; }
1273 //===----------------------------------------------------------------------===//
1274 // opt - A scalar command line option.
1276 template <class DataType, bool ExternalStorage = false,
1277 class ParserClass = parser<DataType>>
1278 class opt : public Option,
1279 public opt_storage<DataType, ExternalStorage,
1280 std::is_class<DataType>::value> {
1283 bool handleOccurrence(unsigned pos, StringRef ArgName,
1284 StringRef Arg) override {
1285 typename ParserClass::parser_data_type Val =
1286 typename ParserClass::parser_data_type();
1287 if (Parser.parse(*this, ArgName, Arg, Val))
1288 return true; // Parse error!
1289 this->setValue(Val);
1290 this->setPosition(pos);
1294 enum ValueExpected getValueExpectedFlagDefault() const override {
1295 return Parser.getValueExpectedFlagDefault();
1298 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1299 return Parser.getExtraOptionNames(OptionNames);
1302 // Forward printing stuff to the parser...
1303 size_t getOptionWidth() const override {
1304 return Parser.getOptionWidth(*this);
1307 void printOptionInfo(size_t GlobalWidth) const override {
1308 Parser.printOptionInfo(*this, GlobalWidth);
1311 void printOptionValue(size_t GlobalWidth, bool Force) const override {
1312 if (Force || this->getDefault().compare(this->getValue())) {
1313 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1314 this->getDefault(), GlobalWidth);
1320 Parser.initialize();
1324 // Command line options should not be copyable
1325 opt(const opt &) = delete;
1326 opt &operator=(const opt &) = delete;
1328 // setInitialValue - Used by the cl::init modifier...
1329 void setInitialValue(const DataType &V) { this->setValue(V, true); }
1331 ParserClass &getParser() { return Parser; }
1333 template <class T> DataType &operator=(const T &Val) {
1334 this->setValue(Val);
1335 return this->getValue();
1338 template <class... Mods>
1339 explicit opt(const Mods &... Ms)
1340 : Option(Optional, NotHidden), Parser(*this) {
1346 extern template class opt<unsigned>;
1347 extern template class opt<int>;
1348 extern template class opt<std::string>;
1349 extern template class opt<char>;
1350 extern template class opt<bool>;
1352 //===----------------------------------------------------------------------===//
1353 // list_storage class
1355 // Default storage class definition: external storage. This implementation
1356 // assumes the user will specify a variable to store the data into with the
1357 // cl::location(x) modifier.
1359 template <class DataType, class StorageClass> class list_storage {
1360 StorageClass *Location = nullptr; // Where to store the object...
1363 list_storage() = default;
1365 bool setLocation(Option &O, StorageClass &L) {
1367 return O.error("cl::location(x) specified more than once!");
1372 template <class T> void addValue(const T &V) {
1373 assert(Location != 0 && "cl::location(...) not specified for a command "
1374 "line option with external storage!");
1375 Location->push_back(V);
1379 // Define how to hold a class type object, such as a string.
1380 // Originally this code inherited from std::vector. In transitioning to a new
1381 // API for command line options we should change this. The new implementation
1382 // of this list_storage specialization implements the minimum subset of the
1383 // std::vector API required for all the current clients.
1385 // FIXME: Reduce this API to a more narrow subset of std::vector
1387 template <class DataType> class list_storage<DataType, bool> {
1388 std::vector<DataType> Storage;
1391 using iterator = typename std::vector<DataType>::iterator;
1393 iterator begin() { return Storage.begin(); }
1394 iterator end() { return Storage.end(); }
1396 using const_iterator = typename std::vector<DataType>::const_iterator;
1398 const_iterator begin() const { return Storage.begin(); }
1399 const_iterator end() const { return Storage.end(); }
1401 using size_type = typename std::vector<DataType>::size_type;
1403 size_type size() const { return Storage.size(); }
1405 bool empty() const { return Storage.empty(); }
1407 void push_back(const DataType &value) { Storage.push_back(value); }
1408 void push_back(DataType &&value) { Storage.push_back(value); }
1410 using reference = typename std::vector<DataType>::reference;
1411 using const_reference = typename std::vector<DataType>::const_reference;
1413 reference operator[](size_type pos) { return Storage[pos]; }
1414 const_reference operator[](size_type pos) const { return Storage[pos]; }
1416 iterator erase(const_iterator pos) { return Storage.erase(pos); }
1417 iterator erase(const_iterator first, const_iterator last) {
1418 return Storage.erase(first, last);
1421 iterator erase(iterator pos) { return Storage.erase(pos); }
1422 iterator erase(iterator first, iterator last) {
1423 return Storage.erase(first, last);
1426 iterator insert(const_iterator pos, const DataType &value) {
1427 return Storage.insert(pos, value);
1429 iterator insert(const_iterator pos, DataType &&value) {
1430 return Storage.insert(pos, value);
1433 iterator insert(iterator pos, const DataType &value) {
1434 return Storage.insert(pos, value);
1436 iterator insert(iterator pos, DataType &&value) {
1437 return Storage.insert(pos, value);
1440 reference front() { return Storage.front(); }
1441 const_reference front() const { return Storage.front(); }
1443 operator std::vector<DataType>&() { return Storage; }
1444 operator ArrayRef<DataType>() { return Storage; }
1445 std::vector<DataType> *operator&() { return &Storage; }
1446 const std::vector<DataType> *operator&() const { return &Storage; }
1448 template <class T> void addValue(const T &V) { Storage.push_back(V); }
1451 //===----------------------------------------------------------------------===//
1452 // list - A list of command line options.
1454 template <class DataType, class StorageClass = bool,
1455 class ParserClass = parser<DataType>>
1456 class list : public Option, public list_storage<DataType, StorageClass> {
1457 std::vector<unsigned> Positions;
1460 enum ValueExpected getValueExpectedFlagDefault() const override {
1461 return Parser.getValueExpectedFlagDefault();
1464 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1465 return Parser.getExtraOptionNames(OptionNames);
1468 bool handleOccurrence(unsigned pos, StringRef ArgName,
1469 StringRef Arg) override {
1470 typename ParserClass::parser_data_type Val =
1471 typename ParserClass::parser_data_type();
1472 if (Parser.parse(*this, ArgName, Arg, Val))
1473 return true; // Parse Error!
1474 list_storage<DataType, StorageClass>::addValue(Val);
1476 Positions.push_back(pos);
1480 // Forward printing stuff to the parser...
1481 size_t getOptionWidth() const override {
1482 return Parser.getOptionWidth(*this);
1485 void printOptionInfo(size_t GlobalWidth) const override {
1486 Parser.printOptionInfo(*this, GlobalWidth);
1489 // Unimplemented: list options don't currently store their default value.
1490 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1495 Parser.initialize();
1499 // Command line options should not be copyable
1500 list(const list &) = delete;
1501 list &operator=(const list &) = delete;
1503 ParserClass &getParser() { return Parser; }
1505 unsigned getPosition(unsigned optnum) const {
1506 assert(optnum < this->size() && "Invalid option index");
1507 return Positions[optnum];
1510 void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
1512 template <class... Mods>
1513 explicit list(const Mods &... Ms)
1514 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1520 // multi_val - Modifier to set the number of additional values.
1522 unsigned AdditionalVals;
1523 explicit multi_val(unsigned N) : AdditionalVals(N) {}
1525 template <typename D, typename S, typename P>
1526 void apply(list<D, S, P> &L) const {
1527 L.setNumAdditionalVals(AdditionalVals);
1531 //===----------------------------------------------------------------------===//
1532 // bits_storage class
1534 // Default storage class definition: external storage. This implementation
1535 // assumes the user will specify a variable to store the data into with the
1536 // cl::location(x) modifier.
1538 template <class DataType, class StorageClass> class bits_storage {
1539 unsigned *Location = nullptr; // Where to store the bits...
1541 template <class T> static unsigned Bit(const T &V) {
1542 unsigned BitPos = reinterpret_cast<unsigned>(V);
1543 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1544 "enum exceeds width of bit vector!");
1549 bits_storage() = default;
1551 bool setLocation(Option &O, unsigned &L) {
1553 return O.error("cl::location(x) specified more than once!");
1558 template <class T> void addValue(const T &V) {
1559 assert(Location != 0 && "cl::location(...) not specified for a command "
1560 "line option with external storage!");
1561 *Location |= Bit(V);
1564 unsigned getBits() { return *Location; }
1566 template <class T> bool isSet(const T &V) {
1567 return (*Location & Bit(V)) != 0;
1571 // Define how to hold bits. Since we can inherit from a class, we do so.
1572 // This makes us exactly compatible with the bits in all cases that it is used.
1574 template <class DataType> class bits_storage<DataType, bool> {
1575 unsigned Bits; // Where to store the bits...
1577 template <class T> static unsigned Bit(const T &V) {
1578 unsigned BitPos = (unsigned)V;
1579 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1580 "enum exceeds width of bit vector!");
1585 template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1587 unsigned getBits() { return Bits; }
1589 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1592 //===----------------------------------------------------------------------===//
1593 // bits - A bit vector of command options.
1595 template <class DataType, class Storage = bool,
1596 class ParserClass = parser<DataType>>
1597 class bits : public Option, public bits_storage<DataType, Storage> {
1598 std::vector<unsigned> Positions;
1601 enum ValueExpected getValueExpectedFlagDefault() const override {
1602 return Parser.getValueExpectedFlagDefault();
1605 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1606 return Parser.getExtraOptionNames(OptionNames);
1609 bool handleOccurrence(unsigned pos, StringRef ArgName,
1610 StringRef Arg) override {
1611 typename ParserClass::parser_data_type Val =
1612 typename ParserClass::parser_data_type();
1613 if (Parser.parse(*this, ArgName, Arg, Val))
1614 return true; // Parse Error!
1615 this->addValue(Val);
1617 Positions.push_back(pos);
1621 // Forward printing stuff to the parser...
1622 size_t getOptionWidth() const override {
1623 return Parser.getOptionWidth(*this);
1626 void printOptionInfo(size_t GlobalWidth) const override {
1627 Parser.printOptionInfo(*this, GlobalWidth);
1630 // Unimplemented: bits options don't currently store their default values.
1631 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1636 Parser.initialize();
1640 // Command line options should not be copyable
1641 bits(const bits &) = delete;
1642 bits &operator=(const bits &) = delete;
1644 ParserClass &getParser() { return Parser; }
1646 unsigned getPosition(unsigned optnum) const {
1647 assert(optnum < this->size() && "Invalid option index");
1648 return Positions[optnum];
1651 template <class... Mods>
1652 explicit bits(const Mods &... Ms)
1653 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1659 //===----------------------------------------------------------------------===//
1660 // Aliased command line option (alias this name to a preexisting name)
1663 class alias : public Option {
1666 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1667 StringRef Arg) override {
1668 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1671 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1672 bool MultiArg = false) override {
1673 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1676 // Handle printing stuff...
1677 size_t getOptionWidth() const override;
1678 void printOptionInfo(size_t GlobalWidth) const override;
1680 // Aliases do not need to print their values.
1681 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1684 ValueExpected getValueExpectedFlagDefault() const override {
1685 return AliasFor->getValueExpectedFlag();
1690 error("cl::alias must have argument name specified!");
1692 error("cl::alias must have an cl::aliasopt(option) specified!");
1693 Subs = AliasFor->Subs;
1698 // Command line options should not be copyable
1699 alias(const alias &) = delete;
1700 alias &operator=(const alias &) = delete;
1702 void setAliasFor(Option &O) {
1704 error("cl::alias must only have one cl::aliasopt(...) specified!");
1708 template <class... Mods>
1709 explicit alias(const Mods &... Ms)
1710 : Option(Optional, Hidden), AliasFor(nullptr) {
1716 // aliasfor - Modifier to set the option an alias aliases.
1720 explicit aliasopt(Option &O) : Opt(O) {}
1722 void apply(alias &A) const { A.setAliasFor(Opt); }
1725 // extrahelp - provide additional help at the end of the normal help
1726 // output. All occurrences of cl::extrahelp will be accumulated and
1727 // printed to stderr at the end of the regular help, just before
1732 explicit extrahelp(StringRef help);
1735 void PrintVersionMessage();
1737 /// This function just prints the help message, exactly the same way as if the
1738 /// -help or -help-hidden option had been given on the command line.
1740 /// NOTE: THIS FUNCTION TERMINATES THE PROGRAM!
1742 /// \param Hidden if true will print hidden options
1743 /// \param Categorized if true print options in categories
1744 void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
1746 //===----------------------------------------------------------------------===//
1747 // Public interface for accessing registered options.
1750 /// \brief Use this to get a StringMap to all registered named options
1751 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1753 /// \return A reference to the StringMap used by the cl APIs to parse options.
1755 /// Access to unnamed arguments (i.e. positional) are not provided because
1756 /// it is expected that the client already has access to these.
1760 /// main(int argc,char* argv[]) {
1761 /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions();
1762 /// assert(opts.count("help") == 1)
1763 /// opts["help"]->setDescription("Show alphabetical help information")
1765 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1770 /// This interface is useful for modifying options in libraries that are out of
1771 /// the control of the client. The options should be modified before calling
1772 /// llvm::cl::ParseCommandLineOptions().
1774 /// Hopefully this API can be deprecated soon. Any situation where options need
1775 /// to be modified by tools or libraries should be handled by sane APIs rather
1776 /// than just handing around a global list.
1777 StringMap<Option *> &getRegisteredOptions(SubCommand &Sub = *TopLevelSubCommand);
1779 /// \brief Use this to get all registered SubCommands from the provided parser.
1781 /// \return A range of all SubCommand pointers registered with the parser.
1785 /// main(int argc, char* argv[]) {
1786 /// llvm::cl::ParseCommandLineOptions(argc, argv);
1787 /// for (auto* S : llvm::cl::getRegisteredSubcommands()) {
1789 /// std::cout << "Executing subcommand: " << S->getName() << std::endl;
1790 /// // Execute some function based on the name...
1796 /// This interface is useful for defining subcommands in libraries and
1797 /// the dispatch from a single point (like in the main function).
1798 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
1799 getRegisteredSubcommands();
1801 //===----------------------------------------------------------------------===//
1802 // Standalone command line processing utilities.
1805 /// \brief Tokenizes a command line that can contain escapes and quotes.
1807 /// The quoting rules match those used by GCC and other tools that use
1808 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1809 /// They differ from buildargv() on treatment of backslashes that do not escape
1810 /// a special character to make it possible to accept most Windows file paths.
1812 /// \param [in] Source The string to be split on whitespace with quotes.
1813 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1814 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1815 /// lines and end of the response file to be marked with a nullptr string.
1816 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1817 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
1818 SmallVectorImpl<const char *> &NewArgv,
1819 bool MarkEOLs = false);
1821 /// \brief Tokenizes a Windows command line which may contain quotes and escaped
1824 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1825 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1827 /// \param [in] Source The string to be split on whitespace with quotes.
1828 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1829 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1830 /// lines and end of the response file to be marked with a nullptr string.
1831 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1832 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
1833 SmallVectorImpl<const char *> &NewArgv,
1834 bool MarkEOLs = false);
1836 /// \brief String tokenization function type. Should be compatible with either
1837 /// Windows or Unix command line tokenizers.
1838 using TokenizerCallback = void (*)(StringRef Source, StringSaver &Saver,
1839 SmallVectorImpl<const char *> &NewArgv,
1842 /// \brief Expand response files on a command line recursively using the given
1843 /// StringSaver and tokenization strategy. Argv should contain the command line
1844 /// before expansion and will be modified in place. If requested, Argv will
1845 /// also be populated with nullptrs indicating where each response file line
1846 /// ends, which is useful for the "/link" argument that needs to consume all
1847 /// remaining arguments only until the next end of line, when in a response
1850 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1851 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1852 /// \param [in,out] Argv Command line into which to expand response files.
1853 /// \param [in] MarkEOLs Mark end of lines and the end of the response file
1854 /// with nullptrs in the Argv vector.
1855 /// \param [in] RelativeNames true if names of nested response files must be
1856 /// resolved relative to including file.
1857 /// \return true if all @files were expanded successfully or there were none.
1858 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1859 SmallVectorImpl<const char *> &Argv,
1860 bool MarkEOLs = false, bool RelativeNames = false);
1862 /// \brief Mark all options not part of this category as cl::ReallyHidden.
1864 /// \param Category the category of options to keep displaying
1866 /// Some tools (like clang-format) like to be able to hide all options that are
1867 /// not specific to the tool. This function allows a tool to specify a single
1868 /// option category to display in the -help output.
1869 void HideUnrelatedOptions(cl::OptionCategory &Category,
1870 SubCommand &Sub = *TopLevelSubCommand);
1872 /// \brief Mark all options not part of the categories as cl::ReallyHidden.
1874 /// \param Categories the categories of options to keep displaying.
1876 /// Some tools (like clang-format) like to be able to hide all options that are
1877 /// not specific to the tool. This function allows a tool to specify a single
1878 /// option category to display in the -help output.
1879 void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
1880 SubCommand &Sub = *TopLevelSubCommand);
1882 /// \brief Reset all command line options to a state that looks as if they have
1883 /// never appeared on the command line. This is useful for being able to parse
1884 /// a command line multiple times (especially useful for writing tests).
1885 void ResetAllOptionOccurrences();
1887 /// \brief Reset the command line parser back to its initial state. This
1889 /// all options, categories, and subcommands and returns the parser to a state
1890 /// where no options are supported.
1891 void ResetCommandLineParser();
1893 } // end namespace cl
1895 } // end namespace llvm
1897 #endif // LLVM_SUPPORT_COMMANDLINE_H