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/SmallVector.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Support/Compiler.h"
36 class BumpPtrStringSaver;
39 /// cl Namespace - This namespace contains all of the command line option
40 /// processing machinery. It is intentionally a short name to make qualified
44 //===----------------------------------------------------------------------===//
45 // ParseCommandLineOptions - Command line option processing entry point.
47 void ParseCommandLineOptions(int argc, const char *const *argv,
48 const char *Overview = nullptr);
50 //===----------------------------------------------------------------------===//
51 // ParseEnvironmentOptions - Environment variable option processing alternate
54 void ParseEnvironmentOptions(const char *progName, const char *envvar,
55 const char *Overview = nullptr);
57 ///===---------------------------------------------------------------------===//
58 /// SetVersionPrinter - Override the default (LLVM specific) version printer
59 /// used to print out the version when --version is given
60 /// on the command line. This allows other systems using the
61 /// CommandLine utilities to print their own version string.
62 void SetVersionPrinter(void (*func)());
64 ///===---------------------------------------------------------------------===//
65 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
66 /// default one. This can be called multiple times,
67 /// and each time it adds a new function to the list
68 /// which will be called after the basic LLVM version
69 /// printing is complete. Each can then add additional
70 /// information specific to the tool.
71 void AddExtraVersionPrinter(void (*func)());
73 // PrintOptionValues - Print option values.
74 // With -print-options print the difference between option values and defaults.
75 // With -print-all-options print all option values.
76 // (Currently not perfect, but best-effort.)
77 void PrintOptionValues();
79 // Forward declaration - AddLiteralOption needs to be up here to make gcc happy.
82 /// \brief Adds a new option for parsing and provides the option it refers to.
84 /// \param O pointer to the option
85 /// \param Name the string name for the option to handle during parsing
87 /// Literal options are used by some parsers to register special option values.
88 /// This is how the PassNameParser registers pass names for opt.
89 void AddLiteralOption(Option &O, const char *Name);
91 //===----------------------------------------------------------------------===//
92 // Flags permitted to be passed to command line arguments
95 enum NumOccurrencesFlag { // Flags for the number of occurrences allowed
96 Optional = 0x00, // Zero or One occurrence
97 ZeroOrMore = 0x01, // Zero or more occurrences allowed
98 Required = 0x02, // One occurrence required
99 OneOrMore = 0x03, // One or more occurrences required
101 // ConsumeAfter - Indicates that this option is fed anything that follows the
102 // last positional argument required by the application (it is an error if
103 // there are zero positional arguments, and a ConsumeAfter option is used).
104 // Thus, for example, all arguments to LLI are processed until a filename is
105 // found. Once a filename is found, all of the succeeding arguments are
106 // passed, unprocessed, to the ConsumeAfter option.
111 enum ValueExpected { // Is a value required for the option?
112 // zero reserved for the unspecified value
113 ValueOptional = 0x01, // The value can appear... or not
114 ValueRequired = 0x02, // The value is required to appear!
115 ValueDisallowed = 0x03 // A value may not be specified (for flags)
118 enum OptionHidden { // Control whether -help shows this option
119 NotHidden = 0x00, // Option included in -help & -help-hidden
120 Hidden = 0x01, // -help doesn't, but -help-hidden does
121 ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg
124 // Formatting flags - This controls special features that the option might have
125 // that cause it to be parsed differently...
127 // Prefix - This option allows arguments that are otherwise unrecognized to be
128 // matched by options that are a prefix of the actual value. This is useful for
129 // cases like a linker, where options are typically of the form '-lfoo' or
130 // '-L../../include' where -l or -L are the actual flags. When prefix is
131 // enabled, and used, the value for the flag comes from the suffix of the
134 // Grouping - With this option enabled, multiple letter options are allowed to
135 // bunch together with only a single hyphen for the whole group. This allows
136 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
139 enum FormattingFlags {
140 NormalFormatting = 0x00, // Nothing special
141 Positional = 0x01, // Is a positional argument, no '-' required
142 Prefix = 0x02, // Can this option directly prefix its value?
143 Grouping = 0x03 // Can this option group with other options?
146 enum MiscFlags { // Miscellaneous flags to adjust argument
147 CommaSeparated = 0x01, // Should this cl::list split between commas?
148 PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args?
149 Sink = 0x04 // Should this cl::list eat all unknown options?
152 //===----------------------------------------------------------------------===//
153 // Option Category class
155 class OptionCategory {
157 const char *const Name;
158 const char *const Description;
159 void registerCategory();
162 OptionCategory(const char *const Name,
163 const char *const Description = nullptr)
164 : Name(Name), Description(Description) {
167 const char *getName() const { return Name; }
168 const char *getDescription() const { return Description; }
171 // The general Option Category (used as default category).
172 extern OptionCategory GeneralCategory;
174 //===----------------------------------------------------------------------===//
181 // handleOccurrences - Overriden by subclasses to handle the value passed into
182 // an argument. Should return true if there was an error processing the
183 // argument and the program should exit.
185 virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
188 virtual enum ValueExpected getValueExpectedFlagDefault() const {
189 return ValueOptional;
192 // Out of line virtual function to provide home for the class.
193 virtual void anchor();
195 int NumOccurrences; // The number of times specified
196 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
197 // problems with signed enums in bitfields.
198 unsigned Occurrences : 3; // enum NumOccurrencesFlag
199 // not using the enum type for 'Value' because zero is an implementation
200 // detail representing the non-value
202 unsigned HiddenFlag : 2; // enum OptionHidden
203 unsigned Formatting : 2; // enum FormattingFlags
205 unsigned Position; // Position of last occurrence of the option
206 unsigned AdditionalVals; // Greater than 0 for multi-valued option.
209 const char *ArgStr; // The argument string itself (ex: "help", "o")
210 const char *HelpStr; // The descriptive text message for -help
211 const char *ValueStr; // String describing what the value of this option is
212 OptionCategory *Category; // The Category this option belongs to
213 bool FullyInitialized; // Has addArguemnt been called?
215 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
216 return (enum NumOccurrencesFlag)Occurrences;
218 inline enum ValueExpected getValueExpectedFlag() const {
219 return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
221 inline enum OptionHidden getOptionHiddenFlag() const {
222 return (enum OptionHidden)HiddenFlag;
224 inline enum FormattingFlags getFormattingFlag() const {
225 return (enum FormattingFlags)Formatting;
227 inline unsigned getMiscFlags() const { return Misc; }
228 inline unsigned getPosition() const { return Position; }
229 inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
231 // hasArgStr - Return true if the argstr != ""
232 bool hasArgStr() const { return ArgStr[0] != 0; }
234 //-------------------------------------------------------------------------===
235 // Accessor functions set by OptionModifiers
237 void setArgStr(const char *S);
238 void setDescription(const char *S) { HelpStr = S; }
239 void setValueStr(const char *S) { ValueStr = S; }
240 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
241 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
242 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
243 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
244 void setMiscFlag(enum MiscFlags M) { Misc |= M; }
245 void setPosition(unsigned pos) { Position = pos; }
246 void setCategory(OptionCategory &C) { Category = &C; }
249 explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
250 enum OptionHidden Hidden)
251 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
252 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0),
253 AdditionalVals(0), ArgStr(""), HelpStr(""), ValueStr(""),
254 Category(&GeneralCategory), FullyInitialized(false) {}
256 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
259 // addArgument - Register this argument with the commandline system.
263 /// Unregisters this option from the CommandLine system.
265 /// This option must have been the last option registered.
266 /// For testing purposes only.
267 void removeArgument();
269 // Return the width of the option tag for printing...
270 virtual size_t getOptionWidth() const = 0;
272 // printOptionInfo - Print out information about this option. The
273 // to-be-maintained width is specified.
275 virtual void printOptionInfo(size_t GlobalWidth) const = 0;
277 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
279 virtual void getExtraOptionNames(SmallVectorImpl<const char *> &) {}
281 // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
283 virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
284 bool MultiArg = false);
286 // Prints option name followed by message. Always returns true.
287 bool error(const Twine &Message, StringRef ArgName = StringRef());
290 inline int getNumOccurrences() const { return NumOccurrences; }
294 //===----------------------------------------------------------------------===//
295 // Command line option modifiers that can be used to modify the behavior of
296 // command line option parsers...
299 // desc - Modifier to set the description shown in the -help output...
302 desc(const char *Str) : Desc(Str) {}
303 void apply(Option &O) const { O.setDescription(Desc); }
306 // value_desc - Modifier to set the value description shown in the -help
310 value_desc(const char *Str) : Desc(Str) {}
311 void apply(Option &O) const { O.setValueStr(Desc); }
314 // init - Specify a default (initial) value for the command line argument, if
315 // the default constructor for the argument type does not give you what you
316 // want. This is only valid on "opt" arguments, not on "list" arguments.
318 template <class Ty> struct initializer {
320 initializer(const Ty &Val) : Init(Val) {}
322 template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
325 template <class Ty> initializer<Ty> init(const Ty &Val) {
326 return initializer<Ty>(Val);
329 // location - Allow the user to specify which external variable they want to
330 // store the results of the command line argument processing into, if they don't
331 // want to store it in the option itself.
333 template <class Ty> struct LocationClass {
335 LocationClass(Ty &L) : Loc(L) {}
337 template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
340 template <class Ty> LocationClass<Ty> location(Ty &L) {
341 return LocationClass<Ty>(L);
344 // cat - Specifiy the Option category for the command line argument to belong
347 OptionCategory &Category;
348 cat(OptionCategory &c) : Category(c) {}
350 template <class Opt> void apply(Opt &O) const { O.setCategory(Category); }
353 //===----------------------------------------------------------------------===//
356 // Support value comparison outside the template.
357 struct GenericOptionValue {
358 virtual bool compare(const GenericOptionValue &V) const = 0;
361 ~GenericOptionValue() = default;
362 GenericOptionValue() = default;
363 GenericOptionValue(const GenericOptionValue&) = default;
364 GenericOptionValue &operator=(const GenericOptionValue &) = default;
367 virtual void anchor();
370 template <class DataType> struct OptionValue;
372 // The default value safely does nothing. Option value printing is only
374 template <class DataType, bool isClass>
375 struct OptionValueBase : public GenericOptionValue {
376 // Temporary storage for argument passing.
377 typedef OptionValue<DataType> WrapperType;
379 bool hasValue() const { return false; }
381 const DataType &getValue() const { llvm_unreachable("no default value"); }
383 // Some options may take their value from a different data type.
384 template <class DT> void setValue(const DT & /*V*/) {}
386 bool compare(const DataType & /*V*/) const { return false; }
388 bool compare(const GenericOptionValue & /*V*/) const override {
393 ~OptionValueBase() = default;
396 // Simple copy of the option value.
397 template <class DataType> class OptionValueCopy : public GenericOptionValue {
402 ~OptionValueCopy() = default;
403 OptionValueCopy(const OptionValueCopy&) = default;
404 OptionValueCopy &operator=(const OptionValueCopy&) = default;
407 OptionValueCopy() : Valid(false) {}
409 bool hasValue() const { return Valid; }
411 const DataType &getValue() const {
412 assert(Valid && "invalid option value");
416 void setValue(const DataType &V) {
421 bool compare(const DataType &V) const { return Valid && (Value != V); }
423 bool compare(const GenericOptionValue &V) const override {
424 const OptionValueCopy<DataType> &VC =
425 static_cast<const OptionValueCopy<DataType> &>(V);
428 return compare(VC.getValue());
432 // Non-class option values.
433 template <class DataType>
434 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
435 typedef DataType WrapperType;
438 ~OptionValueBase() = default;
439 OptionValueBase() = default;
440 OptionValueBase(const OptionValueBase&) = default;
441 OptionValueBase &operator=(const OptionValueBase&) = default;
444 // Top-level option class.
445 template <class DataType>
446 struct OptionValue final
447 : OptionValueBase<DataType, std::is_class<DataType>::value> {
448 OptionValue() = default;
450 OptionValue(const DataType &V) { this->setValue(V); }
451 // Some options may take their value from a different data type.
452 template <class DT> OptionValue<DataType> &operator=(const DT &V) {
458 // Other safe-to-copy-by-value common option types.
459 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
461 struct OptionValue<cl::boolOrDefault> final
462 : OptionValueCopy<cl::boolOrDefault> {
463 typedef cl::boolOrDefault WrapperType;
467 OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
468 OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
474 void anchor() override;
478 struct OptionValue<std::string> final : OptionValueCopy<std::string> {
479 typedef StringRef WrapperType;
483 OptionValue(const std::string &V) { this->setValue(V); }
484 OptionValue<std::string> &operator=(const std::string &V) {
490 void anchor() override;
493 //===----------------------------------------------------------------------===//
494 // Enum valued command line option
496 #define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
497 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
498 #define clEnumValEnd (reinterpret_cast<void *>(0))
500 // values - For custom data types, allow specifying a group of values together
501 // as the values that go into the mapping that the option handler uses. Note
502 // that the values list must always have a 0 at the end of the list to indicate
503 // that the list has ended.
505 template <class DataType> class ValuesClass {
506 // Use a vector instead of a map, because the lists should be short,
507 // the overhead is less, and most importantly, it keeps them in the order
508 // inserted so we can print our option out nicely.
509 SmallVector<std::pair<const char *, std::pair<int, const char *>>, 4> Values;
510 void processValues(va_list Vals);
513 ValuesClass(const char *EnumName, DataType Val, const char *Desc,
515 // Insert the first value, which is required.
516 Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
518 // Process the varargs portion of the values...
519 while (const char *enumName = va_arg(ValueArgs, const char *)) {
520 DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
521 const char *EnumDesc = va_arg(ValueArgs, const char *);
522 Values.push_back(std::make_pair(enumName, // Add value to value map
523 std::make_pair(EnumVal, EnumDesc)));
527 template <class Opt> void apply(Opt &O) const {
528 for (size_t i = 0, e = Values.size(); i != e; ++i)
529 O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
530 Values[i].second.second);
534 template <class DataType>
535 ValuesClass<DataType> LLVM_END_WITH_NULL
536 values(const char *Arg, DataType Val, const char *Desc, ...) {
538 va_start(ValueArgs, Desc);
539 ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
544 //===----------------------------------------------------------------------===//
545 // parser class - Parameterizable parser for different data types. By default,
546 // known data types (string, int, bool) have specialized parsers, that do what
547 // you would expect. The default parser, used for data types that are not
548 // built-in, uses a mapping table to map specific options to values, which is
549 // used, among other things, to handle enum types.
551 //--------------------------------------------------
552 // generic_parser_base - This class holds all the non-generic code that we do
553 // not need replicated for every instance of the generic parser. This also
554 // allows us to put stuff into CommandLine.cpp
556 class generic_parser_base {
558 class GenericOptionInfo {
560 GenericOptionInfo(const char *name, const char *helpStr)
561 : Name(name), HelpStr(helpStr) {}
567 generic_parser_base(Option &O) : Owner(O) {}
569 virtual ~generic_parser_base() {} // Base class should have virtual-dtor
571 // getNumOptions - Virtual function implemented by generic subclass to
572 // indicate how many entries are in Values.
574 virtual unsigned getNumOptions() const = 0;
576 // getOption - Return option name N.
577 virtual const char *getOption(unsigned N) const = 0;
579 // getDescription - Return description N
580 virtual const char *getDescription(unsigned N) const = 0;
582 // Return the width of the option tag for printing...
583 virtual size_t getOptionWidth(const Option &O) const;
585 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
587 // printOptionInfo - Print out information about this option. The
588 // to-be-maintained width is specified.
590 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
592 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
593 const GenericOptionValue &Default,
594 size_t GlobalWidth) const;
596 // printOptionDiff - print the value of an option and it's default.
598 // Template definition ensures that the option and default have the same
599 // DataType (via the same AnyOptionValue).
600 template <class AnyOptionValue>
601 void printOptionDiff(const Option &O, const AnyOptionValue &V,
602 const AnyOptionValue &Default,
603 size_t GlobalWidth) const {
604 printGenericOptionDiff(O, V, Default, GlobalWidth);
609 void getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) {
610 // If there has been no argstr specified, that means that we need to add an
611 // argument for every possible option. This ensures that our options are
613 if (!Owner.hasArgStr())
614 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
615 OptionNames.push_back(getOption(i));
618 enum ValueExpected getValueExpectedFlagDefault() const {
619 // If there is an ArgStr specified, then we are of the form:
621 // -opt=O2 or -opt O2 or -optO2
623 // In which case, the value is required. Otherwise if an arg str has not
624 // been specified, we are of the form:
626 // -O2 or O2 or -la (where -l and -a are separate options)
628 // If this is the case, we cannot allow a value.
630 if (Owner.hasArgStr())
631 return ValueRequired;
633 return ValueDisallowed;
636 // findOption - Return the option number corresponding to the specified
637 // argument string. If the option is not found, getNumOptions() is returned.
639 unsigned findOption(const char *Name);
645 // Default parser implementation - This implementation depends on having a
646 // mapping of recognized options to values of some sort. In addition to this,
647 // each entry in the mapping also tracks a help message that is printed with the
648 // command line option for -help. Because this is a simple mapping parser, the
649 // data type can be any unsupported type.
651 template <class DataType> class parser : public generic_parser_base {
653 class OptionInfo : public GenericOptionInfo {
655 OptionInfo(const char *name, DataType v, const char *helpStr)
656 : GenericOptionInfo(name, helpStr), V(v) {}
657 OptionValue<DataType> V;
659 SmallVector<OptionInfo, 8> Values;
662 parser(Option &O) : generic_parser_base(O) {}
663 typedef DataType parser_data_type;
665 // Implement virtual functions needed by generic_parser_base
666 unsigned getNumOptions() const override { return unsigned(Values.size()); }
667 const char *getOption(unsigned N) const override { return Values[N].Name; }
668 const char *getDescription(unsigned N) const override {
669 return Values[N].HelpStr;
672 // getOptionValue - Return the value of option name N.
673 const GenericOptionValue &getOptionValue(unsigned N) const override {
677 // parse - Return true on error.
678 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
680 if (Owner.hasArgStr())
685 for (size_t i = 0, e = Values.size(); i != e; ++i)
686 if (Values[i].Name == ArgVal) {
687 V = Values[i].V.getValue();
691 return O.error("Cannot find option named '" + ArgVal + "'!");
694 /// addLiteralOption - Add an entry to the mapping table.
697 void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
698 assert(findOption(Name) == Values.size() && "Option already exists!");
699 OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
701 AddLiteralOption(Owner, Name);
704 /// removeLiteralOption - Remove the specified option.
706 void removeLiteralOption(const char *Name) {
707 unsigned N = findOption(Name);
708 assert(N != Values.size() && "Option not found!");
709 Values.erase(Values.begin() + N);
713 //--------------------------------------------------
714 // basic_parser - Super class of parsers to provide boilerplate code
716 class basic_parser_impl { // non-template implementation of basic_parser<t>
718 basic_parser_impl(Option &O) {}
721 enum ValueExpected getValueExpectedFlagDefault() const {
722 return ValueRequired;
725 void getExtraOptionNames(SmallVectorImpl<const char *> &) {}
729 // Return the width of the option tag for printing...
730 size_t getOptionWidth(const Option &O) const;
732 // printOptionInfo - Print out information about this option. The
733 // to-be-maintained width is specified.
735 void printOptionInfo(const Option &O, size_t GlobalWidth) const;
737 // printOptionNoValue - Print a placeholder for options that don't yet support
738 // printOptionDiff().
739 void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
741 // getValueName - Overload in subclass to provide a better default value.
742 virtual const char *getValueName() const { return "value"; }
744 // An out-of-line virtual method to provide a 'home' for this class.
745 virtual void anchor();
748 ~basic_parser_impl() = default;
749 // A helper for basic_parser::printOptionDiff.
750 void printOptionName(const Option &O, size_t GlobalWidth) const;
753 // basic_parser - The real basic parser is just a template wrapper that provides
754 // a typedef for the provided data type.
756 template <class DataType> class basic_parser : public basic_parser_impl {
758 basic_parser(Option &O) : basic_parser_impl(O) {}
759 typedef DataType parser_data_type;
760 typedef OptionValue<DataType> OptVal;
763 // Workaround Clang PR22793
767 //--------------------------------------------------
770 template <> class parser<bool> final : public basic_parser<bool> {
772 parser(Option &O) : basic_parser(O) {}
774 // parse - Return true on error.
775 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
779 enum ValueExpected getValueExpectedFlagDefault() const {
780 return ValueOptional;
783 // getValueName - Do not print =<value> at all.
784 const char *getValueName() const override { return nullptr; }
786 void printOptionDiff(const Option &O, bool V, OptVal Default,
787 size_t GlobalWidth) const;
789 // An out-of-line virtual method to provide a 'home' for this class.
790 void anchor() override;
793 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<bool>);
795 //--------------------------------------------------
796 // parser<boolOrDefault>
798 class parser<boolOrDefault> final : public basic_parser<boolOrDefault> {
800 parser(Option &O) : basic_parser(O) {}
802 // parse - Return true on error.
803 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
805 enum ValueExpected getValueExpectedFlagDefault() const {
806 return ValueOptional;
809 // getValueName - Do not print =<value> at all.
810 const char *getValueName() const override { return nullptr; }
812 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
813 size_t GlobalWidth) const;
815 // An out-of-line virtual method to provide a 'home' for this class.
816 void anchor() override;
819 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
821 //--------------------------------------------------
824 template <> class parser<int> final : public basic_parser<int> {
826 parser(Option &O) : basic_parser(O) {}
828 // parse - Return true on error.
829 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
831 // getValueName - Overload in subclass to provide a better default value.
832 const char *getValueName() const override { return "int"; }
834 void printOptionDiff(const Option &O, int V, OptVal Default,
835 size_t GlobalWidth) const;
837 // An out-of-line virtual method to provide a 'home' for this class.
838 void anchor() override;
841 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<int>);
843 //--------------------------------------------------
846 template <> class parser<unsigned> final : public basic_parser<unsigned> {
848 parser(Option &O) : basic_parser(O) {}
850 // parse - Return true on error.
851 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
853 // getValueName - Overload in subclass to provide a better default value.
854 const char *getValueName() const override { return "uint"; }
856 void printOptionDiff(const Option &O, unsigned V, OptVal Default,
857 size_t GlobalWidth) const;
859 // An out-of-line virtual method to provide a 'home' for this class.
860 void anchor() override;
863 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
865 //--------------------------------------------------
866 // parser<unsigned long long>
869 class parser<unsigned long long> final
870 : public basic_parser<unsigned long long> {
872 parser(Option &O) : basic_parser(O) {}
874 // parse - Return true on error.
875 bool parse(Option &O, StringRef ArgName, StringRef Arg,
876 unsigned long long &Val);
878 // getValueName - Overload in subclass to provide a better default value.
879 const char *getValueName() const override { return "uint"; }
881 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
882 size_t GlobalWidth) const;
884 // An out-of-line virtual method to provide a 'home' for this class.
885 void anchor() override;
888 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
890 //--------------------------------------------------
893 template <> class parser<double> final : public basic_parser<double> {
895 parser(Option &O) : basic_parser(O) {}
897 // parse - Return true on error.
898 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
900 // getValueName - Overload in subclass to provide a better default value.
901 const char *getValueName() const override { return "number"; }
903 void printOptionDiff(const Option &O, double V, OptVal Default,
904 size_t GlobalWidth) const;
906 // An out-of-line virtual method to provide a 'home' for this class.
907 void anchor() override;
910 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<double>);
912 //--------------------------------------------------
915 template <> class parser<float> final : public basic_parser<float> {
917 parser(Option &O) : basic_parser(O) {}
919 // parse - Return true on error.
920 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
922 // getValueName - Overload in subclass to provide a better default value.
923 const char *getValueName() const override { return "number"; }
925 void printOptionDiff(const Option &O, float V, OptVal Default,
926 size_t GlobalWidth) const;
928 // An out-of-line virtual method to provide a 'home' for this class.
929 void anchor() override;
932 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<float>);
934 //--------------------------------------------------
935 // parser<std::string>
937 template <> class parser<std::string> final : public basic_parser<std::string> {
939 parser(Option &O) : basic_parser(O) {}
941 // parse - Return true on error.
942 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
947 // getValueName - Overload in subclass to provide a better default value.
948 const char *getValueName() const override { return "string"; }
950 void printOptionDiff(const Option &O, StringRef V, OptVal Default,
951 size_t GlobalWidth) const;
953 // An out-of-line virtual method to provide a 'home' for this class.
954 void anchor() override;
957 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
959 //--------------------------------------------------
962 template <> class parser<char> final : public basic_parser<char> {
964 parser(Option &O) : basic_parser(O) {}
966 // parse - Return true on error.
967 bool parse(Option &, StringRef, StringRef Arg, char &Value) {
972 // getValueName - Overload in subclass to provide a better default value.
973 const char *getValueName() const override { return "char"; }
975 void printOptionDiff(const Option &O, char V, OptVal Default,
976 size_t GlobalWidth) const;
978 // An out-of-line virtual method to provide a 'home' for this class.
979 void anchor() override;
982 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<char>);
984 //--------------------------------------------------
987 // This collection of wrappers is the intermediary between class opt and class
988 // parser to handle all the template nastiness.
990 // This overloaded function is selected by the generic parser.
991 template <class ParserClass, class DT>
992 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
993 const OptionValue<DT> &Default, size_t GlobalWidth) {
994 OptionValue<DT> OV = V;
995 P.printOptionDiff(O, OV, Default, GlobalWidth);
998 // This is instantiated for basic parsers when the parsed value has a different
999 // type than the option value. e.g. HelpPrinter.
1000 template <class ParserDT, class ValDT> struct OptionDiffPrinter {
1001 void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/,
1002 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
1003 P.printOptionNoValue(O, GlobalWidth);
1007 // This is instantiated for basic parsers when the parsed value has the same
1008 // type as the option value.
1009 template <class DT> struct OptionDiffPrinter<DT, DT> {
1010 void print(const Option &O, const parser<DT> &P, const DT &V,
1011 const OptionValue<DT> &Default, size_t GlobalWidth) {
1012 P.printOptionDiff(O, V, Default, GlobalWidth);
1016 // This overloaded function is selected by the basic parser, which may parse a
1017 // different type than the option type.
1018 template <class ParserClass, class ValDT>
1019 void printOptionDiff(
1021 const basic_parser<typename ParserClass::parser_data_type> &P,
1022 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
1024 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
1025 printer.print(O, static_cast<const ParserClass &>(P), V, Default,
1029 //===----------------------------------------------------------------------===//
1030 // applicator class - This class is used because we must use partial
1031 // specialization to handle literal string arguments specially (const char* does
1032 // not correctly respond to the apply method). Because the syntax to use this
1033 // is a pain, we have the 'apply' method below to handle the nastiness...
1035 template <class Mod> struct applicator {
1036 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1039 // Handle const char* as a special case...
1040 template <unsigned n> struct applicator<char[n]> {
1041 template <class Opt> static void opt(const char *Str, Opt &O) {
1045 template <unsigned n> struct applicator<const char[n]> {
1046 template <class Opt> static void opt(const char *Str, Opt &O) {
1050 template <> struct applicator<const char *> {
1051 template <class Opt> static void opt(const char *Str, Opt &O) {
1056 template <> struct applicator<NumOccurrencesFlag> {
1057 static void opt(NumOccurrencesFlag N, Option &O) {
1058 O.setNumOccurrencesFlag(N);
1061 template <> struct applicator<ValueExpected> {
1062 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1064 template <> struct applicator<OptionHidden> {
1065 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1067 template <> struct applicator<FormattingFlags> {
1068 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1070 template <> struct applicator<MiscFlags> {
1071 static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1074 // apply method - Apply modifiers to an option in a type safe way.
1075 template <class Opt, class Mod, class... Mods>
1076 void apply(Opt *O, const Mod &M, const Mods &... Ms) {
1077 applicator<Mod>::opt(M, *O);
1081 template <class Opt, class Mod> void apply(Opt *O, const Mod &M) {
1082 applicator<Mod>::opt(M, *O);
1085 //===----------------------------------------------------------------------===//
1086 // opt_storage class
1088 // Default storage class definition: external storage. This implementation
1089 // assumes the user will specify a variable to store the data into with the
1090 // cl::location(x) modifier.
1092 template <class DataType, bool ExternalStorage, bool isClass>
1094 DataType *Location; // Where to store the object...
1095 OptionValue<DataType> Default;
1097 void check_location() const {
1098 assert(Location && "cl::location(...) not specified for a command "
1099 "line option with external storage, "
1100 "or cl::init specified before cl::location()!!");
1104 opt_storage() : Location(nullptr) {}
1106 bool setLocation(Option &O, DataType &L) {
1108 return O.error("cl::location(x) specified more than once!");
1114 template <class T> void setValue(const T &V, bool initial = false) {
1121 DataType &getValue() {
1125 const DataType &getValue() const {
1130 operator DataType() const { return this->getValue(); }
1132 const OptionValue<DataType> &getDefault() const { return Default; }
1135 // Define how to hold a class type object, such as a string. Since we can
1136 // inherit from a class, we do so. This makes us exactly compatible with the
1137 // object in all cases that it is used.
1139 template <class DataType>
1140 class opt_storage<DataType, false, true> : public DataType {
1142 OptionValue<DataType> Default;
1144 template <class T> void setValue(const T &V, bool initial = false) {
1145 DataType::operator=(V);
1150 DataType &getValue() { return *this; }
1151 const DataType &getValue() const { return *this; }
1153 const OptionValue<DataType> &getDefault() const { return Default; }
1156 // Define a partial specialization to handle things we cannot inherit from. In
1157 // this case, we store an instance through containment, and overload operators
1158 // to get at the value.
1160 template <class DataType> class opt_storage<DataType, false, false> {
1163 OptionValue<DataType> Default;
1165 // Make sure we initialize the value with the default constructor for the
1167 opt_storage() : Value(DataType()), Default(DataType()) {}
1169 template <class T> void setValue(const T &V, bool initial = false) {
1174 DataType &getValue() { return Value; }
1175 DataType getValue() const { return Value; }
1177 const OptionValue<DataType> &getDefault() const { return Default; }
1179 operator DataType() const { return getValue(); }
1181 // If the datatype is a pointer, support -> on it.
1182 DataType operator->() const { return Value; }
1185 //===----------------------------------------------------------------------===//
1186 // opt - A scalar command line option.
1188 template <class DataType, bool ExternalStorage = false,
1189 class ParserClass = parser<DataType>>
1190 class opt : public Option,
1191 public opt_storage<DataType, ExternalStorage,
1192 std::is_class<DataType>::value> {
1195 bool handleOccurrence(unsigned pos, StringRef ArgName,
1196 StringRef Arg) override {
1197 typename ParserClass::parser_data_type Val =
1198 typename ParserClass::parser_data_type();
1199 if (Parser.parse(*this, ArgName, Arg, Val))
1200 return true; // Parse error!
1201 this->setValue(Val);
1202 this->setPosition(pos);
1206 enum ValueExpected getValueExpectedFlagDefault() const override {
1207 return Parser.getValueExpectedFlagDefault();
1210 getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
1211 return Parser.getExtraOptionNames(OptionNames);
1214 // Forward printing stuff to the parser...
1215 size_t getOptionWidth() const override {
1216 return Parser.getOptionWidth(*this);
1218 void printOptionInfo(size_t GlobalWidth) const override {
1219 Parser.printOptionInfo(*this, GlobalWidth);
1222 void printOptionValue(size_t GlobalWidth, bool Force) const override {
1223 if (Force || this->getDefault().compare(this->getValue())) {
1224 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1225 this->getDefault(), GlobalWidth);
1231 Parser.initialize();
1234 // Command line options should not be copyable
1235 opt(const opt &) = delete;
1236 opt &operator=(const opt &) = delete;
1239 // setInitialValue - Used by the cl::init modifier...
1240 void setInitialValue(const DataType &V) { this->setValue(V, true); }
1242 ParserClass &getParser() { return Parser; }
1244 template <class T> DataType &operator=(const T &Val) {
1245 this->setValue(Val);
1246 return this->getValue();
1249 template <class... Mods>
1250 explicit opt(const Mods &... Ms)
1251 : Option(Optional, NotHidden), Parser(*this) {
1257 EXTERN_TEMPLATE_INSTANTIATION(class opt<unsigned>);
1258 EXTERN_TEMPLATE_INSTANTIATION(class opt<int>);
1259 EXTERN_TEMPLATE_INSTANTIATION(class opt<std::string>);
1260 EXTERN_TEMPLATE_INSTANTIATION(class opt<char>);
1261 EXTERN_TEMPLATE_INSTANTIATION(class opt<bool>);
1263 //===----------------------------------------------------------------------===//
1264 // list_storage class
1266 // Default storage class definition: external storage. This implementation
1267 // assumes the user will specify a variable to store the data into with the
1268 // cl::location(x) modifier.
1270 template <class DataType, class StorageClass> class list_storage {
1271 StorageClass *Location; // Where to store the object...
1274 list_storage() : Location(0) {}
1276 bool setLocation(Option &O, StorageClass &L) {
1278 return O.error("cl::location(x) specified more than once!");
1283 template <class T> void addValue(const T &V) {
1284 assert(Location != 0 && "cl::location(...) not specified for a command "
1285 "line option with external storage!");
1286 Location->push_back(V);
1290 // Define how to hold a class type object, such as a string.
1291 // Originally this code inherited from std::vector. In transitioning to a new
1292 // API for command line options we should change this. The new implementation
1293 // of this list_storage specialization implements the minimum subset of the
1294 // std::vector API required for all the current clients.
1296 // FIXME: Reduce this API to a more narrow subset of std::vector
1298 template <class DataType> class list_storage<DataType, bool> {
1299 std::vector<DataType> Storage;
1302 typedef typename std::vector<DataType>::iterator iterator;
1304 iterator begin() { return Storage.begin(); }
1305 iterator end() { return Storage.end(); }
1307 typedef typename std::vector<DataType>::const_iterator const_iterator;
1308 const_iterator begin() const { return Storage.begin(); }
1309 const_iterator end() const { return Storage.end(); }
1311 typedef typename std::vector<DataType>::size_type size_type;
1312 size_type size() const { return Storage.size(); }
1314 bool empty() const { return Storage.empty(); }
1316 void push_back(const DataType &value) { Storage.push_back(value); }
1317 void push_back(DataType &&value) { Storage.push_back(value); }
1319 typedef typename std::vector<DataType>::reference reference;
1320 typedef typename std::vector<DataType>::const_reference const_reference;
1321 reference operator[](size_type pos) { return Storage[pos]; }
1322 const_reference operator[](size_type pos) const { return Storage[pos]; }
1324 iterator erase(const_iterator pos) { return Storage.erase(pos); }
1325 iterator erase(const_iterator first, const_iterator last) {
1326 return Storage.erase(first, last);
1329 iterator erase(iterator pos) { return Storage.erase(pos); }
1330 iterator erase(iterator first, iterator last) {
1331 return Storage.erase(first, last);
1334 iterator insert(const_iterator pos, const DataType &value) {
1335 return Storage.insert(pos, value);
1337 iterator insert(const_iterator pos, DataType &&value) {
1338 return Storage.insert(pos, value);
1341 iterator insert(iterator pos, const DataType &value) {
1342 return Storage.insert(pos, value);
1344 iterator insert(iterator pos, DataType &&value) {
1345 return Storage.insert(pos, value);
1348 reference front() { return Storage.front(); }
1349 const_reference front() const { return Storage.front(); }
1351 operator std::vector<DataType>&() { return Storage; }
1352 operator ArrayRef<DataType>() { return Storage; }
1353 std::vector<DataType> *operator&() { return &Storage; }
1354 const std::vector<DataType> *operator&() const { return &Storage; }
1356 template <class T> void addValue(const T &V) { Storage.push_back(V); }
1359 //===----------------------------------------------------------------------===//
1360 // list - A list of command line options.
1362 template <class DataType, class StorageClass = bool,
1363 class ParserClass = parser<DataType>>
1364 class list : public Option, public list_storage<DataType, StorageClass> {
1365 std::vector<unsigned> Positions;
1368 enum ValueExpected getValueExpectedFlagDefault() const override {
1369 return Parser.getValueExpectedFlagDefault();
1372 getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
1373 return Parser.getExtraOptionNames(OptionNames);
1376 bool handleOccurrence(unsigned pos, StringRef ArgName,
1377 StringRef Arg) override {
1378 typename ParserClass::parser_data_type Val =
1379 typename ParserClass::parser_data_type();
1380 if (Parser.parse(*this, ArgName, Arg, Val))
1381 return true; // Parse Error!
1382 list_storage<DataType, StorageClass>::addValue(Val);
1384 Positions.push_back(pos);
1388 // Forward printing stuff to the parser...
1389 size_t getOptionWidth() const override {
1390 return Parser.getOptionWidth(*this);
1392 void printOptionInfo(size_t GlobalWidth) const override {
1393 Parser.printOptionInfo(*this, GlobalWidth);
1396 // Unimplemented: list options don't currently store their default value.
1397 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1402 Parser.initialize();
1405 // Command line options should not be copyable
1406 list(const list &) = delete;
1407 list &operator=(const list &) = delete;
1410 ParserClass &getParser() { return Parser; }
1412 unsigned getPosition(unsigned optnum) const {
1413 assert(optnum < this->size() && "Invalid option index");
1414 return Positions[optnum];
1417 void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
1419 template <class... Mods>
1420 explicit list(const Mods &... Ms)
1421 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1427 // multi_val - Modifier to set the number of additional values.
1429 unsigned AdditionalVals;
1430 explicit multi_val(unsigned N) : AdditionalVals(N) {}
1432 template <typename D, typename S, typename P>
1433 void apply(list<D, S, P> &L) const {
1434 L.setNumAdditionalVals(AdditionalVals);
1438 //===----------------------------------------------------------------------===//
1439 // bits_storage class
1441 // Default storage class definition: external storage. This implementation
1442 // assumes the user will specify a variable to store the data into with the
1443 // cl::location(x) modifier.
1445 template <class DataType, class StorageClass> class bits_storage {
1446 unsigned *Location; // Where to store the bits...
1448 template <class T> static unsigned Bit(const T &V) {
1449 unsigned BitPos = reinterpret_cast<unsigned>(V);
1450 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1451 "enum exceeds width of bit vector!");
1456 bits_storage() : Location(nullptr) {}
1458 bool setLocation(Option &O, unsigned &L) {
1460 return O.error("cl::location(x) specified more than once!");
1465 template <class T> void addValue(const T &V) {
1466 assert(Location != 0 && "cl::location(...) not specified for a command "
1467 "line option with external storage!");
1468 *Location |= Bit(V);
1471 unsigned getBits() { return *Location; }
1473 template <class T> bool isSet(const T &V) {
1474 return (*Location & Bit(V)) != 0;
1478 // Define how to hold bits. Since we can inherit from a class, we do so.
1479 // This makes us exactly compatible with the bits in all cases that it is used.
1481 template <class DataType> class bits_storage<DataType, bool> {
1482 unsigned Bits; // Where to store the bits...
1484 template <class T> static unsigned Bit(const T &V) {
1485 unsigned BitPos = (unsigned)V;
1486 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1487 "enum exceeds width of bit vector!");
1492 template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1494 unsigned getBits() { return Bits; }
1496 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1499 //===----------------------------------------------------------------------===//
1500 // bits - A bit vector of command options.
1502 template <class DataType, class Storage = bool,
1503 class ParserClass = parser<DataType>>
1504 class bits : public Option, public bits_storage<DataType, Storage> {
1505 std::vector<unsigned> Positions;
1508 enum ValueExpected getValueExpectedFlagDefault() const override {
1509 return Parser.getValueExpectedFlagDefault();
1512 getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
1513 return Parser.getExtraOptionNames(OptionNames);
1516 bool handleOccurrence(unsigned pos, StringRef ArgName,
1517 StringRef Arg) override {
1518 typename ParserClass::parser_data_type Val =
1519 typename ParserClass::parser_data_type();
1520 if (Parser.parse(*this, ArgName, Arg, Val))
1521 return true; // Parse Error!
1522 this->addValue(Val);
1524 Positions.push_back(pos);
1528 // Forward printing stuff to the parser...
1529 size_t getOptionWidth() const override {
1530 return Parser.getOptionWidth(*this);
1532 void printOptionInfo(size_t GlobalWidth) const override {
1533 Parser.printOptionInfo(*this, GlobalWidth);
1536 // Unimplemented: bits options don't currently store their default values.
1537 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1542 Parser.initialize();
1545 // Command line options should not be copyable
1546 bits(const bits &) = delete;
1547 bits &operator=(const bits &) = delete;
1550 ParserClass &getParser() { return Parser; }
1552 unsigned getPosition(unsigned optnum) const {
1553 assert(optnum < this->size() && "Invalid option index");
1554 return Positions[optnum];
1557 template <class... Mods>
1558 explicit bits(const Mods &... Ms)
1559 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1565 //===----------------------------------------------------------------------===//
1566 // Aliased command line option (alias this name to a preexisting name)
1569 class alias : public Option {
1571 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1572 StringRef Arg) override {
1573 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1575 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1576 bool MultiArg = false) override {
1577 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1579 // Handle printing stuff...
1580 size_t getOptionWidth() const override;
1581 void printOptionInfo(size_t GlobalWidth) const override;
1583 // Aliases do not need to print their values.
1584 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1587 ValueExpected getValueExpectedFlagDefault() const override {
1588 return AliasFor->getValueExpectedFlag();
1593 error("cl::alias must have argument name specified!");
1595 error("cl::alias must have an cl::aliasopt(option) specified!");
1599 // Command line options should not be copyable
1600 alias(const alias &) = delete;
1601 alias &operator=(const alias &) = delete;
1604 void setAliasFor(Option &O) {
1606 error("cl::alias must only have one cl::aliasopt(...) specified!");
1610 template <class... Mods>
1611 explicit alias(const Mods &... Ms)
1612 : Option(Optional, Hidden), AliasFor(nullptr) {
1618 // aliasfor - Modifier to set the option an alias aliases.
1621 explicit aliasopt(Option &O) : Opt(O) {}
1622 void apply(alias &A) const { A.setAliasFor(Opt); }
1625 // extrahelp - provide additional help at the end of the normal help
1626 // output. All occurrences of cl::extrahelp will be accumulated and
1627 // printed to stderr at the end of the regular help, just before
1630 const char *morehelp;
1631 explicit extrahelp(const char *help);
1634 void PrintVersionMessage();
1636 /// This function just prints the help message, exactly the same way as if the
1637 /// -help or -help-hidden option had been given on the command line.
1639 /// NOTE: THIS FUNCTION TERMINATES THE PROGRAM!
1641 /// \param Hidden if true will print hidden options
1642 /// \param Categorized if true print options in categories
1643 void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
1645 //===----------------------------------------------------------------------===//
1646 // Public interface for accessing registered options.
1649 /// \brief Use this to get a StringMap to all registered named options
1650 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1652 /// \return A reference to the StringMap used by the cl APIs to parse options.
1654 /// Access to unnamed arguments (i.e. positional) are not provided because
1655 /// it is expected that the client already has access to these.
1659 /// main(int argc,char* argv[]) {
1660 /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions();
1661 /// assert(opts.count("help") == 1)
1662 /// opts["help"]->setDescription("Show alphabetical help information")
1664 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1669 /// This interface is useful for modifying options in libraries that are out of
1670 /// the control of the client. The options should be modified before calling
1671 /// llvm::cl::ParseCommandLineOptions().
1673 /// Hopefully this API can be depricated soon. Any situation where options need
1674 /// to be modified by tools or libraries should be handled by sane APIs rather
1675 /// than just handing around a global list.
1676 StringMap<Option *> &getRegisteredOptions();
1678 //===----------------------------------------------------------------------===//
1679 // Standalone command line processing utilities.
1682 /// \brief Tokenizes a command line that can contain escapes and quotes.
1684 /// The quoting rules match those used by GCC and other tools that use
1685 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1686 /// They differ from buildargv() on treatment of backslashes that do not escape
1687 /// a special character to make it possible to accept most Windows file paths.
1689 /// \param [in] Source The string to be split on whitespace with quotes.
1690 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1691 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1692 /// lines and end of the response file to be marked with a nullptr string.
1693 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1694 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
1695 SmallVectorImpl<const char *> &NewArgv,
1696 bool MarkEOLs = false);
1698 /// \brief Tokenizes a Windows command line which may contain quotes and escaped
1701 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1702 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1704 /// \param [in] Source The string to be split on whitespace with quotes.
1705 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1706 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1707 /// lines and end of the response file to be marked with a nullptr string.
1708 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1709 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
1710 SmallVectorImpl<const char *> &NewArgv,
1711 bool MarkEOLs = false);
1713 /// \brief String tokenization function type. Should be compatible with either
1714 /// Windows or Unix command line tokenizers.
1715 typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
1716 SmallVectorImpl<const char *> &NewArgv,
1719 /// \brief Expand response files on a command line recursively using the given
1720 /// StringSaver and tokenization strategy. Argv should contain the command line
1721 /// before expansion and will be modified in place. If requested, Argv will
1722 /// also be populated with nullptrs indicating where each response file line
1723 /// ends, which is useful for the "/link" argument that needs to consume all
1724 /// remaining arguments only until the next end of line, when in a response
1727 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1728 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1729 /// \param [in,out] Argv Command line into which to expand response files.
1730 /// \param [in] MarkEOLs Mark end of lines and the end of the response file
1731 /// with nullptrs in the Argv vector.
1732 /// \return true if all @files were expanded successfully or there were none.
1733 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1734 SmallVectorImpl<const char *> &Argv,
1735 bool MarkEOLs = false);
1737 /// \brief Mark all options not part of this category as cl::ReallyHidden.
1739 /// \param Category the category of options to keep displaying
1741 /// Some tools (like clang-format) like to be able to hide all options that are
1742 /// not specific to the tool. This function allows a tool to specify a single
1743 /// option category to display in the -help output.
1744 void HideUnrelatedOptions(cl::OptionCategory &Category);
1746 /// \brief Mark all options not part of the categories as cl::ReallyHidden.
1748 /// \param Categories the categories of options to keep displaying.
1750 /// Some tools (like clang-format) like to be able to hide all options that are
1751 /// not specific to the tool. This function allows a tool to specify a single
1752 /// option category to display in the -help output.
1753 void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories);
1755 } // End namespace cl
1757 } // End namespace llvm