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"
38 /// cl Namespace - This namespace contains all of the command line option
39 /// processing machinery. It is intentionally a short name to make qualified
43 //===----------------------------------------------------------------------===//
44 // ParseCommandLineOptions - Command line option processing entry point.
46 void ParseCommandLineOptions(int argc, const char *const *argv,
47 const char *Overview = nullptr);
49 //===----------------------------------------------------------------------===//
50 // ParseEnvironmentOptions - Environment variable option processing alternate
53 void ParseEnvironmentOptions(const char *progName, const char *envvar,
54 const char *Overview = nullptr);
56 ///===---------------------------------------------------------------------===//
57 /// SetVersionPrinter - Override the default (LLVM specific) version printer
58 /// used to print out the version when --version is given
59 /// on the command line. This allows other systems using the
60 /// CommandLine utilities to print their own version string.
61 void SetVersionPrinter(void (*func)());
63 ///===---------------------------------------------------------------------===//
64 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
65 /// default one. This can be called multiple times,
66 /// and each time it adds a new function to the list
67 /// which will be called after the basic LLVM version
68 /// printing is complete. Each can then add additional
69 /// information specific to the tool.
70 void AddExtraVersionPrinter(void (*func)());
72 // PrintOptionValues - Print option values.
73 // With -print-options print the difference between option values and defaults.
74 // With -print-all-options print all option values.
75 // (Currently not perfect, but best-effort.)
76 void PrintOptionValues();
78 // Forward declaration - AddLiteralOption needs to be up here to make gcc happy.
81 /// \brief Adds a new option for parsing and provides the option it refers to.
83 /// \param O pointer to the option
84 /// \param Name the string name for the option to handle during parsing
86 /// Literal options are used by some parsers to register special option values.
87 /// This is how the PassNameParser registers pass names for opt.
88 void AddLiteralOption(Option &O, const char *Name);
90 //===----------------------------------------------------------------------===//
91 // Flags permitted to be passed to command line arguments
94 enum NumOccurrencesFlag { // Flags for the number of occurrences allowed
95 Optional = 0x00, // Zero or One occurrence
96 ZeroOrMore = 0x01, // Zero or more occurrences allowed
97 Required = 0x02, // One occurrence required
98 OneOrMore = 0x03, // One or more occurrences required
100 // ConsumeAfter - Indicates that this option is fed anything that follows the
101 // last positional argument required by the application (it is an error if
102 // there are zero positional arguments, and a ConsumeAfter option is used).
103 // Thus, for example, all arguments to LLI are processed until a filename is
104 // found. Once a filename is found, all of the succeeding arguments are
105 // passed, unprocessed, to the ConsumeAfter option.
110 enum ValueExpected { // Is a value required for the option?
111 // zero reserved for the unspecified value
112 ValueOptional = 0x01, // The value can appear... or not
113 ValueRequired = 0x02, // The value is required to appear!
114 ValueDisallowed = 0x03 // A value may not be specified (for flags)
117 enum OptionHidden { // Control whether -help shows this option
118 NotHidden = 0x00, // Option included in -help & -help-hidden
119 Hidden = 0x01, // -help doesn't, but -help-hidden does
120 ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg
123 // Formatting flags - This controls special features that the option might have
124 // that cause it to be parsed differently...
126 // Prefix - This option allows arguments that are otherwise unrecognized to be
127 // matched by options that are a prefix of the actual value. This is useful for
128 // cases like a linker, where options are typically of the form '-lfoo' or
129 // '-L../../include' where -l or -L are the actual flags. When prefix is
130 // enabled, and used, the value for the flag comes from the suffix of the
133 // Grouping - With this option enabled, multiple letter options are allowed to
134 // bunch together with only a single hyphen for the whole group. This allows
135 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
138 enum FormattingFlags {
139 NormalFormatting = 0x00, // Nothing special
140 Positional = 0x01, // Is a positional argument, no '-' required
141 Prefix = 0x02, // Can this option directly prefix its value?
142 Grouping = 0x03 // Can this option group with other options?
145 enum MiscFlags { // Miscellaneous flags to adjust argument
146 CommaSeparated = 0x01, // Should this cl::list split between commas?
147 PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args?
148 Sink = 0x04 // Should this cl::list eat all unknown options?
151 //===----------------------------------------------------------------------===//
152 // Option Category class
154 class OptionCategory {
156 const char *const Name;
157 const char *const Description;
158 void registerCategory();
161 OptionCategory(const char *const Name,
162 const char *const Description = nullptr)
163 : Name(Name), Description(Description) {
166 const char *getName() const { return Name; }
167 const char *getDescription() const { return Description; }
170 // The general Option Category (used as default category).
171 extern OptionCategory GeneralCategory;
173 //===----------------------------------------------------------------------===//
180 // handleOccurrences - Overriden by subclasses to handle the value passed into
181 // an argument. Should return true if there was an error processing the
182 // argument and the program should exit.
184 virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
187 virtual enum ValueExpected getValueExpectedFlagDefault() const {
188 return ValueOptional;
191 // Out of line virtual function to provide home for the class.
192 virtual void anchor();
194 int NumOccurrences; // The number of times specified
195 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
196 // problems with signed enums in bitfields.
197 unsigned Occurrences : 3; // enum NumOccurrencesFlag
198 // not using the enum type for 'Value' because zero is an implementation
199 // detail representing the non-value
201 unsigned HiddenFlag : 2; // enum OptionHidden
202 unsigned Formatting : 2; // enum FormattingFlags
204 unsigned Position; // Position of last occurrence of the option
205 unsigned AdditionalVals; // Greater than 0 for multi-valued option.
208 StringRef ArgStr; // The argument string itself (ex: "help", "o")
209 StringRef HelpStr; // The descriptive text message for -help
210 StringRef ValueStr; // String describing what the value of this option is
211 OptionCategory *Category; // The Category this option belongs to
212 bool FullyInitialized; // Has addArguemnt been called?
214 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
215 return (enum NumOccurrencesFlag)Occurrences;
217 inline enum ValueExpected getValueExpectedFlag() const {
218 return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
220 inline enum OptionHidden getOptionHiddenFlag() const {
221 return (enum OptionHidden)HiddenFlag;
223 inline enum FormattingFlags getFormattingFlag() const {
224 return (enum FormattingFlags)Formatting;
226 inline unsigned getMiscFlags() const { return Misc; }
227 inline unsigned getPosition() const { return Position; }
228 inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
230 // hasArgStr - Return true if the argstr != ""
231 bool hasArgStr() const { return !ArgStr.empty(); }
233 //-------------------------------------------------------------------------===
234 // Accessor functions set by OptionModifiers
236 void setArgStr(StringRef S);
237 void setDescription(StringRef S) { HelpStr = S; }
238 void setValueStr(StringRef S) { ValueStr = S; }
239 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
240 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
241 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
242 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
243 void setMiscFlag(enum MiscFlags M) { Misc |= M; }
244 void setPosition(unsigned pos) { Position = pos; }
245 void setCategory(OptionCategory &C) { Category = &C; }
248 explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
249 enum OptionHidden Hidden)
250 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
251 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0),
252 AdditionalVals(0), ArgStr(""), HelpStr(""), ValueStr(""),
253 Category(&GeneralCategory), FullyInitialized(false) {}
255 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
258 // addArgument - Register this argument with the commandline system.
262 /// Unregisters this option from the CommandLine system.
264 /// This option must have been the last option registered.
265 /// For testing purposes only.
266 void removeArgument();
268 // Return the width of the option tag for printing...
269 virtual size_t getOptionWidth() const = 0;
271 // printOptionInfo - Print out information about this option. The
272 // to-be-maintained width is specified.
274 virtual void printOptionInfo(size_t GlobalWidth) const = 0;
276 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
278 virtual void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
280 // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
282 virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
283 bool MultiArg = false);
285 // Prints option name followed by message. Always returns true.
286 bool error(const Twine &Message, StringRef ArgName = StringRef());
289 inline int getNumOccurrences() const { return NumOccurrences; }
293 //===----------------------------------------------------------------------===//
294 // Command line option modifiers that can be used to modify the behavior of
295 // command line option parsers...
298 // desc - Modifier to set the description shown in the -help output...
301 desc(const char *Str) : Desc(Str) {}
302 void apply(Option &O) const { O.setDescription(Desc); }
305 // value_desc - Modifier to set the value description shown in the -help
309 value_desc(const char *Str) : Desc(Str) {}
310 void apply(Option &O) const { O.setValueStr(Desc); }
313 // init - Specify a default (initial) value for the command line argument, if
314 // the default constructor for the argument type does not give you what you
315 // want. This is only valid on "opt" arguments, not on "list" arguments.
317 template <class Ty> struct initializer {
319 initializer(const Ty &Val) : Init(Val) {}
321 template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
324 template <class Ty> initializer<Ty> init(const Ty &Val) {
325 return initializer<Ty>(Val);
328 // location - Allow the user to specify which external variable they want to
329 // store the results of the command line argument processing into, if they don't
330 // want to store it in the option itself.
332 template <class Ty> struct LocationClass {
334 LocationClass(Ty &L) : Loc(L) {}
336 template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
339 template <class Ty> LocationClass<Ty> location(Ty &L) {
340 return LocationClass<Ty>(L);
343 // cat - Specifiy the Option category for the command line argument to belong
346 OptionCategory &Category;
347 cat(OptionCategory &c) : Category(c) {}
349 template <class Opt> void apply(Opt &O) const { O.setCategory(Category); }
352 //===----------------------------------------------------------------------===//
355 // Support value comparison outside the template.
356 struct GenericOptionValue {
357 virtual bool compare(const GenericOptionValue &V) const = 0;
360 ~GenericOptionValue() = default;
361 GenericOptionValue() = default;
362 GenericOptionValue(const GenericOptionValue&) = default;
363 GenericOptionValue &operator=(const GenericOptionValue &) = default;
366 virtual void anchor();
369 template <class DataType> struct OptionValue;
371 // The default value safely does nothing. Option value printing is only
373 template <class DataType, bool isClass>
374 struct OptionValueBase : public GenericOptionValue {
375 // Temporary storage for argument passing.
376 typedef OptionValue<DataType> WrapperType;
378 bool hasValue() const { return false; }
380 const DataType &getValue() const { llvm_unreachable("no default value"); }
382 // Some options may take their value from a different data type.
383 template <class DT> void setValue(const DT & /*V*/) {}
385 bool compare(const DataType & /*V*/) const { return false; }
387 bool compare(const GenericOptionValue & /*V*/) const override {
392 ~OptionValueBase() = default;
395 // Simple copy of the option value.
396 template <class DataType> class OptionValueCopy : public GenericOptionValue {
401 ~OptionValueCopy() = default;
402 OptionValueCopy(const OptionValueCopy&) = default;
403 OptionValueCopy &operator=(const OptionValueCopy&) = default;
406 OptionValueCopy() : Valid(false) {}
408 bool hasValue() const { return Valid; }
410 const DataType &getValue() const {
411 assert(Valid && "invalid option value");
415 void setValue(const DataType &V) {
420 bool compare(const DataType &V) const { return Valid && (Value != V); }
422 bool compare(const GenericOptionValue &V) const override {
423 const OptionValueCopy<DataType> &VC =
424 static_cast<const OptionValueCopy<DataType> &>(V);
427 return compare(VC.getValue());
431 // Non-class option values.
432 template <class DataType>
433 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
434 typedef DataType WrapperType;
437 ~OptionValueBase() = default;
438 OptionValueBase() = default;
439 OptionValueBase(const OptionValueBase&) = default;
440 OptionValueBase &operator=(const OptionValueBase&) = default;
443 // Top-level option class.
444 template <class DataType>
445 struct OptionValue final
446 : OptionValueBase<DataType, std::is_class<DataType>::value> {
447 OptionValue() = default;
449 OptionValue(const DataType &V) { this->setValue(V); }
450 // Some options may take their value from a different data type.
451 template <class DT> OptionValue<DataType> &operator=(const DT &V) {
457 // Other safe-to-copy-by-value common option types.
458 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
460 struct OptionValue<cl::boolOrDefault> final
461 : OptionValueCopy<cl::boolOrDefault> {
462 typedef cl::boolOrDefault WrapperType;
466 OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
467 OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
473 void anchor() override;
477 struct OptionValue<std::string> final : OptionValueCopy<std::string> {
478 typedef StringRef WrapperType;
482 OptionValue(const std::string &V) { this->setValue(V); }
483 OptionValue<std::string> &operator=(const std::string &V) {
489 void anchor() override;
492 //===----------------------------------------------------------------------===//
493 // Enum valued command line option
495 #define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
496 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
497 #define clEnumValEnd (reinterpret_cast<void *>(0))
499 // values - For custom data types, allow specifying a group of values together
500 // as the values that go into the mapping that the option handler uses. Note
501 // that the values list must always have a 0 at the end of the list to indicate
502 // that the list has ended.
504 template <class DataType> class ValuesClass {
505 // Use a vector instead of a map, because the lists should be short,
506 // the overhead is less, and most importantly, it keeps them in the order
507 // inserted so we can print our option out nicely.
508 SmallVector<std::pair<const char *, std::pair<int, const char *>>, 4> Values;
509 void processValues(va_list Vals);
512 ValuesClass(const char *EnumName, DataType Val, const char *Desc,
514 // Insert the first value, which is required.
515 Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
517 // Process the varargs portion of the values...
518 while (const char *enumName = va_arg(ValueArgs, const char *)) {
519 DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
520 const char *EnumDesc = va_arg(ValueArgs, const char *);
521 Values.push_back(std::make_pair(enumName, // Add value to value map
522 std::make_pair(EnumVal, EnumDesc)));
526 template <class Opt> void apply(Opt &O) const {
527 for (size_t i = 0, e = Values.size(); i != e; ++i)
528 O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
529 Values[i].second.second);
533 template <class DataType>
534 ValuesClass<DataType> LLVM_END_WITH_NULL
535 values(const char *Arg, DataType Val, const char *Desc, ...) {
537 va_start(ValueArgs, Desc);
538 ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
543 //===----------------------------------------------------------------------===//
544 // parser class - Parameterizable parser for different data types. By default,
545 // known data types (string, int, bool) have specialized parsers, that do what
546 // you would expect. The default parser, used for data types that are not
547 // built-in, uses a mapping table to map specific options to values, which is
548 // used, among other things, to handle enum types.
550 //--------------------------------------------------
551 // generic_parser_base - This class holds all the non-generic code that we do
552 // not need replicated for every instance of the generic parser. This also
553 // allows us to put stuff into CommandLine.cpp
555 class generic_parser_base {
557 class GenericOptionInfo {
559 GenericOptionInfo(const char *name, const char *helpStr)
560 : Name(name), HelpStr(helpStr) {}
566 generic_parser_base(Option &O) : Owner(O) {}
568 virtual ~generic_parser_base() {} // Base class should have virtual-dtor
570 // getNumOptions - Virtual function implemented by generic subclass to
571 // indicate how many entries are in Values.
573 virtual unsigned getNumOptions() const = 0;
575 // getOption - Return option name N.
576 virtual const char *getOption(unsigned N) const = 0;
578 // getDescription - Return description N
579 virtual const char *getDescription(unsigned N) const = 0;
581 // Return the width of the option tag for printing...
582 virtual size_t getOptionWidth(const Option &O) const;
584 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
586 // printOptionInfo - Print out information about this option. The
587 // to-be-maintained width is specified.
589 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
591 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
592 const GenericOptionValue &Default,
593 size_t GlobalWidth) const;
595 // printOptionDiff - print the value of an option and it's default.
597 // Template definition ensures that the option and default have the same
598 // DataType (via the same AnyOptionValue).
599 template <class AnyOptionValue>
600 void printOptionDiff(const Option &O, const AnyOptionValue &V,
601 const AnyOptionValue &Default,
602 size_t GlobalWidth) const {
603 printGenericOptionDiff(O, V, Default, GlobalWidth);
608 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) {
609 // If there has been no argstr specified, that means that we need to add an
610 // argument for every possible option. This ensures that our options are
612 if (!Owner.hasArgStr())
613 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
614 OptionNames.push_back(getOption(i));
617 enum ValueExpected getValueExpectedFlagDefault() const {
618 // If there is an ArgStr specified, then we are of the form:
620 // -opt=O2 or -opt O2 or -optO2
622 // In which case, the value is required. Otherwise if an arg str has not
623 // been specified, we are of the form:
625 // -O2 or O2 or -la (where -l and -a are separate options)
627 // If this is the case, we cannot allow a value.
629 if (Owner.hasArgStr())
630 return ValueRequired;
632 return ValueDisallowed;
635 // findOption - Return the option number corresponding to the specified
636 // argument string. If the option is not found, getNumOptions() is returned.
638 unsigned findOption(const char *Name);
644 // Default parser implementation - This implementation depends on having a
645 // mapping of recognized options to values of some sort. In addition to this,
646 // each entry in the mapping also tracks a help message that is printed with the
647 // command line option for -help. Because this is a simple mapping parser, the
648 // data type can be any unsupported type.
650 template <class DataType> class parser : public generic_parser_base {
652 class OptionInfo : public GenericOptionInfo {
654 OptionInfo(const char *name, DataType v, const char *helpStr)
655 : GenericOptionInfo(name, helpStr), V(v) {}
656 OptionValue<DataType> V;
658 SmallVector<OptionInfo, 8> Values;
661 parser(Option &O) : generic_parser_base(O) {}
662 typedef DataType parser_data_type;
664 // Implement virtual functions needed by generic_parser_base
665 unsigned getNumOptions() const override { return unsigned(Values.size()); }
666 const char *getOption(unsigned N) const override { return Values[N].Name; }
667 const char *getDescription(unsigned N) const override {
668 return Values[N].HelpStr;
671 // getOptionValue - Return the value of option name N.
672 const GenericOptionValue &getOptionValue(unsigned N) const override {
676 // parse - Return true on error.
677 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
679 if (Owner.hasArgStr())
684 for (size_t i = 0, e = Values.size(); i != e; ++i)
685 if (Values[i].Name == ArgVal) {
686 V = Values[i].V.getValue();
690 return O.error("Cannot find option named '" + ArgVal + "'!");
693 /// addLiteralOption - Add an entry to the mapping table.
696 void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
697 assert(findOption(Name) == Values.size() && "Option already exists!");
698 OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
700 AddLiteralOption(Owner, Name);
703 /// removeLiteralOption - Remove the specified option.
705 void removeLiteralOption(const char *Name) {
706 unsigned N = findOption(Name);
707 assert(N != Values.size() && "Option not found!");
708 Values.erase(Values.begin() + N);
712 //--------------------------------------------------
713 // basic_parser - Super class of parsers to provide boilerplate code
715 class basic_parser_impl { // non-template implementation of basic_parser<t>
717 basic_parser_impl(Option &) {}
720 enum ValueExpected getValueExpectedFlagDefault() const {
721 return ValueRequired;
724 void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
728 // Return the width of the option tag for printing...
729 size_t getOptionWidth(const Option &O) const;
731 // printOptionInfo - Print out information about this option. The
732 // to-be-maintained width is specified.
734 void printOptionInfo(const Option &O, size_t GlobalWidth) const;
736 // printOptionNoValue - Print a placeholder for options that don't yet support
737 // printOptionDiff().
738 void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
740 // getValueName - Overload in subclass to provide a better default value.
741 virtual const char *getValueName() const { return "value"; }
743 // An out-of-line virtual method to provide a 'home' for this class.
744 virtual void anchor();
747 ~basic_parser_impl() = default;
748 // A helper for basic_parser::printOptionDiff.
749 void printOptionName(const Option &O, size_t GlobalWidth) const;
752 // basic_parser - The real basic parser is just a template wrapper that provides
753 // a typedef for the provided data type.
755 template <class DataType> class basic_parser : public basic_parser_impl {
757 basic_parser(Option &O) : basic_parser_impl(O) {}
758 typedef DataType parser_data_type;
759 typedef OptionValue<DataType> OptVal;
762 // Workaround Clang PR22793
766 //--------------------------------------------------
769 template <> class parser<bool> final : public basic_parser<bool> {
771 parser(Option &O) : basic_parser(O) {}
773 // parse - Return true on error.
774 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
778 enum ValueExpected getValueExpectedFlagDefault() const {
779 return ValueOptional;
782 // getValueName - Do not print =<value> at all.
783 const char *getValueName() const override { return nullptr; }
785 void printOptionDiff(const Option &O, bool V, OptVal Default,
786 size_t GlobalWidth) const;
788 // An out-of-line virtual method to provide a 'home' for this class.
789 void anchor() override;
792 extern template class basic_parser<bool>;
794 //--------------------------------------------------
795 // parser<boolOrDefault>
797 class parser<boolOrDefault> final : public basic_parser<boolOrDefault> {
799 parser(Option &O) : basic_parser(O) {}
801 // parse - Return true on error.
802 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
804 enum ValueExpected getValueExpectedFlagDefault() const {
805 return ValueOptional;
808 // getValueName - Do not print =<value> at all.
809 const char *getValueName() const override { return nullptr; }
811 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
812 size_t GlobalWidth) const;
814 // An out-of-line virtual method to provide a 'home' for this class.
815 void anchor() override;
818 extern template class basic_parser<boolOrDefault>;
820 //--------------------------------------------------
823 template <> class parser<int> final : public basic_parser<int> {
825 parser(Option &O) : basic_parser(O) {}
827 // parse - Return true on error.
828 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
830 // getValueName - Overload in subclass to provide a better default value.
831 const char *getValueName() const override { return "int"; }
833 void printOptionDiff(const Option &O, int V, OptVal Default,
834 size_t GlobalWidth) const;
836 // An out-of-line virtual method to provide a 'home' for this class.
837 void anchor() override;
840 extern template class basic_parser<int>;
842 //--------------------------------------------------
845 template <> class parser<unsigned> final : public basic_parser<unsigned> {
847 parser(Option &O) : basic_parser(O) {}
849 // parse - Return true on error.
850 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
852 // getValueName - Overload in subclass to provide a better default value.
853 const char *getValueName() const override { return "uint"; }
855 void printOptionDiff(const Option &O, unsigned V, OptVal Default,
856 size_t GlobalWidth) const;
858 // An out-of-line virtual method to provide a 'home' for this class.
859 void anchor() override;
862 extern template class basic_parser<unsigned>;
864 //--------------------------------------------------
865 // parser<unsigned long long>
868 class parser<unsigned long long> final
869 : public basic_parser<unsigned long long> {
871 parser(Option &O) : basic_parser(O) {}
873 // parse - Return true on error.
874 bool parse(Option &O, StringRef ArgName, StringRef Arg,
875 unsigned long long &Val);
877 // getValueName - Overload in subclass to provide a better default value.
878 const char *getValueName() const override { return "uint"; }
880 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
881 size_t GlobalWidth) const;
883 // An out-of-line virtual method to provide a 'home' for this class.
884 void anchor() override;
887 extern template class basic_parser<unsigned long long>;
889 //--------------------------------------------------
892 template <> class parser<double> final : public basic_parser<double> {
894 parser(Option &O) : basic_parser(O) {}
896 // parse - Return true on error.
897 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
899 // getValueName - Overload in subclass to provide a better default value.
900 const char *getValueName() const override { return "number"; }
902 void printOptionDiff(const Option &O, double V, OptVal Default,
903 size_t GlobalWidth) const;
905 // An out-of-line virtual method to provide a 'home' for this class.
906 void anchor() override;
909 extern template class basic_parser<double>;
911 //--------------------------------------------------
914 template <> class parser<float> final : public basic_parser<float> {
916 parser(Option &O) : basic_parser(O) {}
918 // parse - Return true on error.
919 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
921 // getValueName - Overload in subclass to provide a better default value.
922 const char *getValueName() const override { return "number"; }
924 void printOptionDiff(const Option &O, float V, OptVal Default,
925 size_t GlobalWidth) const;
927 // An out-of-line virtual method to provide a 'home' for this class.
928 void anchor() override;
931 extern template class basic_parser<float>;
933 //--------------------------------------------------
934 // parser<std::string>
936 template <> class parser<std::string> final : public basic_parser<std::string> {
938 parser(Option &O) : basic_parser(O) {}
940 // parse - Return true on error.
941 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
946 // getValueName - Overload in subclass to provide a better default value.
947 const char *getValueName() const override { return "string"; }
949 void printOptionDiff(const Option &O, StringRef V, OptVal Default,
950 size_t GlobalWidth) const;
952 // An out-of-line virtual method to provide a 'home' for this class.
953 void anchor() override;
956 extern template class basic_parser<std::string>;
958 //--------------------------------------------------
961 template <> class parser<char> final : public basic_parser<char> {
963 parser(Option &O) : basic_parser(O) {}
965 // parse - Return true on error.
966 bool parse(Option &, StringRef, StringRef Arg, char &Value) {
971 // getValueName - Overload in subclass to provide a better default value.
972 const char *getValueName() const override { return "char"; }
974 void printOptionDiff(const Option &O, char V, OptVal Default,
975 size_t GlobalWidth) const;
977 // An out-of-line virtual method to provide a 'home' for this class.
978 void anchor() override;
981 extern template class basic_parser<char>;
983 //--------------------------------------------------
986 // This collection of wrappers is the intermediary between class opt and class
987 // parser to handle all the template nastiness.
989 // This overloaded function is selected by the generic parser.
990 template <class ParserClass, class DT>
991 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
992 const OptionValue<DT> &Default, size_t GlobalWidth) {
993 OptionValue<DT> OV = V;
994 P.printOptionDiff(O, OV, Default, GlobalWidth);
997 // This is instantiated for basic parsers when the parsed value has a different
998 // type than the option value. e.g. HelpPrinter.
999 template <class ParserDT, class ValDT> struct OptionDiffPrinter {
1000 void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/,
1001 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
1002 P.printOptionNoValue(O, GlobalWidth);
1006 // This is instantiated for basic parsers when the parsed value has the same
1007 // type as the option value.
1008 template <class DT> struct OptionDiffPrinter<DT, DT> {
1009 void print(const Option &O, const parser<DT> &P, const DT &V,
1010 const OptionValue<DT> &Default, size_t GlobalWidth) {
1011 P.printOptionDiff(O, V, Default, GlobalWidth);
1015 // This overloaded function is selected by the basic parser, which may parse a
1016 // different type than the option type.
1017 template <class ParserClass, class ValDT>
1018 void printOptionDiff(
1020 const basic_parser<typename ParserClass::parser_data_type> &P,
1021 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
1023 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
1024 printer.print(O, static_cast<const ParserClass &>(P), V, Default,
1028 //===----------------------------------------------------------------------===//
1029 // applicator class - This class is used because we must use partial
1030 // specialization to handle literal string arguments specially (const char* does
1031 // not correctly respond to the apply method). Because the syntax to use this
1032 // is a pain, we have the 'apply' method below to handle the nastiness...
1034 template <class Mod> struct applicator {
1035 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1038 // Handle const char* as a special case...
1039 template <unsigned n> struct applicator<char[n]> {
1040 template <class Opt> static void opt(const char *Str, Opt &O) {
1044 template <unsigned n> struct applicator<const char[n]> {
1045 template <class Opt> static void opt(const char *Str, Opt &O) {
1049 template <> struct applicator<const char *> {
1050 template <class Opt> static void opt(const char *Str, Opt &O) {
1055 template <> struct applicator<NumOccurrencesFlag> {
1056 static void opt(NumOccurrencesFlag N, Option &O) {
1057 O.setNumOccurrencesFlag(N);
1060 template <> struct applicator<ValueExpected> {
1061 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1063 template <> struct applicator<OptionHidden> {
1064 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1066 template <> struct applicator<FormattingFlags> {
1067 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1069 template <> struct applicator<MiscFlags> {
1070 static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1073 // apply method - Apply modifiers to an option in a type safe way.
1074 template <class Opt, class Mod, class... Mods>
1075 void apply(Opt *O, const Mod &M, const Mods &... Ms) {
1076 applicator<Mod>::opt(M, *O);
1080 template <class Opt, class Mod> void apply(Opt *O, const Mod &M) {
1081 applicator<Mod>::opt(M, *O);
1084 //===----------------------------------------------------------------------===//
1085 // opt_storage class
1087 // Default storage class definition: external storage. This implementation
1088 // assumes the user will specify a variable to store the data into with the
1089 // cl::location(x) modifier.
1091 template <class DataType, bool ExternalStorage, bool isClass>
1093 DataType *Location; // Where to store the object...
1094 OptionValue<DataType> Default;
1096 void check_location() const {
1097 assert(Location && "cl::location(...) not specified for a command "
1098 "line option with external storage, "
1099 "or cl::init specified before cl::location()!!");
1103 opt_storage() : Location(nullptr) {}
1105 bool setLocation(Option &O, DataType &L) {
1107 return O.error("cl::location(x) specified more than once!");
1113 template <class T> void setValue(const T &V, bool initial = false) {
1120 DataType &getValue() {
1124 const DataType &getValue() const {
1129 operator DataType() const { return this->getValue(); }
1131 const OptionValue<DataType> &getDefault() const { return Default; }
1134 // Define how to hold a class type object, such as a string. Since we can
1135 // inherit from a class, we do so. This makes us exactly compatible with the
1136 // object in all cases that it is used.
1138 template <class DataType>
1139 class opt_storage<DataType, false, true> : public DataType {
1141 OptionValue<DataType> Default;
1143 template <class T> void setValue(const T &V, bool initial = false) {
1144 DataType::operator=(V);
1149 DataType &getValue() { return *this; }
1150 const DataType &getValue() const { return *this; }
1152 const OptionValue<DataType> &getDefault() const { return Default; }
1155 // Define a partial specialization to handle things we cannot inherit from. In
1156 // this case, we store an instance through containment, and overload operators
1157 // to get at the value.
1159 template <class DataType> class opt_storage<DataType, false, false> {
1162 OptionValue<DataType> Default;
1164 // Make sure we initialize the value with the default constructor for the
1166 opt_storage() : Value(DataType()), Default(DataType()) {}
1168 template <class T> void setValue(const T &V, bool initial = false) {
1173 DataType &getValue() { return Value; }
1174 DataType getValue() const { return Value; }
1176 const OptionValue<DataType> &getDefault() const { return Default; }
1178 operator DataType() const { return getValue(); }
1180 // If the datatype is a pointer, support -> on it.
1181 DataType operator->() const { return Value; }
1184 //===----------------------------------------------------------------------===//
1185 // opt - A scalar command line option.
1187 template <class DataType, bool ExternalStorage = false,
1188 class ParserClass = parser<DataType>>
1189 class opt : public Option,
1190 public opt_storage<DataType, ExternalStorage,
1191 std::is_class<DataType>::value> {
1194 bool handleOccurrence(unsigned pos, StringRef ArgName,
1195 StringRef Arg) override {
1196 typename ParserClass::parser_data_type Val =
1197 typename ParserClass::parser_data_type();
1198 if (Parser.parse(*this, ArgName, Arg, Val))
1199 return true; // Parse error!
1200 this->setValue(Val);
1201 this->setPosition(pos);
1205 enum ValueExpected getValueExpectedFlagDefault() const override {
1206 return Parser.getValueExpectedFlagDefault();
1208 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1209 return Parser.getExtraOptionNames(OptionNames);
1212 // Forward printing stuff to the parser...
1213 size_t getOptionWidth() const override {
1214 return Parser.getOptionWidth(*this);
1216 void printOptionInfo(size_t GlobalWidth) const override {
1217 Parser.printOptionInfo(*this, GlobalWidth);
1220 void printOptionValue(size_t GlobalWidth, bool Force) const override {
1221 if (Force || this->getDefault().compare(this->getValue())) {
1222 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1223 this->getDefault(), GlobalWidth);
1229 Parser.initialize();
1232 // Command line options should not be copyable
1233 opt(const opt &) = delete;
1234 opt &operator=(const opt &) = delete;
1237 // setInitialValue - Used by the cl::init modifier...
1238 void setInitialValue(const DataType &V) { this->setValue(V, true); }
1240 ParserClass &getParser() { return Parser; }
1242 template <class T> DataType &operator=(const T &Val) {
1243 this->setValue(Val);
1244 return this->getValue();
1247 template <class... Mods>
1248 explicit opt(const Mods &... Ms)
1249 : Option(Optional, NotHidden), Parser(*this) {
1255 extern template class opt<unsigned>;
1256 extern template class opt<int>;
1257 extern template class opt<std::string>;
1258 extern template class opt<char>;
1259 extern template class opt<bool>;
1261 //===----------------------------------------------------------------------===//
1262 // list_storage class
1264 // Default storage class definition: external storage. This implementation
1265 // assumes the user will specify a variable to store the data into with the
1266 // cl::location(x) modifier.
1268 template <class DataType, class StorageClass> class list_storage {
1269 StorageClass *Location; // Where to store the object...
1272 list_storage() : Location(0) {}
1274 bool setLocation(Option &O, StorageClass &L) {
1276 return O.error("cl::location(x) specified more than once!");
1281 template <class T> void addValue(const T &V) {
1282 assert(Location != 0 && "cl::location(...) not specified for a command "
1283 "line option with external storage!");
1284 Location->push_back(V);
1288 // Define how to hold a class type object, such as a string.
1289 // Originally this code inherited from std::vector. In transitioning to a new
1290 // API for command line options we should change this. The new implementation
1291 // of this list_storage specialization implements the minimum subset of the
1292 // std::vector API required for all the current clients.
1294 // FIXME: Reduce this API to a more narrow subset of std::vector
1296 template <class DataType> class list_storage<DataType, bool> {
1297 std::vector<DataType> Storage;
1300 typedef typename std::vector<DataType>::iterator iterator;
1302 iterator begin() { return Storage.begin(); }
1303 iterator end() { return Storage.end(); }
1305 typedef typename std::vector<DataType>::const_iterator const_iterator;
1306 const_iterator begin() const { return Storage.begin(); }
1307 const_iterator end() const { return Storage.end(); }
1309 typedef typename std::vector<DataType>::size_type size_type;
1310 size_type size() const { return Storage.size(); }
1312 bool empty() const { return Storage.empty(); }
1314 void push_back(const DataType &value) { Storage.push_back(value); }
1315 void push_back(DataType &&value) { Storage.push_back(value); }
1317 typedef typename std::vector<DataType>::reference reference;
1318 typedef typename std::vector<DataType>::const_reference const_reference;
1319 reference operator[](size_type pos) { return Storage[pos]; }
1320 const_reference operator[](size_type pos) const { return Storage[pos]; }
1322 iterator erase(const_iterator pos) { return Storage.erase(pos); }
1323 iterator erase(const_iterator first, const_iterator last) {
1324 return Storage.erase(first, last);
1327 iterator erase(iterator pos) { return Storage.erase(pos); }
1328 iterator erase(iterator first, iterator last) {
1329 return Storage.erase(first, last);
1332 iterator insert(const_iterator pos, const DataType &value) {
1333 return Storage.insert(pos, value);
1335 iterator insert(const_iterator pos, DataType &&value) {
1336 return Storage.insert(pos, value);
1339 iterator insert(iterator pos, const DataType &value) {
1340 return Storage.insert(pos, value);
1342 iterator insert(iterator pos, DataType &&value) {
1343 return Storage.insert(pos, value);
1346 reference front() { return Storage.front(); }
1347 const_reference front() const { return Storage.front(); }
1349 operator std::vector<DataType>&() { return Storage; }
1350 operator ArrayRef<DataType>() { return Storage; }
1351 std::vector<DataType> *operator&() { return &Storage; }
1352 const std::vector<DataType> *operator&() const { return &Storage; }
1354 template <class T> void addValue(const T &V) { Storage.push_back(V); }
1357 //===----------------------------------------------------------------------===//
1358 // list - A list of command line options.
1360 template <class DataType, class StorageClass = bool,
1361 class ParserClass = parser<DataType>>
1362 class list : public Option, public list_storage<DataType, StorageClass> {
1363 std::vector<unsigned> Positions;
1366 enum ValueExpected getValueExpectedFlagDefault() const override {
1367 return Parser.getValueExpectedFlagDefault();
1369 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1370 return Parser.getExtraOptionNames(OptionNames);
1373 bool handleOccurrence(unsigned pos, StringRef ArgName,
1374 StringRef Arg) override {
1375 typename ParserClass::parser_data_type Val =
1376 typename ParserClass::parser_data_type();
1377 if (Parser.parse(*this, ArgName, Arg, Val))
1378 return true; // Parse Error!
1379 list_storage<DataType, StorageClass>::addValue(Val);
1381 Positions.push_back(pos);
1385 // Forward printing stuff to the parser...
1386 size_t getOptionWidth() const override {
1387 return Parser.getOptionWidth(*this);
1389 void printOptionInfo(size_t GlobalWidth) const override {
1390 Parser.printOptionInfo(*this, GlobalWidth);
1393 // Unimplemented: list options don't currently store their default value.
1394 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1399 Parser.initialize();
1402 // Command line options should not be copyable
1403 list(const list &) = delete;
1404 list &operator=(const list &) = delete;
1407 ParserClass &getParser() { return Parser; }
1409 unsigned getPosition(unsigned optnum) const {
1410 assert(optnum < this->size() && "Invalid option index");
1411 return Positions[optnum];
1414 void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
1416 template <class... Mods>
1417 explicit list(const Mods &... Ms)
1418 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1424 // multi_val - Modifier to set the number of additional values.
1426 unsigned AdditionalVals;
1427 explicit multi_val(unsigned N) : AdditionalVals(N) {}
1429 template <typename D, typename S, typename P>
1430 void apply(list<D, S, P> &L) const {
1431 L.setNumAdditionalVals(AdditionalVals);
1435 //===----------------------------------------------------------------------===//
1436 // bits_storage class
1438 // Default storage class definition: external storage. This implementation
1439 // assumes the user will specify a variable to store the data into with the
1440 // cl::location(x) modifier.
1442 template <class DataType, class StorageClass> class bits_storage {
1443 unsigned *Location; // Where to store the bits...
1445 template <class T> static unsigned Bit(const T &V) {
1446 unsigned BitPos = reinterpret_cast<unsigned>(V);
1447 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1448 "enum exceeds width of bit vector!");
1453 bits_storage() : Location(nullptr) {}
1455 bool setLocation(Option &O, unsigned &L) {
1457 return O.error("cl::location(x) specified more than once!");
1462 template <class T> void addValue(const T &V) {
1463 assert(Location != 0 && "cl::location(...) not specified for a command "
1464 "line option with external storage!");
1465 *Location |= Bit(V);
1468 unsigned getBits() { return *Location; }
1470 template <class T> bool isSet(const T &V) {
1471 return (*Location & Bit(V)) != 0;
1475 // Define how to hold bits. Since we can inherit from a class, we do so.
1476 // This makes us exactly compatible with the bits in all cases that it is used.
1478 template <class DataType> class bits_storage<DataType, bool> {
1479 unsigned Bits; // Where to store the bits...
1481 template <class T> static unsigned Bit(const T &V) {
1482 unsigned BitPos = (unsigned)V;
1483 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1484 "enum exceeds width of bit vector!");
1489 template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1491 unsigned getBits() { return Bits; }
1493 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1496 //===----------------------------------------------------------------------===//
1497 // bits - A bit vector of command options.
1499 template <class DataType, class Storage = bool,
1500 class ParserClass = parser<DataType>>
1501 class bits : public Option, public bits_storage<DataType, Storage> {
1502 std::vector<unsigned> Positions;
1505 enum ValueExpected getValueExpectedFlagDefault() const override {
1506 return Parser.getValueExpectedFlagDefault();
1508 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1509 return Parser.getExtraOptionNames(OptionNames);
1512 bool handleOccurrence(unsigned pos, StringRef ArgName,
1513 StringRef Arg) override {
1514 typename ParserClass::parser_data_type Val =
1515 typename ParserClass::parser_data_type();
1516 if (Parser.parse(*this, ArgName, Arg, Val))
1517 return true; // Parse Error!
1518 this->addValue(Val);
1520 Positions.push_back(pos);
1524 // Forward printing stuff to the parser...
1525 size_t getOptionWidth() const override {
1526 return Parser.getOptionWidth(*this);
1528 void printOptionInfo(size_t GlobalWidth) const override {
1529 Parser.printOptionInfo(*this, GlobalWidth);
1532 // Unimplemented: bits options don't currently store their default values.
1533 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1538 Parser.initialize();
1541 // Command line options should not be copyable
1542 bits(const bits &) = delete;
1543 bits &operator=(const bits &) = delete;
1546 ParserClass &getParser() { return Parser; }
1548 unsigned getPosition(unsigned optnum) const {
1549 assert(optnum < this->size() && "Invalid option index");
1550 return Positions[optnum];
1553 template <class... Mods>
1554 explicit bits(const Mods &... Ms)
1555 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1561 //===----------------------------------------------------------------------===//
1562 // Aliased command line option (alias this name to a preexisting name)
1565 class alias : public Option {
1567 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1568 StringRef Arg) override {
1569 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1571 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1572 bool MultiArg = false) override {
1573 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1575 // Handle printing stuff...
1576 size_t getOptionWidth() const override;
1577 void printOptionInfo(size_t GlobalWidth) const override;
1579 // Aliases do not need to print their values.
1580 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1583 ValueExpected getValueExpectedFlagDefault() const override {
1584 return AliasFor->getValueExpectedFlag();
1589 error("cl::alias must have argument name specified!");
1591 error("cl::alias must have an cl::aliasopt(option) specified!");
1595 // Command line options should not be copyable
1596 alias(const alias &) = delete;
1597 alias &operator=(const alias &) = delete;
1600 void setAliasFor(Option &O) {
1602 error("cl::alias must only have one cl::aliasopt(...) specified!");
1606 template <class... Mods>
1607 explicit alias(const Mods &... Ms)
1608 : Option(Optional, Hidden), AliasFor(nullptr) {
1614 // aliasfor - Modifier to set the option an alias aliases.
1617 explicit aliasopt(Option &O) : Opt(O) {}
1618 void apply(alias &A) const { A.setAliasFor(Opt); }
1621 // extrahelp - provide additional help at the end of the normal help
1622 // output. All occurrences of cl::extrahelp will be accumulated and
1623 // printed to stderr at the end of the regular help, just before
1626 const char *morehelp;
1627 explicit extrahelp(const char *help);
1630 void PrintVersionMessage();
1632 /// This function just prints the help message, exactly the same way as if the
1633 /// -help or -help-hidden option had been given on the command line.
1635 /// NOTE: THIS FUNCTION TERMINATES THE PROGRAM!
1637 /// \param Hidden if true will print hidden options
1638 /// \param Categorized if true print options in categories
1639 void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
1641 //===----------------------------------------------------------------------===//
1642 // Public interface for accessing registered options.
1645 /// \brief Use this to get a StringMap to all registered named options
1646 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1648 /// \return A reference to the StringMap used by the cl APIs to parse options.
1650 /// Access to unnamed arguments (i.e. positional) are not provided because
1651 /// it is expected that the client already has access to these.
1655 /// main(int argc,char* argv[]) {
1656 /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions();
1657 /// assert(opts.count("help") == 1)
1658 /// opts["help"]->setDescription("Show alphabetical help information")
1660 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1665 /// This interface is useful for modifying options in libraries that are out of
1666 /// the control of the client. The options should be modified before calling
1667 /// llvm::cl::ParseCommandLineOptions().
1669 /// Hopefully this API can be depricated soon. Any situation where options need
1670 /// to be modified by tools or libraries should be handled by sane APIs rather
1671 /// than just handing around a global list.
1672 StringMap<Option *> &getRegisteredOptions();
1674 //===----------------------------------------------------------------------===//
1675 // Standalone command line processing utilities.
1678 /// \brief Tokenizes a command line that can contain escapes and quotes.
1680 /// The quoting rules match those used by GCC and other tools that use
1681 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1682 /// They differ from buildargv() on treatment of backslashes that do not escape
1683 /// a special character to make it possible to accept most Windows file paths.
1685 /// \param [in] Source The string to be split on whitespace with quotes.
1686 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1687 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1688 /// lines and end of the response file to be marked with a nullptr string.
1689 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1690 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
1691 SmallVectorImpl<const char *> &NewArgv,
1692 bool MarkEOLs = false);
1694 /// \brief Tokenizes a Windows command line which may contain quotes and escaped
1697 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1698 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1700 /// \param [in] Source The string to be split on whitespace with quotes.
1701 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1702 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1703 /// lines and end of the response file to be marked with a nullptr string.
1704 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1705 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
1706 SmallVectorImpl<const char *> &NewArgv,
1707 bool MarkEOLs = false);
1709 /// \brief String tokenization function type. Should be compatible with either
1710 /// Windows or Unix command line tokenizers.
1711 typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
1712 SmallVectorImpl<const char *> &NewArgv,
1715 /// \brief Expand response files on a command line recursively using the given
1716 /// StringSaver and tokenization strategy. Argv should contain the command line
1717 /// before expansion and will be modified in place. If requested, Argv will
1718 /// also be populated with nullptrs indicating where each response file line
1719 /// ends, which is useful for the "/link" argument that needs to consume all
1720 /// remaining arguments only until the next end of line, when in a response
1723 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1724 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1725 /// \param [in,out] Argv Command line into which to expand response files.
1726 /// \param [in] MarkEOLs Mark end of lines and the end of the response file
1727 /// with nullptrs in the Argv vector.
1728 /// \return true if all @files were expanded successfully or there were none.
1729 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1730 SmallVectorImpl<const char *> &Argv,
1731 bool MarkEOLs = false);
1733 /// \brief Mark all options not part of this category as cl::ReallyHidden.
1735 /// \param Category the category of options to keep displaying
1737 /// Some tools (like clang-format) like to be able to hide all options that are
1738 /// not specific to the tool. This function allows a tool to specify a single
1739 /// option category to display in the -help output.
1740 void HideUnrelatedOptions(cl::OptionCategory &Category);
1742 /// \brief Mark all options not part of the categories as cl::ReallyHidden.
1744 /// \param Categories the categories of options to keep displaying.
1746 /// Some tools (like clang-format) like to be able to hide all options that are
1747 /// not specific to the tool. This function allows a tool to specify a single
1748 /// option category to display in the -help output.
1749 void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories);
1751 } // End namespace cl
1753 } // End namespace llvm