1 //===- llvm/Support/CommandLine.h - Command line handler --------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This class implements a command line argument processor that is useful when
10 // creating a tool. It provides a simple, minimalistic interface that is easily
11 // extensible and supports nonlocal (library) command line options.
13 // Note that rather than trying to figure out what this code does, you should
14 // read the library documentation located in docs/CommandLine.html or looks at
15 // the many example usages in tools/*/*.cpp
17 //===----------------------------------------------------------------------===//
19 #ifndef LLVM_SUPPORT_COMMANDLINE_H
20 #define LLVM_SUPPORT_COMMANDLINE_H
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/ADT/iterator_range.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/raw_ostream.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.
59 // If EnvVar is not nullptr, command-line options are also parsed from the
60 // environment variable named by EnvVar. Precedence is given to occurrences
61 // from argv. This precedence is currently implemented by parsing argv after
62 // the environment variable, so it is only implemented correctly for options
63 // that give precedence to later occurrences. If your program supports options
64 // that give precedence to earlier occurrences, you will need to extend this
65 // function to support it correctly.
66 bool ParseCommandLineOptions(int argc
, const char *const *argv
,
67 StringRef Overview
= "",
68 raw_ostream
*Errs
= nullptr,
69 const char *EnvVar
= nullptr,
70 bool LongOptionsUseDoubleDash
= false);
72 //===----------------------------------------------------------------------===//
73 // ParseEnvironmentOptions - Environment variable option processing alternate
76 void ParseEnvironmentOptions(const char *progName
, const char *envvar
,
77 const char *Overview
= "");
79 // Function pointer type for printing version information.
80 using VersionPrinterTy
= std::function
<void(raw_ostream
&)>;
82 ///===---------------------------------------------------------------------===//
83 /// SetVersionPrinter - Override the default (LLVM specific) version printer
84 /// used to print out the version when --version is given
85 /// on the command line. This allows other systems using the
86 /// CommandLine utilities to print their own version string.
87 void SetVersionPrinter(VersionPrinterTy func
);
89 ///===---------------------------------------------------------------------===//
90 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
91 /// default one. This can be called multiple times,
92 /// and each time it adds a new function to the list
93 /// which will be called after the basic LLVM version
94 /// printing is complete. Each can then add additional
95 /// information specific to the tool.
96 void AddExtraVersionPrinter(VersionPrinterTy func
);
98 // PrintOptionValues - Print option values.
99 // With -print-options print the difference between option values and defaults.
100 // With -print-all-options print all option values.
101 // (Currently not perfect, but best-effort.)
102 void PrintOptionValues();
104 // Forward declaration - AddLiteralOption needs to be up here to make gcc happy.
107 /// Adds a new option for parsing and provides the option it refers to.
109 /// \param O pointer to the option
110 /// \param Name the string name for the option to handle during parsing
112 /// Literal options are used by some parsers to register special option values.
113 /// This is how the PassNameParser registers pass names for opt.
114 void AddLiteralOption(Option
&O
, StringRef Name
);
116 //===----------------------------------------------------------------------===//
117 // Flags permitted to be passed to command line arguments
120 enum NumOccurrencesFlag
{ // Flags for the number of occurrences allowed
121 Optional
= 0x00, // Zero or One occurrence
122 ZeroOrMore
= 0x01, // Zero or more occurrences allowed
123 Required
= 0x02, // One occurrence required
124 OneOrMore
= 0x03, // One or more occurrences required
126 // ConsumeAfter - Indicates that this option is fed anything that follows the
127 // last positional argument required by the application (it is an error if
128 // there are zero positional arguments, and a ConsumeAfter option is used).
129 // Thus, for example, all arguments to LLI are processed until a filename is
130 // found. Once a filename is found, all of the succeeding arguments are
131 // passed, unprocessed, to the ConsumeAfter option.
136 enum ValueExpected
{ // Is a value required for the option?
137 // zero reserved for the unspecified value
138 ValueOptional
= 0x01, // The value can appear... or not
139 ValueRequired
= 0x02, // The value is required to appear!
140 ValueDisallowed
= 0x03 // A value may not be specified (for flags)
143 enum OptionHidden
{ // Control whether -help shows this option
144 NotHidden
= 0x00, // Option included in -help & -help-hidden
145 Hidden
= 0x01, // -help doesn't, but -help-hidden does
146 ReallyHidden
= 0x02 // Neither -help nor -help-hidden show this arg
149 // Formatting flags - This controls special features that the option might have
150 // that cause it to be parsed differently...
152 // Prefix - This option allows arguments that are otherwise unrecognized to be
153 // matched by options that are a prefix of the actual value. This is useful for
154 // cases like a linker, where options are typically of the form '-lfoo' or
155 // '-L../../include' where -l or -L are the actual flags. When prefix is
156 // enabled, and used, the value for the flag comes from the suffix of the
159 // AlwaysPrefix - Only allow the behavior enabled by the Prefix flag and reject
160 // the Option=Value form.
163 enum FormattingFlags
{
164 NormalFormatting
= 0x00, // Nothing special
165 Positional
= 0x01, // Is a positional argument, no '-' required
166 Prefix
= 0x02, // Can this option directly prefix its value?
167 AlwaysPrefix
= 0x03 // Can this option only directly prefix its value?
170 enum MiscFlags
{ // Miscellaneous flags to adjust argument
171 CommaSeparated
= 0x01, // Should this cl::list split between commas?
172 PositionalEatsArgs
= 0x02, // Should this positional cl::list eat -args?
173 Sink
= 0x04, // Should this cl::list eat all unknown options?
175 // Grouping - Can this option group with other options?
176 // If this is enabled, multiple letter options are allowed to bunch together
177 // with only a single hyphen for the whole group. This allows emulation
178 // of the behavior that ls uses for example: ls -la === ls -l -a
185 //===----------------------------------------------------------------------===//
186 // Option Category class
188 class OptionCategory
{
190 StringRef
const Name
;
191 StringRef
const Description
;
193 void registerCategory();
196 OptionCategory(StringRef
const Name
,
197 StringRef
const Description
= "")
198 : Name(Name
), Description(Description
) {
202 StringRef
getName() const { return Name
; }
203 StringRef
getDescription() const { return Description
; }
206 // The general Option Category (used as default category).
207 extern OptionCategory GeneralCategory
;
209 //===----------------------------------------------------------------------===//
215 StringRef Description
;
218 void registerSubCommand();
219 void unregisterSubCommand();
222 SubCommand(StringRef Name
, StringRef Description
= "")
223 : Name(Name
), Description(Description
) {
224 registerSubCommand();
226 SubCommand() = default;
230 explicit operator bool() const;
232 StringRef
getName() const { return Name
; }
233 StringRef
getDescription() const { return Description
; }
235 SmallVector
<Option
*, 4> PositionalOpts
;
236 SmallVector
<Option
*, 4> SinkOpts
;
237 StringMap
<Option
*> OptionsMap
;
239 Option
*ConsumeAfterOpt
= nullptr; // The ConsumeAfter option if it exists.
242 // A special subcommand representing no subcommand
243 extern ManagedStatic
<SubCommand
> TopLevelSubCommand
;
245 // A special subcommand that can be used to put an option into all subcommands.
246 extern ManagedStatic
<SubCommand
> AllSubCommands
;
248 //===----------------------------------------------------------------------===//
254 // handleOccurrences - Overriden by subclasses to handle the value passed into
255 // an argument. Should return true if there was an error processing the
256 // argument and the program should exit.
258 virtual bool handleOccurrence(unsigned pos
, StringRef ArgName
,
261 virtual enum ValueExpected
getValueExpectedFlagDefault() const {
262 return ValueOptional
;
265 // Out of line virtual function to provide home for the class.
266 virtual void anchor();
268 uint16_t NumOccurrences
; // The number of times specified
269 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
270 // problems with signed enums in bitfields.
271 uint16_t Occurrences
: 3; // enum NumOccurrencesFlag
272 // not using the enum type for 'Value' because zero is an implementation
273 // detail representing the non-value
275 uint16_t HiddenFlag
: 2; // enum OptionHidden
276 uint16_t Formatting
: 2; // enum FormattingFlags
278 uint16_t FullyInitialized
: 1; // Has addArgument been called?
279 uint16_t Position
; // Position of last occurrence of the option
280 uint16_t AdditionalVals
; // Greater than 0 for multi-valued option.
283 StringRef ArgStr
; // The argument string itself (ex: "help", "o")
284 StringRef HelpStr
; // The descriptive text message for -help
285 StringRef ValueStr
; // String describing what the value of this option is
286 SmallVector
<OptionCategory
*, 1>
287 Categories
; // The Categories this option belongs to
288 SmallPtrSet
<SubCommand
*, 1> Subs
; // The subcommands this option belongs to.
290 inline enum NumOccurrencesFlag
getNumOccurrencesFlag() const {
291 return (enum NumOccurrencesFlag
)Occurrences
;
294 inline enum ValueExpected
getValueExpectedFlag() const {
295 return Value
? ((enum ValueExpected
)Value
) : getValueExpectedFlagDefault();
298 inline enum OptionHidden
getOptionHiddenFlag() const {
299 return (enum OptionHidden
)HiddenFlag
;
302 inline enum FormattingFlags
getFormattingFlag() const {
303 return (enum FormattingFlags
)Formatting
;
306 inline unsigned getMiscFlags() const { return Misc
; }
307 inline unsigned getPosition() const { return Position
; }
308 inline unsigned getNumAdditionalVals() const { return AdditionalVals
; }
310 // hasArgStr - Return true if the argstr != ""
311 bool hasArgStr() const { return !ArgStr
.empty(); }
312 bool isPositional() const { return getFormattingFlag() == cl::Positional
; }
313 bool isSink() const { return getMiscFlags() & cl::Sink
; }
314 bool isDefaultOption() const { return getMiscFlags() & cl::DefaultOption
; }
316 bool isConsumeAfter() const {
317 return getNumOccurrencesFlag() == cl::ConsumeAfter
;
320 bool isInAllSubCommands() const {
321 return any_of(Subs
, [](const SubCommand
*SC
) {
322 return SC
== &*AllSubCommands
;
326 //-------------------------------------------------------------------------===
327 // Accessor functions set by OptionModifiers
329 void setArgStr(StringRef S
);
330 void setDescription(StringRef S
) { HelpStr
= S
; }
331 void setValueStr(StringRef S
) { ValueStr
= S
; }
332 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val
) { Occurrences
= Val
; }
333 void setValueExpectedFlag(enum ValueExpected Val
) { Value
= Val
; }
334 void setHiddenFlag(enum OptionHidden Val
) { HiddenFlag
= Val
; }
335 void setFormattingFlag(enum FormattingFlags V
) { Formatting
= V
; }
336 void setMiscFlag(enum MiscFlags M
) { Misc
|= M
; }
337 void setPosition(unsigned pos
) { Position
= pos
; }
338 void addCategory(OptionCategory
&C
);
339 void addSubCommand(SubCommand
&S
) { Subs
.insert(&S
); }
342 explicit Option(enum NumOccurrencesFlag OccurrencesFlag
,
343 enum OptionHidden Hidden
)
344 : NumOccurrences(0), Occurrences(OccurrencesFlag
), Value(0),
345 HiddenFlag(Hidden
), Formatting(NormalFormatting
), Misc(0),
346 FullyInitialized(false), Position(0), AdditionalVals(0) {
347 Categories
.push_back(&GeneralCategory
);
350 inline void setNumAdditionalVals(unsigned n
) { AdditionalVals
= n
; }
353 virtual ~Option() = default;
355 // addArgument - Register this argument with the commandline system.
359 /// Unregisters this option from the CommandLine system.
361 /// This option must have been the last option registered.
362 /// For testing purposes only.
363 void removeArgument();
365 // Return the width of the option tag for printing...
366 virtual size_t getOptionWidth() const = 0;
368 // printOptionInfo - Print out information about this option. The
369 // to-be-maintained width is specified.
371 virtual void printOptionInfo(size_t GlobalWidth
) const = 0;
373 virtual void printOptionValue(size_t GlobalWidth
, bool Force
) const = 0;
375 virtual void setDefault() = 0;
377 static void printHelpStr(StringRef HelpStr
, size_t Indent
,
378 size_t FirstLineIndentedBy
);
380 virtual void getExtraOptionNames(SmallVectorImpl
<StringRef
> &) {}
382 // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
384 virtual bool addOccurrence(unsigned pos
, StringRef ArgName
, StringRef Value
,
385 bool MultiArg
= false);
387 // Prints option name followed by message. Always returns true.
388 bool error(const Twine
&Message
, StringRef ArgName
= StringRef(), raw_ostream
&Errs
= llvm::errs());
389 bool error(const Twine
&Message
, raw_ostream
&Errs
) {
390 return error(Message
, StringRef(), Errs
);
393 inline int getNumOccurrences() const { return NumOccurrences
; }
397 //===----------------------------------------------------------------------===//
398 // Command line option modifiers that can be used to modify the behavior of
399 // command line option parsers...
402 // desc - Modifier to set the description shown in the -help output...
406 desc(StringRef Str
) : Desc(Str
) {}
408 void apply(Option
&O
) const { O
.setDescription(Desc
); }
411 // value_desc - Modifier to set the value description shown in the -help
416 value_desc(StringRef Str
) : Desc(Str
) {}
418 void apply(Option
&O
) const { O
.setValueStr(Desc
); }
421 // init - Specify a default (initial) value for the command line argument, if
422 // the default constructor for the argument type does not give you what you
423 // want. This is only valid on "opt" arguments, not on "list" arguments.
425 template <class Ty
> struct initializer
{
427 initializer(const Ty
&Val
) : Init(Val
) {}
429 template <class Opt
> void apply(Opt
&O
) const { O
.setInitialValue(Init
); }
432 template <class Ty
> initializer
<Ty
> init(const Ty
&Val
) {
433 return initializer
<Ty
>(Val
);
436 // location - Allow the user to specify which external variable they want to
437 // store the results of the command line argument processing into, if they don't
438 // want to store it in the option itself.
440 template <class Ty
> struct LocationClass
{
443 LocationClass(Ty
&L
) : Loc(L
) {}
445 template <class Opt
> void apply(Opt
&O
) const { O
.setLocation(O
, Loc
); }
448 template <class Ty
> LocationClass
<Ty
> location(Ty
&L
) {
449 return LocationClass
<Ty
>(L
);
452 // cat - Specifiy the Option category for the command line argument to belong
455 OptionCategory
&Category
;
457 cat(OptionCategory
&c
) : Category(c
) {}
459 template <class Opt
> void apply(Opt
&O
) const { O
.addCategory(Category
); }
462 // sub - Specify the subcommand that this option belongs to.
466 sub(SubCommand
&S
) : Sub(S
) {}
468 template <class Opt
> void apply(Opt
&O
) const { O
.addSubCommand(Sub
); }
471 //===----------------------------------------------------------------------===//
474 // Support value comparison outside the template.
475 struct GenericOptionValue
{
476 virtual bool compare(const GenericOptionValue
&V
) const = 0;
479 GenericOptionValue() = default;
480 GenericOptionValue(const GenericOptionValue
&) = default;
481 GenericOptionValue
&operator=(const GenericOptionValue
&) = default;
482 ~GenericOptionValue() = default;
485 virtual void anchor();
488 template <class DataType
> struct OptionValue
;
490 // The default value safely does nothing. Option value printing is only
492 template <class DataType
, bool isClass
>
493 struct OptionValueBase
: public GenericOptionValue
{
494 // Temporary storage for argument passing.
495 using WrapperType
= OptionValue
<DataType
>;
497 bool hasValue() const { return false; }
499 const DataType
&getValue() const { llvm_unreachable("no default value"); }
501 // Some options may take their value from a different data type.
502 template <class DT
> void setValue(const DT
& /*V*/) {}
504 bool compare(const DataType
& /*V*/) const { return false; }
506 bool compare(const GenericOptionValue
& /*V*/) const override
{
511 ~OptionValueBase() = default;
514 // Simple copy of the option value.
515 template <class DataType
> class OptionValueCopy
: public GenericOptionValue
{
520 OptionValueCopy(const OptionValueCopy
&) = default;
521 OptionValueCopy
&operator=(const OptionValueCopy
&) = default;
522 ~OptionValueCopy() = default;
525 OptionValueCopy() = default;
527 bool hasValue() const { return Valid
; }
529 const DataType
&getValue() const {
530 assert(Valid
&& "invalid option value");
534 void setValue(const DataType
&V
) {
539 bool compare(const DataType
&V
) const { return Valid
&& (Value
!= V
); }
541 bool compare(const GenericOptionValue
&V
) const override
{
542 const OptionValueCopy
<DataType
> &VC
=
543 static_cast<const OptionValueCopy
<DataType
> &>(V
);
546 return compare(VC
.getValue());
550 // Non-class option values.
551 template <class DataType
>
552 struct OptionValueBase
<DataType
, false> : OptionValueCopy
<DataType
> {
553 using WrapperType
= DataType
;
556 OptionValueBase() = default;
557 OptionValueBase(const OptionValueBase
&) = default;
558 OptionValueBase
&operator=(const OptionValueBase
&) = default;
559 ~OptionValueBase() = default;
562 // Top-level option class.
563 template <class DataType
>
564 struct OptionValue final
565 : OptionValueBase
<DataType
, std::is_class
<DataType
>::value
> {
566 OptionValue() = default;
568 OptionValue(const DataType
&V
) { this->setValue(V
); }
570 // Some options may take their value from a different data type.
571 template <class DT
> OptionValue
<DataType
> &operator=(const DT
&V
) {
577 // Other safe-to-copy-by-value common option types.
578 enum boolOrDefault
{ BOU_UNSET
, BOU_TRUE
, BOU_FALSE
};
580 struct OptionValue
<cl::boolOrDefault
> final
581 : OptionValueCopy
<cl::boolOrDefault
> {
582 using WrapperType
= cl::boolOrDefault
;
584 OptionValue() = default;
586 OptionValue(const cl::boolOrDefault
&V
) { this->setValue(V
); }
588 OptionValue
<cl::boolOrDefault
> &operator=(const cl::boolOrDefault
&V
) {
594 void anchor() override
;
598 struct OptionValue
<std::string
> final
: OptionValueCopy
<std::string
> {
599 using WrapperType
= StringRef
;
601 OptionValue() = default;
603 OptionValue(const std::string
&V
) { this->setValue(V
); }
605 OptionValue
<std::string
> &operator=(const std::string
&V
) {
611 void anchor() override
;
614 //===----------------------------------------------------------------------===//
615 // Enum valued command line option
618 // This represents a single enum value, using "int" as the underlying type.
619 struct OptionEnumValue
{
622 StringRef Description
;
625 #define clEnumVal(ENUMVAL, DESC) \
626 llvm::cl::OptionEnumValue { #ENUMVAL, int(ENUMVAL), DESC }
627 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) \
628 llvm::cl::OptionEnumValue { FLAGNAME, int(ENUMVAL), DESC }
630 // values - For custom data types, allow specifying a group of values together
631 // as the values that go into the mapping that the option handler uses.
634 // Use a vector instead of a map, because the lists should be short,
635 // the overhead is less, and most importantly, it keeps them in the order
636 // inserted so we can print our option out nicely.
637 SmallVector
<OptionEnumValue
, 4> Values
;
640 ValuesClass(std::initializer_list
<OptionEnumValue
> Options
)
643 template <class Opt
> void apply(Opt
&O
) const {
644 for (auto Value
: Values
)
645 O
.getParser().addLiteralOption(Value
.Name
, Value
.Value
,
650 /// Helper to build a ValuesClass by forwarding a variable number of arguments
651 /// as an initializer list to the ValuesClass constructor.
652 template <typename
... OptsTy
> ValuesClass
values(OptsTy
... Options
) {
653 return ValuesClass({Options
...});
656 //===----------------------------------------------------------------------===//
657 // parser class - Parameterizable parser for different data types. By default,
658 // known data types (string, int, bool) have specialized parsers, that do what
659 // you would expect. The default parser, used for data types that are not
660 // built-in, uses a mapping table to map specific options to values, which is
661 // used, among other things, to handle enum types.
663 //--------------------------------------------------
664 // generic_parser_base - This class holds all the non-generic code that we do
665 // not need replicated for every instance of the generic parser. This also
666 // allows us to put stuff into CommandLine.cpp
668 class generic_parser_base
{
670 class GenericOptionInfo
{
672 GenericOptionInfo(StringRef name
, StringRef helpStr
)
673 : Name(name
), HelpStr(helpStr
) {}
679 generic_parser_base(Option
&O
) : Owner(O
) {}
681 virtual ~generic_parser_base() = default;
682 // Base class should have virtual-destructor
684 // getNumOptions - Virtual function implemented by generic subclass to
685 // indicate how many entries are in Values.
687 virtual unsigned getNumOptions() const = 0;
689 // getOption - Return option name N.
690 virtual StringRef
getOption(unsigned N
) const = 0;
692 // getDescription - Return description N
693 virtual StringRef
getDescription(unsigned N
) const = 0;
695 // Return the width of the option tag for printing...
696 virtual size_t getOptionWidth(const Option
&O
) const;
698 virtual const GenericOptionValue
&getOptionValue(unsigned N
) const = 0;
700 // printOptionInfo - Print out information about this option. The
701 // to-be-maintained width is specified.
703 virtual void printOptionInfo(const Option
&O
, size_t GlobalWidth
) const;
705 void printGenericOptionDiff(const Option
&O
, const GenericOptionValue
&V
,
706 const GenericOptionValue
&Default
,
707 size_t GlobalWidth
) const;
709 // printOptionDiff - print the value of an option and it's default.
711 // Template definition ensures that the option and default have the same
712 // DataType (via the same AnyOptionValue).
713 template <class AnyOptionValue
>
714 void printOptionDiff(const Option
&O
, const AnyOptionValue
&V
,
715 const AnyOptionValue
&Default
,
716 size_t GlobalWidth
) const {
717 printGenericOptionDiff(O
, V
, Default
, GlobalWidth
);
722 void getExtraOptionNames(SmallVectorImpl
<StringRef
> &OptionNames
) {
723 // If there has been no argstr specified, that means that we need to add an
724 // argument for every possible option. This ensures that our options are
726 if (!Owner
.hasArgStr())
727 for (unsigned i
= 0, e
= getNumOptions(); i
!= e
; ++i
)
728 OptionNames
.push_back(getOption(i
));
731 enum ValueExpected
getValueExpectedFlagDefault() const {
732 // If there is an ArgStr specified, then we are of the form:
734 // -opt=O2 or -opt O2 or -optO2
736 // In which case, the value is required. Otherwise if an arg str has not
737 // been specified, we are of the form:
739 // -O2 or O2 or -la (where -l and -a are separate options)
741 // If this is the case, we cannot allow a value.
743 if (Owner
.hasArgStr())
744 return ValueRequired
;
746 return ValueDisallowed
;
749 // findOption - Return the option number corresponding to the specified
750 // argument string. If the option is not found, getNumOptions() is returned.
752 unsigned findOption(StringRef Name
);
758 // Default parser implementation - This implementation depends on having a
759 // mapping of recognized options to values of some sort. In addition to this,
760 // each entry in the mapping also tracks a help message that is printed with the
761 // command line option for -help. Because this is a simple mapping parser, the
762 // data type can be any unsupported type.
764 template <class DataType
> class parser
: public generic_parser_base
{
766 class OptionInfo
: public GenericOptionInfo
{
768 OptionInfo(StringRef name
, DataType v
, StringRef helpStr
)
769 : GenericOptionInfo(name
, helpStr
), V(v
) {}
771 OptionValue
<DataType
> V
;
773 SmallVector
<OptionInfo
, 8> Values
;
776 parser(Option
&O
) : generic_parser_base(O
) {}
778 using parser_data_type
= DataType
;
780 // Implement virtual functions needed by generic_parser_base
781 unsigned getNumOptions() const override
{ return unsigned(Values
.size()); }
782 StringRef
getOption(unsigned N
) const override
{ return Values
[N
].Name
; }
783 StringRef
getDescription(unsigned N
) const override
{
784 return Values
[N
].HelpStr
;
787 // getOptionValue - Return the value of option name N.
788 const GenericOptionValue
&getOptionValue(unsigned N
) const override
{
792 // parse - Return true on error.
793 bool parse(Option
&O
, StringRef ArgName
, StringRef Arg
, DataType
&V
) {
795 if (Owner
.hasArgStr())
800 for (size_t i
= 0, e
= Values
.size(); i
!= e
; ++i
)
801 if (Values
[i
].Name
== ArgVal
) {
802 V
= Values
[i
].V
.getValue();
806 return O
.error("Cannot find option named '" + ArgVal
+ "'!");
809 /// addLiteralOption - Add an entry to the mapping table.
812 void addLiteralOption(StringRef Name
, const DT
&V
, StringRef HelpStr
) {
813 assert(findOption(Name
) == Values
.size() && "Option already exists!");
814 OptionInfo
X(Name
, static_cast<DataType
>(V
), HelpStr
);
816 AddLiteralOption(Owner
, Name
);
819 /// removeLiteralOption - Remove the specified option.
821 void removeLiteralOption(StringRef Name
) {
822 unsigned N
= findOption(Name
);
823 assert(N
!= Values
.size() && "Option not found!");
824 Values
.erase(Values
.begin() + N
);
828 //--------------------------------------------------
829 // basic_parser - Super class of parsers to provide boilerplate code
831 class basic_parser_impl
{ // non-template implementation of basic_parser<t>
833 basic_parser_impl(Option
&) {}
835 virtual ~basic_parser_impl() {}
837 enum ValueExpected
getValueExpectedFlagDefault() const {
838 return ValueRequired
;
841 void getExtraOptionNames(SmallVectorImpl
<StringRef
> &) {}
845 // Return the width of the option tag for printing...
846 size_t getOptionWidth(const Option
&O
) const;
848 // printOptionInfo - Print out information about this option. The
849 // to-be-maintained width is specified.
851 void printOptionInfo(const Option
&O
, size_t GlobalWidth
) const;
853 // printOptionNoValue - Print a placeholder for options that don't yet support
854 // printOptionDiff().
855 void printOptionNoValue(const Option
&O
, size_t GlobalWidth
) const;
857 // getValueName - Overload in subclass to provide a better default value.
858 virtual StringRef
getValueName() const { return "value"; }
860 // An out-of-line virtual method to provide a 'home' for this class.
861 virtual void anchor();
864 // A helper for basic_parser::printOptionDiff.
865 void printOptionName(const Option
&O
, size_t GlobalWidth
) const;
868 // basic_parser - The real basic parser is just a template wrapper that provides
869 // a typedef for the provided data type.
871 template <class DataType
> class basic_parser
: public basic_parser_impl
{
873 using parser_data_type
= DataType
;
874 using OptVal
= OptionValue
<DataType
>;
876 basic_parser(Option
&O
) : basic_parser_impl(O
) {}
879 //--------------------------------------------------
882 template <> class parser
<bool> : public basic_parser
<bool> {
884 parser(Option
&O
) : basic_parser(O
) {}
886 // parse - Return true on error.
887 bool parse(Option
&O
, StringRef ArgName
, StringRef Arg
, bool &Val
);
891 enum ValueExpected
getValueExpectedFlagDefault() const {
892 return ValueOptional
;
895 // getValueName - Do not print =<value> at all.
896 StringRef
getValueName() const override
{ return StringRef(); }
898 void printOptionDiff(const Option
&O
, bool V
, OptVal Default
,
899 size_t GlobalWidth
) const;
901 // An out-of-line virtual method to provide a 'home' for this class.
902 void anchor() override
;
905 extern template class basic_parser
<bool>;
907 //--------------------------------------------------
908 // parser<boolOrDefault>
909 template <> class parser
<boolOrDefault
> : public basic_parser
<boolOrDefault
> {
911 parser(Option
&O
) : basic_parser(O
) {}
913 // parse - Return true on error.
914 bool parse(Option
&O
, StringRef ArgName
, StringRef Arg
, boolOrDefault
&Val
);
916 enum ValueExpected
getValueExpectedFlagDefault() const {
917 return ValueOptional
;
920 // getValueName - Do not print =<value> at all.
921 StringRef
getValueName() const override
{ return StringRef(); }
923 void printOptionDiff(const Option
&O
, boolOrDefault 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
<boolOrDefault
>;
932 //--------------------------------------------------
935 template <> class parser
<int> : public basic_parser
<int> {
937 parser(Option
&O
) : basic_parser(O
) {}
939 // parse - Return true on error.
940 bool parse(Option
&O
, StringRef ArgName
, StringRef Arg
, int &Val
);
942 // getValueName - Overload in subclass to provide a better default value.
943 StringRef
getValueName() const override
{ return "int"; }
945 void printOptionDiff(const Option
&O
, int 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
<int>;
954 //--------------------------------------------------
957 template <> class parser
<unsigned> : public basic_parser
<unsigned> {
959 parser(Option
&O
) : basic_parser(O
) {}
961 // parse - Return true on error.
962 bool parse(Option
&O
, StringRef ArgName
, StringRef Arg
, unsigned &Val
);
964 // getValueName - Overload in subclass to provide a better default value.
965 StringRef
getValueName() const override
{ return "uint"; }
967 void printOptionDiff(const Option
&O
, unsigned V
, OptVal Default
,
968 size_t GlobalWidth
) const;
970 // An out-of-line virtual method to provide a 'home' for this class.
971 void anchor() override
;
974 extern template class basic_parser
<unsigned>;
976 //--------------------------------------------------
977 // parser<unsigned long>
980 class parser
<unsigned long> final
: public basic_parser
<unsigned long> {
982 parser(Option
&O
) : basic_parser(O
) {}
984 // parse - Return true on error.
985 bool parse(Option
&O
, StringRef ArgName
, StringRef Arg
, unsigned long &Val
);
987 // getValueName - Overload in subclass to provide a better default value.
988 StringRef
getValueName() const override
{ return "ulong"; }
990 void printOptionDiff(const Option
&O
, unsigned long V
, OptVal Default
,
991 size_t GlobalWidth
) const;
993 // An out-of-line virtual method to provide a 'home' for this class.
994 void anchor() override
;
997 extern template class basic_parser
<unsigned long>;
999 //--------------------------------------------------
1000 // parser<unsigned long long>
1003 class parser
<unsigned long long> : public basic_parser
<unsigned long long> {
1005 parser(Option
&O
) : basic_parser(O
) {}
1007 // parse - Return true on error.
1008 bool parse(Option
&O
, StringRef ArgName
, StringRef Arg
,
1009 unsigned long long &Val
);
1011 // getValueName - Overload in subclass to provide a better default value.
1012 StringRef
getValueName() const override
{ return "ulong"; }
1014 void printOptionDiff(const Option
&O
, unsigned long long 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
<unsigned long long>;
1023 //--------------------------------------------------
1026 template <> class parser
<double> : public basic_parser
<double> {
1028 parser(Option
&O
) : basic_parser(O
) {}
1030 // parse - Return true on error.
1031 bool parse(Option
&O
, StringRef ArgName
, StringRef Arg
, double &Val
);
1033 // getValueName - Overload in subclass to provide a better default value.
1034 StringRef
getValueName() const override
{ return "number"; }
1036 void printOptionDiff(const Option
&O
, double V
, OptVal Default
,
1037 size_t GlobalWidth
) const;
1039 // An out-of-line virtual method to provide a 'home' for this class.
1040 void anchor() override
;
1043 extern template class basic_parser
<double>;
1045 //--------------------------------------------------
1048 template <> class parser
<float> : public basic_parser
<float> {
1050 parser(Option
&O
) : basic_parser(O
) {}
1052 // parse - Return true on error.
1053 bool parse(Option
&O
, StringRef ArgName
, StringRef Arg
, float &Val
);
1055 // getValueName - Overload in subclass to provide a better default value.
1056 StringRef
getValueName() const override
{ return "number"; }
1058 void printOptionDiff(const Option
&O
, float V
, OptVal Default
,
1059 size_t GlobalWidth
) const;
1061 // An out-of-line virtual method to provide a 'home' for this class.
1062 void anchor() override
;
1065 extern template class basic_parser
<float>;
1067 //--------------------------------------------------
1068 // parser<std::string>
1070 template <> class parser
<std::string
> : public basic_parser
<std::string
> {
1072 parser(Option
&O
) : basic_parser(O
) {}
1074 // parse - Return true on error.
1075 bool parse(Option
&, StringRef
, StringRef Arg
, std::string
&Value
) {
1080 // getValueName - Overload in subclass to provide a better default value.
1081 StringRef
getValueName() const override
{ return "string"; }
1083 void printOptionDiff(const Option
&O
, StringRef V
, const OptVal
&Default
,
1084 size_t GlobalWidth
) const;
1086 // An out-of-line virtual method to provide a 'home' for this class.
1087 void anchor() override
;
1090 extern template class basic_parser
<std::string
>;
1092 //--------------------------------------------------
1095 template <> class parser
<char> : public basic_parser
<char> {
1097 parser(Option
&O
) : basic_parser(O
) {}
1099 // parse - Return true on error.
1100 bool parse(Option
&, StringRef
, StringRef Arg
, char &Value
) {
1105 // getValueName - Overload in subclass to provide a better default value.
1106 StringRef
getValueName() const override
{ return "char"; }
1108 void printOptionDiff(const Option
&O
, char V
, OptVal Default
,
1109 size_t GlobalWidth
) const;
1111 // An out-of-line virtual method to provide a 'home' for this class.
1112 void anchor() override
;
1115 extern template class basic_parser
<char>;
1117 //--------------------------------------------------
1120 // This collection of wrappers is the intermediary between class opt and class
1121 // parser to handle all the template nastiness.
1123 // This overloaded function is selected by the generic parser.
1124 template <class ParserClass
, class DT
>
1125 void printOptionDiff(const Option
&O
, const generic_parser_base
&P
, const DT
&V
,
1126 const OptionValue
<DT
> &Default
, size_t GlobalWidth
) {
1127 OptionValue
<DT
> OV
= V
;
1128 P
.printOptionDiff(O
, OV
, Default
, GlobalWidth
);
1131 // This is instantiated for basic parsers when the parsed value has a different
1132 // type than the option value. e.g. HelpPrinter.
1133 template <class ParserDT
, class ValDT
> struct OptionDiffPrinter
{
1134 void print(const Option
&O
, const parser
<ParserDT
> &P
, const ValDT
& /*V*/,
1135 const OptionValue
<ValDT
> & /*Default*/, size_t GlobalWidth
) {
1136 P
.printOptionNoValue(O
, GlobalWidth
);
1140 // This is instantiated for basic parsers when the parsed value has the same
1141 // type as the option value.
1142 template <class DT
> struct OptionDiffPrinter
<DT
, DT
> {
1143 void print(const Option
&O
, const parser
<DT
> &P
, const DT
&V
,
1144 const OptionValue
<DT
> &Default
, size_t GlobalWidth
) {
1145 P
.printOptionDiff(O
, V
, Default
, GlobalWidth
);
1149 // This overloaded function is selected by the basic parser, which may parse a
1150 // different type than the option type.
1151 template <class ParserClass
, class ValDT
>
1152 void printOptionDiff(
1154 const basic_parser
<typename
ParserClass::parser_data_type
> &P
,
1155 const ValDT
&V
, const OptionValue
<ValDT
> &Default
, size_t GlobalWidth
) {
1157 OptionDiffPrinter
<typename
ParserClass::parser_data_type
, ValDT
> printer
;
1158 printer
.print(O
, static_cast<const ParserClass
&>(P
), V
, Default
,
1162 //===----------------------------------------------------------------------===//
1163 // applicator class - This class is used because we must use partial
1164 // specialization to handle literal string arguments specially (const char* does
1165 // not correctly respond to the apply method). Because the syntax to use this
1166 // is a pain, we have the 'apply' method below to handle the nastiness...
1168 template <class Mod
> struct applicator
{
1169 template <class Opt
> static void opt(const Mod
&M
, Opt
&O
) { M
.apply(O
); }
1172 // Handle const char* as a special case...
1173 template <unsigned n
> struct applicator
<char[n
]> {
1174 template <class Opt
> static void opt(StringRef Str
, Opt
&O
) {
1178 template <unsigned n
> struct applicator
<const char[n
]> {
1179 template <class Opt
> static void opt(StringRef Str
, Opt
&O
) {
1183 template <> struct applicator
<StringRef
> {
1184 template <class Opt
> static void opt(StringRef Str
, Opt
&O
) {
1189 template <> struct applicator
<NumOccurrencesFlag
> {
1190 static void opt(NumOccurrencesFlag N
, Option
&O
) {
1191 O
.setNumOccurrencesFlag(N
);
1195 template <> struct applicator
<ValueExpected
> {
1196 static void opt(ValueExpected VE
, Option
&O
) { O
.setValueExpectedFlag(VE
); }
1199 template <> struct applicator
<OptionHidden
> {
1200 static void opt(OptionHidden OH
, Option
&O
) { O
.setHiddenFlag(OH
); }
1203 template <> struct applicator
<FormattingFlags
> {
1204 static void opt(FormattingFlags FF
, Option
&O
) { O
.setFormattingFlag(FF
); }
1207 template <> struct applicator
<MiscFlags
> {
1208 static void opt(MiscFlags MF
, Option
&O
) {
1209 assert((MF
!= Grouping
|| O
.ArgStr
.size() == 1) &&
1210 "cl::Grouping can only apply to single charater Options.");
1215 // apply method - Apply modifiers to an option in a type safe way.
1216 template <class Opt
, class Mod
, class... Mods
>
1217 void apply(Opt
*O
, const Mod
&M
, const Mods
&... Ms
) {
1218 applicator
<Mod
>::opt(M
, *O
);
1222 template <class Opt
, class Mod
> void apply(Opt
*O
, const Mod
&M
) {
1223 applicator
<Mod
>::opt(M
, *O
);
1226 //===----------------------------------------------------------------------===//
1227 // opt_storage class
1229 // Default storage class definition: external storage. This implementation
1230 // assumes the user will specify a variable to store the data into with the
1231 // cl::location(x) modifier.
1233 template <class DataType
, bool ExternalStorage
, bool isClass
>
1235 DataType
*Location
= nullptr; // Where to store the object...
1236 OptionValue
<DataType
> Default
;
1238 void check_location() const {
1239 assert(Location
&& "cl::location(...) not specified for a command "
1240 "line option with external storage, "
1241 "or cl::init specified before cl::location()!!");
1245 opt_storage() = default;
1247 bool setLocation(Option
&O
, DataType
&L
) {
1249 return O
.error("cl::location(x) specified more than once!");
1255 template <class T
> void setValue(const T
&V
, bool initial
= false) {
1262 DataType
&getValue() {
1266 const DataType
&getValue() const {
1271 operator DataType() const { return this->getValue(); }
1273 const OptionValue
<DataType
> &getDefault() const { return Default
; }
1276 // Define how to hold a class type object, such as a string. Since we can
1277 // inherit from a class, we do so. This makes us exactly compatible with the
1278 // object in all cases that it is used.
1280 template <class DataType
>
1281 class opt_storage
<DataType
, false, true> : public DataType
{
1283 OptionValue
<DataType
> Default
;
1285 template <class T
> void setValue(const T
&V
, bool initial
= false) {
1286 DataType::operator=(V
);
1291 DataType
&getValue() { return *this; }
1292 const DataType
&getValue() const { return *this; }
1294 const OptionValue
<DataType
> &getDefault() const { return Default
; }
1297 // Define a partial specialization to handle things we cannot inherit from. In
1298 // this case, we store an instance through containment, and overload operators
1299 // to get at the value.
1301 template <class DataType
> class opt_storage
<DataType
, false, false> {
1304 OptionValue
<DataType
> Default
;
1306 // Make sure we initialize the value with the default constructor for the
1308 opt_storage() : Value(DataType()), Default(DataType()) {}
1310 template <class T
> void setValue(const T
&V
, bool initial
= false) {
1315 DataType
&getValue() { return Value
; }
1316 DataType
getValue() const { return Value
; }
1318 const OptionValue
<DataType
> &getDefault() const { return Default
; }
1320 operator DataType() const { return getValue(); }
1322 // If the datatype is a pointer, support -> on it.
1323 DataType
operator->() const { return Value
; }
1326 //===----------------------------------------------------------------------===//
1327 // opt - A scalar command line option.
1329 template <class DataType
, bool ExternalStorage
= false,
1330 class ParserClass
= parser
<DataType
>>
1331 class opt
: public Option
,
1332 public opt_storage
<DataType
, ExternalStorage
,
1333 std::is_class
<DataType
>::value
> {
1336 bool handleOccurrence(unsigned pos
, StringRef ArgName
,
1337 StringRef Arg
) override
{
1338 typename
ParserClass::parser_data_type Val
=
1339 typename
ParserClass::parser_data_type();
1340 if (Parser
.parse(*this, ArgName
, Arg
, Val
))
1341 return true; // Parse error!
1342 this->setValue(Val
);
1343 this->setPosition(pos
);
1347 enum ValueExpected
getValueExpectedFlagDefault() const override
{
1348 return Parser
.getValueExpectedFlagDefault();
1351 void getExtraOptionNames(SmallVectorImpl
<StringRef
> &OptionNames
) override
{
1352 return Parser
.getExtraOptionNames(OptionNames
);
1355 // Forward printing stuff to the parser...
1356 size_t getOptionWidth() const override
{
1357 return Parser
.getOptionWidth(*this);
1360 void printOptionInfo(size_t GlobalWidth
) const override
{
1361 Parser
.printOptionInfo(*this, GlobalWidth
);
1364 void printOptionValue(size_t GlobalWidth
, bool Force
) const override
{
1365 if (Force
|| this->getDefault().compare(this->getValue())) {
1366 cl::printOptionDiff
<ParserClass
>(*this, Parser
, this->getValue(),
1367 this->getDefault(), GlobalWidth
);
1371 template <class T
, class = typename
std::enable_if
<
1372 std::is_assignable
<T
&, T
>::value
>::type
>
1373 void setDefaultImpl() {
1374 const OptionValue
<DataType
> &V
= this->getDefault();
1376 this->setValue(V
.getValue());
1379 template <class T
, class = typename
std::enable_if
<
1380 !std::is_assignable
<T
&, T
>::value
>::type
>
1381 void setDefaultImpl(...) {}
1383 void setDefault() override
{ setDefaultImpl
<DataType
>(); }
1387 Parser
.initialize();
1391 // Command line options should not be copyable
1392 opt(const opt
&) = delete;
1393 opt
&operator=(const opt
&) = delete;
1395 // setInitialValue - Used by the cl::init modifier...
1396 void setInitialValue(const DataType
&V
) { this->setValue(V
, true); }
1398 ParserClass
&getParser() { return Parser
; }
1400 template <class T
> DataType
&operator=(const T
&Val
) {
1401 this->setValue(Val
);
1402 return this->getValue();
1405 template <class... Mods
>
1406 explicit opt(const Mods
&... Ms
)
1407 : Option(Optional
, NotHidden
), Parser(*this) {
1413 extern template class opt
<unsigned>;
1414 extern template class opt
<int>;
1415 extern template class opt
<std::string
>;
1416 extern template class opt
<char>;
1417 extern template class opt
<bool>;
1419 //===----------------------------------------------------------------------===//
1420 // list_storage class
1422 // Default storage class definition: external storage. This implementation
1423 // assumes the user will specify a variable to store the data into with the
1424 // cl::location(x) modifier.
1426 template <class DataType
, class StorageClass
> class list_storage
{
1427 StorageClass
*Location
= nullptr; // Where to store the object...
1430 list_storage() = default;
1434 bool setLocation(Option
&O
, StorageClass
&L
) {
1436 return O
.error("cl::location(x) specified more than once!");
1441 template <class T
> void addValue(const T
&V
) {
1442 assert(Location
!= 0 && "cl::location(...) not specified for a command "
1443 "line option with external storage!");
1444 Location
->push_back(V
);
1448 // Define how to hold a class type object, such as a string.
1449 // Originally this code inherited from std::vector. In transitioning to a new
1450 // API for command line options we should change this. The new implementation
1451 // of this list_storage specialization implements the minimum subset of the
1452 // std::vector API required for all the current clients.
1454 // FIXME: Reduce this API to a more narrow subset of std::vector
1456 template <class DataType
> class list_storage
<DataType
, bool> {
1457 std::vector
<DataType
> Storage
;
1460 using iterator
= typename
std::vector
<DataType
>::iterator
;
1462 iterator
begin() { return Storage
.begin(); }
1463 iterator
end() { return Storage
.end(); }
1465 using const_iterator
= typename
std::vector
<DataType
>::const_iterator
;
1467 const_iterator
begin() const { return Storage
.begin(); }
1468 const_iterator
end() const { return Storage
.end(); }
1470 using size_type
= typename
std::vector
<DataType
>::size_type
;
1472 size_type
size() const { return Storage
.size(); }
1474 bool empty() const { return Storage
.empty(); }
1476 void push_back(const DataType
&value
) { Storage
.push_back(value
); }
1477 void push_back(DataType
&&value
) { Storage
.push_back(value
); }
1479 using reference
= typename
std::vector
<DataType
>::reference
;
1480 using const_reference
= typename
std::vector
<DataType
>::const_reference
;
1482 reference
operator[](size_type pos
) { return Storage
[pos
]; }
1483 const_reference
operator[](size_type pos
) const { return Storage
[pos
]; }
1489 iterator
erase(const_iterator pos
) { return Storage
.erase(pos
); }
1490 iterator
erase(const_iterator first
, const_iterator last
) {
1491 return Storage
.erase(first
, last
);
1494 iterator
erase(iterator pos
) { return Storage
.erase(pos
); }
1495 iterator
erase(iterator first
, iterator last
) {
1496 return Storage
.erase(first
, last
);
1499 iterator
insert(const_iterator pos
, const DataType
&value
) {
1500 return Storage
.insert(pos
, value
);
1502 iterator
insert(const_iterator pos
, DataType
&&value
) {
1503 return Storage
.insert(pos
, value
);
1506 iterator
insert(iterator pos
, const DataType
&value
) {
1507 return Storage
.insert(pos
, value
);
1509 iterator
insert(iterator pos
, DataType
&&value
) {
1510 return Storage
.insert(pos
, value
);
1513 reference
front() { return Storage
.front(); }
1514 const_reference
front() const { return Storage
.front(); }
1516 operator std::vector
<DataType
>&() { return Storage
; }
1517 operator ArrayRef
<DataType
>() { return Storage
; }
1518 std::vector
<DataType
> *operator&() { return &Storage
; }
1519 const std::vector
<DataType
> *operator&() const { return &Storage
; }
1521 template <class T
> void addValue(const T
&V
) { Storage
.push_back(V
); }
1524 //===----------------------------------------------------------------------===//
1525 // list - A list of command line options.
1527 template <class DataType
, class StorageClass
= bool,
1528 class ParserClass
= parser
<DataType
>>
1529 class list
: public Option
, public list_storage
<DataType
, StorageClass
> {
1530 std::vector
<unsigned> Positions
;
1533 enum ValueExpected
getValueExpectedFlagDefault() const override
{
1534 return Parser
.getValueExpectedFlagDefault();
1537 void getExtraOptionNames(SmallVectorImpl
<StringRef
> &OptionNames
) override
{
1538 return Parser
.getExtraOptionNames(OptionNames
);
1541 bool handleOccurrence(unsigned pos
, StringRef ArgName
,
1542 StringRef Arg
) override
{
1543 typename
ParserClass::parser_data_type Val
=
1544 typename
ParserClass::parser_data_type();
1545 if (Parser
.parse(*this, ArgName
, Arg
, Val
))
1546 return true; // Parse Error!
1547 list_storage
<DataType
, StorageClass
>::addValue(Val
);
1549 Positions
.push_back(pos
);
1553 // Forward printing stuff to the parser...
1554 size_t getOptionWidth() const override
{
1555 return Parser
.getOptionWidth(*this);
1558 void printOptionInfo(size_t GlobalWidth
) const override
{
1559 Parser
.printOptionInfo(*this, GlobalWidth
);
1562 // Unimplemented: list options don't currently store their default value.
1563 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override
{
1566 void setDefault() override
{
1568 list_storage
<DataType
, StorageClass
>::clear();
1573 Parser
.initialize();
1577 // Command line options should not be copyable
1578 list(const list
&) = delete;
1579 list
&operator=(const list
&) = delete;
1581 ParserClass
&getParser() { return Parser
; }
1583 unsigned getPosition(unsigned optnum
) const {
1584 assert(optnum
< this->size() && "Invalid option index");
1585 return Positions
[optnum
];
1588 void setNumAdditionalVals(unsigned n
) { Option::setNumAdditionalVals(n
); }
1590 template <class... Mods
>
1591 explicit list(const Mods
&... Ms
)
1592 : Option(ZeroOrMore
, NotHidden
), Parser(*this) {
1598 // multi_val - Modifier to set the number of additional values.
1600 unsigned AdditionalVals
;
1601 explicit multi_val(unsigned N
) : AdditionalVals(N
) {}
1603 template <typename D
, typename S
, typename P
>
1604 void apply(list
<D
, S
, P
> &L
) const {
1605 L
.setNumAdditionalVals(AdditionalVals
);
1609 //===----------------------------------------------------------------------===//
1610 // bits_storage class
1612 // Default storage class definition: external storage. This implementation
1613 // assumes the user will specify a variable to store the data into with the
1614 // cl::location(x) modifier.
1616 template <class DataType
, class StorageClass
> class bits_storage
{
1617 unsigned *Location
= nullptr; // Where to store the bits...
1619 template <class T
> static unsigned Bit(const T
&V
) {
1620 unsigned BitPos
= reinterpret_cast<unsigned>(V
);
1621 assert(BitPos
< sizeof(unsigned) * CHAR_BIT
&&
1622 "enum exceeds width of bit vector!");
1627 bits_storage() = default;
1629 bool setLocation(Option
&O
, unsigned &L
) {
1631 return O
.error("cl::location(x) specified more than once!");
1636 template <class T
> void addValue(const T
&V
) {
1637 assert(Location
!= 0 && "cl::location(...) not specified for a command "
1638 "line option with external storage!");
1639 *Location
|= Bit(V
);
1642 unsigned getBits() { return *Location
; }
1644 template <class T
> bool isSet(const T
&V
) {
1645 return (*Location
& Bit(V
)) != 0;
1649 // Define how to hold bits. Since we can inherit from a class, we do so.
1650 // This makes us exactly compatible with the bits in all cases that it is used.
1652 template <class DataType
> class bits_storage
<DataType
, bool> {
1653 unsigned Bits
; // Where to store the bits...
1655 template <class T
> static unsigned Bit(const T
&V
) {
1656 unsigned BitPos
= (unsigned)V
;
1657 assert(BitPos
< sizeof(unsigned) * CHAR_BIT
&&
1658 "enum exceeds width of bit vector!");
1663 template <class T
> void addValue(const T
&V
) { Bits
|= Bit(V
); }
1665 unsigned getBits() { return Bits
; }
1667 template <class T
> bool isSet(const T
&V
) { return (Bits
& Bit(V
)) != 0; }
1670 //===----------------------------------------------------------------------===//
1671 // bits - A bit vector of command options.
1673 template <class DataType
, class Storage
= bool,
1674 class ParserClass
= parser
<DataType
>>
1675 class bits
: public Option
, public bits_storage
<DataType
, Storage
> {
1676 std::vector
<unsigned> Positions
;
1679 enum ValueExpected
getValueExpectedFlagDefault() const override
{
1680 return Parser
.getValueExpectedFlagDefault();
1683 void getExtraOptionNames(SmallVectorImpl
<StringRef
> &OptionNames
) override
{
1684 return Parser
.getExtraOptionNames(OptionNames
);
1687 bool handleOccurrence(unsigned pos
, StringRef ArgName
,
1688 StringRef Arg
) override
{
1689 typename
ParserClass::parser_data_type Val
=
1690 typename
ParserClass::parser_data_type();
1691 if (Parser
.parse(*this, ArgName
, Arg
, Val
))
1692 return true; // Parse Error!
1693 this->addValue(Val
);
1695 Positions
.push_back(pos
);
1699 // Forward printing stuff to the parser...
1700 size_t getOptionWidth() const override
{
1701 return Parser
.getOptionWidth(*this);
1704 void printOptionInfo(size_t GlobalWidth
) const override
{
1705 Parser
.printOptionInfo(*this, GlobalWidth
);
1708 // Unimplemented: bits options don't currently store their default values.
1709 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override
{
1712 void setDefault() override
{}
1716 Parser
.initialize();
1720 // Command line options should not be copyable
1721 bits(const bits
&) = delete;
1722 bits
&operator=(const bits
&) = delete;
1724 ParserClass
&getParser() { return Parser
; }
1726 unsigned getPosition(unsigned optnum
) const {
1727 assert(optnum
< this->size() && "Invalid option index");
1728 return Positions
[optnum
];
1731 template <class... Mods
>
1732 explicit bits(const Mods
&... Ms
)
1733 : Option(ZeroOrMore
, NotHidden
), Parser(*this) {
1739 //===----------------------------------------------------------------------===//
1740 // Aliased command line option (alias this name to a preexisting name)
1743 class alias
: public Option
{
1746 bool handleOccurrence(unsigned pos
, StringRef
/*ArgName*/,
1747 StringRef Arg
) override
{
1748 return AliasFor
->handleOccurrence(pos
, AliasFor
->ArgStr
, Arg
);
1751 bool addOccurrence(unsigned pos
, StringRef
/*ArgName*/, StringRef Value
,
1752 bool MultiArg
= false) override
{
1753 return AliasFor
->addOccurrence(pos
, AliasFor
->ArgStr
, Value
, MultiArg
);
1756 // Handle printing stuff...
1757 size_t getOptionWidth() const override
;
1758 void printOptionInfo(size_t GlobalWidth
) const override
;
1760 // Aliases do not need to print their values.
1761 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override
{
1764 void setDefault() override
{ AliasFor
->setDefault(); }
1766 ValueExpected
getValueExpectedFlagDefault() const override
{
1767 return AliasFor
->getValueExpectedFlag();
1772 error("cl::alias must have argument name specified!");
1774 error("cl::alias must have an cl::aliasopt(option) specified!");
1776 error("cl::alias must not have cl::sub(), aliased option's cl::sub() will be used!");
1777 Subs
= AliasFor
->Subs
;
1778 Categories
= AliasFor
->Categories
;
1783 // Command line options should not be copyable
1784 alias(const alias
&) = delete;
1785 alias
&operator=(const alias
&) = delete;
1787 void setAliasFor(Option
&O
) {
1789 error("cl::alias must only have one cl::aliasopt(...) specified!");
1793 template <class... Mods
>
1794 explicit alias(const Mods
&... Ms
)
1795 : Option(Optional
, Hidden
), AliasFor(nullptr) {
1801 // aliasfor - Modifier to set the option an alias aliases.
1805 explicit aliasopt(Option
&O
) : Opt(O
) {}
1807 void apply(alias
&A
) const { A
.setAliasFor(Opt
); }
1810 // extrahelp - provide additional help at the end of the normal help
1811 // output. All occurrences of cl::extrahelp will be accumulated and
1812 // printed to stderr at the end of the regular help, just before
1817 explicit extrahelp(StringRef help
);
1820 void PrintVersionMessage();
1822 /// This function just prints the help message, exactly the same way as if the
1823 /// -help or -help-hidden option had been given on the command line.
1825 /// \param Hidden if true will print hidden options
1826 /// \param Categorized if true print options in categories
1827 void PrintHelpMessage(bool Hidden
= false, bool Categorized
= false);
1829 //===----------------------------------------------------------------------===//
1830 // Public interface for accessing registered options.
1833 /// Use this to get a StringMap to all registered named options
1834 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1836 /// \return A reference to the StringMap used by the cl APIs to parse options.
1838 /// Access to unnamed arguments (i.e. positional) are not provided because
1839 /// it is expected that the client already has access to these.
1843 /// main(int argc,char* argv[]) {
1844 /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions();
1845 /// assert(opts.count("help") == 1)
1846 /// opts["help"]->setDescription("Show alphabetical help information")
1848 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1853 /// This interface is useful for modifying options in libraries that are out of
1854 /// the control of the client. The options should be modified before calling
1855 /// llvm::cl::ParseCommandLineOptions().
1857 /// Hopefully this API can be deprecated soon. Any situation where options need
1858 /// to be modified by tools or libraries should be handled by sane APIs rather
1859 /// than just handing around a global list.
1860 StringMap
<Option
*> &getRegisteredOptions(SubCommand
&Sub
= *TopLevelSubCommand
);
1862 /// Use this to get all registered SubCommands from the provided parser.
1864 /// \return A range of all SubCommand pointers registered with the parser.
1868 /// main(int argc, char* argv[]) {
1869 /// llvm::cl::ParseCommandLineOptions(argc, argv);
1870 /// for (auto* S : llvm::cl::getRegisteredSubcommands()) {
1872 /// std::cout << "Executing subcommand: " << S->getName() << std::endl;
1873 /// // Execute some function based on the name...
1879 /// This interface is useful for defining subcommands in libraries and
1880 /// the dispatch from a single point (like in the main function).
1881 iterator_range
<typename SmallPtrSet
<SubCommand
*, 4>::iterator
>
1882 getRegisteredSubcommands();
1884 //===----------------------------------------------------------------------===//
1885 // Standalone command line processing utilities.
1888 /// Tokenizes a command line that can contain escapes and quotes.
1890 /// The quoting rules match those used by GCC and other tools that use
1891 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1892 /// They differ from buildargv() on treatment of backslashes that do not escape
1893 /// a special character to make it possible to accept most Windows file paths.
1895 /// \param [in] Source The string to be split on whitespace with quotes.
1896 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1897 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1898 /// lines and end of the response file to be marked with a nullptr string.
1899 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1900 void TokenizeGNUCommandLine(StringRef Source
, StringSaver
&Saver
,
1901 SmallVectorImpl
<const char *> &NewArgv
,
1902 bool MarkEOLs
= false);
1904 /// Tokenizes a Windows command line which may contain quotes and escaped
1907 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1908 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1910 /// \param [in] Source The string to be split on whitespace with quotes.
1911 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1912 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1913 /// lines and end of the response file to be marked with a nullptr string.
1914 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1915 void TokenizeWindowsCommandLine(StringRef Source
, StringSaver
&Saver
,
1916 SmallVectorImpl
<const char *> &NewArgv
,
1917 bool MarkEOLs
= false);
1919 /// String tokenization function type. Should be compatible with either
1920 /// Windows or Unix command line tokenizers.
1921 using TokenizerCallback
= void (*)(StringRef Source
, StringSaver
&Saver
,
1922 SmallVectorImpl
<const char *> &NewArgv
,
1925 /// Tokenizes content of configuration file.
1927 /// \param [in] Source The string representing content of config file.
1928 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1929 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1930 /// \param [in] MarkEOLs Added for compatibility with TokenizerCallback.
1932 /// It works like TokenizeGNUCommandLine with ability to skip comment lines.
1934 void tokenizeConfigFile(StringRef Source
, StringSaver
&Saver
,
1935 SmallVectorImpl
<const char *> &NewArgv
,
1936 bool MarkEOLs
= false);
1938 /// Reads command line options from the given configuration file.
1940 /// \param [in] CfgFileName Path to configuration file.
1941 /// \param [in] Saver Objects that saves allocated strings.
1942 /// \param [out] Argv Array to which the read options are added.
1943 /// \return true if the file was successfully read.
1945 /// It reads content of the specified file, tokenizes it and expands "@file"
1946 /// commands resolving file names in them relative to the directory where
1947 /// CfgFilename resides.
1949 bool readConfigFile(StringRef CfgFileName
, StringSaver
&Saver
,
1950 SmallVectorImpl
<const char *> &Argv
);
1952 /// Expand response files on a command line recursively using the given
1953 /// StringSaver and tokenization strategy. Argv should contain the command line
1954 /// before expansion and will be modified in place. If requested, Argv will
1955 /// also be populated with nullptrs indicating where each response file line
1956 /// ends, which is useful for the "/link" argument that needs to consume all
1957 /// remaining arguments only until the next end of line, when in a response
1960 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1961 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1962 /// \param [in,out] Argv Command line into which to expand response files.
1963 /// \param [in] MarkEOLs Mark end of lines and the end of the response file
1964 /// with nullptrs in the Argv vector.
1965 /// \param [in] RelativeNames true if names of nested response files must be
1966 /// resolved relative to including file.
1967 /// \return true if all @files were expanded successfully or there were none.
1968 bool ExpandResponseFiles(StringSaver
&Saver
, TokenizerCallback Tokenizer
,
1969 SmallVectorImpl
<const char *> &Argv
,
1970 bool MarkEOLs
= false, bool RelativeNames
= false);
1972 /// Mark all options not part of this category as cl::ReallyHidden.
1974 /// \param Category the category of options to keep displaying
1976 /// Some tools (like clang-format) like to be able to hide all options that are
1977 /// not specific to the tool. This function allows a tool to specify a single
1978 /// option category to display in the -help output.
1979 void HideUnrelatedOptions(cl::OptionCategory
&Category
,
1980 SubCommand
&Sub
= *TopLevelSubCommand
);
1982 /// Mark all options not part of the categories as cl::ReallyHidden.
1984 /// \param Categories the categories of options to keep displaying.
1986 /// Some tools (like clang-format) like to be able to hide all options that are
1987 /// not specific to the tool. This function allows a tool to specify a single
1988 /// option category to display in the -help output.
1989 void HideUnrelatedOptions(ArrayRef
<const cl::OptionCategory
*> Categories
,
1990 SubCommand
&Sub
= *TopLevelSubCommand
);
1992 /// Reset all command line options to a state that looks as if they have
1993 /// never appeared on the command line. This is useful for being able to parse
1994 /// a command line multiple times (especially useful for writing tests).
1995 void ResetAllOptionOccurrences();
1997 /// Reset the command line parser back to its initial state. This
1999 /// all options, categories, and subcommands and returns the parser to a state
2000 /// where no options are supported.
2001 void ResetCommandLineParser();
2003 /// Parses `Arg` into the option handler `Handler`.
2004 bool ProvidePositionalOption(Option
*Handler
, StringRef Arg
, int i
);
2006 } // end namespace cl
2008 } // end namespace llvm
2010 #endif // LLVM_SUPPORT_COMMANDLINE_H