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 // Function pointer type for printing version information.
70 using VersionPrinterTy = std::function<void(raw_ostream &)>;
72 ///===---------------------------------------------------------------------===//
73 /// SetVersionPrinter - Override the default (LLVM specific) version printer
74 /// used to print out the version when --version is given
75 /// on the command line. This allows other systems using the
76 /// CommandLine utilities to print their own version string.
77 void SetVersionPrinter(VersionPrinterTy func);
79 ///===---------------------------------------------------------------------===//
80 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
81 /// default one. This can be called multiple times,
82 /// and each time it adds a new function to the list
83 /// which will be called after the basic LLVM version
84 /// printing is complete. Each can then add additional
85 /// information specific to the tool.
86 void AddExtraVersionPrinter(VersionPrinterTy func);
88 // PrintOptionValues - Print option values.
89 // With -print-options print the difference between option values and defaults.
90 // With -print-all-options print all option values.
91 // (Currently not perfect, but best-effort.)
92 void PrintOptionValues();
94 // Forward declaration - AddLiteralOption needs to be up here to make gcc happy.
97 /// \brief Adds a new option for parsing and provides the option it refers to.
99 /// \param O pointer to the option
100 /// \param Name the string name for the option to handle during parsing
102 /// Literal options are used by some parsers to register special option values.
103 /// This is how the PassNameParser registers pass names for opt.
104 void AddLiteralOption(Option &O, StringRef Name);
106 //===----------------------------------------------------------------------===//
107 // Flags permitted to be passed to command line arguments
110 enum NumOccurrencesFlag { // Flags for the number of occurrences allowed
111 Optional = 0x00, // Zero or One occurrence
112 ZeroOrMore = 0x01, // Zero or more occurrences allowed
113 Required = 0x02, // One occurrence required
114 OneOrMore = 0x03, // One or more occurrences required
116 // ConsumeAfter - Indicates that this option is fed anything that follows the
117 // last positional argument required by the application (it is an error if
118 // there are zero positional arguments, and a ConsumeAfter option is used).
119 // Thus, for example, all arguments to LLI are processed until a filename is
120 // found. Once a filename is found, all of the succeeding arguments are
121 // passed, unprocessed, to the ConsumeAfter option.
126 enum ValueExpected { // Is a value required for the option?
127 // zero reserved for the unspecified value
128 ValueOptional = 0x01, // The value can appear... or not
129 ValueRequired = 0x02, // The value is required to appear!
130 ValueDisallowed = 0x03 // A value may not be specified (for flags)
133 enum OptionHidden { // Control whether -help shows this option
134 NotHidden = 0x00, // Option included in -help & -help-hidden
135 Hidden = 0x01, // -help doesn't, but -help-hidden does
136 ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg
139 // Formatting flags - This controls special features that the option might have
140 // that cause it to be parsed differently...
142 // Prefix - This option allows arguments that are otherwise unrecognized to be
143 // matched by options that are a prefix of the actual value. This is useful for
144 // cases like a linker, where options are typically of the form '-lfoo' or
145 // '-L../../include' where -l or -L are the actual flags. When prefix is
146 // enabled, and used, the value for the flag comes from the suffix of the
149 // Grouping - With this option enabled, multiple letter options are allowed to
150 // bunch together with only a single hyphen for the whole group. This allows
151 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
154 enum FormattingFlags {
155 NormalFormatting = 0x00, // Nothing special
156 Positional = 0x01, // Is a positional argument, no '-' required
157 Prefix = 0x02, // Can this option directly prefix its value?
158 Grouping = 0x03 // Can this option group with other options?
161 enum MiscFlags { // Miscellaneous flags to adjust argument
162 CommaSeparated = 0x01, // Should this cl::list split between commas?
163 PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args?
164 Sink = 0x04 // Should this cl::list eat all unknown options?
167 //===----------------------------------------------------------------------===//
168 // Option Category class
170 class OptionCategory {
172 StringRef const Name;
173 StringRef const Description;
175 void registerCategory();
178 OptionCategory(StringRef const Name,
179 StringRef const Description = "")
180 : Name(Name), Description(Description) {
184 StringRef getName() const { return Name; }
185 StringRef getDescription() const { return Description; }
188 // The general Option Category (used as default category).
189 extern OptionCategory GeneralCategory;
191 //===----------------------------------------------------------------------===//
197 StringRef Description;
200 void registerSubCommand();
201 void unregisterSubCommand();
204 SubCommand(StringRef Name, StringRef Description = "")
205 : Name(Name), Description(Description) {
206 registerSubCommand();
208 SubCommand() = default;
212 explicit operator bool() const;
214 StringRef getName() const { return Name; }
215 StringRef getDescription() const { return Description; }
217 SmallVector<Option *, 4> PositionalOpts;
218 SmallVector<Option *, 4> SinkOpts;
219 StringMap<Option *> OptionsMap;
221 Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists.
224 // A special subcommand representing no subcommand
225 extern ManagedStatic<SubCommand> TopLevelSubCommand;
227 // A special subcommand that can be used to put an option into all subcommands.
228 extern ManagedStatic<SubCommand> AllSubCommands;
230 //===----------------------------------------------------------------------===//
236 // handleOccurrences - Overriden by subclasses to handle the value passed into
237 // an argument. Should return true if there was an error processing the
238 // argument and the program should exit.
240 virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
243 virtual enum ValueExpected getValueExpectedFlagDefault() const {
244 return ValueOptional;
247 // Out of line virtual function to provide home for the class.
248 virtual void anchor();
250 int NumOccurrences = 0; // The number of times specified
251 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
252 // problems with signed enums in bitfields.
253 unsigned Occurrences : 3; // enum NumOccurrencesFlag
254 // not using the enum type for 'Value' because zero is an implementation
255 // detail representing the non-value
257 unsigned HiddenFlag : 2; // enum OptionHidden
258 unsigned Formatting : 2; // enum FormattingFlags
260 unsigned Position = 0; // Position of last occurrence of the option
261 unsigned AdditionalVals = 0; // Greater than 0 for multi-valued option.
264 StringRef ArgStr; // The argument string itself (ex: "help", "o")
265 StringRef HelpStr; // The descriptive text message for -help
266 StringRef ValueStr; // String describing what the value of this option is
267 OptionCategory *Category; // The Category this option belongs to
268 SmallPtrSet<SubCommand *, 4> Subs; // The subcommands this option belongs to.
269 bool FullyInitialized = false; // Has addArgument been called?
271 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
272 return (enum NumOccurrencesFlag)Occurrences;
275 inline enum ValueExpected getValueExpectedFlag() const {
276 return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
279 inline enum OptionHidden getOptionHiddenFlag() const {
280 return (enum OptionHidden)HiddenFlag;
283 inline enum FormattingFlags getFormattingFlag() const {
284 return (enum FormattingFlags)Formatting;
287 inline unsigned getMiscFlags() const { return Misc; }
288 inline unsigned getPosition() const { return Position; }
289 inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
291 // hasArgStr - Return true if the argstr != ""
292 bool hasArgStr() const { return !ArgStr.empty(); }
293 bool isPositional() const { return getFormattingFlag() == cl::Positional; }
294 bool isSink() const { return getMiscFlags() & cl::Sink; }
296 bool isConsumeAfter() const {
297 return getNumOccurrencesFlag() == cl::ConsumeAfter;
300 bool isInAllSubCommands() const {
301 return any_of(Subs, [](const SubCommand *SC) {
302 return SC == &*AllSubCommands;
306 //-------------------------------------------------------------------------===
307 // Accessor functions set by OptionModifiers
309 void setArgStr(StringRef S);
310 void setDescription(StringRef S) { HelpStr = S; }
311 void setValueStr(StringRef S) { ValueStr = S; }
312 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
313 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
314 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
315 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
316 void setMiscFlag(enum MiscFlags M) { Misc |= M; }
317 void setPosition(unsigned pos) { Position = pos; }
318 void setCategory(OptionCategory &C) { Category = &C; }
319 void addSubCommand(SubCommand &S) { Subs.insert(&S); }
322 explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
323 enum OptionHidden Hidden)
324 : Occurrences(OccurrencesFlag), Value(0), HiddenFlag(Hidden),
325 Formatting(NormalFormatting), Misc(0), Category(&GeneralCategory) {}
327 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
330 virtual ~Option() = default;
332 // addArgument - Register this argument with the commandline system.
336 /// Unregisters this option from the CommandLine system.
338 /// This option must have been the last option registered.
339 /// For testing purposes only.
340 void removeArgument();
342 // Return the width of the option tag for printing...
343 virtual size_t getOptionWidth() const = 0;
345 // printOptionInfo - Print out information about this option. The
346 // to-be-maintained width is specified.
348 virtual void printOptionInfo(size_t GlobalWidth) const = 0;
350 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
352 virtual void setDefault() = 0;
354 static void printHelpStr(StringRef HelpStr, size_t Indent,
355 size_t FirstLineIndentedBy);
357 virtual void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
359 // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
361 virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
362 bool MultiArg = false);
364 // Prints option name followed by message. Always returns true.
365 bool error(const Twine &Message, StringRef ArgName = StringRef());
367 inline int getNumOccurrences() const { return NumOccurrences; }
368 inline void reset() { NumOccurrences = 0; }
371 //===----------------------------------------------------------------------===//
372 // Command line option modifiers that can be used to modify the behavior of
373 // command line option parsers...
376 // desc - Modifier to set the description shown in the -help output...
380 desc(StringRef Str) : Desc(Str) {}
382 void apply(Option &O) const { O.setDescription(Desc); }
385 // value_desc - Modifier to set the value description shown in the -help
390 value_desc(StringRef Str) : Desc(Str) {}
392 void apply(Option &O) const { O.setValueStr(Desc); }
395 // init - Specify a default (initial) value for the command line argument, if
396 // the default constructor for the argument type does not give you what you
397 // want. This is only valid on "opt" arguments, not on "list" arguments.
399 template <class Ty> struct initializer {
401 initializer(const Ty &Val) : Init(Val) {}
403 template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
406 template <class Ty> initializer<Ty> init(const Ty &Val) {
407 return initializer<Ty>(Val);
410 // location - Allow the user to specify which external variable they want to
411 // store the results of the command line argument processing into, if they don't
412 // want to store it in the option itself.
414 template <class Ty> struct LocationClass {
417 LocationClass(Ty &L) : Loc(L) {}
419 template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
422 template <class Ty> LocationClass<Ty> location(Ty &L) {
423 return LocationClass<Ty>(L);
426 // cat - Specifiy the Option category for the command line argument to belong
429 OptionCategory &Category;
431 cat(OptionCategory &c) : Category(c) {}
433 template <class Opt> void apply(Opt &O) const { O.setCategory(Category); }
436 // sub - Specify the subcommand that this option belongs to.
440 sub(SubCommand &S) : Sub(S) {}
442 template <class Opt> void apply(Opt &O) const { O.addSubCommand(Sub); }
445 //===----------------------------------------------------------------------===//
448 // Support value comparison outside the template.
449 struct GenericOptionValue {
450 virtual bool compare(const GenericOptionValue &V) const = 0;
453 GenericOptionValue() = default;
454 GenericOptionValue(const GenericOptionValue&) = default;
455 GenericOptionValue &operator=(const GenericOptionValue &) = default;
456 ~GenericOptionValue() = default;
459 virtual void anchor();
462 template <class DataType> struct OptionValue;
464 // The default value safely does nothing. Option value printing is only
466 template <class DataType, bool isClass>
467 struct OptionValueBase : public GenericOptionValue {
468 // Temporary storage for argument passing.
469 using WrapperType = OptionValue<DataType>;
471 bool hasValue() const { return false; }
473 const DataType &getValue() const { llvm_unreachable("no default value"); }
475 // Some options may take their value from a different data type.
476 template <class DT> void setValue(const DT & /*V*/) {}
478 bool compare(const DataType & /*V*/) const { return false; }
480 bool compare(const GenericOptionValue & /*V*/) const override {
485 ~OptionValueBase() = default;
488 // Simple copy of the option value.
489 template <class DataType> class OptionValueCopy : public GenericOptionValue {
494 OptionValueCopy(const OptionValueCopy&) = default;
495 OptionValueCopy &operator=(const OptionValueCopy &) = default;
496 ~OptionValueCopy() = default;
499 OptionValueCopy() = default;
501 bool hasValue() const { return Valid; }
503 const DataType &getValue() const {
504 assert(Valid && "invalid option value");
508 void setValue(const DataType &V) {
513 bool compare(const DataType &V) const { return Valid && (Value != V); }
515 bool compare(const GenericOptionValue &V) const override {
516 const OptionValueCopy<DataType> &VC =
517 static_cast<const OptionValueCopy<DataType> &>(V);
520 return compare(VC.getValue());
524 // Non-class option values.
525 template <class DataType>
526 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
527 using WrapperType = DataType;
530 OptionValueBase() = default;
531 OptionValueBase(const OptionValueBase&) = default;
532 OptionValueBase &operator=(const OptionValueBase &) = default;
533 ~OptionValueBase() = default;
536 // Top-level option class.
537 template <class DataType>
538 struct OptionValue final
539 : OptionValueBase<DataType, std::is_class<DataType>::value> {
540 OptionValue() = default;
542 OptionValue(const DataType &V) { this->setValue(V); }
544 // Some options may take their value from a different data type.
545 template <class DT> OptionValue<DataType> &operator=(const DT &V) {
551 // Other safe-to-copy-by-value common option types.
552 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
554 struct OptionValue<cl::boolOrDefault> final
555 : OptionValueCopy<cl::boolOrDefault> {
556 using WrapperType = cl::boolOrDefault;
558 OptionValue() = default;
560 OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
562 OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
568 void anchor() override;
572 struct OptionValue<std::string> final : OptionValueCopy<std::string> {
573 using WrapperType = StringRef;
575 OptionValue() = default;
577 OptionValue(const std::string &V) { this->setValue(V); }
579 OptionValue<std::string> &operator=(const std::string &V) {
585 void anchor() override;
588 //===----------------------------------------------------------------------===//
589 // Enum valued command line option
592 // This represents a single enum value, using "int" as the underlying type.
593 struct OptionEnumValue {
596 StringRef Description;
599 #define clEnumVal(ENUMVAL, DESC) \
600 llvm::cl::OptionEnumValue { #ENUMVAL, int(ENUMVAL), DESC }
601 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) \
602 llvm::cl::OptionEnumValue { FLAGNAME, int(ENUMVAL), DESC }
604 // values - For custom data types, allow specifying a group of values together
605 // as the values that go into the mapping that the option handler uses.
608 // Use a vector instead of a map, because the lists should be short,
609 // the overhead is less, and most importantly, it keeps them in the order
610 // inserted so we can print our option out nicely.
611 SmallVector<OptionEnumValue, 4> Values;
614 ValuesClass(std::initializer_list<OptionEnumValue> Options)
617 template <class Opt> void apply(Opt &O) const {
618 for (auto Value : Values)
619 O.getParser().addLiteralOption(Value.Name, Value.Value,
624 /// Helper to build a ValuesClass by forwarding a variable number of arguments
625 /// as an initializer list to the ValuesClass constructor.
626 template <typename... OptsTy> ValuesClass values(OptsTy... Options) {
627 return ValuesClass({Options...});
630 //===----------------------------------------------------------------------===//
631 // parser class - Parameterizable parser for different data types. By default,
632 // known data types (string, int, bool) have specialized parsers, that do what
633 // you would expect. The default parser, used for data types that are not
634 // built-in, uses a mapping table to map specific options to values, which is
635 // used, among other things, to handle enum types.
637 //--------------------------------------------------
638 // generic_parser_base - This class holds all the non-generic code that we do
639 // not need replicated for every instance of the generic parser. This also
640 // allows us to put stuff into CommandLine.cpp
642 class generic_parser_base {
644 class GenericOptionInfo {
646 GenericOptionInfo(StringRef name, StringRef helpStr)
647 : Name(name), HelpStr(helpStr) {}
653 generic_parser_base(Option &O) : Owner(O) {}
655 virtual ~generic_parser_base() = default;
656 // Base class should have virtual-destructor
658 // getNumOptions - Virtual function implemented by generic subclass to
659 // indicate how many entries are in Values.
661 virtual unsigned getNumOptions() const = 0;
663 // getOption - Return option name N.
664 virtual StringRef getOption(unsigned N) const = 0;
666 // getDescription - Return description N
667 virtual StringRef getDescription(unsigned N) const = 0;
669 // Return the width of the option tag for printing...
670 virtual size_t getOptionWidth(const Option &O) const;
672 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
674 // printOptionInfo - Print out information about this option. The
675 // to-be-maintained width is specified.
677 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
679 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
680 const GenericOptionValue &Default,
681 size_t GlobalWidth) const;
683 // printOptionDiff - print the value of an option and it's default.
685 // Template definition ensures that the option and default have the same
686 // DataType (via the same AnyOptionValue).
687 template <class AnyOptionValue>
688 void printOptionDiff(const Option &O, const AnyOptionValue &V,
689 const AnyOptionValue &Default,
690 size_t GlobalWidth) const {
691 printGenericOptionDiff(O, V, Default, GlobalWidth);
696 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) {
697 // If there has been no argstr specified, that means that we need to add an
698 // argument for every possible option. This ensures that our options are
700 if (!Owner.hasArgStr())
701 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
702 OptionNames.push_back(getOption(i));
705 enum ValueExpected getValueExpectedFlagDefault() const {
706 // If there is an ArgStr specified, then we are of the form:
708 // -opt=O2 or -opt O2 or -optO2
710 // In which case, the value is required. Otherwise if an arg str has not
711 // been specified, we are of the form:
713 // -O2 or O2 or -la (where -l and -a are separate options)
715 // If this is the case, we cannot allow a value.
717 if (Owner.hasArgStr())
718 return ValueRequired;
720 return ValueDisallowed;
723 // findOption - Return the option number corresponding to the specified
724 // argument string. If the option is not found, getNumOptions() is returned.
726 unsigned findOption(StringRef Name);
732 // Default parser implementation - This implementation depends on having a
733 // mapping of recognized options to values of some sort. In addition to this,
734 // each entry in the mapping also tracks a help message that is printed with the
735 // command line option for -help. Because this is a simple mapping parser, the
736 // data type can be any unsupported type.
738 template <class DataType> class parser : public generic_parser_base {
740 class OptionInfo : public GenericOptionInfo {
742 OptionInfo(StringRef name, DataType v, StringRef helpStr)
743 : GenericOptionInfo(name, helpStr), V(v) {}
745 OptionValue<DataType> V;
747 SmallVector<OptionInfo, 8> Values;
750 parser(Option &O) : generic_parser_base(O) {}
752 using parser_data_type = DataType;
754 // Implement virtual functions needed by generic_parser_base
755 unsigned getNumOptions() const override { return unsigned(Values.size()); }
756 StringRef getOption(unsigned N) const override { return Values[N].Name; }
757 StringRef getDescription(unsigned N) const override {
758 return Values[N].HelpStr;
761 // getOptionValue - Return the value of option name N.
762 const GenericOptionValue &getOptionValue(unsigned N) const override {
766 // parse - Return true on error.
767 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
769 if (Owner.hasArgStr())
774 for (size_t i = 0, e = Values.size(); i != e; ++i)
775 if (Values[i].Name == ArgVal) {
776 V = Values[i].V.getValue();
780 return O.error("Cannot find option named '" + ArgVal + "'!");
783 /// addLiteralOption - Add an entry to the mapping table.
786 void addLiteralOption(StringRef Name, const DT &V, StringRef HelpStr) {
787 assert(findOption(Name) == Values.size() && "Option already exists!");
788 OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
790 AddLiteralOption(Owner, Name);
793 /// removeLiteralOption - Remove the specified option.
795 void removeLiteralOption(StringRef Name) {
796 unsigned N = findOption(Name);
797 assert(N != Values.size() && "Option not found!");
798 Values.erase(Values.begin() + N);
802 //--------------------------------------------------
803 // basic_parser - Super class of parsers to provide boilerplate code
805 class basic_parser_impl { // non-template implementation of basic_parser<t>
807 basic_parser_impl(Option &) {}
809 enum ValueExpected getValueExpectedFlagDefault() const {
810 return ValueRequired;
813 void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
817 // Return the width of the option tag for printing...
818 size_t getOptionWidth(const Option &O) const;
820 // printOptionInfo - Print out information about this option. The
821 // to-be-maintained width is specified.
823 void printOptionInfo(const Option &O, size_t GlobalWidth) const;
825 // printOptionNoValue - Print a placeholder for options that don't yet support
826 // printOptionDiff().
827 void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
829 // getValueName - Overload in subclass to provide a better default value.
830 virtual StringRef getValueName() const { return "value"; }
832 // An out-of-line virtual method to provide a 'home' for this class.
833 virtual void anchor();
836 ~basic_parser_impl() = default;
838 // A helper for basic_parser::printOptionDiff.
839 void printOptionName(const Option &O, size_t GlobalWidth) const;
842 // basic_parser - The real basic parser is just a template wrapper that provides
843 // a typedef for the provided data type.
845 template <class DataType> class basic_parser : public basic_parser_impl {
847 using parser_data_type = DataType;
848 using OptVal = OptionValue<DataType>;
850 basic_parser(Option &O) : basic_parser_impl(O) {}
853 ~basic_parser() = default;
856 //--------------------------------------------------
859 template <> class parser<bool> final : public basic_parser<bool> {
861 parser(Option &O) : basic_parser(O) {}
863 // parse - Return true on error.
864 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
868 enum ValueExpected getValueExpectedFlagDefault() const {
869 return ValueOptional;
872 // getValueName - Do not print =<value> at all.
873 StringRef getValueName() const override { return StringRef(); }
875 void printOptionDiff(const Option &O, bool V, OptVal Default,
876 size_t GlobalWidth) const;
878 // An out-of-line virtual method to provide a 'home' for this class.
879 void anchor() override;
882 extern template class basic_parser<bool>;
884 //--------------------------------------------------
885 // parser<boolOrDefault>
887 class parser<boolOrDefault> final : public basic_parser<boolOrDefault> {
889 parser(Option &O) : basic_parser(O) {}
891 // parse - Return true on error.
892 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
894 enum ValueExpected getValueExpectedFlagDefault() const {
895 return ValueOptional;
898 // getValueName - Do not print =<value> at all.
899 StringRef getValueName() const override { return StringRef(); }
901 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
902 size_t GlobalWidth) const;
904 // An out-of-line virtual method to provide a 'home' for this class.
905 void anchor() override;
908 extern template class basic_parser<boolOrDefault>;
910 //--------------------------------------------------
913 template <> class parser<int> final : public basic_parser<int> {
915 parser(Option &O) : basic_parser(O) {}
917 // parse - Return true on error.
918 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
920 // getValueName - Overload in subclass to provide a better default value.
921 StringRef getValueName() const override { return "int"; }
923 void printOptionDiff(const Option &O, int V, OptVal Default,
924 size_t GlobalWidth) const;
926 // An out-of-line virtual method to provide a 'home' for this class.
927 void anchor() override;
930 extern template class basic_parser<int>;
932 //--------------------------------------------------
935 template <> class parser<unsigned> final : public basic_parser<unsigned> {
937 parser(Option &O) : basic_parser(O) {}
939 // parse - Return true on error.
940 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
942 // getValueName - Overload in subclass to provide a better default value.
943 StringRef getValueName() const override { return "uint"; }
945 void printOptionDiff(const Option &O, unsigned V, OptVal Default,
946 size_t GlobalWidth) const;
948 // An out-of-line virtual method to provide a 'home' for this class.
949 void anchor() override;
952 extern template class basic_parser<unsigned>;
954 //--------------------------------------------------
955 // parser<unsigned long long>
958 class parser<unsigned long long> final
959 : public basic_parser<unsigned long long> {
961 parser(Option &O) : basic_parser(O) {}
963 // parse - Return true on error.
964 bool parse(Option &O, StringRef ArgName, StringRef Arg,
965 unsigned long long &Val);
967 // getValueName - Overload in subclass to provide a better default value.
968 StringRef getValueName() const override { return "uint"; }
970 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
971 size_t GlobalWidth) const;
973 // An out-of-line virtual method to provide a 'home' for this class.
974 void anchor() override;
977 extern template class basic_parser<unsigned long long>;
979 //--------------------------------------------------
982 template <> class parser<double> final : public basic_parser<double> {
984 parser(Option &O) : basic_parser(O) {}
986 // parse - Return true on error.
987 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
989 // getValueName - Overload in subclass to provide a better default value.
990 StringRef getValueName() const override { return "number"; }
992 void printOptionDiff(const Option &O, double V, OptVal Default,
993 size_t GlobalWidth) const;
995 // An out-of-line virtual method to provide a 'home' for this class.
996 void anchor() override;
999 extern template class basic_parser<double>;
1001 //--------------------------------------------------
1004 template <> class parser<float> final : public basic_parser<float> {
1006 parser(Option &O) : basic_parser(O) {}
1008 // parse - Return true on error.
1009 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
1011 // getValueName - Overload in subclass to provide a better default value.
1012 StringRef getValueName() const override { return "number"; }
1014 void printOptionDiff(const Option &O, float V, OptVal Default,
1015 size_t GlobalWidth) const;
1017 // An out-of-line virtual method to provide a 'home' for this class.
1018 void anchor() override;
1021 extern template class basic_parser<float>;
1023 //--------------------------------------------------
1024 // parser<std::string>
1026 template <> class parser<std::string> final : public basic_parser<std::string> {
1028 parser(Option &O) : basic_parser(O) {}
1030 // parse - Return true on error.
1031 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
1036 // getValueName - Overload in subclass to provide a better default value.
1037 StringRef getValueName() const override { return "string"; }
1039 void printOptionDiff(const Option &O, StringRef V, const OptVal &Default,
1040 size_t GlobalWidth) const;
1042 // An out-of-line virtual method to provide a 'home' for this class.
1043 void anchor() override;
1046 extern template class basic_parser<std::string>;
1048 //--------------------------------------------------
1051 template <> class parser<char> final : public basic_parser<char> {
1053 parser(Option &O) : basic_parser(O) {}
1055 // parse - Return true on error.
1056 bool parse(Option &, StringRef, StringRef Arg, char &Value) {
1061 // getValueName - Overload in subclass to provide a better default value.
1062 StringRef getValueName() const override { return "char"; }
1064 void printOptionDiff(const Option &O, char V, OptVal Default,
1065 size_t GlobalWidth) const;
1067 // An out-of-line virtual method to provide a 'home' for this class.
1068 void anchor() override;
1071 extern template class basic_parser<char>;
1073 //--------------------------------------------------
1076 // This collection of wrappers is the intermediary between class opt and class
1077 // parser to handle all the template nastiness.
1079 // This overloaded function is selected by the generic parser.
1080 template <class ParserClass, class DT>
1081 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
1082 const OptionValue<DT> &Default, size_t GlobalWidth) {
1083 OptionValue<DT> OV = V;
1084 P.printOptionDiff(O, OV, Default, GlobalWidth);
1087 // This is instantiated for basic parsers when the parsed value has a different
1088 // type than the option value. e.g. HelpPrinter.
1089 template <class ParserDT, class ValDT> struct OptionDiffPrinter {
1090 void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/,
1091 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
1092 P.printOptionNoValue(O, GlobalWidth);
1096 // This is instantiated for basic parsers when the parsed value has the same
1097 // type as the option value.
1098 template <class DT> struct OptionDiffPrinter<DT, DT> {
1099 void print(const Option &O, const parser<DT> &P, const DT &V,
1100 const OptionValue<DT> &Default, size_t GlobalWidth) {
1101 P.printOptionDiff(O, V, Default, GlobalWidth);
1105 // This overloaded function is selected by the basic parser, which may parse a
1106 // different type than the option type.
1107 template <class ParserClass, class ValDT>
1108 void printOptionDiff(
1110 const basic_parser<typename ParserClass::parser_data_type> &P,
1111 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
1113 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
1114 printer.print(O, static_cast<const ParserClass &>(P), V, Default,
1118 //===----------------------------------------------------------------------===//
1119 // applicator class - This class is used because we must use partial
1120 // specialization to handle literal string arguments specially (const char* does
1121 // not correctly respond to the apply method). Because the syntax to use this
1122 // is a pain, we have the 'apply' method below to handle the nastiness...
1124 template <class Mod> struct applicator {
1125 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1128 // Handle const char* as a special case...
1129 template <unsigned n> struct applicator<char[n]> {
1130 template <class Opt> static void opt(StringRef Str, Opt &O) {
1134 template <unsigned n> struct applicator<const char[n]> {
1135 template <class Opt> static void opt(StringRef Str, Opt &O) {
1139 template <> struct applicator<StringRef > {
1140 template <class Opt> static void opt(StringRef Str, Opt &O) {
1145 template <> struct applicator<NumOccurrencesFlag> {
1146 static void opt(NumOccurrencesFlag N, Option &O) {
1147 O.setNumOccurrencesFlag(N);
1151 template <> struct applicator<ValueExpected> {
1152 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1155 template <> struct applicator<OptionHidden> {
1156 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1159 template <> struct applicator<FormattingFlags> {
1160 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1163 template <> struct applicator<MiscFlags> {
1164 static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1167 // apply method - Apply modifiers to an option in a type safe way.
1168 template <class Opt, class Mod, class... Mods>
1169 void apply(Opt *O, const Mod &M, const Mods &... Ms) {
1170 applicator<Mod>::opt(M, *O);
1174 template <class Opt, class Mod> void apply(Opt *O, const Mod &M) {
1175 applicator<Mod>::opt(M, *O);
1178 //===----------------------------------------------------------------------===//
1179 // opt_storage class
1181 // Default storage class definition: external storage. This implementation
1182 // assumes the user will specify a variable to store the data into with the
1183 // cl::location(x) modifier.
1185 template <class DataType, bool ExternalStorage, bool isClass>
1187 DataType *Location = nullptr; // Where to store the object...
1188 OptionValue<DataType> Default;
1190 void check_location() const {
1191 assert(Location && "cl::location(...) not specified for a command "
1192 "line option with external storage, "
1193 "or cl::init specified before cl::location()!!");
1197 opt_storage() = default;
1199 bool setLocation(Option &O, DataType &L) {
1201 return O.error("cl::location(x) specified more than once!");
1207 template <class T> void setValue(const T &V, bool initial = false) {
1214 DataType &getValue() {
1218 const DataType &getValue() const {
1223 operator DataType() const { return this->getValue(); }
1225 const OptionValue<DataType> &getDefault() const { return Default; }
1228 // Define how to hold a class type object, such as a string. Since we can
1229 // inherit from a class, we do so. This makes us exactly compatible with the
1230 // object in all cases that it is used.
1232 template <class DataType>
1233 class opt_storage<DataType, false, true> : public DataType {
1235 OptionValue<DataType> Default;
1237 template <class T> void setValue(const T &V, bool initial = false) {
1238 DataType::operator=(V);
1243 DataType &getValue() { return *this; }
1244 const DataType &getValue() const { return *this; }
1246 const OptionValue<DataType> &getDefault() const { return Default; }
1249 // Define a partial specialization to handle things we cannot inherit from. In
1250 // this case, we store an instance through containment, and overload operators
1251 // to get at the value.
1253 template <class DataType> class opt_storage<DataType, false, false> {
1256 OptionValue<DataType> Default;
1258 // Make sure we initialize the value with the default constructor for the
1260 opt_storage() : Value(DataType()), Default(DataType()) {}
1262 template <class T> void setValue(const T &V, bool initial = false) {
1267 DataType &getValue() { return Value; }
1268 DataType getValue() const { return Value; }
1270 const OptionValue<DataType> &getDefault() const { return Default; }
1272 operator DataType() const { return getValue(); }
1274 // If the datatype is a pointer, support -> on it.
1275 DataType operator->() const { return Value; }
1278 //===----------------------------------------------------------------------===//
1279 // opt - A scalar command line option.
1281 template <class DataType, bool ExternalStorage = false,
1282 class ParserClass = parser<DataType>>
1283 class opt : public Option,
1284 public opt_storage<DataType, ExternalStorage,
1285 std::is_class<DataType>::value> {
1288 bool handleOccurrence(unsigned pos, StringRef ArgName,
1289 StringRef Arg) override {
1290 typename ParserClass::parser_data_type Val =
1291 typename ParserClass::parser_data_type();
1292 if (Parser.parse(*this, ArgName, Arg, Val))
1293 return true; // Parse error!
1294 this->setValue(Val);
1295 this->setPosition(pos);
1299 enum ValueExpected getValueExpectedFlagDefault() const override {
1300 return Parser.getValueExpectedFlagDefault();
1303 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1304 return Parser.getExtraOptionNames(OptionNames);
1307 // Forward printing stuff to the parser...
1308 size_t getOptionWidth() const override {
1309 return Parser.getOptionWidth(*this);
1312 void printOptionInfo(size_t GlobalWidth) const override {
1313 Parser.printOptionInfo(*this, GlobalWidth);
1316 void printOptionValue(size_t GlobalWidth, bool Force) const override {
1317 if (Force || this->getDefault().compare(this->getValue())) {
1318 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1319 this->getDefault(), GlobalWidth);
1323 template <class T, class = typename std::enable_if<
1324 std::is_assignable<T&, T>::value>::type>
1325 void setDefaultImpl() {
1326 const OptionValue<DataType> &V = this->getDefault();
1328 this->setValue(V.getValue());
1331 template <class T, class = typename std::enable_if<
1332 !std::is_assignable<T&, T>::value>::type>
1333 void setDefaultImpl(...) {}
1335 void setDefault() override { setDefaultImpl<DataType>(); }
1339 Parser.initialize();
1343 // Command line options should not be copyable
1344 opt(const opt &) = delete;
1345 opt &operator=(const opt &) = delete;
1347 // setInitialValue - Used by the cl::init modifier...
1348 void setInitialValue(const DataType &V) { this->setValue(V, true); }
1350 ParserClass &getParser() { return Parser; }
1352 template <class T> DataType &operator=(const T &Val) {
1353 this->setValue(Val);
1354 return this->getValue();
1357 template <class... Mods>
1358 explicit opt(const Mods &... Ms)
1359 : Option(Optional, NotHidden), Parser(*this) {
1365 extern template class opt<unsigned>;
1366 extern template class opt<int>;
1367 extern template class opt<std::string>;
1368 extern template class opt<char>;
1369 extern template class opt<bool>;
1371 //===----------------------------------------------------------------------===//
1372 // list_storage class
1374 // Default storage class definition: external storage. This implementation
1375 // assumes the user will specify a variable to store the data into with the
1376 // cl::location(x) modifier.
1378 template <class DataType, class StorageClass> class list_storage {
1379 StorageClass *Location = nullptr; // Where to store the object...
1382 list_storage() = default;
1384 bool setLocation(Option &O, StorageClass &L) {
1386 return O.error("cl::location(x) specified more than once!");
1391 template <class T> void addValue(const T &V) {
1392 assert(Location != 0 && "cl::location(...) not specified for a command "
1393 "line option with external storage!");
1394 Location->push_back(V);
1398 // Define how to hold a class type object, such as a string.
1399 // Originally this code inherited from std::vector. In transitioning to a new
1400 // API for command line options we should change this. The new implementation
1401 // of this list_storage specialization implements the minimum subset of the
1402 // std::vector API required for all the current clients.
1404 // FIXME: Reduce this API to a more narrow subset of std::vector
1406 template <class DataType> class list_storage<DataType, bool> {
1407 std::vector<DataType> Storage;
1410 using iterator = typename std::vector<DataType>::iterator;
1412 iterator begin() { return Storage.begin(); }
1413 iterator end() { return Storage.end(); }
1415 using const_iterator = typename std::vector<DataType>::const_iterator;
1417 const_iterator begin() const { return Storage.begin(); }
1418 const_iterator end() const { return Storage.end(); }
1420 using size_type = typename std::vector<DataType>::size_type;
1422 size_type size() const { return Storage.size(); }
1424 bool empty() const { return Storage.empty(); }
1426 void push_back(const DataType &value) { Storage.push_back(value); }
1427 void push_back(DataType &&value) { Storage.push_back(value); }
1429 using reference = typename std::vector<DataType>::reference;
1430 using const_reference = typename std::vector<DataType>::const_reference;
1432 reference operator[](size_type pos) { return Storage[pos]; }
1433 const_reference operator[](size_type pos) const { return Storage[pos]; }
1435 iterator erase(const_iterator pos) { return Storage.erase(pos); }
1436 iterator erase(const_iterator first, const_iterator last) {
1437 return Storage.erase(first, last);
1440 iterator erase(iterator pos) { return Storage.erase(pos); }
1441 iterator erase(iterator first, iterator last) {
1442 return Storage.erase(first, last);
1445 iterator insert(const_iterator pos, const DataType &value) {
1446 return Storage.insert(pos, value);
1448 iterator insert(const_iterator pos, DataType &&value) {
1449 return Storage.insert(pos, value);
1452 iterator insert(iterator pos, const DataType &value) {
1453 return Storage.insert(pos, value);
1455 iterator insert(iterator pos, DataType &&value) {
1456 return Storage.insert(pos, value);
1459 reference front() { return Storage.front(); }
1460 const_reference front() const { return Storage.front(); }
1462 operator std::vector<DataType>&() { return Storage; }
1463 operator ArrayRef<DataType>() { return Storage; }
1464 std::vector<DataType> *operator&() { return &Storage; }
1465 const std::vector<DataType> *operator&() const { return &Storage; }
1467 template <class T> void addValue(const T &V) { Storage.push_back(V); }
1470 //===----------------------------------------------------------------------===//
1471 // list - A list of command line options.
1473 template <class DataType, class StorageClass = bool,
1474 class ParserClass = parser<DataType>>
1475 class list : public Option, public list_storage<DataType, StorageClass> {
1476 std::vector<unsigned> Positions;
1479 enum ValueExpected getValueExpectedFlagDefault() const override {
1480 return Parser.getValueExpectedFlagDefault();
1483 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1484 return Parser.getExtraOptionNames(OptionNames);
1487 bool handleOccurrence(unsigned pos, StringRef ArgName,
1488 StringRef Arg) override {
1489 typename ParserClass::parser_data_type Val =
1490 typename ParserClass::parser_data_type();
1491 if (Parser.parse(*this, ArgName, Arg, Val))
1492 return true; // Parse Error!
1493 list_storage<DataType, StorageClass>::addValue(Val);
1495 Positions.push_back(pos);
1499 // Forward printing stuff to the parser...
1500 size_t getOptionWidth() const override {
1501 return Parser.getOptionWidth(*this);
1504 void printOptionInfo(size_t GlobalWidth) const override {
1505 Parser.printOptionInfo(*this, GlobalWidth);
1508 // Unimplemented: list options don't currently store their default value.
1509 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1512 void setDefault() override {}
1516 Parser.initialize();
1520 // Command line options should not be copyable
1521 list(const list &) = delete;
1522 list &operator=(const list &) = delete;
1524 ParserClass &getParser() { return Parser; }
1526 unsigned getPosition(unsigned optnum) const {
1527 assert(optnum < this->size() && "Invalid option index");
1528 return Positions[optnum];
1531 void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
1533 template <class... Mods>
1534 explicit list(const Mods &... Ms)
1535 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1541 // multi_val - Modifier to set the number of additional values.
1543 unsigned AdditionalVals;
1544 explicit multi_val(unsigned N) : AdditionalVals(N) {}
1546 template <typename D, typename S, typename P>
1547 void apply(list<D, S, P> &L) const {
1548 L.setNumAdditionalVals(AdditionalVals);
1552 //===----------------------------------------------------------------------===//
1553 // bits_storage class
1555 // Default storage class definition: external storage. This implementation
1556 // assumes the user will specify a variable to store the data into with the
1557 // cl::location(x) modifier.
1559 template <class DataType, class StorageClass> class bits_storage {
1560 unsigned *Location = nullptr; // Where to store the bits...
1562 template <class T> static unsigned Bit(const T &V) {
1563 unsigned BitPos = reinterpret_cast<unsigned>(V);
1564 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1565 "enum exceeds width of bit vector!");
1570 bits_storage() = default;
1572 bool setLocation(Option &O, unsigned &L) {
1574 return O.error("cl::location(x) specified more than once!");
1579 template <class T> void addValue(const T &V) {
1580 assert(Location != 0 && "cl::location(...) not specified for a command "
1581 "line option with external storage!");
1582 *Location |= Bit(V);
1585 unsigned getBits() { return *Location; }
1587 template <class T> bool isSet(const T &V) {
1588 return (*Location & Bit(V)) != 0;
1592 // Define how to hold bits. Since we can inherit from a class, we do so.
1593 // This makes us exactly compatible with the bits in all cases that it is used.
1595 template <class DataType> class bits_storage<DataType, bool> {
1596 unsigned Bits; // Where to store the bits...
1598 template <class T> static unsigned Bit(const T &V) {
1599 unsigned BitPos = (unsigned)V;
1600 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1601 "enum exceeds width of bit vector!");
1606 template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1608 unsigned getBits() { return Bits; }
1610 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1613 //===----------------------------------------------------------------------===//
1614 // bits - A bit vector of command options.
1616 template <class DataType, class Storage = bool,
1617 class ParserClass = parser<DataType>>
1618 class bits : public Option, public bits_storage<DataType, Storage> {
1619 std::vector<unsigned> Positions;
1622 enum ValueExpected getValueExpectedFlagDefault() const override {
1623 return Parser.getValueExpectedFlagDefault();
1626 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1627 return Parser.getExtraOptionNames(OptionNames);
1630 bool handleOccurrence(unsigned pos, StringRef ArgName,
1631 StringRef Arg) override {
1632 typename ParserClass::parser_data_type Val =
1633 typename ParserClass::parser_data_type();
1634 if (Parser.parse(*this, ArgName, Arg, Val))
1635 return true; // Parse Error!
1636 this->addValue(Val);
1638 Positions.push_back(pos);
1642 // Forward printing stuff to the parser...
1643 size_t getOptionWidth() const override {
1644 return Parser.getOptionWidth(*this);
1647 void printOptionInfo(size_t GlobalWidth) const override {
1648 Parser.printOptionInfo(*this, GlobalWidth);
1651 // Unimplemented: bits options don't currently store their default values.
1652 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1655 void setDefault() override {}
1659 Parser.initialize();
1663 // Command line options should not be copyable
1664 bits(const bits &) = delete;
1665 bits &operator=(const bits &) = delete;
1667 ParserClass &getParser() { return Parser; }
1669 unsigned getPosition(unsigned optnum) const {
1670 assert(optnum < this->size() && "Invalid option index");
1671 return Positions[optnum];
1674 template <class... Mods>
1675 explicit bits(const Mods &... Ms)
1676 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1682 //===----------------------------------------------------------------------===//
1683 // Aliased command line option (alias this name to a preexisting name)
1686 class alias : public Option {
1689 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1690 StringRef Arg) override {
1691 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1694 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1695 bool MultiArg = false) override {
1696 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1699 // Handle printing stuff...
1700 size_t getOptionWidth() const override;
1701 void printOptionInfo(size_t GlobalWidth) const override;
1703 // Aliases do not need to print their values.
1704 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1707 void setDefault() override { AliasFor->setDefault(); }
1709 ValueExpected getValueExpectedFlagDefault() const override {
1710 return AliasFor->getValueExpectedFlag();
1715 error("cl::alias must have argument name specified!");
1717 error("cl::alias must have an cl::aliasopt(option) specified!");
1718 Subs = AliasFor->Subs;
1723 // Command line options should not be copyable
1724 alias(const alias &) = delete;
1725 alias &operator=(const alias &) = delete;
1727 void setAliasFor(Option &O) {
1729 error("cl::alias must only have one cl::aliasopt(...) specified!");
1733 template <class... Mods>
1734 explicit alias(const Mods &... Ms)
1735 : Option(Optional, Hidden), AliasFor(nullptr) {
1741 // aliasfor - Modifier to set the option an alias aliases.
1745 explicit aliasopt(Option &O) : Opt(O) {}
1747 void apply(alias &A) const { A.setAliasFor(Opt); }
1750 // extrahelp - provide additional help at the end of the normal help
1751 // output. All occurrences of cl::extrahelp will be accumulated and
1752 // printed to stderr at the end of the regular help, just before
1757 explicit extrahelp(StringRef help);
1760 void PrintVersionMessage();
1762 /// This function just prints the help message, exactly the same way as if the
1763 /// -help or -help-hidden option had been given on the command line.
1765 /// \param Hidden if true will print hidden options
1766 /// \param Categorized if true print options in categories
1767 void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
1769 //===----------------------------------------------------------------------===//
1770 // Public interface for accessing registered options.
1773 /// \brief Use this to get a StringMap to all registered named options
1774 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1776 /// \return A reference to the StringMap used by the cl APIs to parse options.
1778 /// Access to unnamed arguments (i.e. positional) are not provided because
1779 /// it is expected that the client already has access to these.
1783 /// main(int argc,char* argv[]) {
1784 /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions();
1785 /// assert(opts.count("help") == 1)
1786 /// opts["help"]->setDescription("Show alphabetical help information")
1788 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1793 /// This interface is useful for modifying options in libraries that are out of
1794 /// the control of the client. The options should be modified before calling
1795 /// llvm::cl::ParseCommandLineOptions().
1797 /// Hopefully this API can be deprecated soon. Any situation where options need
1798 /// to be modified by tools or libraries should be handled by sane APIs rather
1799 /// than just handing around a global list.
1800 StringMap<Option *> &getRegisteredOptions(SubCommand &Sub = *TopLevelSubCommand);
1802 /// \brief Use this to get all registered SubCommands from the provided parser.
1804 /// \return A range of all SubCommand pointers registered with the parser.
1808 /// main(int argc, char* argv[]) {
1809 /// llvm::cl::ParseCommandLineOptions(argc, argv);
1810 /// for (auto* S : llvm::cl::getRegisteredSubcommands()) {
1812 /// std::cout << "Executing subcommand: " << S->getName() << std::endl;
1813 /// // Execute some function based on the name...
1819 /// This interface is useful for defining subcommands in libraries and
1820 /// the dispatch from a single point (like in the main function).
1821 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
1822 getRegisteredSubcommands();
1824 //===----------------------------------------------------------------------===//
1825 // Standalone command line processing utilities.
1828 /// \brief Tokenizes a command line that can contain escapes and quotes.
1830 /// The quoting rules match those used by GCC and other tools that use
1831 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1832 /// They differ from buildargv() on treatment of backslashes that do not escape
1833 /// a special character to make it possible to accept most Windows file paths.
1835 /// \param [in] Source The string to be split on whitespace with quotes.
1836 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1837 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1838 /// lines and end of the response file to be marked with a nullptr string.
1839 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1840 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
1841 SmallVectorImpl<const char *> &NewArgv,
1842 bool MarkEOLs = false);
1844 /// \brief Tokenizes a Windows command line which may contain quotes and escaped
1847 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1848 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1850 /// \param [in] Source The string to be split on whitespace with quotes.
1851 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1852 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1853 /// lines and end of the response file to be marked with a nullptr string.
1854 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1855 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
1856 SmallVectorImpl<const char *> &NewArgv,
1857 bool MarkEOLs = false);
1859 /// \brief String tokenization function type. Should be compatible with either
1860 /// Windows or Unix command line tokenizers.
1861 using TokenizerCallback = void (*)(StringRef Source, StringSaver &Saver,
1862 SmallVectorImpl<const char *> &NewArgv,
1865 /// Tokenizes content of configuration file.
1867 /// \param [in] Source The string representing content of config file.
1868 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1869 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1870 /// \param [in] MarkEOLs Added for compatibility with TokenizerCallback.
1872 /// It works like TokenizeGNUCommandLine with ability to skip comment lines.
1874 void tokenizeConfigFile(StringRef Source, StringSaver &Saver,
1875 SmallVectorImpl<const char *> &NewArgv,
1876 bool MarkEOLs = false);
1878 /// Reads command line options from the given configuration file.
1880 /// \param [in] CfgFileName Path to configuration file.
1881 /// \param [in] Saver Objects that saves allocated strings.
1882 /// \param [out] Argv Array to which the read options are added.
1883 /// \return true if the file was successfully read.
1885 /// It reads content of the specified file, tokenizes it and expands "@file"
1886 /// commands resolving file names in them relative to the directory where
1887 /// CfgFilename resides.
1889 bool readConfigFile(StringRef CfgFileName, StringSaver &Saver,
1890 SmallVectorImpl<const char *> &Argv);
1892 /// \brief Expand response files on a command line recursively using the given
1893 /// StringSaver and tokenization strategy. Argv should contain the command line
1894 /// before expansion and will be modified in place. If requested, Argv will
1895 /// also be populated with nullptrs indicating where each response file line
1896 /// ends, which is useful for the "/link" argument that needs to consume all
1897 /// remaining arguments only until the next end of line, when in a response
1900 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1901 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1902 /// \param [in,out] Argv Command line into which to expand response files.
1903 /// \param [in] MarkEOLs Mark end of lines and the end of the response file
1904 /// with nullptrs in the Argv vector.
1905 /// \param [in] RelativeNames true if names of nested response files must be
1906 /// resolved relative to including file.
1907 /// \return true if all @files were expanded successfully or there were none.
1908 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1909 SmallVectorImpl<const char *> &Argv,
1910 bool MarkEOLs = false, bool RelativeNames = false);
1912 /// \brief Mark all options not part of this category as cl::ReallyHidden.
1914 /// \param Category the category of options to keep displaying
1916 /// Some tools (like clang-format) like to be able to hide all options that are
1917 /// not specific to the tool. This function allows a tool to specify a single
1918 /// option category to display in the -help output.
1919 void HideUnrelatedOptions(cl::OptionCategory &Category,
1920 SubCommand &Sub = *TopLevelSubCommand);
1922 /// \brief Mark all options not part of the categories as cl::ReallyHidden.
1924 /// \param Categories the categories of options to keep displaying.
1926 /// Some tools (like clang-format) like to be able to hide all options that are
1927 /// not specific to the tool. This function allows a tool to specify a single
1928 /// option category to display in the -help output.
1929 void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
1930 SubCommand &Sub = *TopLevelSubCommand);
1932 /// \brief Reset all command line options to a state that looks as if they have
1933 /// never appeared on the command line. This is useful for being able to parse
1934 /// a command line multiple times (especially useful for writing tests).
1935 void ResetAllOptionOccurrences();
1937 /// \brief Reset the command line parser back to its initial state. This
1939 /// all options, categories, and subcommands and returns the parser to a state
1940 /// where no options are supported.
1941 void ResetCommandLineParser();
1943 } // end namespace cl
1945 } // end namespace llvm
1947 #endif // LLVM_SUPPORT_COMMANDLINE_H