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 bool ParseCommandLineOptions(int argc, const char *const *argv,
54 StringRef Overview = "",
55 bool IgnoreErrors = false);
57 //===----------------------------------------------------------------------===//
58 // ParseEnvironmentOptions - Environment variable option processing alternate
61 void ParseEnvironmentOptions(const char *progName, const char *envvar,
62 const char *Overview = "");
64 ///===---------------------------------------------------------------------===//
65 /// SetVersionPrinter - Override the default (LLVM specific) version printer
66 /// used to print out the version when --version is given
67 /// on the command line. This allows other systems using the
68 /// CommandLine utilities to print their own version string.
69 void SetVersionPrinter(void (*func)());
71 ///===---------------------------------------------------------------------===//
72 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
73 /// default one. This can be called multiple times,
74 /// and each time it adds a new function to the list
75 /// which will be called after the basic LLVM version
76 /// printing is complete. Each can then add additional
77 /// information specific to the tool.
78 void AddExtraVersionPrinter(void (*func)());
80 // PrintOptionValues - Print option values.
81 // With -print-options print the difference between option values and defaults.
82 // With -print-all-options print all option values.
83 // (Currently not perfect, but best-effort.)
84 void PrintOptionValues();
86 // Forward declaration - AddLiteralOption needs to be up here to make gcc happy.
89 /// \brief Adds a new option for parsing and provides the option it refers to.
91 /// \param O pointer to the option
92 /// \param Name the string name for the option to handle during parsing
94 /// Literal options are used by some parsers to register special option values.
95 /// This is how the PassNameParser registers pass names for opt.
96 void AddLiteralOption(Option &O, StringRef Name);
98 //===----------------------------------------------------------------------===//
99 // Flags permitted to be passed to command line arguments
102 enum NumOccurrencesFlag { // Flags for the number of occurrences allowed
103 Optional = 0x00, // Zero or One occurrence
104 ZeroOrMore = 0x01, // Zero or more occurrences allowed
105 Required = 0x02, // One occurrence required
106 OneOrMore = 0x03, // One or more occurrences required
108 // ConsumeAfter - Indicates that this option is fed anything that follows the
109 // last positional argument required by the application (it is an error if
110 // there are zero positional arguments, and a ConsumeAfter option is used).
111 // Thus, for example, all arguments to LLI are processed until a filename is
112 // found. Once a filename is found, all of the succeeding arguments are
113 // passed, unprocessed, to the ConsumeAfter option.
118 enum ValueExpected { // Is a value required for the option?
119 // zero reserved for the unspecified value
120 ValueOptional = 0x01, // The value can appear... or not
121 ValueRequired = 0x02, // The value is required to appear!
122 ValueDisallowed = 0x03 // A value may not be specified (for flags)
125 enum OptionHidden { // Control whether -help shows this option
126 NotHidden = 0x00, // Option included in -help & -help-hidden
127 Hidden = 0x01, // -help doesn't, but -help-hidden does
128 ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg
131 // Formatting flags - This controls special features that the option might have
132 // that cause it to be parsed differently...
134 // Prefix - This option allows arguments that are otherwise unrecognized to be
135 // matched by options that are a prefix of the actual value. This is useful for
136 // cases like a linker, where options are typically of the form '-lfoo' or
137 // '-L../../include' where -l or -L are the actual flags. When prefix is
138 // enabled, and used, the value for the flag comes from the suffix of the
141 // Grouping - With this option enabled, multiple letter options are allowed to
142 // bunch together with only a single hyphen for the whole group. This allows
143 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
146 enum FormattingFlags {
147 NormalFormatting = 0x00, // Nothing special
148 Positional = 0x01, // Is a positional argument, no '-' required
149 Prefix = 0x02, // Can this option directly prefix its value?
150 Grouping = 0x03 // Can this option group with other options?
153 enum MiscFlags { // Miscellaneous flags to adjust argument
154 CommaSeparated = 0x01, // Should this cl::list split between commas?
155 PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args?
156 Sink = 0x04 // Should this cl::list eat all unknown options?
159 //===----------------------------------------------------------------------===//
160 // Option Category class
162 class OptionCategory {
164 StringRef const Name;
165 StringRef const Description;
167 void registerCategory();
170 OptionCategory(StringRef const Name,
171 StringRef const Description = "")
172 : Name(Name), Description(Description) {
176 StringRef getName() const { return Name; }
177 StringRef getDescription() const { return Description; }
180 // The general Option Category (used as default category).
181 extern OptionCategory GeneralCategory;
183 //===----------------------------------------------------------------------===//
189 StringRef Description;
192 void registerSubCommand();
193 void unregisterSubCommand();
196 SubCommand(StringRef Name, StringRef Description = "")
197 : Name(Name), Description(Description) {
198 registerSubCommand();
200 SubCommand() = default;
204 operator bool() const;
206 StringRef getName() const { return Name; }
207 StringRef getDescription() const { return Description; }
209 SmallVector<Option *, 4> PositionalOpts;
210 SmallVector<Option *, 4> SinkOpts;
211 StringMap<Option *> OptionsMap;
213 Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists.
216 // A special subcommand representing no subcommand
217 extern ManagedStatic<SubCommand> TopLevelSubCommand;
219 // A special subcommand that can be used to put an option into all subcommands.
220 extern ManagedStatic<SubCommand> AllSubCommands;
222 //===----------------------------------------------------------------------===//
228 // handleOccurrences - Overriden by subclasses to handle the value passed into
229 // an argument. Should return true if there was an error processing the
230 // argument and the program should exit.
232 virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
235 virtual enum ValueExpected getValueExpectedFlagDefault() const {
236 return ValueOptional;
239 // Out of line virtual function to provide home for the class.
240 virtual void anchor();
242 int NumOccurrences; // The number of times specified
243 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
244 // problems with signed enums in bitfields.
245 unsigned Occurrences : 3; // enum NumOccurrencesFlag
246 // not using the enum type for 'Value' because zero is an implementation
247 // detail representing the non-value
249 unsigned HiddenFlag : 2; // enum OptionHidden
250 unsigned Formatting : 2; // enum FormattingFlags
252 unsigned Position; // Position of last occurrence of the option
253 unsigned AdditionalVals; // Greater than 0 for multi-valued option.
256 StringRef ArgStr; // The argument string itself (ex: "help", "o")
257 StringRef HelpStr; // The descriptive text message for -help
258 StringRef ValueStr; // String describing what the value of this option is
259 OptionCategory *Category; // The Category this option belongs to
260 SmallPtrSet<SubCommand *, 4> Subs; // The subcommands this option belongs to.
261 bool FullyInitialized; // Has addArguemnt been called?
263 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
264 return (enum NumOccurrencesFlag)Occurrences;
267 inline enum ValueExpected getValueExpectedFlag() const {
268 return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
271 inline enum OptionHidden getOptionHiddenFlag() const {
272 return (enum OptionHidden)HiddenFlag;
275 inline enum FormattingFlags getFormattingFlag() const {
276 return (enum FormattingFlags)Formatting;
279 inline unsigned getMiscFlags() const { return Misc; }
280 inline unsigned getPosition() const { return Position; }
281 inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
283 // hasArgStr - Return true if the argstr != ""
284 bool hasArgStr() const { return !ArgStr.empty(); }
285 bool isPositional() const { return getFormattingFlag() == cl::Positional; }
286 bool isSink() const { return getMiscFlags() & cl::Sink; }
288 bool isConsumeAfter() const {
289 return getNumOccurrencesFlag() == cl::ConsumeAfter;
292 bool isInAllSubCommands() const {
293 return any_of(Subs, [](const SubCommand *SC) {
294 return SC == &*AllSubCommands;
298 //-------------------------------------------------------------------------===
299 // Accessor functions set by OptionModifiers
301 void setArgStr(StringRef S);
302 void setDescription(StringRef S) { HelpStr = S; }
303 void setValueStr(StringRef S) { ValueStr = S; }
304 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
305 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
306 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
307 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
308 void setMiscFlag(enum MiscFlags M) { Misc |= M; }
309 void setPosition(unsigned pos) { Position = pos; }
310 void setCategory(OptionCategory &C) { Category = &C; }
311 void addSubCommand(SubCommand &S) { Subs.insert(&S); }
314 explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
315 enum OptionHidden Hidden)
316 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
317 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0),
318 AdditionalVals(0), Category(&GeneralCategory), FullyInitialized(false) {
321 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
324 virtual ~Option() = default;
326 // addArgument - Register this argument with the commandline system.
330 /// Unregisters this option from the CommandLine system.
332 /// This option must have been the last option registered.
333 /// For testing purposes only.
334 void removeArgument();
336 // Return the width of the option tag for printing...
337 virtual size_t getOptionWidth() const = 0;
339 // printOptionInfo - Print out information about this option. The
340 // to-be-maintained width is specified.
342 virtual void printOptionInfo(size_t GlobalWidth) const = 0;
344 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
346 virtual void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
348 // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
350 virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
351 bool MultiArg = false);
353 // Prints option name followed by message. Always returns true.
354 bool error(const Twine &Message, StringRef ArgName = StringRef());
356 inline int getNumOccurrences() const { return NumOccurrences; }
357 inline void reset() { NumOccurrences = 0; }
360 //===----------------------------------------------------------------------===//
361 // Command line option modifiers that can be used to modify the behavior of
362 // command line option parsers...
365 // desc - Modifier to set the description shown in the -help output...
369 desc(StringRef Str) : Desc(Str) {}
371 void apply(Option &O) const { O.setDescription(Desc); }
374 // value_desc - Modifier to set the value description shown in the -help
379 value_desc(StringRef Str) : Desc(Str) {}
381 void apply(Option &O) const { O.setValueStr(Desc); }
384 // init - Specify a default (initial) value for the command line argument, if
385 // the default constructor for the argument type does not give you what you
386 // want. This is only valid on "opt" arguments, not on "list" arguments.
388 template <class Ty> struct initializer {
390 initializer(const Ty &Val) : Init(Val) {}
392 template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
395 template <class Ty> initializer<Ty> init(const Ty &Val) {
396 return initializer<Ty>(Val);
399 // location - Allow the user to specify which external variable they want to
400 // store the results of the command line argument processing into, if they don't
401 // want to store it in the option itself.
403 template <class Ty> struct LocationClass {
406 LocationClass(Ty &L) : Loc(L) {}
408 template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
411 template <class Ty> LocationClass<Ty> location(Ty &L) {
412 return LocationClass<Ty>(L);
415 // cat - Specifiy the Option category for the command line argument to belong
418 OptionCategory &Category;
420 cat(OptionCategory &c) : Category(c) {}
422 template <class Opt> void apply(Opt &O) const { O.setCategory(Category); }
425 // sub - Specify the subcommand that this option belongs to.
429 sub(SubCommand &S) : Sub(S) {}
431 template <class Opt> void apply(Opt &O) const { O.addSubCommand(Sub); }
434 //===----------------------------------------------------------------------===//
437 // Support value comparison outside the template.
438 struct GenericOptionValue {
439 virtual bool compare(const GenericOptionValue &V) const = 0;
442 GenericOptionValue() = default;
443 GenericOptionValue(const GenericOptionValue&) = default;
444 ~GenericOptionValue() = default;
445 GenericOptionValue &operator=(const GenericOptionValue &) = default;
448 virtual void anchor();
451 template <class DataType> struct OptionValue;
453 // The default value safely does nothing. Option value printing is only
455 template <class DataType, bool isClass>
456 struct OptionValueBase : public GenericOptionValue {
457 // Temporary storage for argument passing.
458 typedef OptionValue<DataType> WrapperType;
460 bool hasValue() const { return false; }
462 const DataType &getValue() const { llvm_unreachable("no default value"); }
464 // Some options may take their value from a different data type.
465 template <class DT> void setValue(const DT & /*V*/) {}
467 bool compare(const DataType & /*V*/) const { return false; }
469 bool compare(const GenericOptionValue & /*V*/) const override {
474 ~OptionValueBase() = default;
477 // Simple copy of the option value.
478 template <class DataType> class OptionValueCopy : public GenericOptionValue {
483 OptionValueCopy(const OptionValueCopy&) = default;
484 ~OptionValueCopy() = default;
485 OptionValueCopy &operator=(const OptionValueCopy&) = default;
488 OptionValueCopy() = default;
490 bool hasValue() const { return Valid; }
492 const DataType &getValue() const {
493 assert(Valid && "invalid option value");
497 void setValue(const DataType &V) {
502 bool compare(const DataType &V) const { return Valid && (Value != V); }
504 bool compare(const GenericOptionValue &V) const override {
505 const OptionValueCopy<DataType> &VC =
506 static_cast<const OptionValueCopy<DataType> &>(V);
509 return compare(VC.getValue());
513 // Non-class option values.
514 template <class DataType>
515 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
516 typedef DataType WrapperType;
519 OptionValueBase() = default;
520 OptionValueBase(const OptionValueBase&) = default;
521 ~OptionValueBase() = default;
522 OptionValueBase &operator=(const OptionValueBase&) = default;
525 // Top-level option class.
526 template <class DataType>
527 struct OptionValue final
528 : OptionValueBase<DataType, std::is_class<DataType>::value> {
529 OptionValue() = default;
531 OptionValue(const DataType &V) { this->setValue(V); }
533 // Some options may take their value from a different data type.
534 template <class DT> OptionValue<DataType> &operator=(const DT &V) {
540 // Other safe-to-copy-by-value common option types.
541 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
543 struct OptionValue<cl::boolOrDefault> final
544 : OptionValueCopy<cl::boolOrDefault> {
545 typedef cl::boolOrDefault WrapperType;
547 OptionValue() = default;
549 OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
551 OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
557 void anchor() override;
561 struct OptionValue<std::string> final : OptionValueCopy<std::string> {
562 typedef StringRef WrapperType;
564 OptionValue() = default;
566 OptionValue(const std::string &V) { this->setValue(V); }
568 OptionValue<std::string> &operator=(const std::string &V) {
574 void anchor() override;
577 //===----------------------------------------------------------------------===//
578 // Enum valued command line option
581 // This represents a single enum value, using "int" as the underlying type.
582 struct OptionEnumValue {
585 StringRef Description;
588 #define clEnumVal(ENUMVAL, DESC) \
589 llvm::cl::OptionEnumValue { #ENUMVAL, int(ENUMVAL), DESC }
590 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) \
591 llvm::cl::OptionEnumValue { FLAGNAME, int(ENUMVAL), DESC }
593 // values - For custom data types, allow specifying a group of values together
594 // as the values that go into the mapping that the option handler uses.
597 // Use a vector instead of a map, because the lists should be short,
598 // the overhead is less, and most importantly, it keeps them in the order
599 // inserted so we can print our option out nicely.
600 SmallVector<OptionEnumValue, 4> Values;
603 ValuesClass(std::initializer_list<OptionEnumValue> Options)
606 template <class Opt> void apply(Opt &O) const {
607 for (auto Value : Values)
608 O.getParser().addLiteralOption(Value.Name, Value.Value,
613 /// Helper to build a ValuesClass by forwarding a variable number of arguments
614 /// as an initializer list to the ValuesClass constructor.
615 template <typename... OptsTy> ValuesClass values(OptsTy... Options) {
616 return ValuesClass({Options...});
619 //===----------------------------------------------------------------------===//
620 // parser class - Parameterizable parser for different data types. By default,
621 // known data types (string, int, bool) have specialized parsers, that do what
622 // you would expect. The default parser, used for data types that are not
623 // built-in, uses a mapping table to map specific options to values, which is
624 // used, among other things, to handle enum types.
626 //--------------------------------------------------
627 // generic_parser_base - This class holds all the non-generic code that we do
628 // not need replicated for every instance of the generic parser. This also
629 // allows us to put stuff into CommandLine.cpp
631 class generic_parser_base {
633 class GenericOptionInfo {
635 GenericOptionInfo(StringRef name, StringRef helpStr)
636 : Name(name), HelpStr(helpStr) {}
642 generic_parser_base(Option &O) : Owner(O) {}
644 virtual ~generic_parser_base() = default;
645 // Base class should have virtual-destructor
647 // getNumOptions - Virtual function implemented by generic subclass to
648 // indicate how many entries are in Values.
650 virtual unsigned getNumOptions() const = 0;
652 // getOption - Return option name N.
653 virtual StringRef getOption(unsigned N) const = 0;
655 // getDescription - Return description N
656 virtual StringRef getDescription(unsigned N) const = 0;
658 // Return the width of the option tag for printing...
659 virtual size_t getOptionWidth(const Option &O) const;
661 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
663 // printOptionInfo - Print out information about this option. The
664 // to-be-maintained width is specified.
666 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
668 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
669 const GenericOptionValue &Default,
670 size_t GlobalWidth) const;
672 // printOptionDiff - print the value of an option and it's default.
674 // Template definition ensures that the option and default have the same
675 // DataType (via the same AnyOptionValue).
676 template <class AnyOptionValue>
677 void printOptionDiff(const Option &O, const AnyOptionValue &V,
678 const AnyOptionValue &Default,
679 size_t GlobalWidth) const {
680 printGenericOptionDiff(O, V, Default, GlobalWidth);
685 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) {
686 // If there has been no argstr specified, that means that we need to add an
687 // argument for every possible option. This ensures that our options are
689 if (!Owner.hasArgStr())
690 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
691 OptionNames.push_back(getOption(i));
694 enum ValueExpected getValueExpectedFlagDefault() const {
695 // If there is an ArgStr specified, then we are of the form:
697 // -opt=O2 or -opt O2 or -optO2
699 // In which case, the value is required. Otherwise if an arg str has not
700 // been specified, we are of the form:
702 // -O2 or O2 or -la (where -l and -a are separate options)
704 // If this is the case, we cannot allow a value.
706 if (Owner.hasArgStr())
707 return ValueRequired;
709 return ValueDisallowed;
712 // findOption - Return the option number corresponding to the specified
713 // argument string. If the option is not found, getNumOptions() is returned.
715 unsigned findOption(StringRef Name);
721 // Default parser implementation - This implementation depends on having a
722 // mapping of recognized options to values of some sort. In addition to this,
723 // each entry in the mapping also tracks a help message that is printed with the
724 // command line option for -help. Because this is a simple mapping parser, the
725 // data type can be any unsupported type.
727 template <class DataType> class parser : public generic_parser_base {
729 class OptionInfo : public GenericOptionInfo {
731 OptionInfo(StringRef name, DataType v, StringRef helpStr)
732 : GenericOptionInfo(name, helpStr), V(v) {}
733 OptionValue<DataType> V;
735 SmallVector<OptionInfo, 8> Values;
738 parser(Option &O) : generic_parser_base(O) {}
739 typedef DataType parser_data_type;
741 // Implement virtual functions needed by generic_parser_base
742 unsigned getNumOptions() const override { return unsigned(Values.size()); }
743 StringRef getOption(unsigned N) const override { return Values[N].Name; }
744 StringRef getDescription(unsigned N) const override {
745 return Values[N].HelpStr;
748 // getOptionValue - Return the value of option name N.
749 const GenericOptionValue &getOptionValue(unsigned N) const override {
753 // parse - Return true on error.
754 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
756 if (Owner.hasArgStr())
761 for (size_t i = 0, e = Values.size(); i != e; ++i)
762 if (Values[i].Name == ArgVal) {
763 V = Values[i].V.getValue();
767 return O.error("Cannot find option named '" + ArgVal + "'!");
770 /// addLiteralOption - Add an entry to the mapping table.
773 void addLiteralOption(StringRef Name, const DT &V, StringRef HelpStr) {
774 assert(findOption(Name) == Values.size() && "Option already exists!");
775 OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
777 AddLiteralOption(Owner, Name);
780 /// removeLiteralOption - Remove the specified option.
782 void removeLiteralOption(StringRef Name) {
783 unsigned N = findOption(Name);
784 assert(N != Values.size() && "Option not found!");
785 Values.erase(Values.begin() + N);
789 //--------------------------------------------------
790 // basic_parser - Super class of parsers to provide boilerplate code
792 class basic_parser_impl { // non-template implementation of basic_parser<t>
794 basic_parser_impl(Option &) {}
796 enum ValueExpected getValueExpectedFlagDefault() const {
797 return ValueRequired;
800 void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
804 // Return the width of the option tag for printing...
805 size_t getOptionWidth(const Option &O) const;
807 // printOptionInfo - Print out information about this option. The
808 // to-be-maintained width is specified.
810 void printOptionInfo(const Option &O, size_t GlobalWidth) const;
812 // printOptionNoValue - Print a placeholder for options that don't yet support
813 // printOptionDiff().
814 void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
816 // getValueName - Overload in subclass to provide a better default value.
817 virtual StringRef getValueName() const { return "value"; }
819 // An out-of-line virtual method to provide a 'home' for this class.
820 virtual void anchor();
823 ~basic_parser_impl() = default;
825 // A helper for basic_parser::printOptionDiff.
826 void printOptionName(const Option &O, size_t GlobalWidth) const;
829 // basic_parser - The real basic parser is just a template wrapper that provides
830 // a typedef for the provided data type.
832 template <class DataType> class basic_parser : public basic_parser_impl {
834 basic_parser(Option &O) : basic_parser_impl(O) {}
836 typedef DataType parser_data_type;
837 typedef OptionValue<DataType> OptVal;
840 ~basic_parser() = default;
843 //--------------------------------------------------
846 template <> class parser<bool> final : public basic_parser<bool> {
848 parser(Option &O) : basic_parser(O) {}
850 // parse - Return true on error.
851 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
855 enum ValueExpected getValueExpectedFlagDefault() const {
856 return ValueOptional;
859 // getValueName - Do not print =<value> at all.
860 StringRef getValueName() const override { return StringRef(); }
862 void printOptionDiff(const Option &O, bool V, OptVal Default,
863 size_t GlobalWidth) const;
865 // An out-of-line virtual method to provide a 'home' for this class.
866 void anchor() override;
869 extern template class basic_parser<bool>;
871 //--------------------------------------------------
872 // parser<boolOrDefault>
874 class parser<boolOrDefault> final : public basic_parser<boolOrDefault> {
876 parser(Option &O) : basic_parser(O) {}
878 // parse - Return true on error.
879 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
881 enum ValueExpected getValueExpectedFlagDefault() const {
882 return ValueOptional;
885 // getValueName - Do not print =<value> at all.
886 StringRef getValueName() const override { return StringRef(); }
888 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
889 size_t GlobalWidth) const;
891 // An out-of-line virtual method to provide a 'home' for this class.
892 void anchor() override;
895 extern template class basic_parser<boolOrDefault>;
897 //--------------------------------------------------
900 template <> class parser<int> final : public basic_parser<int> {
902 parser(Option &O) : basic_parser(O) {}
904 // parse - Return true on error.
905 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
907 // getValueName - Overload in subclass to provide a better default value.
908 StringRef getValueName() const override { return "int"; }
910 void printOptionDiff(const Option &O, int V, OptVal Default,
911 size_t GlobalWidth) const;
913 // An out-of-line virtual method to provide a 'home' for this class.
914 void anchor() override;
917 extern template class basic_parser<int>;
919 //--------------------------------------------------
922 template <> class parser<unsigned> final : public basic_parser<unsigned> {
924 parser(Option &O) : basic_parser(O) {}
926 // parse - Return true on error.
927 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
929 // getValueName - Overload in subclass to provide a better default value.
930 StringRef getValueName() const override { return "uint"; }
932 void printOptionDiff(const Option &O, unsigned V, OptVal Default,
933 size_t GlobalWidth) const;
935 // An out-of-line virtual method to provide a 'home' for this class.
936 void anchor() override;
939 extern template class basic_parser<unsigned>;
941 //--------------------------------------------------
942 // parser<unsigned long long>
945 class parser<unsigned long long> final
946 : public basic_parser<unsigned long long> {
948 parser(Option &O) : basic_parser(O) {}
950 // parse - Return true on error.
951 bool parse(Option &O, StringRef ArgName, StringRef Arg,
952 unsigned long long &Val);
954 // getValueName - Overload in subclass to provide a better default value.
955 StringRef getValueName() const override { return "uint"; }
957 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
958 size_t GlobalWidth) const;
960 // An out-of-line virtual method to provide a 'home' for this class.
961 void anchor() override;
964 extern template class basic_parser<unsigned long long>;
966 //--------------------------------------------------
969 template <> class parser<double> final : public basic_parser<double> {
971 parser(Option &O) : basic_parser(O) {}
973 // parse - Return true on error.
974 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
976 // getValueName - Overload in subclass to provide a better default value.
977 StringRef getValueName() const override { return "number"; }
979 void printOptionDiff(const Option &O, double V, OptVal Default,
980 size_t GlobalWidth) const;
982 // An out-of-line virtual method to provide a 'home' for this class.
983 void anchor() override;
986 extern template class basic_parser<double>;
988 //--------------------------------------------------
991 template <> class parser<float> final : public basic_parser<float> {
993 parser(Option &O) : basic_parser(O) {}
995 // parse - Return true on error.
996 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
998 // getValueName - Overload in subclass to provide a better default value.
999 StringRef getValueName() const override { return "number"; }
1001 void printOptionDiff(const Option &O, float V, OptVal Default,
1002 size_t GlobalWidth) const;
1004 // An out-of-line virtual method to provide a 'home' for this class.
1005 void anchor() override;
1008 extern template class basic_parser<float>;
1010 //--------------------------------------------------
1011 // parser<std::string>
1013 template <> class parser<std::string> final : public basic_parser<std::string> {
1015 parser(Option &O) : basic_parser(O) {}
1017 // parse - Return true on error.
1018 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
1023 // getValueName - Overload in subclass to provide a better default value.
1024 StringRef getValueName() const override { return "string"; }
1026 void printOptionDiff(const Option &O, StringRef V, const OptVal &Default,
1027 size_t GlobalWidth) const;
1029 // An out-of-line virtual method to provide a 'home' for this class.
1030 void anchor() override;
1033 extern template class basic_parser<std::string>;
1035 //--------------------------------------------------
1038 template <> class parser<char> final : public basic_parser<char> {
1040 parser(Option &O) : basic_parser(O) {}
1042 // parse - Return true on error.
1043 bool parse(Option &, StringRef, StringRef Arg, char &Value) {
1048 // getValueName - Overload in subclass to provide a better default value.
1049 StringRef getValueName() const override { return "char"; }
1051 void printOptionDiff(const Option &O, char V, OptVal Default,
1052 size_t GlobalWidth) const;
1054 // An out-of-line virtual method to provide a 'home' for this class.
1055 void anchor() override;
1058 extern template class basic_parser<char>;
1060 //--------------------------------------------------
1063 // This collection of wrappers is the intermediary between class opt and class
1064 // parser to handle all the template nastiness.
1066 // This overloaded function is selected by the generic parser.
1067 template <class ParserClass, class DT>
1068 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
1069 const OptionValue<DT> &Default, size_t GlobalWidth) {
1070 OptionValue<DT> OV = V;
1071 P.printOptionDiff(O, OV, Default, GlobalWidth);
1074 // This is instantiated for basic parsers when the parsed value has a different
1075 // type than the option value. e.g. HelpPrinter.
1076 template <class ParserDT, class ValDT> struct OptionDiffPrinter {
1077 void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/,
1078 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
1079 P.printOptionNoValue(O, GlobalWidth);
1083 // This is instantiated for basic parsers when the parsed value has the same
1084 // type as the option value.
1085 template <class DT> struct OptionDiffPrinter<DT, DT> {
1086 void print(const Option &O, const parser<DT> &P, const DT &V,
1087 const OptionValue<DT> &Default, size_t GlobalWidth) {
1088 P.printOptionDiff(O, V, Default, GlobalWidth);
1092 // This overloaded function is selected by the basic parser, which may parse a
1093 // different type than the option type.
1094 template <class ParserClass, class ValDT>
1095 void printOptionDiff(
1097 const basic_parser<typename ParserClass::parser_data_type> &P,
1098 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
1100 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
1101 printer.print(O, static_cast<const ParserClass &>(P), V, Default,
1105 //===----------------------------------------------------------------------===//
1106 // applicator class - This class is used because we must use partial
1107 // specialization to handle literal string arguments specially (const char* does
1108 // not correctly respond to the apply method). Because the syntax to use this
1109 // is a pain, we have the 'apply' method below to handle the nastiness...
1111 template <class Mod> struct applicator {
1112 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1115 // Handle const char* as a special case...
1116 template <unsigned n> struct applicator<char[n]> {
1117 template <class Opt> static void opt(StringRef Str, Opt &O) {
1121 template <unsigned n> struct applicator<const char[n]> {
1122 template <class Opt> static void opt(StringRef Str, Opt &O) {
1126 template <> struct applicator<StringRef > {
1127 template <class Opt> static void opt(StringRef Str, Opt &O) {
1132 template <> struct applicator<NumOccurrencesFlag> {
1133 static void opt(NumOccurrencesFlag N, Option &O) {
1134 O.setNumOccurrencesFlag(N);
1138 template <> struct applicator<ValueExpected> {
1139 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1142 template <> struct applicator<OptionHidden> {
1143 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1146 template <> struct applicator<FormattingFlags> {
1147 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1150 template <> struct applicator<MiscFlags> {
1151 static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1154 // apply method - Apply modifiers to an option in a type safe way.
1155 template <class Opt, class Mod, class... Mods>
1156 void apply(Opt *O, const Mod &M, const Mods &... Ms) {
1157 applicator<Mod>::opt(M, *O);
1161 template <class Opt, class Mod> void apply(Opt *O, const Mod &M) {
1162 applicator<Mod>::opt(M, *O);
1165 //===----------------------------------------------------------------------===//
1166 // opt_storage class
1168 // Default storage class definition: external storage. This implementation
1169 // assumes the user will specify a variable to store the data into with the
1170 // cl::location(x) modifier.
1172 template <class DataType, bool ExternalStorage, bool isClass>
1174 DataType *Location = nullptr; // Where to store the object...
1175 OptionValue<DataType> Default;
1177 void check_location() const {
1178 assert(Location && "cl::location(...) not specified for a command "
1179 "line option with external storage, "
1180 "or cl::init specified before cl::location()!!");
1184 opt_storage() = default;
1186 bool setLocation(Option &O, DataType &L) {
1188 return O.error("cl::location(x) specified more than once!");
1194 template <class T> void setValue(const T &V, bool initial = false) {
1201 DataType &getValue() {
1205 const DataType &getValue() const {
1210 operator DataType() const { return this->getValue(); }
1212 const OptionValue<DataType> &getDefault() const { return Default; }
1215 // Define how to hold a class type object, such as a string. Since we can
1216 // inherit from a class, we do so. This makes us exactly compatible with the
1217 // object in all cases that it is used.
1219 template <class DataType>
1220 class opt_storage<DataType, false, true> : public DataType {
1222 OptionValue<DataType> Default;
1224 template <class T> void setValue(const T &V, bool initial = false) {
1225 DataType::operator=(V);
1230 DataType &getValue() { return *this; }
1231 const DataType &getValue() const { return *this; }
1233 const OptionValue<DataType> &getDefault() const { return Default; }
1236 // Define a partial specialization to handle things we cannot inherit from. In
1237 // this case, we store an instance through containment, and overload operators
1238 // to get at the value.
1240 template <class DataType> class opt_storage<DataType, false, false> {
1243 OptionValue<DataType> Default;
1245 // Make sure we initialize the value with the default constructor for the
1247 opt_storage() : Value(DataType()), Default(DataType()) {}
1249 template <class T> void setValue(const T &V, bool initial = false) {
1254 DataType &getValue() { return Value; }
1255 DataType getValue() const { return Value; }
1257 const OptionValue<DataType> &getDefault() const { return Default; }
1259 operator DataType() const { return getValue(); }
1261 // If the datatype is a pointer, support -> on it.
1262 DataType operator->() const { return Value; }
1265 //===----------------------------------------------------------------------===//
1266 // opt - A scalar command line option.
1268 template <class DataType, bool ExternalStorage = false,
1269 class ParserClass = parser<DataType>>
1270 class opt : public Option,
1271 public opt_storage<DataType, ExternalStorage,
1272 std::is_class<DataType>::value> {
1275 bool handleOccurrence(unsigned pos, StringRef ArgName,
1276 StringRef Arg) override {
1277 typename ParserClass::parser_data_type Val =
1278 typename ParserClass::parser_data_type();
1279 if (Parser.parse(*this, ArgName, Arg, Val))
1280 return true; // Parse error!
1281 this->setValue(Val);
1282 this->setPosition(pos);
1286 enum ValueExpected getValueExpectedFlagDefault() const override {
1287 return Parser.getValueExpectedFlagDefault();
1289 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1290 return Parser.getExtraOptionNames(OptionNames);
1293 // Forward printing stuff to the parser...
1294 size_t getOptionWidth() const override {
1295 return Parser.getOptionWidth(*this);
1297 void printOptionInfo(size_t GlobalWidth) const override {
1298 Parser.printOptionInfo(*this, GlobalWidth);
1301 void printOptionValue(size_t GlobalWidth, bool Force) const override {
1302 if (Force || this->getDefault().compare(this->getValue())) {
1303 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1304 this->getDefault(), GlobalWidth);
1310 Parser.initialize();
1314 // Command line options should not be copyable
1315 opt(const opt &) = delete;
1316 opt &operator=(const opt &) = delete;
1318 // setInitialValue - Used by the cl::init modifier...
1319 void setInitialValue(const DataType &V) { this->setValue(V, true); }
1321 ParserClass &getParser() { return Parser; }
1323 template <class T> DataType &operator=(const T &Val) {
1324 this->setValue(Val);
1325 return this->getValue();
1328 template <class... Mods>
1329 explicit opt(const Mods &... Ms)
1330 : Option(Optional, NotHidden), Parser(*this) {
1336 extern template class opt<unsigned>;
1337 extern template class opt<int>;
1338 extern template class opt<std::string>;
1339 extern template class opt<char>;
1340 extern template class opt<bool>;
1342 //===----------------------------------------------------------------------===//
1343 // list_storage class
1345 // Default storage class definition: external storage. This implementation
1346 // assumes the user will specify a variable to store the data into with the
1347 // cl::location(x) modifier.
1349 template <class DataType, class StorageClass> class list_storage {
1350 StorageClass *Location = nullptr; // Where to store the object...
1353 list_storage() = default;
1355 bool setLocation(Option &O, StorageClass &L) {
1357 return O.error("cl::location(x) specified more than once!");
1362 template <class T> void addValue(const T &V) {
1363 assert(Location != 0 && "cl::location(...) not specified for a command "
1364 "line option with external storage!");
1365 Location->push_back(V);
1369 // Define how to hold a class type object, such as a string.
1370 // Originally this code inherited from std::vector. In transitioning to a new
1371 // API for command line options we should change this. The new implementation
1372 // of this list_storage specialization implements the minimum subset of the
1373 // std::vector API required for all the current clients.
1375 // FIXME: Reduce this API to a more narrow subset of std::vector
1377 template <class DataType> class list_storage<DataType, bool> {
1378 std::vector<DataType> Storage;
1381 typedef typename std::vector<DataType>::iterator iterator;
1383 iterator begin() { return Storage.begin(); }
1384 iterator end() { return Storage.end(); }
1386 typedef typename std::vector<DataType>::const_iterator const_iterator;
1387 const_iterator begin() const { return Storage.begin(); }
1388 const_iterator end() const { return Storage.end(); }
1390 typedef typename std::vector<DataType>::size_type size_type;
1391 size_type size() const { return Storage.size(); }
1393 bool empty() const { return Storage.empty(); }
1395 void push_back(const DataType &value) { Storage.push_back(value); }
1396 void push_back(DataType &&value) { Storage.push_back(value); }
1398 typedef typename std::vector<DataType>::reference reference;
1399 typedef typename std::vector<DataType>::const_reference const_reference;
1400 reference operator[](size_type pos) { return Storage[pos]; }
1401 const_reference operator[](size_type pos) const { return Storage[pos]; }
1403 iterator erase(const_iterator pos) { return Storage.erase(pos); }
1404 iterator erase(const_iterator first, const_iterator last) {
1405 return Storage.erase(first, last);
1408 iterator erase(iterator pos) { return Storage.erase(pos); }
1409 iterator erase(iterator first, iterator last) {
1410 return Storage.erase(first, last);
1413 iterator insert(const_iterator pos, const DataType &value) {
1414 return Storage.insert(pos, value);
1416 iterator insert(const_iterator pos, DataType &&value) {
1417 return Storage.insert(pos, value);
1420 iterator insert(iterator pos, const DataType &value) {
1421 return Storage.insert(pos, value);
1423 iterator insert(iterator pos, DataType &&value) {
1424 return Storage.insert(pos, value);
1427 reference front() { return Storage.front(); }
1428 const_reference front() const { return Storage.front(); }
1430 operator std::vector<DataType>&() { return Storage; }
1431 operator ArrayRef<DataType>() { return Storage; }
1432 std::vector<DataType> *operator&() { return &Storage; }
1433 const std::vector<DataType> *operator&() const { return &Storage; }
1435 template <class T> void addValue(const T &V) { Storage.push_back(V); }
1438 //===----------------------------------------------------------------------===//
1439 // list - A list of command line options.
1441 template <class DataType, class StorageClass = bool,
1442 class ParserClass = parser<DataType>>
1443 class list : public Option, public list_storage<DataType, StorageClass> {
1444 std::vector<unsigned> Positions;
1447 enum ValueExpected getValueExpectedFlagDefault() const override {
1448 return Parser.getValueExpectedFlagDefault();
1450 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1451 return Parser.getExtraOptionNames(OptionNames);
1454 bool handleOccurrence(unsigned pos, StringRef ArgName,
1455 StringRef Arg) override {
1456 typename ParserClass::parser_data_type Val =
1457 typename ParserClass::parser_data_type();
1458 if (Parser.parse(*this, ArgName, Arg, Val))
1459 return true; // Parse Error!
1460 list_storage<DataType, StorageClass>::addValue(Val);
1462 Positions.push_back(pos);
1466 // Forward printing stuff to the parser...
1467 size_t getOptionWidth() const override {
1468 return Parser.getOptionWidth(*this);
1470 void printOptionInfo(size_t GlobalWidth) const override {
1471 Parser.printOptionInfo(*this, GlobalWidth);
1474 // Unimplemented: list options don't currently store their default value.
1475 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1480 Parser.initialize();
1484 // Command line options should not be copyable
1485 list(const list &) = delete;
1486 list &operator=(const list &) = delete;
1488 ParserClass &getParser() { return Parser; }
1490 unsigned getPosition(unsigned optnum) const {
1491 assert(optnum < this->size() && "Invalid option index");
1492 return Positions[optnum];
1495 void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
1497 template <class... Mods>
1498 explicit list(const Mods &... Ms)
1499 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1505 // multi_val - Modifier to set the number of additional values.
1507 unsigned AdditionalVals;
1508 explicit multi_val(unsigned N) : AdditionalVals(N) {}
1510 template <typename D, typename S, typename P>
1511 void apply(list<D, S, P> &L) const {
1512 L.setNumAdditionalVals(AdditionalVals);
1516 //===----------------------------------------------------------------------===//
1517 // bits_storage class
1519 // Default storage class definition: external storage. This implementation
1520 // assumes the user will specify a variable to store the data into with the
1521 // cl::location(x) modifier.
1523 template <class DataType, class StorageClass> class bits_storage {
1524 unsigned *Location = nullptr; // Where to store the bits...
1526 template <class T> static unsigned Bit(const T &V) {
1527 unsigned BitPos = reinterpret_cast<unsigned>(V);
1528 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1529 "enum exceeds width of bit vector!");
1534 bits_storage() = default;
1536 bool setLocation(Option &O, unsigned &L) {
1538 return O.error("cl::location(x) specified more than once!");
1543 template <class T> void addValue(const T &V) {
1544 assert(Location != 0 && "cl::location(...) not specified for a command "
1545 "line option with external storage!");
1546 *Location |= Bit(V);
1549 unsigned getBits() { return *Location; }
1551 template <class T> bool isSet(const T &V) {
1552 return (*Location & Bit(V)) != 0;
1556 // Define how to hold bits. Since we can inherit from a class, we do so.
1557 // This makes us exactly compatible with the bits in all cases that it is used.
1559 template <class DataType> class bits_storage<DataType, bool> {
1560 unsigned Bits; // Where to store the bits...
1562 template <class T> static unsigned Bit(const T &V) {
1563 unsigned BitPos = (unsigned)V;
1564 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1565 "enum exceeds width of bit vector!");
1570 template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1572 unsigned getBits() { return Bits; }
1574 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1577 //===----------------------------------------------------------------------===//
1578 // bits - A bit vector of command options.
1580 template <class DataType, class Storage = bool,
1581 class ParserClass = parser<DataType>>
1582 class bits : public Option, public bits_storage<DataType, Storage> {
1583 std::vector<unsigned> Positions;
1586 enum ValueExpected getValueExpectedFlagDefault() const override {
1587 return Parser.getValueExpectedFlagDefault();
1589 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1590 return Parser.getExtraOptionNames(OptionNames);
1593 bool handleOccurrence(unsigned pos, StringRef ArgName,
1594 StringRef Arg) override {
1595 typename ParserClass::parser_data_type Val =
1596 typename ParserClass::parser_data_type();
1597 if (Parser.parse(*this, ArgName, Arg, Val))
1598 return true; // Parse Error!
1599 this->addValue(Val);
1601 Positions.push_back(pos);
1605 // Forward printing stuff to the parser...
1606 size_t getOptionWidth() const override {
1607 return Parser.getOptionWidth(*this);
1609 void printOptionInfo(size_t GlobalWidth) const override {
1610 Parser.printOptionInfo(*this, GlobalWidth);
1613 // Unimplemented: bits options don't currently store their default values.
1614 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1619 Parser.initialize();
1623 // Command line options should not be copyable
1624 bits(const bits &) = delete;
1625 bits &operator=(const bits &) = delete;
1627 ParserClass &getParser() { return Parser; }
1629 unsigned getPosition(unsigned optnum) const {
1630 assert(optnum < this->size() && "Invalid option index");
1631 return Positions[optnum];
1634 template <class... Mods>
1635 explicit bits(const Mods &... Ms)
1636 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1642 //===----------------------------------------------------------------------===//
1643 // Aliased command line option (alias this name to a preexisting name)
1646 class alias : public Option {
1649 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1650 StringRef Arg) override {
1651 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1654 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1655 bool MultiArg = false) override {
1656 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1659 // Handle printing stuff...
1660 size_t getOptionWidth() const override;
1661 void printOptionInfo(size_t GlobalWidth) const override;
1663 // Aliases do not need to print their values.
1664 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1667 ValueExpected getValueExpectedFlagDefault() const override {
1668 return AliasFor->getValueExpectedFlag();
1673 error("cl::alias must have argument name specified!");
1675 error("cl::alias must have an cl::aliasopt(option) specified!");
1676 Subs = AliasFor->Subs;
1681 // Command line options should not be copyable
1682 alias(const alias &) = delete;
1683 alias &operator=(const alias &) = delete;
1685 void setAliasFor(Option &O) {
1687 error("cl::alias must only have one cl::aliasopt(...) specified!");
1691 template <class... Mods>
1692 explicit alias(const Mods &... Ms)
1693 : Option(Optional, Hidden), AliasFor(nullptr) {
1699 // aliasfor - Modifier to set the option an alias aliases.
1703 explicit aliasopt(Option &O) : Opt(O) {}
1705 void apply(alias &A) const { A.setAliasFor(Opt); }
1708 // extrahelp - provide additional help at the end of the normal help
1709 // output. All occurrences of cl::extrahelp will be accumulated and
1710 // printed to stderr at the end of the regular help, just before
1715 explicit extrahelp(StringRef help);
1718 void PrintVersionMessage();
1720 /// This function just prints the help message, exactly the same way as if the
1721 /// -help or -help-hidden option had been given on the command line.
1723 /// NOTE: THIS FUNCTION TERMINATES THE PROGRAM!
1725 /// \param Hidden if true will print hidden options
1726 /// \param Categorized if true print options in categories
1727 void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
1729 //===----------------------------------------------------------------------===//
1730 // Public interface for accessing registered options.
1733 /// \brief Use this to get a StringMap to all registered named options
1734 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1736 /// \return A reference to the StringMap used by the cl APIs to parse options.
1738 /// Access to unnamed arguments (i.e. positional) are not provided because
1739 /// it is expected that the client already has access to these.
1743 /// main(int argc,char* argv[]) {
1744 /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions();
1745 /// assert(opts.count("help") == 1)
1746 /// opts["help"]->setDescription("Show alphabetical help information")
1748 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1753 /// This interface is useful for modifying options in libraries that are out of
1754 /// the control of the client. The options should be modified before calling
1755 /// llvm::cl::ParseCommandLineOptions().
1757 /// Hopefully this API can be deprecated soon. Any situation where options need
1758 /// to be modified by tools or libraries should be handled by sane APIs rather
1759 /// than just handing around a global list.
1760 StringMap<Option *> &getRegisteredOptions(SubCommand &Sub = *TopLevelSubCommand);
1762 /// \brief Use this to get all registered SubCommands from the provided parser.
1764 /// \return A range of all SubCommand pointers registered with the parser.
1768 /// main(int argc, char* argv[]) {
1769 /// llvm::cl::ParseCommandLineOptions(argc, argv);
1770 /// for (auto* S : llvm::cl::getRegisteredSubcommands()) {
1772 /// std::cout << "Executing subcommand: " << S->getName() << std::endl;
1773 /// // Execute some function based on the name...
1779 /// This interface is useful for defining subcommands in libraries and
1780 /// the dispatch from a single point (like in the main function).
1781 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
1782 getRegisteredSubcommands();
1784 //===----------------------------------------------------------------------===//
1785 // Standalone command line processing utilities.
1788 /// \brief Tokenizes a command line that can contain escapes and quotes.
1790 /// The quoting rules match those used by GCC and other tools that use
1791 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1792 /// They differ from buildargv() on treatment of backslashes that do not escape
1793 /// a special character to make it possible to accept most Windows file paths.
1795 /// \param [in] Source The string to be split on whitespace with quotes.
1796 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1797 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1798 /// lines and end of the response file to be marked with a nullptr string.
1799 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1800 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
1801 SmallVectorImpl<const char *> &NewArgv,
1802 bool MarkEOLs = false);
1804 /// \brief Tokenizes a Windows command line which may contain quotes and escaped
1807 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1808 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1810 /// \param [in] Source The string to be split on whitespace with quotes.
1811 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1812 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1813 /// lines and end of the response file to be marked with a nullptr string.
1814 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1815 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
1816 SmallVectorImpl<const char *> &NewArgv,
1817 bool MarkEOLs = false);
1819 /// \brief String tokenization function type. Should be compatible with either
1820 /// Windows or Unix command line tokenizers.
1821 typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
1822 SmallVectorImpl<const char *> &NewArgv,
1825 /// \brief Expand response files on a command line recursively using the given
1826 /// StringSaver and tokenization strategy. Argv should contain the command line
1827 /// before expansion and will be modified in place. If requested, Argv will
1828 /// also be populated with nullptrs indicating where each response file line
1829 /// ends, which is useful for the "/link" argument that needs to consume all
1830 /// remaining arguments only until the next end of line, when in a response
1833 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1834 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1835 /// \param [in,out] Argv Command line into which to expand response files.
1836 /// \param [in] MarkEOLs Mark end of lines and the end of the response file
1837 /// with nullptrs in the Argv vector.
1838 /// \param [in] RelativeNames true if names of nested response files must be
1839 /// resolved relative to including file.
1840 /// \return true if all @files were expanded successfully or there were none.
1841 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1842 SmallVectorImpl<const char *> &Argv,
1843 bool MarkEOLs = false, bool RelativeNames = false);
1845 /// \brief Mark all options not part of this category as cl::ReallyHidden.
1847 /// \param Category the category of options to keep displaying
1849 /// Some tools (like clang-format) like to be able to hide all options that are
1850 /// not specific to the tool. This function allows a tool to specify a single
1851 /// option category to display in the -help output.
1852 void HideUnrelatedOptions(cl::OptionCategory &Category,
1853 SubCommand &Sub = *TopLevelSubCommand);
1855 /// \brief Mark all options not part of the categories as cl::ReallyHidden.
1857 /// \param Categories the categories of options to keep displaying.
1859 /// Some tools (like clang-format) like to be able to hide all options that are
1860 /// not specific to the tool. This function allows a tool to specify a single
1861 /// option category to display in the -help output.
1862 void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
1863 SubCommand &Sub = *TopLevelSubCommand);
1865 /// \brief Reset all command line options to a state that looks as if they have
1866 /// never appeared on the command line. This is useful for being able to parse
1867 /// a command line multiple times (especially useful for writing tests).
1868 void ResetAllOptionOccurrences();
1870 /// \brief Reset the command line parser back to its initial state. This
1872 /// all options, categories, and subcommands and returns the parser to a state
1873 /// where no options are supported.
1874 void ResetCommandLineParser();
1876 } // end namespace cl
1877 } // end namespace llvm
1879 #endif // LLVM_SUPPORT_COMMANDLINE_H