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/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/ManagedStatic.h"
40 /// cl Namespace - This namespace contains all of the command line option
41 /// processing machinery. It is intentionally a short name to make qualified
45 //===----------------------------------------------------------------------===//
46 // ParseCommandLineOptions - Command line option processing entry point.
48 bool ParseCommandLineOptions(int argc, const char *const *argv,
49 const char *Overview = nullptr,
50 bool IgnoreErrors = false);
52 //===----------------------------------------------------------------------===//
53 // ParseEnvironmentOptions - Environment variable option processing alternate
56 void ParseEnvironmentOptions(const char *progName, const char *envvar,
57 const char *Overview = nullptr);
59 ///===---------------------------------------------------------------------===//
60 /// SetVersionPrinter - Override the default (LLVM specific) version printer
61 /// used to print out the version when --version is given
62 /// on the command line. This allows other systems using the
63 /// CommandLine utilities to print their own version string.
64 void SetVersionPrinter(void (*func)());
66 ///===---------------------------------------------------------------------===//
67 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
68 /// default one. This can be called multiple times,
69 /// and each time it adds a new function to the list
70 /// which will be called after the basic LLVM version
71 /// printing is complete. Each can then add additional
72 /// information specific to the tool.
73 void AddExtraVersionPrinter(void (*func)());
75 // PrintOptionValues - Print option values.
76 // With -print-options print the difference between option values and defaults.
77 // With -print-all-options print all option values.
78 // (Currently not perfect, but best-effort.)
79 void PrintOptionValues();
81 // Forward declaration - AddLiteralOption needs to be up here to make gcc happy.
84 /// \brief Adds a new option for parsing and provides the option it refers to.
86 /// \param O pointer to the option
87 /// \param Name the string name for the option to handle during parsing
89 /// Literal options are used by some parsers to register special option values.
90 /// This is how the PassNameParser registers pass names for opt.
91 void AddLiteralOption(Option &O, const char *Name);
93 //===----------------------------------------------------------------------===//
94 // Flags permitted to be passed to command line arguments
97 enum NumOccurrencesFlag { // Flags for the number of occurrences allowed
98 Optional = 0x00, // Zero or One occurrence
99 ZeroOrMore = 0x01, // Zero or more occurrences allowed
100 Required = 0x02, // One occurrence required
101 OneOrMore = 0x03, // One or more occurrences required
103 // ConsumeAfter - Indicates that this option is fed anything that follows the
104 // last positional argument required by the application (it is an error if
105 // there are zero positional arguments, and a ConsumeAfter option is used).
106 // Thus, for example, all arguments to LLI are processed until a filename is
107 // found. Once a filename is found, all of the succeeding arguments are
108 // passed, unprocessed, to the ConsumeAfter option.
113 enum ValueExpected { // Is a value required for the option?
114 // zero reserved for the unspecified value
115 ValueOptional = 0x01, // The value can appear... or not
116 ValueRequired = 0x02, // The value is required to appear!
117 ValueDisallowed = 0x03 // A value may not be specified (for flags)
120 enum OptionHidden { // Control whether -help shows this option
121 NotHidden = 0x00, // Option included in -help & -help-hidden
122 Hidden = 0x01, // -help doesn't, but -help-hidden does
123 ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg
126 // Formatting flags - This controls special features that the option might have
127 // that cause it to be parsed differently...
129 // Prefix - This option allows arguments that are otherwise unrecognized to be
130 // matched by options that are a prefix of the actual value. This is useful for
131 // cases like a linker, where options are typically of the form '-lfoo' or
132 // '-L../../include' where -l or -L are the actual flags. When prefix is
133 // enabled, and used, the value for the flag comes from the suffix of the
136 // Grouping - With this option enabled, multiple letter options are allowed to
137 // bunch together with only a single hyphen for the whole group. This allows
138 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
141 enum FormattingFlags {
142 NormalFormatting = 0x00, // Nothing special
143 Positional = 0x01, // Is a positional argument, no '-' required
144 Prefix = 0x02, // Can this option directly prefix its value?
145 Grouping = 0x03 // Can this option group with other options?
148 enum MiscFlags { // Miscellaneous flags to adjust argument
149 CommaSeparated = 0x01, // Should this cl::list split between commas?
150 PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args?
151 Sink = 0x04 // Should this cl::list eat all unknown options?
154 //===----------------------------------------------------------------------===//
155 // Option Category class
157 class OptionCategory {
159 const char *const Name;
160 const char *const Description;
161 void registerCategory();
164 OptionCategory(const char *const Name,
165 const char *const Description = nullptr)
166 : Name(Name), Description(Description) {
169 const char *getName() const { return Name; }
170 const char *getDescription() const { return Description; }
173 // The general Option Category (used as default category).
174 extern OptionCategory GeneralCategory;
176 //===----------------------------------------------------------------------===//
181 const char *const Name = nullptr;
182 const char *const Description = nullptr;
185 void registerSubCommand();
186 void unregisterSubCommand();
189 SubCommand(const char *const Name, const char *const Description = nullptr)
190 : Name(Name), Description(Description) {
191 registerSubCommand();
197 operator bool() const;
199 const char *getName() const { return Name; }
200 const char *getDescription() const { return Description; }
202 SmallVector<Option *, 4> PositionalOpts;
203 SmallVector<Option *, 4> SinkOpts;
204 StringMap<Option *> OptionsMap;
206 Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists.
209 // A special subcommand representing no subcommand
210 extern ManagedStatic<SubCommand> TopLevelSubCommand;
212 // A special subcommand that can be used to put an option into all subcommands.
213 extern ManagedStatic<SubCommand> AllSubCommands;
215 //===----------------------------------------------------------------------===//
222 // handleOccurrences - Overriden by subclasses to handle the value passed into
223 // an argument. Should return true if there was an error processing the
224 // argument and the program should exit.
226 virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
229 virtual enum ValueExpected getValueExpectedFlagDefault() const {
230 return ValueOptional;
233 // Out of line virtual function to provide home for the class.
234 virtual void anchor();
236 int NumOccurrences; // The number of times specified
237 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
238 // problems with signed enums in bitfields.
239 unsigned Occurrences : 3; // enum NumOccurrencesFlag
240 // not using the enum type for 'Value' because zero is an implementation
241 // detail representing the non-value
243 unsigned HiddenFlag : 2; // enum OptionHidden
244 unsigned Formatting : 2; // enum FormattingFlags
246 unsigned Position; // Position of last occurrence of the option
247 unsigned AdditionalVals; // Greater than 0 for multi-valued option.
250 StringRef ArgStr; // The argument string itself (ex: "help", "o")
251 StringRef HelpStr; // The descriptive text message for -help
252 StringRef ValueStr; // String describing what the value of this option is
253 OptionCategory *Category; // The Category this option belongs to
254 SmallPtrSet<SubCommand *, 4> Subs; // The subcommands this option belongs to.
255 bool FullyInitialized; // Has addArguemnt been called?
257 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
258 return (enum NumOccurrencesFlag)Occurrences;
260 inline enum ValueExpected getValueExpectedFlag() const {
261 return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
263 inline enum OptionHidden getOptionHiddenFlag() const {
264 return (enum OptionHidden)HiddenFlag;
266 inline enum FormattingFlags getFormattingFlag() const {
267 return (enum FormattingFlags)Formatting;
269 inline unsigned getMiscFlags() const { return Misc; }
270 inline unsigned getPosition() const { return Position; }
271 inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
273 // hasArgStr - Return true if the argstr != ""
274 bool hasArgStr() const { return !ArgStr.empty(); }
275 bool isPositional() const { return getFormattingFlag() == cl::Positional; }
276 bool isSink() const { return getMiscFlags() & cl::Sink; }
277 bool isConsumeAfter() const {
278 return getNumOccurrencesFlag() == cl::ConsumeAfter;
280 bool isInAllSubCommands() const {
281 return std::any_of(Subs.begin(), Subs.end(), [](const SubCommand *SC) {
282 return SC == &*AllSubCommands;
286 //-------------------------------------------------------------------------===
287 // Accessor functions set by OptionModifiers
289 void setArgStr(StringRef S);
290 void setDescription(StringRef S) { HelpStr = S; }
291 void setValueStr(StringRef S) { ValueStr = S; }
292 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
293 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
294 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
295 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
296 void setMiscFlag(enum MiscFlags M) { Misc |= M; }
297 void setPosition(unsigned pos) { Position = pos; }
298 void setCategory(OptionCategory &C) { Category = &C; }
299 void addSubCommand(SubCommand &S) { Subs.insert(&S); }
302 explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
303 enum OptionHidden Hidden)
304 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
305 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0),
306 AdditionalVals(0), ArgStr(""), HelpStr(""), ValueStr(""),
307 Category(&GeneralCategory), FullyInitialized(false) {}
309 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
312 // addArgument - Register this argument with the commandline system.
316 /// Unregisters this option from the CommandLine system.
318 /// This option must have been the last option registered.
319 /// For testing purposes only.
320 void removeArgument();
322 // Return the width of the option tag for printing...
323 virtual size_t getOptionWidth() const = 0;
325 // printOptionInfo - Print out information about this option. The
326 // to-be-maintained width is specified.
328 virtual void printOptionInfo(size_t GlobalWidth) const = 0;
330 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
332 virtual void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
334 // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
336 virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
337 bool MultiArg = false);
339 // Prints option name followed by message. Always returns true.
340 bool error(const Twine &Message, StringRef ArgName = StringRef());
343 inline int getNumOccurrences() const { return NumOccurrences; }
344 inline void reset() { NumOccurrences = 0; }
348 //===----------------------------------------------------------------------===//
349 // Command line option modifiers that can be used to modify the behavior of
350 // command line option parsers...
353 // desc - Modifier to set the description shown in the -help output...
356 desc(const char *Str) : Desc(Str) {}
357 void apply(Option &O) const { O.setDescription(Desc); }
360 // value_desc - Modifier to set the value description shown in the -help
364 value_desc(const char *Str) : Desc(Str) {}
365 void apply(Option &O) const { O.setValueStr(Desc); }
368 // init - Specify a default (initial) value for the command line argument, if
369 // the default constructor for the argument type does not give you what you
370 // want. This is only valid on "opt" arguments, not on "list" arguments.
372 template <class Ty> struct initializer {
374 initializer(const Ty &Val) : Init(Val) {}
376 template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
379 template <class Ty> initializer<Ty> init(const Ty &Val) {
380 return initializer<Ty>(Val);
383 // location - Allow the user to specify which external variable they want to
384 // store the results of the command line argument processing into, if they don't
385 // want to store it in the option itself.
387 template <class Ty> struct LocationClass {
389 LocationClass(Ty &L) : Loc(L) {}
391 template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
394 template <class Ty> LocationClass<Ty> location(Ty &L) {
395 return LocationClass<Ty>(L);
398 // cat - Specifiy the Option category for the command line argument to belong
401 OptionCategory &Category;
402 cat(OptionCategory &c) : Category(c) {}
404 template <class Opt> void apply(Opt &O) const { O.setCategory(Category); }
407 // sub - Specify the subcommand that this option belongs to.
410 sub(SubCommand &S) : Sub(S) {}
412 template <class Opt> void apply(Opt &O) const { O.addSubCommand(Sub); }
415 //===----------------------------------------------------------------------===//
418 // Support value comparison outside the template.
419 struct GenericOptionValue {
420 virtual bool compare(const GenericOptionValue &V) const = 0;
423 ~GenericOptionValue() = default;
424 GenericOptionValue() = default;
425 GenericOptionValue(const GenericOptionValue&) = default;
426 GenericOptionValue &operator=(const GenericOptionValue &) = default;
429 virtual void anchor();
432 template <class DataType> struct OptionValue;
434 // The default value safely does nothing. Option value printing is only
436 template <class DataType, bool isClass>
437 struct OptionValueBase : public GenericOptionValue {
438 // Temporary storage for argument passing.
439 typedef OptionValue<DataType> WrapperType;
441 bool hasValue() const { return false; }
443 const DataType &getValue() const { llvm_unreachable("no default value"); }
445 // Some options may take their value from a different data type.
446 template <class DT> void setValue(const DT & /*V*/) {}
448 bool compare(const DataType & /*V*/) const { return false; }
450 bool compare(const GenericOptionValue & /*V*/) const override {
455 ~OptionValueBase() = default;
458 // Simple copy of the option value.
459 template <class DataType> class OptionValueCopy : public GenericOptionValue {
464 ~OptionValueCopy() = default;
465 OptionValueCopy(const OptionValueCopy&) = default;
466 OptionValueCopy &operator=(const OptionValueCopy&) = default;
469 OptionValueCopy() : Valid(false) {}
471 bool hasValue() const { return Valid; }
473 const DataType &getValue() const {
474 assert(Valid && "invalid option value");
478 void setValue(const DataType &V) {
483 bool compare(const DataType &V) const { return Valid && (Value != V); }
485 bool compare(const GenericOptionValue &V) const override {
486 const OptionValueCopy<DataType> &VC =
487 static_cast<const OptionValueCopy<DataType> &>(V);
490 return compare(VC.getValue());
494 // Non-class option values.
495 template <class DataType>
496 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
497 typedef DataType WrapperType;
500 ~OptionValueBase() = default;
501 OptionValueBase() = default;
502 OptionValueBase(const OptionValueBase&) = default;
503 OptionValueBase &operator=(const OptionValueBase&) = default;
506 // Top-level option class.
507 template <class DataType>
508 struct OptionValue final
509 : OptionValueBase<DataType, std::is_class<DataType>::value> {
510 OptionValue() = default;
512 OptionValue(const DataType &V) { this->setValue(V); }
513 // Some options may take their value from a different data type.
514 template <class DT> OptionValue<DataType> &operator=(const DT &V) {
520 // Other safe-to-copy-by-value common option types.
521 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
523 struct OptionValue<cl::boolOrDefault> final
524 : OptionValueCopy<cl::boolOrDefault> {
525 typedef cl::boolOrDefault WrapperType;
529 OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
530 OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
536 void anchor() override;
540 struct OptionValue<std::string> final : OptionValueCopy<std::string> {
541 typedef StringRef WrapperType;
545 OptionValue(const std::string &V) { this->setValue(V); }
546 OptionValue<std::string> &operator=(const std::string &V) {
552 void anchor() override;
555 //===----------------------------------------------------------------------===//
556 // Enum valued command line option
558 #define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
559 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
560 #define clEnumValEnd (reinterpret_cast<void *>(0))
562 // values - For custom data types, allow specifying a group of values together
563 // as the values that go into the mapping that the option handler uses. Note
564 // that the values list must always have a 0 at the end of the list to indicate
565 // that the list has ended.
567 template <class DataType> class ValuesClass {
568 // Use a vector instead of a map, because the lists should be short,
569 // the overhead is less, and most importantly, it keeps them in the order
570 // inserted so we can print our option out nicely.
571 SmallVector<std::pair<const char *, std::pair<int, const char *>>, 4> Values;
572 void processValues(va_list Vals);
575 ValuesClass(const char *EnumName, DataType Val, const char *Desc,
577 // Insert the first value, which is required.
578 Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
580 // Process the varargs portion of the values...
581 while (const char *enumName = va_arg(ValueArgs, const char *)) {
582 DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
583 const char *EnumDesc = va_arg(ValueArgs, const char *);
584 Values.push_back(std::make_pair(enumName, // Add value to value map
585 std::make_pair(EnumVal, EnumDesc)));
589 template <class Opt> void apply(Opt &O) const {
590 for (size_t i = 0, e = Values.size(); i != e; ++i)
591 O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
592 Values[i].second.second);
596 template <class DataType>
597 ValuesClass<DataType> LLVM_END_WITH_NULL
598 values(const char *Arg, DataType Val, const char *Desc, ...) {
600 va_start(ValueArgs, Desc);
601 ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
606 //===----------------------------------------------------------------------===//
607 // parser class - Parameterizable parser for different data types. By default,
608 // known data types (string, int, bool) have specialized parsers, that do what
609 // you would expect. The default parser, used for data types that are not
610 // built-in, uses a mapping table to map specific options to values, which is
611 // used, among other things, to handle enum types.
613 //--------------------------------------------------
614 // generic_parser_base - This class holds all the non-generic code that we do
615 // not need replicated for every instance of the generic parser. This also
616 // allows us to put stuff into CommandLine.cpp
618 class generic_parser_base {
620 class GenericOptionInfo {
622 GenericOptionInfo(const char *name, const char *helpStr)
623 : Name(name), HelpStr(helpStr) {}
629 generic_parser_base(Option &O) : Owner(O) {}
631 virtual ~generic_parser_base() {} // Base class should have virtual-dtor
633 // getNumOptions - Virtual function implemented by generic subclass to
634 // indicate how many entries are in Values.
636 virtual unsigned getNumOptions() const = 0;
638 // getOption - Return option name N.
639 virtual const char *getOption(unsigned N) const = 0;
641 // getDescription - Return description N
642 virtual const char *getDescription(unsigned N) const = 0;
644 // Return the width of the option tag for printing...
645 virtual size_t getOptionWidth(const Option &O) const;
647 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
649 // printOptionInfo - Print out information about this option. The
650 // to-be-maintained width is specified.
652 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
654 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
655 const GenericOptionValue &Default,
656 size_t GlobalWidth) const;
658 // printOptionDiff - print the value of an option and it's default.
660 // Template definition ensures that the option and default have the same
661 // DataType (via the same AnyOptionValue).
662 template <class AnyOptionValue>
663 void printOptionDiff(const Option &O, const AnyOptionValue &V,
664 const AnyOptionValue &Default,
665 size_t GlobalWidth) const {
666 printGenericOptionDiff(O, V, Default, GlobalWidth);
671 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) {
672 // If there has been no argstr specified, that means that we need to add an
673 // argument for every possible option. This ensures that our options are
675 if (!Owner.hasArgStr())
676 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
677 OptionNames.push_back(getOption(i));
680 enum ValueExpected getValueExpectedFlagDefault() const {
681 // If there is an ArgStr specified, then we are of the form:
683 // -opt=O2 or -opt O2 or -optO2
685 // In which case, the value is required. Otherwise if an arg str has not
686 // been specified, we are of the form:
688 // -O2 or O2 or -la (where -l and -a are separate options)
690 // If this is the case, we cannot allow a value.
692 if (Owner.hasArgStr())
693 return ValueRequired;
695 return ValueDisallowed;
698 // findOption - Return the option number corresponding to the specified
699 // argument string. If the option is not found, getNumOptions() is returned.
701 unsigned findOption(const char *Name);
707 // Default parser implementation - This implementation depends on having a
708 // mapping of recognized options to values of some sort. In addition to this,
709 // each entry in the mapping also tracks a help message that is printed with the
710 // command line option for -help. Because this is a simple mapping parser, the
711 // data type can be any unsupported type.
713 template <class DataType> class parser : public generic_parser_base {
715 class OptionInfo : public GenericOptionInfo {
717 OptionInfo(const char *name, DataType v, const char *helpStr)
718 : GenericOptionInfo(name, helpStr), V(v) {}
719 OptionValue<DataType> V;
721 SmallVector<OptionInfo, 8> Values;
724 parser(Option &O) : generic_parser_base(O) {}
725 typedef DataType parser_data_type;
727 // Implement virtual functions needed by generic_parser_base
728 unsigned getNumOptions() const override { return unsigned(Values.size()); }
729 const char *getOption(unsigned N) const override { return Values[N].Name; }
730 const char *getDescription(unsigned N) const override {
731 return Values[N].HelpStr;
734 // getOptionValue - Return the value of option name N.
735 const GenericOptionValue &getOptionValue(unsigned N) const override {
739 // parse - Return true on error.
740 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
742 if (Owner.hasArgStr())
747 for (size_t i = 0, e = Values.size(); i != e; ++i)
748 if (Values[i].Name == ArgVal) {
749 V = Values[i].V.getValue();
753 return O.error("Cannot find option named '" + ArgVal + "'!");
756 /// addLiteralOption - Add an entry to the mapping table.
759 void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
760 assert(findOption(Name) == Values.size() && "Option already exists!");
761 OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
763 AddLiteralOption(Owner, Name);
766 /// removeLiteralOption - Remove the specified option.
768 void removeLiteralOption(const char *Name) {
769 unsigned N = findOption(Name);
770 assert(N != Values.size() && "Option not found!");
771 Values.erase(Values.begin() + N);
775 //--------------------------------------------------
776 // basic_parser - Super class of parsers to provide boilerplate code
778 class basic_parser_impl { // non-template implementation of basic_parser<t>
780 basic_parser_impl(Option &) {}
783 enum ValueExpected getValueExpectedFlagDefault() const {
784 return ValueRequired;
787 void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
791 // Return the width of the option tag for printing...
792 size_t getOptionWidth(const Option &O) const;
794 // printOptionInfo - Print out information about this option. The
795 // to-be-maintained width is specified.
797 void printOptionInfo(const Option &O, size_t GlobalWidth) const;
799 // printOptionNoValue - Print a placeholder for options that don't yet support
800 // printOptionDiff().
801 void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
803 // getValueName - Overload in subclass to provide a better default value.
804 virtual const char *getValueName() const { return "value"; }
806 // An out-of-line virtual method to provide a 'home' for this class.
807 virtual void anchor();
810 ~basic_parser_impl() = default;
811 // A helper for basic_parser::printOptionDiff.
812 void printOptionName(const Option &O, size_t GlobalWidth) const;
815 // basic_parser - The real basic parser is just a template wrapper that provides
816 // a typedef for the provided data type.
818 template <class DataType> class basic_parser : public basic_parser_impl {
820 basic_parser(Option &O) : basic_parser_impl(O) {}
821 typedef DataType parser_data_type;
822 typedef OptionValue<DataType> OptVal;
825 // Workaround Clang PR22793
829 //--------------------------------------------------
832 template <> class parser<bool> final : public basic_parser<bool> {
834 parser(Option &O) : basic_parser(O) {}
836 // parse - Return true on error.
837 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
841 enum ValueExpected getValueExpectedFlagDefault() const {
842 return ValueOptional;
845 // getValueName - Do not print =<value> at all.
846 const char *getValueName() const override { return nullptr; }
848 void printOptionDiff(const Option &O, bool V, OptVal Default,
849 size_t GlobalWidth) const;
851 // An out-of-line virtual method to provide a 'home' for this class.
852 void anchor() override;
855 extern template class basic_parser<bool>;
857 //--------------------------------------------------
858 // parser<boolOrDefault>
860 class parser<boolOrDefault> final : public basic_parser<boolOrDefault> {
862 parser(Option &O) : basic_parser(O) {}
864 // parse - Return true on error.
865 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
867 enum ValueExpected getValueExpectedFlagDefault() const {
868 return ValueOptional;
871 // getValueName - Do not print =<value> at all.
872 const char *getValueName() const override { return nullptr; }
874 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
875 size_t GlobalWidth) const;
877 // An out-of-line virtual method to provide a 'home' for this class.
878 void anchor() override;
881 extern template class basic_parser<boolOrDefault>;
883 //--------------------------------------------------
886 template <> class parser<int> final : public basic_parser<int> {
888 parser(Option &O) : basic_parser(O) {}
890 // parse - Return true on error.
891 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
893 // getValueName - Overload in subclass to provide a better default value.
894 const char *getValueName() const override { return "int"; }
896 void printOptionDiff(const Option &O, int V, OptVal Default,
897 size_t GlobalWidth) const;
899 // An out-of-line virtual method to provide a 'home' for this class.
900 void anchor() override;
903 extern template class basic_parser<int>;
905 //--------------------------------------------------
908 template <> class parser<unsigned> final : public basic_parser<unsigned> {
910 parser(Option &O) : basic_parser(O) {}
912 // parse - Return true on error.
913 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
915 // getValueName - Overload in subclass to provide a better default value.
916 const char *getValueName() const override { return "uint"; }
918 void printOptionDiff(const Option &O, unsigned V, OptVal Default,
919 size_t GlobalWidth) const;
921 // An out-of-line virtual method to provide a 'home' for this class.
922 void anchor() override;
925 extern template class basic_parser<unsigned>;
927 //--------------------------------------------------
928 // parser<unsigned long long>
931 class parser<unsigned long long> final
932 : public basic_parser<unsigned long long> {
934 parser(Option &O) : basic_parser(O) {}
936 // parse - Return true on error.
937 bool parse(Option &O, StringRef ArgName, StringRef Arg,
938 unsigned long long &Val);
940 // getValueName - Overload in subclass to provide a better default value.
941 const char *getValueName() const override { return "uint"; }
943 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
944 size_t GlobalWidth) const;
946 // An out-of-line virtual method to provide a 'home' for this class.
947 void anchor() override;
950 extern template class basic_parser<unsigned long long>;
952 //--------------------------------------------------
955 template <> class parser<double> final : public basic_parser<double> {
957 parser(Option &O) : basic_parser(O) {}
959 // parse - Return true on error.
960 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
962 // getValueName - Overload in subclass to provide a better default value.
963 const char *getValueName() const override { return "number"; }
965 void printOptionDiff(const Option &O, double V, OptVal Default,
966 size_t GlobalWidth) const;
968 // An out-of-line virtual method to provide a 'home' for this class.
969 void anchor() override;
972 extern template class basic_parser<double>;
974 //--------------------------------------------------
977 template <> class parser<float> final : public basic_parser<float> {
979 parser(Option &O) : basic_parser(O) {}
981 // parse - Return true on error.
982 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
984 // getValueName - Overload in subclass to provide a better default value.
985 const char *getValueName() const override { return "number"; }
987 void printOptionDiff(const Option &O, float V, OptVal Default,
988 size_t GlobalWidth) const;
990 // An out-of-line virtual method to provide a 'home' for this class.
991 void anchor() override;
994 extern template class basic_parser<float>;
996 //--------------------------------------------------
997 // parser<std::string>
999 template <> class parser<std::string> final : public basic_parser<std::string> {
1001 parser(Option &O) : basic_parser(O) {}
1003 // parse - Return true on error.
1004 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
1009 // getValueName - Overload in subclass to provide a better default value.
1010 const char *getValueName() const override { return "string"; }
1012 void printOptionDiff(const Option &O, StringRef V, const OptVal &Default,
1013 size_t GlobalWidth) const;
1015 // An out-of-line virtual method to provide a 'home' for this class.
1016 void anchor() override;
1019 extern template class basic_parser<std::string>;
1021 //--------------------------------------------------
1024 template <> class parser<char> final : public basic_parser<char> {
1026 parser(Option &O) : basic_parser(O) {}
1028 // parse - Return true on error.
1029 bool parse(Option &, StringRef, StringRef Arg, char &Value) {
1034 // getValueName - Overload in subclass to provide a better default value.
1035 const char *getValueName() const override { return "char"; }
1037 void printOptionDiff(const Option &O, char V, OptVal Default,
1038 size_t GlobalWidth) const;
1040 // An out-of-line virtual method to provide a 'home' for this class.
1041 void anchor() override;
1044 extern template class basic_parser<char>;
1046 //--------------------------------------------------
1049 // This collection of wrappers is the intermediary between class opt and class
1050 // parser to handle all the template nastiness.
1052 // This overloaded function is selected by the generic parser.
1053 template <class ParserClass, class DT>
1054 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
1055 const OptionValue<DT> &Default, size_t GlobalWidth) {
1056 OptionValue<DT> OV = V;
1057 P.printOptionDiff(O, OV, Default, GlobalWidth);
1060 // This is instantiated for basic parsers when the parsed value has a different
1061 // type than the option value. e.g. HelpPrinter.
1062 template <class ParserDT, class ValDT> struct OptionDiffPrinter {
1063 void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/,
1064 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
1065 P.printOptionNoValue(O, GlobalWidth);
1069 // This is instantiated for basic parsers when the parsed value has the same
1070 // type as the option value.
1071 template <class DT> struct OptionDiffPrinter<DT, DT> {
1072 void print(const Option &O, const parser<DT> &P, const DT &V,
1073 const OptionValue<DT> &Default, size_t GlobalWidth) {
1074 P.printOptionDiff(O, V, Default, GlobalWidth);
1078 // This overloaded function is selected by the basic parser, which may parse a
1079 // different type than the option type.
1080 template <class ParserClass, class ValDT>
1081 void printOptionDiff(
1083 const basic_parser<typename ParserClass::parser_data_type> &P,
1084 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
1086 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
1087 printer.print(O, static_cast<const ParserClass &>(P), V, Default,
1091 //===----------------------------------------------------------------------===//
1092 // applicator class - This class is used because we must use partial
1093 // specialization to handle literal string arguments specially (const char* does
1094 // not correctly respond to the apply method). Because the syntax to use this
1095 // is a pain, we have the 'apply' method below to handle the nastiness...
1097 template <class Mod> struct applicator {
1098 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1101 // Handle const char* as a special case...
1102 template <unsigned n> struct applicator<char[n]> {
1103 template <class Opt> static void opt(const char *Str, Opt &O) {
1107 template <unsigned n> struct applicator<const char[n]> {
1108 template <class Opt> static void opt(const char *Str, Opt &O) {
1112 template <> struct applicator<const char *> {
1113 template <class Opt> static void opt(const char *Str, Opt &O) {
1118 template <> struct applicator<NumOccurrencesFlag> {
1119 static void opt(NumOccurrencesFlag N, Option &O) {
1120 O.setNumOccurrencesFlag(N);
1123 template <> struct applicator<ValueExpected> {
1124 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1126 template <> struct applicator<OptionHidden> {
1127 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1129 template <> struct applicator<FormattingFlags> {
1130 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1132 template <> struct applicator<MiscFlags> {
1133 static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1136 // apply method - Apply modifiers to an option in a type safe way.
1137 template <class Opt, class Mod, class... Mods>
1138 void apply(Opt *O, const Mod &M, const Mods &... Ms) {
1139 applicator<Mod>::opt(M, *O);
1143 template <class Opt, class Mod> void apply(Opt *O, const Mod &M) {
1144 applicator<Mod>::opt(M, *O);
1147 //===----------------------------------------------------------------------===//
1148 // opt_storage class
1150 // Default storage class definition: external storage. This implementation
1151 // assumes the user will specify a variable to store the data into with the
1152 // cl::location(x) modifier.
1154 template <class DataType, bool ExternalStorage, bool isClass>
1156 DataType *Location; // Where to store the object...
1157 OptionValue<DataType> Default;
1159 void check_location() const {
1160 assert(Location && "cl::location(...) not specified for a command "
1161 "line option with external storage, "
1162 "or cl::init specified before cl::location()!!");
1166 opt_storage() : Location(nullptr) {}
1168 bool setLocation(Option &O, DataType &L) {
1170 return O.error("cl::location(x) specified more than once!");
1176 template <class T> void setValue(const T &V, bool initial = false) {
1183 DataType &getValue() {
1187 const DataType &getValue() const {
1192 operator DataType() const { return this->getValue(); }
1194 const OptionValue<DataType> &getDefault() const { return Default; }
1197 // Define how to hold a class type object, such as a string. Since we can
1198 // inherit from a class, we do so. This makes us exactly compatible with the
1199 // object in all cases that it is used.
1201 template <class DataType>
1202 class opt_storage<DataType, false, true> : public DataType {
1204 OptionValue<DataType> Default;
1206 template <class T> void setValue(const T &V, bool initial = false) {
1207 DataType::operator=(V);
1212 DataType &getValue() { return *this; }
1213 const DataType &getValue() const { return *this; }
1215 const OptionValue<DataType> &getDefault() const { return Default; }
1218 // Define a partial specialization to handle things we cannot inherit from. In
1219 // this case, we store an instance through containment, and overload operators
1220 // to get at the value.
1222 template <class DataType> class opt_storage<DataType, false, false> {
1225 OptionValue<DataType> Default;
1227 // Make sure we initialize the value with the default constructor for the
1229 opt_storage() : Value(DataType()), Default(DataType()) {}
1231 template <class T> void setValue(const T &V, bool initial = false) {
1236 DataType &getValue() { return Value; }
1237 DataType getValue() const { return Value; }
1239 const OptionValue<DataType> &getDefault() const { return Default; }
1241 operator DataType() const { return getValue(); }
1243 // If the datatype is a pointer, support -> on it.
1244 DataType operator->() const { return Value; }
1247 //===----------------------------------------------------------------------===//
1248 // opt - A scalar command line option.
1250 template <class DataType, bool ExternalStorage = false,
1251 class ParserClass = parser<DataType>>
1252 class opt : public Option,
1253 public opt_storage<DataType, ExternalStorage,
1254 std::is_class<DataType>::value> {
1257 bool handleOccurrence(unsigned pos, StringRef ArgName,
1258 StringRef Arg) override {
1259 typename ParserClass::parser_data_type Val =
1260 typename ParserClass::parser_data_type();
1261 if (Parser.parse(*this, ArgName, Arg, Val))
1262 return true; // Parse error!
1263 this->setValue(Val);
1264 this->setPosition(pos);
1268 enum ValueExpected getValueExpectedFlagDefault() const override {
1269 return Parser.getValueExpectedFlagDefault();
1271 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1272 return Parser.getExtraOptionNames(OptionNames);
1275 // Forward printing stuff to the parser...
1276 size_t getOptionWidth() const override {
1277 return Parser.getOptionWidth(*this);
1279 void printOptionInfo(size_t GlobalWidth) const override {
1280 Parser.printOptionInfo(*this, GlobalWidth);
1283 void printOptionValue(size_t GlobalWidth, bool Force) const override {
1284 if (Force || this->getDefault().compare(this->getValue())) {
1285 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1286 this->getDefault(), GlobalWidth);
1292 Parser.initialize();
1295 // Command line options should not be copyable
1296 opt(const opt &) = delete;
1297 opt &operator=(const opt &) = delete;
1300 // setInitialValue - Used by the cl::init modifier...
1301 void setInitialValue(const DataType &V) { this->setValue(V, true); }
1303 ParserClass &getParser() { return Parser; }
1305 template <class T> DataType &operator=(const T &Val) {
1306 this->setValue(Val);
1307 return this->getValue();
1310 template <class... Mods>
1311 explicit opt(const Mods &... Ms)
1312 : Option(Optional, NotHidden), Parser(*this) {
1318 extern template class opt<unsigned>;
1319 extern template class opt<int>;
1320 extern template class opt<std::string>;
1321 extern template class opt<char>;
1322 extern template class opt<bool>;
1324 //===----------------------------------------------------------------------===//
1325 // list_storage class
1327 // Default storage class definition: external storage. This implementation
1328 // assumes the user will specify a variable to store the data into with the
1329 // cl::location(x) modifier.
1331 template <class DataType, class StorageClass> class list_storage {
1332 StorageClass *Location; // Where to store the object...
1335 list_storage() : Location(0) {}
1337 bool setLocation(Option &O, StorageClass &L) {
1339 return O.error("cl::location(x) specified more than once!");
1344 template <class T> void addValue(const T &V) {
1345 assert(Location != 0 && "cl::location(...) not specified for a command "
1346 "line option with external storage!");
1347 Location->push_back(V);
1351 // Define how to hold a class type object, such as a string.
1352 // Originally this code inherited from std::vector. In transitioning to a new
1353 // API for command line options we should change this. The new implementation
1354 // of this list_storage specialization implements the minimum subset of the
1355 // std::vector API required for all the current clients.
1357 // FIXME: Reduce this API to a more narrow subset of std::vector
1359 template <class DataType> class list_storage<DataType, bool> {
1360 std::vector<DataType> Storage;
1363 typedef typename std::vector<DataType>::iterator iterator;
1365 iterator begin() { return Storage.begin(); }
1366 iterator end() { return Storage.end(); }
1368 typedef typename std::vector<DataType>::const_iterator const_iterator;
1369 const_iterator begin() const { return Storage.begin(); }
1370 const_iterator end() const { return Storage.end(); }
1372 typedef typename std::vector<DataType>::size_type size_type;
1373 size_type size() const { return Storage.size(); }
1375 bool empty() const { return Storage.empty(); }
1377 void push_back(const DataType &value) { Storage.push_back(value); }
1378 void push_back(DataType &&value) { Storage.push_back(value); }
1380 typedef typename std::vector<DataType>::reference reference;
1381 typedef typename std::vector<DataType>::const_reference const_reference;
1382 reference operator[](size_type pos) { return Storage[pos]; }
1383 const_reference operator[](size_type pos) const { return Storage[pos]; }
1385 iterator erase(const_iterator pos) { return Storage.erase(pos); }
1386 iterator erase(const_iterator first, const_iterator last) {
1387 return Storage.erase(first, last);
1390 iterator erase(iterator pos) { return Storage.erase(pos); }
1391 iterator erase(iterator first, iterator last) {
1392 return Storage.erase(first, last);
1395 iterator insert(const_iterator pos, const DataType &value) {
1396 return Storage.insert(pos, value);
1398 iterator insert(const_iterator pos, DataType &&value) {
1399 return Storage.insert(pos, value);
1402 iterator insert(iterator pos, const DataType &value) {
1403 return Storage.insert(pos, value);
1405 iterator insert(iterator pos, DataType &&value) {
1406 return Storage.insert(pos, value);
1409 reference front() { return Storage.front(); }
1410 const_reference front() const { return Storage.front(); }
1412 operator std::vector<DataType>&() { return Storage; }
1413 operator ArrayRef<DataType>() { return Storage; }
1414 std::vector<DataType> *operator&() { return &Storage; }
1415 const std::vector<DataType> *operator&() const { return &Storage; }
1417 template <class T> void addValue(const T &V) { Storage.push_back(V); }
1420 //===----------------------------------------------------------------------===//
1421 // list - A list of command line options.
1423 template <class DataType, class StorageClass = bool,
1424 class ParserClass = parser<DataType>>
1425 class list : public Option, public list_storage<DataType, StorageClass> {
1426 std::vector<unsigned> Positions;
1429 enum ValueExpected getValueExpectedFlagDefault() const override {
1430 return Parser.getValueExpectedFlagDefault();
1432 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1433 return Parser.getExtraOptionNames(OptionNames);
1436 bool handleOccurrence(unsigned pos, StringRef ArgName,
1437 StringRef Arg) override {
1438 typename ParserClass::parser_data_type Val =
1439 typename ParserClass::parser_data_type();
1440 if (Parser.parse(*this, ArgName, Arg, Val))
1441 return true; // Parse Error!
1442 list_storage<DataType, StorageClass>::addValue(Val);
1444 Positions.push_back(pos);
1448 // Forward printing stuff to the parser...
1449 size_t getOptionWidth() const override {
1450 return Parser.getOptionWidth(*this);
1452 void printOptionInfo(size_t GlobalWidth) const override {
1453 Parser.printOptionInfo(*this, GlobalWidth);
1456 // Unimplemented: list options don't currently store their default value.
1457 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1462 Parser.initialize();
1465 // Command line options should not be copyable
1466 list(const list &) = delete;
1467 list &operator=(const list &) = delete;
1470 ParserClass &getParser() { return Parser; }
1472 unsigned getPosition(unsigned optnum) const {
1473 assert(optnum < this->size() && "Invalid option index");
1474 return Positions[optnum];
1477 void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
1479 template <class... Mods>
1480 explicit list(const Mods &... Ms)
1481 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1487 // multi_val - Modifier to set the number of additional values.
1489 unsigned AdditionalVals;
1490 explicit multi_val(unsigned N) : AdditionalVals(N) {}
1492 template <typename D, typename S, typename P>
1493 void apply(list<D, S, P> &L) const {
1494 L.setNumAdditionalVals(AdditionalVals);
1498 //===----------------------------------------------------------------------===//
1499 // bits_storage class
1501 // Default storage class definition: external storage. This implementation
1502 // assumes the user will specify a variable to store the data into with the
1503 // cl::location(x) modifier.
1505 template <class DataType, class StorageClass> class bits_storage {
1506 unsigned *Location; // Where to store the bits...
1508 template <class T> static unsigned Bit(const T &V) {
1509 unsigned BitPos = reinterpret_cast<unsigned>(V);
1510 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1511 "enum exceeds width of bit vector!");
1516 bits_storage() : Location(nullptr) {}
1518 bool setLocation(Option &O, unsigned &L) {
1520 return O.error("cl::location(x) specified more than once!");
1525 template <class T> void addValue(const T &V) {
1526 assert(Location != 0 && "cl::location(...) not specified for a command "
1527 "line option with external storage!");
1528 *Location |= Bit(V);
1531 unsigned getBits() { return *Location; }
1533 template <class T> bool isSet(const T &V) {
1534 return (*Location & Bit(V)) != 0;
1538 // Define how to hold bits. Since we can inherit from a class, we do so.
1539 // This makes us exactly compatible with the bits in all cases that it is used.
1541 template <class DataType> class bits_storage<DataType, bool> {
1542 unsigned Bits; // Where to store the bits...
1544 template <class T> static unsigned Bit(const T &V) {
1545 unsigned BitPos = (unsigned)V;
1546 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1547 "enum exceeds width of bit vector!");
1552 template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1554 unsigned getBits() { return Bits; }
1556 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1559 //===----------------------------------------------------------------------===//
1560 // bits - A bit vector of command options.
1562 template <class DataType, class Storage = bool,
1563 class ParserClass = parser<DataType>>
1564 class bits : public Option, public bits_storage<DataType, Storage> {
1565 std::vector<unsigned> Positions;
1568 enum ValueExpected getValueExpectedFlagDefault() const override {
1569 return Parser.getValueExpectedFlagDefault();
1571 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1572 return Parser.getExtraOptionNames(OptionNames);
1575 bool handleOccurrence(unsigned pos, StringRef ArgName,
1576 StringRef Arg) override {
1577 typename ParserClass::parser_data_type Val =
1578 typename ParserClass::parser_data_type();
1579 if (Parser.parse(*this, ArgName, Arg, Val))
1580 return true; // Parse Error!
1581 this->addValue(Val);
1583 Positions.push_back(pos);
1587 // Forward printing stuff to the parser...
1588 size_t getOptionWidth() const override {
1589 return Parser.getOptionWidth(*this);
1591 void printOptionInfo(size_t GlobalWidth) const override {
1592 Parser.printOptionInfo(*this, GlobalWidth);
1595 // Unimplemented: bits options don't currently store their default values.
1596 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1601 Parser.initialize();
1604 // Command line options should not be copyable
1605 bits(const bits &) = delete;
1606 bits &operator=(const bits &) = delete;
1609 ParserClass &getParser() { return Parser; }
1611 unsigned getPosition(unsigned optnum) const {
1612 assert(optnum < this->size() && "Invalid option index");
1613 return Positions[optnum];
1616 template <class... Mods>
1617 explicit bits(const Mods &... Ms)
1618 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1624 //===----------------------------------------------------------------------===//
1625 // Aliased command line option (alias this name to a preexisting name)
1628 class alias : public Option {
1630 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1631 StringRef Arg) override {
1632 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1634 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1635 bool MultiArg = false) override {
1636 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1638 // Handle printing stuff...
1639 size_t getOptionWidth() const override;
1640 void printOptionInfo(size_t GlobalWidth) const override;
1642 // Aliases do not need to print their values.
1643 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1646 ValueExpected getValueExpectedFlagDefault() const override {
1647 return AliasFor->getValueExpectedFlag();
1652 error("cl::alias must have argument name specified!");
1654 error("cl::alias must have an cl::aliasopt(option) specified!");
1655 Subs = AliasFor->Subs;
1659 // Command line options should not be copyable
1660 alias(const alias &) = delete;
1661 alias &operator=(const alias &) = delete;
1664 void setAliasFor(Option &O) {
1666 error("cl::alias must only have one cl::aliasopt(...) specified!");
1670 template <class... Mods>
1671 explicit alias(const Mods &... Ms)
1672 : Option(Optional, Hidden), AliasFor(nullptr) {
1678 // aliasfor - Modifier to set the option an alias aliases.
1681 explicit aliasopt(Option &O) : Opt(O) {}
1682 void apply(alias &A) const { A.setAliasFor(Opt); }
1685 // extrahelp - provide additional help at the end of the normal help
1686 // output. All occurrences of cl::extrahelp will be accumulated and
1687 // printed to stderr at the end of the regular help, just before
1690 const char *morehelp;
1691 explicit extrahelp(const char *help);
1694 void PrintVersionMessage();
1696 /// This function just prints the help message, exactly the same way as if the
1697 /// -help or -help-hidden option had been given on the command line.
1699 /// NOTE: THIS FUNCTION TERMINATES THE PROGRAM!
1701 /// \param Hidden if true will print hidden options
1702 /// \param Categorized if true print options in categories
1703 void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
1705 //===----------------------------------------------------------------------===//
1706 // Public interface for accessing registered options.
1709 /// \brief Use this to get a StringMap to all registered named options
1710 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1712 /// \return A reference to the StringMap used by the cl APIs to parse options.
1714 /// Access to unnamed arguments (i.e. positional) are not provided because
1715 /// it is expected that the client already has access to these.
1719 /// main(int argc,char* argv[]) {
1720 /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions();
1721 /// assert(opts.count("help") == 1)
1722 /// opts["help"]->setDescription("Show alphabetical help information")
1724 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1729 /// This interface is useful for modifying options in libraries that are out of
1730 /// the control of the client. The options should be modified before calling
1731 /// llvm::cl::ParseCommandLineOptions().
1733 /// Hopefully this API can be depricated soon. Any situation where options need
1734 /// to be modified by tools or libraries should be handled by sane APIs rather
1735 /// than just handing around a global list.
1736 StringMap<Option *> &getRegisteredOptions(SubCommand &Sub = *TopLevelSubCommand);
1738 //===----------------------------------------------------------------------===//
1739 // Standalone command line processing utilities.
1742 /// \brief Tokenizes a command line that can contain escapes and quotes.
1744 /// The quoting rules match those used by GCC and other tools that use
1745 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1746 /// They differ from buildargv() on treatment of backslashes that do not escape
1747 /// a special character to make it possible to accept most Windows file paths.
1749 /// \param [in] Source The string to be split on whitespace with quotes.
1750 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1751 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1752 /// lines and end of the response file to be marked with a nullptr string.
1753 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1754 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
1755 SmallVectorImpl<const char *> &NewArgv,
1756 bool MarkEOLs = false);
1758 /// \brief Tokenizes a Windows command line which may contain quotes and escaped
1761 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1762 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1764 /// \param [in] Source The string to be split on whitespace with quotes.
1765 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1766 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1767 /// lines and end of the response file to be marked with a nullptr string.
1768 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1769 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
1770 SmallVectorImpl<const char *> &NewArgv,
1771 bool MarkEOLs = false);
1773 /// \brief String tokenization function type. Should be compatible with either
1774 /// Windows or Unix command line tokenizers.
1775 typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
1776 SmallVectorImpl<const char *> &NewArgv,
1779 /// \brief Expand response files on a command line recursively using the given
1780 /// StringSaver and tokenization strategy. Argv should contain the command line
1781 /// before expansion and will be modified in place. If requested, Argv will
1782 /// also be populated with nullptrs indicating where each response file line
1783 /// ends, which is useful for the "/link" argument that needs to consume all
1784 /// remaining arguments only until the next end of line, when in a response
1787 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1788 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1789 /// \param [in,out] Argv Command line into which to expand response files.
1790 /// \param [in] MarkEOLs Mark end of lines and the end of the response file
1791 /// with nullptrs in the Argv vector.
1792 /// \return true if all @files were expanded successfully or there were none.
1793 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1794 SmallVectorImpl<const char *> &Argv,
1795 bool MarkEOLs = false);
1797 /// \brief Mark all options not part of this category as cl::ReallyHidden.
1799 /// \param Category the category of options to keep displaying
1801 /// Some tools (like clang-format) like to be able to hide all options that are
1802 /// not specific to the tool. This function allows a tool to specify a single
1803 /// option category to display in the -help output.
1804 void HideUnrelatedOptions(cl::OptionCategory &Category,
1805 SubCommand &Sub = *TopLevelSubCommand);
1807 /// \brief Mark all options not part of the categories as cl::ReallyHidden.
1809 /// \param Categories the categories of options to keep displaying.
1811 /// Some tools (like clang-format) like to be able to hide all options that are
1812 /// not specific to the tool. This function allows a tool to specify a single
1813 /// option category to display in the -help output.
1814 void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
1815 SubCommand &Sub = *TopLevelSubCommand);
1817 /// \brief Reset all command line options to a state that looks as if they have
1818 /// never appeared on the command line. This is useful for being able to parse
1819 /// a command line multiple times (especially useful for writing tests).
1820 void ResetAllOptionOccurrences();
1822 /// \brief Reset the command line parser back to its initial state. This
1824 /// all options, categories, and subcommands and returns the parser to a state
1825 /// where no options are supported.
1826 void ResetCommandLineParser();
1828 } // End namespace cl
1830 } // End namespace llvm