Recommit [NFC] Better encapsulation of llvm::Optional Storage
[llvm-complete.git] / include / llvm / Support / CommandLine.h
bloba78020f010fa082168c68f62557fe2a36ed8b830
1 //===- llvm/Support/CommandLine.h - Command line handler --------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This class implements a command line argument processor that is useful when
10 // creating a tool. It provides a simple, minimalistic interface that is easily
11 // extensible and supports nonlocal (library) command line options.
13 // Note that rather than trying to figure out what this code does, you should
14 // read the library documentation located in docs/CommandLine.html or looks at
15 // the many example usages in tools/*/*.cpp
17 //===----------------------------------------------------------------------===//
19 #ifndef LLVM_SUPPORT_COMMANDLINE_H
20 #define LLVM_SUPPORT_COMMANDLINE_H
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/ADT/iterator_range.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <cassert>
34 #include <climits>
35 #include <cstddef>
36 #include <functional>
37 #include <initializer_list>
38 #include <string>
39 #include <type_traits>
40 #include <vector>
42 namespace llvm {
44 class StringSaver;
45 class raw_ostream;
47 /// cl Namespace - This namespace contains all of the command line option
48 /// processing machinery. It is intentionally a short name to make qualified
49 /// usage concise.
50 namespace cl {
52 //===----------------------------------------------------------------------===//
53 // ParseCommandLineOptions - Command line option processing entry point.
55 // Returns true on success. Otherwise, this will print the error message to
56 // stderr and exit if \p Errs is not set (nullptr by default), or print the
57 // error message to \p Errs and return false if \p Errs is provided.
59 // If EnvVar is not nullptr, command-line options are also parsed from the
60 // environment variable named by EnvVar. Precedence is given to occurrences
61 // from argv. This precedence is currently implemented by parsing argv after
62 // the environment variable, so it is only implemented correctly for options
63 // that give precedence to later occurrences. If your program supports options
64 // that give precedence to earlier occurrences, you will need to extend this
65 // function to support it correctly.
66 bool ParseCommandLineOptions(int argc, const char *const *argv,
67 StringRef Overview = "",
68 raw_ostream *Errs = nullptr,
69 const char *EnvVar = nullptr);
71 //===----------------------------------------------------------------------===//
72 // ParseEnvironmentOptions - Environment variable option processing alternate
73 // entry point.
75 void ParseEnvironmentOptions(const char *progName, const char *envvar,
76 const char *Overview = "");
78 // Function pointer type for printing version information.
79 using VersionPrinterTy = std::function<void(raw_ostream &)>;
81 ///===---------------------------------------------------------------------===//
82 /// SetVersionPrinter - Override the default (LLVM specific) version printer
83 /// used to print out the version when --version is given
84 /// on the command line. This allows other systems using the
85 /// CommandLine utilities to print their own version string.
86 void SetVersionPrinter(VersionPrinterTy func);
88 ///===---------------------------------------------------------------------===//
89 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
90 /// default one. This can be called multiple times,
91 /// and each time it adds a new function to the list
92 /// which will be called after the basic LLVM version
93 /// printing is complete. Each can then add additional
94 /// information specific to the tool.
95 void AddExtraVersionPrinter(VersionPrinterTy func);
97 // PrintOptionValues - Print option values.
98 // With -print-options print the difference between option values and defaults.
99 // With -print-all-options print all option values.
100 // (Currently not perfect, but best-effort.)
101 void PrintOptionValues();
103 // Forward declaration - AddLiteralOption needs to be up here to make gcc happy.
104 class Option;
106 /// Adds a new option for parsing and provides the option it refers to.
108 /// \param O pointer to the option
109 /// \param Name the string name for the option to handle during parsing
111 /// Literal options are used by some parsers to register special option values.
112 /// This is how the PassNameParser registers pass names for opt.
113 void AddLiteralOption(Option &O, StringRef Name);
115 //===----------------------------------------------------------------------===//
116 // Flags permitted to be passed to command line arguments
119 enum NumOccurrencesFlag { // Flags for the number of occurrences allowed
120 Optional = 0x00, // Zero or One occurrence
121 ZeroOrMore = 0x01, // Zero or more occurrences allowed
122 Required = 0x02, // One occurrence required
123 OneOrMore = 0x03, // One or more occurrences required
125 // ConsumeAfter - Indicates that this option is fed anything that follows the
126 // last positional argument required by the application (it is an error if
127 // there are zero positional arguments, and a ConsumeAfter option is used).
128 // Thus, for example, all arguments to LLI are processed until a filename is
129 // found. Once a filename is found, all of the succeeding arguments are
130 // passed, unprocessed, to the ConsumeAfter option.
132 ConsumeAfter = 0x04
135 enum ValueExpected { // Is a value required for the option?
136 // zero reserved for the unspecified value
137 ValueOptional = 0x01, // The value can appear... or not
138 ValueRequired = 0x02, // The value is required to appear!
139 ValueDisallowed = 0x03 // A value may not be specified (for flags)
142 enum OptionHidden { // Control whether -help shows this option
143 NotHidden = 0x00, // Option included in -help & -help-hidden
144 Hidden = 0x01, // -help doesn't, but -help-hidden does
145 ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg
148 // Formatting flags - This controls special features that the option might have
149 // that cause it to be parsed differently...
151 // Prefix - This option allows arguments that are otherwise unrecognized to be
152 // matched by options that are a prefix of the actual value. This is useful for
153 // cases like a linker, where options are typically of the form '-lfoo' or
154 // '-L../../include' where -l or -L are the actual flags. When prefix is
155 // enabled, and used, the value for the flag comes from the suffix of the
156 // argument.
158 // AlwaysPrefix - Only allow the behavior enabled by the Prefix flag and reject
159 // the Option=Value form.
161 // Grouping - With this option enabled, multiple letter options are allowed to
162 // bunch together with only a single hyphen for the whole group. This allows
163 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
166 enum FormattingFlags {
167 NormalFormatting = 0x00, // Nothing special
168 Positional = 0x01, // Is a positional argument, no '-' required
169 Prefix = 0x02, // Can this option directly prefix its value?
170 AlwaysPrefix = 0x03, // Can this option only directly prefix its value?
171 Grouping = 0x04 // Can this option group with other options?
174 enum MiscFlags { // Miscellaneous flags to adjust argument
175 CommaSeparated = 0x01, // Should this cl::list split between commas?
176 PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args?
177 Sink = 0x04 // Should this cl::list eat all unknown options?
180 //===----------------------------------------------------------------------===//
181 // Option Category class
183 class OptionCategory {
184 private:
185 StringRef const Name;
186 StringRef const Description;
188 void registerCategory();
190 public:
191 OptionCategory(StringRef const Name,
192 StringRef const Description = "")
193 : Name(Name), Description(Description) {
194 registerCategory();
197 StringRef getName() const { return Name; }
198 StringRef getDescription() const { return Description; }
201 // The general Option Category (used as default category).
202 extern OptionCategory GeneralCategory;
204 //===----------------------------------------------------------------------===//
205 // SubCommand class
207 class SubCommand {
208 private:
209 StringRef Name;
210 StringRef Description;
212 protected:
213 void registerSubCommand();
214 void unregisterSubCommand();
216 public:
217 SubCommand(StringRef Name, StringRef Description = "")
218 : Name(Name), Description(Description) {
219 registerSubCommand();
221 SubCommand() = default;
223 void reset();
225 explicit operator bool() const;
227 StringRef getName() const { return Name; }
228 StringRef getDescription() const { return Description; }
230 SmallVector<Option *, 4> PositionalOpts;
231 SmallVector<Option *, 4> SinkOpts;
232 StringMap<Option *> OptionsMap;
234 Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists.
237 // A special subcommand representing no subcommand
238 extern ManagedStatic<SubCommand> TopLevelSubCommand;
240 // A special subcommand that can be used to put an option into all subcommands.
241 extern ManagedStatic<SubCommand> AllSubCommands;
243 //===----------------------------------------------------------------------===//
244 // Option Base class
246 class Option {
247 friend class alias;
249 // handleOccurrences - Overriden by subclasses to handle the value passed into
250 // an argument. Should return true if there was an error processing the
251 // argument and the program should exit.
253 virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
254 StringRef Arg) = 0;
256 virtual enum ValueExpected getValueExpectedFlagDefault() const {
257 return ValueOptional;
260 // Out of line virtual function to provide home for the class.
261 virtual void anchor();
263 int NumOccurrences = 0; // The number of times specified
264 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
265 // problems with signed enums in bitfields.
266 unsigned Occurrences : 3; // enum NumOccurrencesFlag
267 // not using the enum type for 'Value' because zero is an implementation
268 // detail representing the non-value
269 unsigned Value : 2;
270 unsigned HiddenFlag : 2; // enum OptionHidden
271 unsigned Formatting : 3; // enum FormattingFlags
272 unsigned Misc : 3;
273 unsigned Position = 0; // Position of last occurrence of the option
274 unsigned AdditionalVals = 0; // Greater than 0 for multi-valued option.
276 public:
277 StringRef ArgStr; // The argument string itself (ex: "help", "o")
278 StringRef HelpStr; // The descriptive text message for -help
279 StringRef ValueStr; // String describing what the value of this option is
280 OptionCategory *Category; // The Category this option belongs to
281 SmallPtrSet<SubCommand *, 4> Subs; // The subcommands this option belongs to.
282 bool FullyInitialized = false; // Has addArgument been called?
284 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
285 return (enum NumOccurrencesFlag)Occurrences;
288 inline enum ValueExpected getValueExpectedFlag() const {
289 return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
292 inline enum OptionHidden getOptionHiddenFlag() const {
293 return (enum OptionHidden)HiddenFlag;
296 inline enum FormattingFlags getFormattingFlag() const {
297 return (enum FormattingFlags)Formatting;
300 inline unsigned getMiscFlags() const { return Misc; }
301 inline unsigned getPosition() const { return Position; }
302 inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
304 // hasArgStr - Return true if the argstr != ""
305 bool hasArgStr() const { return !ArgStr.empty(); }
306 bool isPositional() const { return getFormattingFlag() == cl::Positional; }
307 bool isSink() const { return getMiscFlags() & cl::Sink; }
309 bool isConsumeAfter() const {
310 return getNumOccurrencesFlag() == cl::ConsumeAfter;
313 bool isInAllSubCommands() const {
314 return any_of(Subs, [](const SubCommand *SC) {
315 return SC == &*AllSubCommands;
319 //-------------------------------------------------------------------------===
320 // Accessor functions set by OptionModifiers
322 void setArgStr(StringRef S);
323 void setDescription(StringRef S) { HelpStr = S; }
324 void setValueStr(StringRef S) { ValueStr = S; }
325 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
326 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
327 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
328 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
329 void setMiscFlag(enum MiscFlags M) { Misc |= M; }
330 void setPosition(unsigned pos) { Position = pos; }
331 void setCategory(OptionCategory &C) { Category = &C; }
332 void addSubCommand(SubCommand &S) { Subs.insert(&S); }
334 protected:
335 explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
336 enum OptionHidden Hidden)
337 : Occurrences(OccurrencesFlag), Value(0), HiddenFlag(Hidden),
338 Formatting(NormalFormatting), Misc(0), Category(&GeneralCategory) {}
340 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
342 public:
343 virtual ~Option() = default;
345 // addArgument - Register this argument with the commandline system.
347 void addArgument();
349 /// Unregisters this option from the CommandLine system.
351 /// This option must have been the last option registered.
352 /// For testing purposes only.
353 void removeArgument();
355 // Return the width of the option tag for printing...
356 virtual size_t getOptionWidth() const = 0;
358 // printOptionInfo - Print out information about this option. The
359 // to-be-maintained width is specified.
361 virtual void printOptionInfo(size_t GlobalWidth) const = 0;
363 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
365 virtual void setDefault() = 0;
367 static void printHelpStr(StringRef HelpStr, size_t Indent,
368 size_t FirstLineIndentedBy);
370 virtual void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
372 // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
374 virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
375 bool MultiArg = false);
377 // Prints option name followed by message. Always returns true.
378 bool error(const Twine &Message, StringRef ArgName = StringRef(), raw_ostream &Errs = llvm::errs());
379 bool error(const Twine &Message, raw_ostream &Errs) {
380 return error(Message, StringRef(), Errs);
383 inline int getNumOccurrences() const { return NumOccurrences; }
384 inline void reset() { NumOccurrences = 0; }
387 //===----------------------------------------------------------------------===//
388 // Command line option modifiers that can be used to modify the behavior of
389 // command line option parsers...
392 // desc - Modifier to set the description shown in the -help output...
393 struct desc {
394 StringRef Desc;
396 desc(StringRef Str) : Desc(Str) {}
398 void apply(Option &O) const { O.setDescription(Desc); }
401 // value_desc - Modifier to set the value description shown in the -help
402 // output...
403 struct value_desc {
404 StringRef Desc;
406 value_desc(StringRef Str) : Desc(Str) {}
408 void apply(Option &O) const { O.setValueStr(Desc); }
411 // init - Specify a default (initial) value for the command line argument, if
412 // the default constructor for the argument type does not give you what you
413 // want. This is only valid on "opt" arguments, not on "list" arguments.
415 template <class Ty> struct initializer {
416 const Ty &Init;
417 initializer(const Ty &Val) : Init(Val) {}
419 template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
422 template <class Ty> initializer<Ty> init(const Ty &Val) {
423 return initializer<Ty>(Val);
426 // location - Allow the user to specify which external variable they want to
427 // store the results of the command line argument processing into, if they don't
428 // want to store it in the option itself.
430 template <class Ty> struct LocationClass {
431 Ty &Loc;
433 LocationClass(Ty &L) : Loc(L) {}
435 template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
438 template <class Ty> LocationClass<Ty> location(Ty &L) {
439 return LocationClass<Ty>(L);
442 // cat - Specifiy the Option category for the command line argument to belong
443 // to.
444 struct cat {
445 OptionCategory &Category;
447 cat(OptionCategory &c) : Category(c) {}
449 template <class Opt> void apply(Opt &O) const { O.setCategory(Category); }
452 // sub - Specify the subcommand that this option belongs to.
453 struct sub {
454 SubCommand &Sub;
456 sub(SubCommand &S) : Sub(S) {}
458 template <class Opt> void apply(Opt &O) const { O.addSubCommand(Sub); }
461 //===----------------------------------------------------------------------===//
462 // OptionValue class
464 // Support value comparison outside the template.
465 struct GenericOptionValue {
466 virtual bool compare(const GenericOptionValue &V) const = 0;
468 protected:
469 GenericOptionValue() = default;
470 GenericOptionValue(const GenericOptionValue&) = default;
471 GenericOptionValue &operator=(const GenericOptionValue &) = default;
472 ~GenericOptionValue() = default;
474 private:
475 virtual void anchor();
478 template <class DataType> struct OptionValue;
480 // The default value safely does nothing. Option value printing is only
481 // best-effort.
482 template <class DataType, bool isClass>
483 struct OptionValueBase : public GenericOptionValue {
484 // Temporary storage for argument passing.
485 using WrapperType = OptionValue<DataType>;
487 bool hasValue() const { return false; }
489 const DataType &getValue() const { llvm_unreachable("no default value"); }
491 // Some options may take their value from a different data type.
492 template <class DT> void setValue(const DT & /*V*/) {}
494 bool compare(const DataType & /*V*/) const { return false; }
496 bool compare(const GenericOptionValue & /*V*/) const override {
497 return false;
500 protected:
501 ~OptionValueBase() = default;
504 // Simple copy of the option value.
505 template <class DataType> class OptionValueCopy : public GenericOptionValue {
506 DataType Value;
507 bool Valid = false;
509 protected:
510 OptionValueCopy(const OptionValueCopy&) = default;
511 OptionValueCopy &operator=(const OptionValueCopy &) = default;
512 ~OptionValueCopy() = default;
514 public:
515 OptionValueCopy() = default;
517 bool hasValue() const { return Valid; }
519 const DataType &getValue() const {
520 assert(Valid && "invalid option value");
521 return Value;
524 void setValue(const DataType &V) {
525 Valid = true;
526 Value = V;
529 bool compare(const DataType &V) const { return Valid && (Value != V); }
531 bool compare(const GenericOptionValue &V) const override {
532 const OptionValueCopy<DataType> &VC =
533 static_cast<const OptionValueCopy<DataType> &>(V);
534 if (!VC.hasValue())
535 return false;
536 return compare(VC.getValue());
540 // Non-class option values.
541 template <class DataType>
542 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
543 using WrapperType = DataType;
545 protected:
546 OptionValueBase() = default;
547 OptionValueBase(const OptionValueBase&) = default;
548 OptionValueBase &operator=(const OptionValueBase &) = default;
549 ~OptionValueBase() = default;
552 // Top-level option class.
553 template <class DataType>
554 struct OptionValue final
555 : OptionValueBase<DataType, std::is_class<DataType>::value> {
556 OptionValue() = default;
558 OptionValue(const DataType &V) { this->setValue(V); }
560 // Some options may take their value from a different data type.
561 template <class DT> OptionValue<DataType> &operator=(const DT &V) {
562 this->setValue(V);
563 return *this;
567 // Other safe-to-copy-by-value common option types.
568 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
569 template <>
570 struct OptionValue<cl::boolOrDefault> final
571 : OptionValueCopy<cl::boolOrDefault> {
572 using WrapperType = cl::boolOrDefault;
574 OptionValue() = default;
576 OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
578 OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
579 setValue(V);
580 return *this;
583 private:
584 void anchor() override;
587 template <>
588 struct OptionValue<std::string> final : OptionValueCopy<std::string> {
589 using WrapperType = StringRef;
591 OptionValue() = default;
593 OptionValue(const std::string &V) { this->setValue(V); }
595 OptionValue<std::string> &operator=(const std::string &V) {
596 setValue(V);
597 return *this;
600 private:
601 void anchor() override;
604 //===----------------------------------------------------------------------===//
605 // Enum valued command line option
608 // This represents a single enum value, using "int" as the underlying type.
609 struct OptionEnumValue {
610 StringRef Name;
611 int Value;
612 StringRef Description;
615 #define clEnumVal(ENUMVAL, DESC) \
616 llvm::cl::OptionEnumValue { #ENUMVAL, int(ENUMVAL), DESC }
617 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) \
618 llvm::cl::OptionEnumValue { FLAGNAME, int(ENUMVAL), DESC }
620 // values - For custom data types, allow specifying a group of values together
621 // as the values that go into the mapping that the option handler uses.
623 class ValuesClass {
624 // Use a vector instead of a map, because the lists should be short,
625 // the overhead is less, and most importantly, it keeps them in the order
626 // inserted so we can print our option out nicely.
627 SmallVector<OptionEnumValue, 4> Values;
629 public:
630 ValuesClass(std::initializer_list<OptionEnumValue> Options)
631 : Values(Options) {}
633 template <class Opt> void apply(Opt &O) const {
634 for (auto Value : Values)
635 O.getParser().addLiteralOption(Value.Name, Value.Value,
636 Value.Description);
640 /// Helper to build a ValuesClass by forwarding a variable number of arguments
641 /// as an initializer list to the ValuesClass constructor.
642 template <typename... OptsTy> ValuesClass values(OptsTy... Options) {
643 return ValuesClass({Options...});
646 //===----------------------------------------------------------------------===//
647 // parser class - Parameterizable parser for different data types. By default,
648 // known data types (string, int, bool) have specialized parsers, that do what
649 // you would expect. The default parser, used for data types that are not
650 // built-in, uses a mapping table to map specific options to values, which is
651 // used, among other things, to handle enum types.
653 //--------------------------------------------------
654 // generic_parser_base - This class holds all the non-generic code that we do
655 // not need replicated for every instance of the generic parser. This also
656 // allows us to put stuff into CommandLine.cpp
658 class generic_parser_base {
659 protected:
660 class GenericOptionInfo {
661 public:
662 GenericOptionInfo(StringRef name, StringRef helpStr)
663 : Name(name), HelpStr(helpStr) {}
664 StringRef Name;
665 StringRef HelpStr;
668 public:
669 generic_parser_base(Option &O) : Owner(O) {}
671 virtual ~generic_parser_base() = default;
672 // Base class should have virtual-destructor
674 // getNumOptions - Virtual function implemented by generic subclass to
675 // indicate how many entries are in Values.
677 virtual unsigned getNumOptions() const = 0;
679 // getOption - Return option name N.
680 virtual StringRef getOption(unsigned N) const = 0;
682 // getDescription - Return description N
683 virtual StringRef getDescription(unsigned N) const = 0;
685 // Return the width of the option tag for printing...
686 virtual size_t getOptionWidth(const Option &O) const;
688 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
690 // printOptionInfo - Print out information about this option. The
691 // to-be-maintained width is specified.
693 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
695 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
696 const GenericOptionValue &Default,
697 size_t GlobalWidth) const;
699 // printOptionDiff - print the value of an option and it's default.
701 // Template definition ensures that the option and default have the same
702 // DataType (via the same AnyOptionValue).
703 template <class AnyOptionValue>
704 void printOptionDiff(const Option &O, const AnyOptionValue &V,
705 const AnyOptionValue &Default,
706 size_t GlobalWidth) const {
707 printGenericOptionDiff(O, V, Default, GlobalWidth);
710 void initialize() {}
712 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) {
713 // If there has been no argstr specified, that means that we need to add an
714 // argument for every possible option. This ensures that our options are
715 // vectored to us.
716 if (!Owner.hasArgStr())
717 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
718 OptionNames.push_back(getOption(i));
721 enum ValueExpected getValueExpectedFlagDefault() const {
722 // If there is an ArgStr specified, then we are of the form:
724 // -opt=O2 or -opt O2 or -optO2
726 // In which case, the value is required. Otherwise if an arg str has not
727 // been specified, we are of the form:
729 // -O2 or O2 or -la (where -l and -a are separate options)
731 // If this is the case, we cannot allow a value.
733 if (Owner.hasArgStr())
734 return ValueRequired;
735 else
736 return ValueDisallowed;
739 // findOption - Return the option number corresponding to the specified
740 // argument string. If the option is not found, getNumOptions() is returned.
742 unsigned findOption(StringRef Name);
744 protected:
745 Option &Owner;
748 // Default parser implementation - This implementation depends on having a
749 // mapping of recognized options to values of some sort. In addition to this,
750 // each entry in the mapping also tracks a help message that is printed with the
751 // command line option for -help. Because this is a simple mapping parser, the
752 // data type can be any unsupported type.
754 template <class DataType> class parser : public generic_parser_base {
755 protected:
756 class OptionInfo : public GenericOptionInfo {
757 public:
758 OptionInfo(StringRef name, DataType v, StringRef helpStr)
759 : GenericOptionInfo(name, helpStr), V(v) {}
761 OptionValue<DataType> V;
763 SmallVector<OptionInfo, 8> Values;
765 public:
766 parser(Option &O) : generic_parser_base(O) {}
768 using parser_data_type = DataType;
770 // Implement virtual functions needed by generic_parser_base
771 unsigned getNumOptions() const override { return unsigned(Values.size()); }
772 StringRef getOption(unsigned N) const override { return Values[N].Name; }
773 StringRef getDescription(unsigned N) const override {
774 return Values[N].HelpStr;
777 // getOptionValue - Return the value of option name N.
778 const GenericOptionValue &getOptionValue(unsigned N) const override {
779 return Values[N].V;
782 // parse - Return true on error.
783 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
784 StringRef ArgVal;
785 if (Owner.hasArgStr())
786 ArgVal = Arg;
787 else
788 ArgVal = ArgName;
790 for (size_t i = 0, e = Values.size(); i != e; ++i)
791 if (Values[i].Name == ArgVal) {
792 V = Values[i].V.getValue();
793 return false;
796 return O.error("Cannot find option named '" + ArgVal + "'!");
799 /// addLiteralOption - Add an entry to the mapping table.
801 template <class DT>
802 void addLiteralOption(StringRef Name, const DT &V, StringRef HelpStr) {
803 assert(findOption(Name) == Values.size() && "Option already exists!");
804 OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
805 Values.push_back(X);
806 AddLiteralOption(Owner, Name);
809 /// removeLiteralOption - Remove the specified option.
811 void removeLiteralOption(StringRef Name) {
812 unsigned N = findOption(Name);
813 assert(N != Values.size() && "Option not found!");
814 Values.erase(Values.begin() + N);
818 //--------------------------------------------------
819 // basic_parser - Super class of parsers to provide boilerplate code
821 class basic_parser_impl { // non-template implementation of basic_parser<t>
822 public:
823 basic_parser_impl(Option &) {}
825 enum ValueExpected getValueExpectedFlagDefault() const {
826 return ValueRequired;
829 void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
831 void initialize() {}
833 // Return the width of the option tag for printing...
834 size_t getOptionWidth(const Option &O) const;
836 // printOptionInfo - Print out information about this option. The
837 // to-be-maintained width is specified.
839 void printOptionInfo(const Option &O, size_t GlobalWidth) const;
841 // printOptionNoValue - Print a placeholder for options that don't yet support
842 // printOptionDiff().
843 void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
845 // getValueName - Overload in subclass to provide a better default value.
846 virtual StringRef getValueName() const { return "value"; }
848 // An out-of-line virtual method to provide a 'home' for this class.
849 virtual void anchor();
851 protected:
852 ~basic_parser_impl() = default;
854 // A helper for basic_parser::printOptionDiff.
855 void printOptionName(const Option &O, size_t GlobalWidth) const;
858 // basic_parser - The real basic parser is just a template wrapper that provides
859 // a typedef for the provided data type.
861 template <class DataType> class basic_parser : public basic_parser_impl {
862 public:
863 using parser_data_type = DataType;
864 using OptVal = OptionValue<DataType>;
866 basic_parser(Option &O) : basic_parser_impl(O) {}
868 protected:
869 ~basic_parser() = default;
872 //--------------------------------------------------
873 // parser<bool>
875 template <> class parser<bool> final : public basic_parser<bool> {
876 public:
877 parser(Option &O) : basic_parser(O) {}
879 // parse - Return true on error.
880 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
882 void initialize() {}
884 enum ValueExpected getValueExpectedFlagDefault() const {
885 return ValueOptional;
888 // getValueName - Do not print =<value> at all.
889 StringRef getValueName() const override { return StringRef(); }
891 void printOptionDiff(const Option &O, bool V, OptVal Default,
892 size_t GlobalWidth) const;
894 // An out-of-line virtual method to provide a 'home' for this class.
895 void anchor() override;
898 extern template class basic_parser<bool>;
900 //--------------------------------------------------
901 // parser<boolOrDefault>
902 template <>
903 class parser<boolOrDefault> final : public basic_parser<boolOrDefault> {
904 public:
905 parser(Option &O) : basic_parser(O) {}
907 // parse - Return true on error.
908 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
910 enum ValueExpected getValueExpectedFlagDefault() const {
911 return ValueOptional;
914 // getValueName - Do not print =<value> at all.
915 StringRef getValueName() const override { return StringRef(); }
917 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
918 size_t GlobalWidth) const;
920 // An out-of-line virtual method to provide a 'home' for this class.
921 void anchor() override;
924 extern template class basic_parser<boolOrDefault>;
926 //--------------------------------------------------
927 // parser<int>
929 template <> class parser<int> final : public basic_parser<int> {
930 public:
931 parser(Option &O) : basic_parser(O) {}
933 // parse - Return true on error.
934 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
936 // getValueName - Overload in subclass to provide a better default value.
937 StringRef getValueName() const override { return "int"; }
939 void printOptionDiff(const Option &O, int V, OptVal Default,
940 size_t GlobalWidth) const;
942 // An out-of-line virtual method to provide a 'home' for this class.
943 void anchor() override;
946 extern template class basic_parser<int>;
948 //--------------------------------------------------
949 // parser<unsigned>
951 template <> class parser<unsigned> final : public basic_parser<unsigned> {
952 public:
953 parser(Option &O) : basic_parser(O) {}
955 // parse - Return true on error.
956 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
958 // getValueName - Overload in subclass to provide a better default value.
959 StringRef getValueName() const override { return "uint"; }
961 void printOptionDiff(const Option &O, unsigned V, OptVal Default,
962 size_t GlobalWidth) const;
964 // An out-of-line virtual method to provide a 'home' for this class.
965 void anchor() override;
968 extern template class basic_parser<unsigned>;
970 //--------------------------------------------------
971 // parser<unsigned long long>
973 template <>
974 class parser<unsigned long long> final
975 : public basic_parser<unsigned long long> {
976 public:
977 parser(Option &O) : basic_parser(O) {}
979 // parse - Return true on error.
980 bool parse(Option &O, StringRef ArgName, StringRef Arg,
981 unsigned long long &Val);
983 // getValueName - Overload in subclass to provide a better default value.
984 StringRef getValueName() const override { return "uint"; }
986 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
987 size_t GlobalWidth) const;
989 // An out-of-line virtual method to provide a 'home' for this class.
990 void anchor() override;
993 extern template class basic_parser<unsigned long long>;
995 //--------------------------------------------------
996 // parser<double>
998 template <> class parser<double> final : public basic_parser<double> {
999 public:
1000 parser(Option &O) : basic_parser(O) {}
1002 // parse - Return true on error.
1003 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
1005 // getValueName - Overload in subclass to provide a better default value.
1006 StringRef getValueName() const override { return "number"; }
1008 void printOptionDiff(const Option &O, double V, OptVal Default,
1009 size_t GlobalWidth) const;
1011 // An out-of-line virtual method to provide a 'home' for this class.
1012 void anchor() override;
1015 extern template class basic_parser<double>;
1017 //--------------------------------------------------
1018 // parser<float>
1020 template <> class parser<float> final : public basic_parser<float> {
1021 public:
1022 parser(Option &O) : basic_parser(O) {}
1024 // parse - Return true on error.
1025 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
1027 // getValueName - Overload in subclass to provide a better default value.
1028 StringRef getValueName() const override { return "number"; }
1030 void printOptionDiff(const Option &O, float V, OptVal Default,
1031 size_t GlobalWidth) const;
1033 // An out-of-line virtual method to provide a 'home' for this class.
1034 void anchor() override;
1037 extern template class basic_parser<float>;
1039 //--------------------------------------------------
1040 // parser<std::string>
1042 template <> class parser<std::string> final : public basic_parser<std::string> {
1043 public:
1044 parser(Option &O) : basic_parser(O) {}
1046 // parse - Return true on error.
1047 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
1048 Value = Arg.str();
1049 return false;
1052 // getValueName - Overload in subclass to provide a better default value.
1053 StringRef getValueName() const override { return "string"; }
1055 void printOptionDiff(const Option &O, StringRef V, const OptVal &Default,
1056 size_t GlobalWidth) const;
1058 // An out-of-line virtual method to provide a 'home' for this class.
1059 void anchor() override;
1062 extern template class basic_parser<std::string>;
1064 //--------------------------------------------------
1065 // parser<char>
1067 template <> class parser<char> final : public basic_parser<char> {
1068 public:
1069 parser(Option &O) : basic_parser(O) {}
1071 // parse - Return true on error.
1072 bool parse(Option &, StringRef, StringRef Arg, char &Value) {
1073 Value = Arg[0];
1074 return false;
1077 // getValueName - Overload in subclass to provide a better default value.
1078 StringRef getValueName() const override { return "char"; }
1080 void printOptionDiff(const Option &O, char V, OptVal Default,
1081 size_t GlobalWidth) const;
1083 // An out-of-line virtual method to provide a 'home' for this class.
1084 void anchor() override;
1087 extern template class basic_parser<char>;
1089 //--------------------------------------------------
1090 // PrintOptionDiff
1092 // This collection of wrappers is the intermediary between class opt and class
1093 // parser to handle all the template nastiness.
1095 // This overloaded function is selected by the generic parser.
1096 template <class ParserClass, class DT>
1097 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
1098 const OptionValue<DT> &Default, size_t GlobalWidth) {
1099 OptionValue<DT> OV = V;
1100 P.printOptionDiff(O, OV, Default, GlobalWidth);
1103 // This is instantiated for basic parsers when the parsed value has a different
1104 // type than the option value. e.g. HelpPrinter.
1105 template <class ParserDT, class ValDT> struct OptionDiffPrinter {
1106 void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/,
1107 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
1108 P.printOptionNoValue(O, GlobalWidth);
1112 // This is instantiated for basic parsers when the parsed value has the same
1113 // type as the option value.
1114 template <class DT> struct OptionDiffPrinter<DT, DT> {
1115 void print(const Option &O, const parser<DT> &P, const DT &V,
1116 const OptionValue<DT> &Default, size_t GlobalWidth) {
1117 P.printOptionDiff(O, V, Default, GlobalWidth);
1121 // This overloaded function is selected by the basic parser, which may parse a
1122 // different type than the option type.
1123 template <class ParserClass, class ValDT>
1124 void printOptionDiff(
1125 const Option &O,
1126 const basic_parser<typename ParserClass::parser_data_type> &P,
1127 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
1129 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
1130 printer.print(O, static_cast<const ParserClass &>(P), V, Default,
1131 GlobalWidth);
1134 //===----------------------------------------------------------------------===//
1135 // applicator class - This class is used because we must use partial
1136 // specialization to handle literal string arguments specially (const char* does
1137 // not correctly respond to the apply method). Because the syntax to use this
1138 // is a pain, we have the 'apply' method below to handle the nastiness...
1140 template <class Mod> struct applicator {
1141 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1144 // Handle const char* as a special case...
1145 template <unsigned n> struct applicator<char[n]> {
1146 template <class Opt> static void opt(StringRef Str, Opt &O) {
1147 O.setArgStr(Str);
1150 template <unsigned n> struct applicator<const char[n]> {
1151 template <class Opt> static void opt(StringRef Str, Opt &O) {
1152 O.setArgStr(Str);
1155 template <> struct applicator<StringRef > {
1156 template <class Opt> static void opt(StringRef Str, Opt &O) {
1157 O.setArgStr(Str);
1161 template <> struct applicator<NumOccurrencesFlag> {
1162 static void opt(NumOccurrencesFlag N, Option &O) {
1163 O.setNumOccurrencesFlag(N);
1167 template <> struct applicator<ValueExpected> {
1168 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1171 template <> struct applicator<OptionHidden> {
1172 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1175 template <> struct applicator<FormattingFlags> {
1176 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1179 template <> struct applicator<MiscFlags> {
1180 static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1183 // apply method - Apply modifiers to an option in a type safe way.
1184 template <class Opt, class Mod, class... Mods>
1185 void apply(Opt *O, const Mod &M, const Mods &... Ms) {
1186 applicator<Mod>::opt(M, *O);
1187 apply(O, Ms...);
1190 template <class Opt, class Mod> void apply(Opt *O, const Mod &M) {
1191 applicator<Mod>::opt(M, *O);
1194 //===----------------------------------------------------------------------===//
1195 // opt_storage class
1197 // Default storage class definition: external storage. This implementation
1198 // assumes the user will specify a variable to store the data into with the
1199 // cl::location(x) modifier.
1201 template <class DataType, bool ExternalStorage, bool isClass>
1202 class opt_storage {
1203 DataType *Location = nullptr; // Where to store the object...
1204 OptionValue<DataType> Default;
1206 void check_location() const {
1207 assert(Location && "cl::location(...) not specified for a command "
1208 "line option with external storage, "
1209 "or cl::init specified before cl::location()!!");
1212 public:
1213 opt_storage() = default;
1215 bool setLocation(Option &O, DataType &L) {
1216 if (Location)
1217 return O.error("cl::location(x) specified more than once!");
1218 Location = &L;
1219 Default = L;
1220 return false;
1223 template <class T> void setValue(const T &V, bool initial = false) {
1224 check_location();
1225 *Location = V;
1226 if (initial)
1227 Default = V;
1230 DataType &getValue() {
1231 check_location();
1232 return *Location;
1234 const DataType &getValue() const {
1235 check_location();
1236 return *Location;
1239 operator DataType() const { return this->getValue(); }
1241 const OptionValue<DataType> &getDefault() const { return Default; }
1244 // Define how to hold a class type object, such as a string. Since we can
1245 // inherit from a class, we do so. This makes us exactly compatible with the
1246 // object in all cases that it is used.
1248 template <class DataType>
1249 class opt_storage<DataType, false, true> : public DataType {
1250 public:
1251 OptionValue<DataType> Default;
1253 template <class T> void setValue(const T &V, bool initial = false) {
1254 DataType::operator=(V);
1255 if (initial)
1256 Default = V;
1259 DataType &getValue() { return *this; }
1260 const DataType &getValue() const { return *this; }
1262 const OptionValue<DataType> &getDefault() const { return Default; }
1265 // Define a partial specialization to handle things we cannot inherit from. In
1266 // this case, we store an instance through containment, and overload operators
1267 // to get at the value.
1269 template <class DataType> class opt_storage<DataType, false, false> {
1270 public:
1271 DataType Value;
1272 OptionValue<DataType> Default;
1274 // Make sure we initialize the value with the default constructor for the
1275 // type.
1276 opt_storage() : Value(DataType()), Default(DataType()) {}
1278 template <class T> void setValue(const T &V, bool initial = false) {
1279 Value = V;
1280 if (initial)
1281 Default = V;
1283 DataType &getValue() { return Value; }
1284 DataType getValue() const { return Value; }
1286 const OptionValue<DataType> &getDefault() const { return Default; }
1288 operator DataType() const { return getValue(); }
1290 // If the datatype is a pointer, support -> on it.
1291 DataType operator->() const { return Value; }
1294 //===----------------------------------------------------------------------===//
1295 // opt - A scalar command line option.
1297 template <class DataType, bool ExternalStorage = false,
1298 class ParserClass = parser<DataType>>
1299 class opt : public Option,
1300 public opt_storage<DataType, ExternalStorage,
1301 std::is_class<DataType>::value> {
1302 ParserClass Parser;
1304 bool handleOccurrence(unsigned pos, StringRef ArgName,
1305 StringRef Arg) override {
1306 typename ParserClass::parser_data_type Val =
1307 typename ParserClass::parser_data_type();
1308 if (Parser.parse(*this, ArgName, Arg, Val))
1309 return true; // Parse error!
1310 this->setValue(Val);
1311 this->setPosition(pos);
1312 return false;
1315 enum ValueExpected getValueExpectedFlagDefault() const override {
1316 return Parser.getValueExpectedFlagDefault();
1319 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1320 return Parser.getExtraOptionNames(OptionNames);
1323 // Forward printing stuff to the parser...
1324 size_t getOptionWidth() const override {
1325 return Parser.getOptionWidth(*this);
1328 void printOptionInfo(size_t GlobalWidth) const override {
1329 Parser.printOptionInfo(*this, GlobalWidth);
1332 void printOptionValue(size_t GlobalWidth, bool Force) const override {
1333 if (Force || this->getDefault().compare(this->getValue())) {
1334 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1335 this->getDefault(), GlobalWidth);
1339 template <class T, class = typename std::enable_if<
1340 std::is_assignable<T&, T>::value>::type>
1341 void setDefaultImpl() {
1342 const OptionValue<DataType> &V = this->getDefault();
1343 if (V.hasValue())
1344 this->setValue(V.getValue());
1347 template <class T, class = typename std::enable_if<
1348 !std::is_assignable<T&, T>::value>::type>
1349 void setDefaultImpl(...) {}
1351 void setDefault() override { setDefaultImpl<DataType>(); }
1353 void done() {
1354 addArgument();
1355 Parser.initialize();
1358 public:
1359 // Command line options should not be copyable
1360 opt(const opt &) = delete;
1361 opt &operator=(const opt &) = delete;
1363 // setInitialValue - Used by the cl::init modifier...
1364 void setInitialValue(const DataType &V) { this->setValue(V, true); }
1366 ParserClass &getParser() { return Parser; }
1368 template <class T> DataType &operator=(const T &Val) {
1369 this->setValue(Val);
1370 return this->getValue();
1373 template <class... Mods>
1374 explicit opt(const Mods &... Ms)
1375 : Option(Optional, NotHidden), Parser(*this) {
1376 apply(this, Ms...);
1377 done();
1381 extern template class opt<unsigned>;
1382 extern template class opt<int>;
1383 extern template class opt<std::string>;
1384 extern template class opt<char>;
1385 extern template class opt<bool>;
1387 //===----------------------------------------------------------------------===//
1388 // list_storage class
1390 // Default storage class definition: external storage. This implementation
1391 // assumes the user will specify a variable to store the data into with the
1392 // cl::location(x) modifier.
1394 template <class DataType, class StorageClass> class list_storage {
1395 StorageClass *Location = nullptr; // Where to store the object...
1397 public:
1398 list_storage() = default;
1400 bool setLocation(Option &O, StorageClass &L) {
1401 if (Location)
1402 return O.error("cl::location(x) specified more than once!");
1403 Location = &L;
1404 return false;
1407 template <class T> void addValue(const T &V) {
1408 assert(Location != 0 && "cl::location(...) not specified for a command "
1409 "line option with external storage!");
1410 Location->push_back(V);
1414 // Define how to hold a class type object, such as a string.
1415 // Originally this code inherited from std::vector. In transitioning to a new
1416 // API for command line options we should change this. The new implementation
1417 // of this list_storage specialization implements the minimum subset of the
1418 // std::vector API required for all the current clients.
1420 // FIXME: Reduce this API to a more narrow subset of std::vector
1422 template <class DataType> class list_storage<DataType, bool> {
1423 std::vector<DataType> Storage;
1425 public:
1426 using iterator = typename std::vector<DataType>::iterator;
1428 iterator begin() { return Storage.begin(); }
1429 iterator end() { return Storage.end(); }
1431 using const_iterator = typename std::vector<DataType>::const_iterator;
1433 const_iterator begin() const { return Storage.begin(); }
1434 const_iterator end() const { return Storage.end(); }
1436 using size_type = typename std::vector<DataType>::size_type;
1438 size_type size() const { return Storage.size(); }
1440 bool empty() const { return Storage.empty(); }
1442 void push_back(const DataType &value) { Storage.push_back(value); }
1443 void push_back(DataType &&value) { Storage.push_back(value); }
1445 using reference = typename std::vector<DataType>::reference;
1446 using const_reference = typename std::vector<DataType>::const_reference;
1448 reference operator[](size_type pos) { return Storage[pos]; }
1449 const_reference operator[](size_type pos) const { return Storage[pos]; }
1451 iterator erase(const_iterator pos) { return Storage.erase(pos); }
1452 iterator erase(const_iterator first, const_iterator last) {
1453 return Storage.erase(first, last);
1456 iterator erase(iterator pos) { return Storage.erase(pos); }
1457 iterator erase(iterator first, iterator last) {
1458 return Storage.erase(first, last);
1461 iterator insert(const_iterator pos, const DataType &value) {
1462 return Storage.insert(pos, value);
1464 iterator insert(const_iterator pos, DataType &&value) {
1465 return Storage.insert(pos, value);
1468 iterator insert(iterator pos, const DataType &value) {
1469 return Storage.insert(pos, value);
1471 iterator insert(iterator pos, DataType &&value) {
1472 return Storage.insert(pos, value);
1475 reference front() { return Storage.front(); }
1476 const_reference front() const { return Storage.front(); }
1478 operator std::vector<DataType>&() { return Storage; }
1479 operator ArrayRef<DataType>() { return Storage; }
1480 std::vector<DataType> *operator&() { return &Storage; }
1481 const std::vector<DataType> *operator&() const { return &Storage; }
1483 template <class T> void addValue(const T &V) { Storage.push_back(V); }
1486 //===----------------------------------------------------------------------===//
1487 // list - A list of command line options.
1489 template <class DataType, class StorageClass = bool,
1490 class ParserClass = parser<DataType>>
1491 class list : public Option, public list_storage<DataType, StorageClass> {
1492 std::vector<unsigned> Positions;
1493 ParserClass Parser;
1495 enum ValueExpected getValueExpectedFlagDefault() const override {
1496 return Parser.getValueExpectedFlagDefault();
1499 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1500 return Parser.getExtraOptionNames(OptionNames);
1503 bool handleOccurrence(unsigned pos, StringRef ArgName,
1504 StringRef Arg) override {
1505 typename ParserClass::parser_data_type Val =
1506 typename ParserClass::parser_data_type();
1507 if (Parser.parse(*this, ArgName, Arg, Val))
1508 return true; // Parse Error!
1509 list_storage<DataType, StorageClass>::addValue(Val);
1510 setPosition(pos);
1511 Positions.push_back(pos);
1512 return false;
1515 // Forward printing stuff to the parser...
1516 size_t getOptionWidth() const override {
1517 return Parser.getOptionWidth(*this);
1520 void printOptionInfo(size_t GlobalWidth) const override {
1521 Parser.printOptionInfo(*this, GlobalWidth);
1524 // Unimplemented: list options don't currently store their default value.
1525 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1528 void setDefault() override {}
1530 void done() {
1531 addArgument();
1532 Parser.initialize();
1535 public:
1536 // Command line options should not be copyable
1537 list(const list &) = delete;
1538 list &operator=(const list &) = delete;
1540 ParserClass &getParser() { return Parser; }
1542 unsigned getPosition(unsigned optnum) const {
1543 assert(optnum < this->size() && "Invalid option index");
1544 return Positions[optnum];
1547 void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
1549 template <class... Mods>
1550 explicit list(const Mods &... Ms)
1551 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1552 apply(this, Ms...);
1553 done();
1557 // multi_val - Modifier to set the number of additional values.
1558 struct multi_val {
1559 unsigned AdditionalVals;
1560 explicit multi_val(unsigned N) : AdditionalVals(N) {}
1562 template <typename D, typename S, typename P>
1563 void apply(list<D, S, P> &L) const {
1564 L.setNumAdditionalVals(AdditionalVals);
1568 //===----------------------------------------------------------------------===//
1569 // bits_storage class
1571 // Default storage class definition: external storage. This implementation
1572 // assumes the user will specify a variable to store the data into with the
1573 // cl::location(x) modifier.
1575 template <class DataType, class StorageClass> class bits_storage {
1576 unsigned *Location = nullptr; // Where to store the bits...
1578 template <class T> static unsigned Bit(const T &V) {
1579 unsigned BitPos = reinterpret_cast<unsigned>(V);
1580 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1581 "enum exceeds width of bit vector!");
1582 return 1 << BitPos;
1585 public:
1586 bits_storage() = default;
1588 bool setLocation(Option &O, unsigned &L) {
1589 if (Location)
1590 return O.error("cl::location(x) specified more than once!");
1591 Location = &L;
1592 return false;
1595 template <class T> void addValue(const T &V) {
1596 assert(Location != 0 && "cl::location(...) not specified for a command "
1597 "line option with external storage!");
1598 *Location |= Bit(V);
1601 unsigned getBits() { return *Location; }
1603 template <class T> bool isSet(const T &V) {
1604 return (*Location & Bit(V)) != 0;
1608 // Define how to hold bits. Since we can inherit from a class, we do so.
1609 // This makes us exactly compatible with the bits in all cases that it is used.
1611 template <class DataType> class bits_storage<DataType, bool> {
1612 unsigned Bits; // Where to store the bits...
1614 template <class T> static unsigned Bit(const T &V) {
1615 unsigned BitPos = (unsigned)V;
1616 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1617 "enum exceeds width of bit vector!");
1618 return 1 << BitPos;
1621 public:
1622 template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1624 unsigned getBits() { return Bits; }
1626 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1629 //===----------------------------------------------------------------------===//
1630 // bits - A bit vector of command options.
1632 template <class DataType, class Storage = bool,
1633 class ParserClass = parser<DataType>>
1634 class bits : public Option, public bits_storage<DataType, Storage> {
1635 std::vector<unsigned> Positions;
1636 ParserClass Parser;
1638 enum ValueExpected getValueExpectedFlagDefault() const override {
1639 return Parser.getValueExpectedFlagDefault();
1642 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1643 return Parser.getExtraOptionNames(OptionNames);
1646 bool handleOccurrence(unsigned pos, StringRef ArgName,
1647 StringRef Arg) override {
1648 typename ParserClass::parser_data_type Val =
1649 typename ParserClass::parser_data_type();
1650 if (Parser.parse(*this, ArgName, Arg, Val))
1651 return true; // Parse Error!
1652 this->addValue(Val);
1653 setPosition(pos);
1654 Positions.push_back(pos);
1655 return false;
1658 // Forward printing stuff to the parser...
1659 size_t getOptionWidth() const override {
1660 return Parser.getOptionWidth(*this);
1663 void printOptionInfo(size_t GlobalWidth) const override {
1664 Parser.printOptionInfo(*this, GlobalWidth);
1667 // Unimplemented: bits options don't currently store their default values.
1668 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1671 void setDefault() override {}
1673 void done() {
1674 addArgument();
1675 Parser.initialize();
1678 public:
1679 // Command line options should not be copyable
1680 bits(const bits &) = delete;
1681 bits &operator=(const bits &) = delete;
1683 ParserClass &getParser() { return Parser; }
1685 unsigned getPosition(unsigned optnum) const {
1686 assert(optnum < this->size() && "Invalid option index");
1687 return Positions[optnum];
1690 template <class... Mods>
1691 explicit bits(const Mods &... Ms)
1692 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1693 apply(this, Ms...);
1694 done();
1698 //===----------------------------------------------------------------------===//
1699 // Aliased command line option (alias this name to a preexisting name)
1702 class alias : public Option {
1703 Option *AliasFor;
1705 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1706 StringRef Arg) override {
1707 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1710 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1711 bool MultiArg = false) override {
1712 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1715 // Handle printing stuff...
1716 size_t getOptionWidth() const override;
1717 void printOptionInfo(size_t GlobalWidth) const override;
1719 // Aliases do not need to print their values.
1720 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1723 void setDefault() override { AliasFor->setDefault(); }
1725 ValueExpected getValueExpectedFlagDefault() const override {
1726 return AliasFor->getValueExpectedFlag();
1729 void done() {
1730 if (!hasArgStr())
1731 error("cl::alias must have argument name specified!");
1732 if (!AliasFor)
1733 error("cl::alias must have an cl::aliasopt(option) specified!");
1734 Subs = AliasFor->Subs;
1735 addArgument();
1738 public:
1739 // Command line options should not be copyable
1740 alias(const alias &) = delete;
1741 alias &operator=(const alias &) = delete;
1743 void setAliasFor(Option &O) {
1744 if (AliasFor)
1745 error("cl::alias must only have one cl::aliasopt(...) specified!");
1746 AliasFor = &O;
1749 template <class... Mods>
1750 explicit alias(const Mods &... Ms)
1751 : Option(Optional, Hidden), AliasFor(nullptr) {
1752 apply(this, Ms...);
1753 done();
1757 // aliasfor - Modifier to set the option an alias aliases.
1758 struct aliasopt {
1759 Option &Opt;
1761 explicit aliasopt(Option &O) : Opt(O) {}
1763 void apply(alias &A) const { A.setAliasFor(Opt); }
1766 // extrahelp - provide additional help at the end of the normal help
1767 // output. All occurrences of cl::extrahelp will be accumulated and
1768 // printed to stderr at the end of the regular help, just before
1769 // exit is called.
1770 struct extrahelp {
1771 StringRef morehelp;
1773 explicit extrahelp(StringRef help);
1776 void PrintVersionMessage();
1778 /// This function just prints the help message, exactly the same way as if the
1779 /// -help or -help-hidden option had been given on the command line.
1781 /// \param Hidden if true will print hidden options
1782 /// \param Categorized if true print options in categories
1783 void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
1785 //===----------------------------------------------------------------------===//
1786 // Public interface for accessing registered options.
1789 /// Use this to get a StringMap to all registered named options
1790 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1792 /// \return A reference to the StringMap used by the cl APIs to parse options.
1794 /// Access to unnamed arguments (i.e. positional) are not provided because
1795 /// it is expected that the client already has access to these.
1797 /// Typical usage:
1798 /// \code
1799 /// main(int argc,char* argv[]) {
1800 /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions();
1801 /// assert(opts.count("help") == 1)
1802 /// opts["help"]->setDescription("Show alphabetical help information")
1803 /// // More code
1804 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1805 /// //More code
1806 /// }
1807 /// \endcode
1809 /// This interface is useful for modifying options in libraries that are out of
1810 /// the control of the client. The options should be modified before calling
1811 /// llvm::cl::ParseCommandLineOptions().
1813 /// Hopefully this API can be deprecated soon. Any situation where options need
1814 /// to be modified by tools or libraries should be handled by sane APIs rather
1815 /// than just handing around a global list.
1816 StringMap<Option *> &getRegisteredOptions(SubCommand &Sub = *TopLevelSubCommand);
1818 /// Use this to get all registered SubCommands from the provided parser.
1820 /// \return A range of all SubCommand pointers registered with the parser.
1822 /// Typical usage:
1823 /// \code
1824 /// main(int argc, char* argv[]) {
1825 /// llvm::cl::ParseCommandLineOptions(argc, argv);
1826 /// for (auto* S : llvm::cl::getRegisteredSubcommands()) {
1827 /// if (*S) {
1828 /// std::cout << "Executing subcommand: " << S->getName() << std::endl;
1829 /// // Execute some function based on the name...
1830 /// }
1831 /// }
1832 /// }
1833 /// \endcode
1835 /// This interface is useful for defining subcommands in libraries and
1836 /// the dispatch from a single point (like in the main function).
1837 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
1838 getRegisteredSubcommands();
1840 //===----------------------------------------------------------------------===//
1841 // Standalone command line processing utilities.
1844 /// Tokenizes a command line that can contain escapes and quotes.
1846 /// The quoting rules match those used by GCC and other tools that use
1847 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1848 /// They differ from buildargv() on treatment of backslashes that do not escape
1849 /// a special character to make it possible to accept most Windows file paths.
1851 /// \param [in] Source The string to be split on whitespace with quotes.
1852 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1853 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1854 /// lines and end of the response file to be marked with a nullptr string.
1855 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1856 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
1857 SmallVectorImpl<const char *> &NewArgv,
1858 bool MarkEOLs = false);
1860 /// Tokenizes a Windows command line which may contain quotes and escaped
1861 /// quotes.
1863 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1864 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1866 /// \param [in] Source The string to be split on whitespace with quotes.
1867 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1868 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1869 /// lines and end of the response file to be marked with a nullptr string.
1870 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1871 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
1872 SmallVectorImpl<const char *> &NewArgv,
1873 bool MarkEOLs = false);
1875 /// String tokenization function type. Should be compatible with either
1876 /// Windows or Unix command line tokenizers.
1877 using TokenizerCallback = void (*)(StringRef Source, StringSaver &Saver,
1878 SmallVectorImpl<const char *> &NewArgv,
1879 bool MarkEOLs);
1881 /// Tokenizes content of configuration file.
1883 /// \param [in] Source The string representing content of config file.
1884 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1885 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1886 /// \param [in] MarkEOLs Added for compatibility with TokenizerCallback.
1888 /// It works like TokenizeGNUCommandLine with ability to skip comment lines.
1890 void tokenizeConfigFile(StringRef Source, StringSaver &Saver,
1891 SmallVectorImpl<const char *> &NewArgv,
1892 bool MarkEOLs = false);
1894 /// Reads command line options from the given configuration file.
1896 /// \param [in] CfgFileName Path to configuration file.
1897 /// \param [in] Saver Objects that saves allocated strings.
1898 /// \param [out] Argv Array to which the read options are added.
1899 /// \return true if the file was successfully read.
1901 /// It reads content of the specified file, tokenizes it and expands "@file"
1902 /// commands resolving file names in them relative to the directory where
1903 /// CfgFilename resides.
1905 bool readConfigFile(StringRef CfgFileName, StringSaver &Saver,
1906 SmallVectorImpl<const char *> &Argv);
1908 /// Expand response files on a command line recursively using the given
1909 /// StringSaver and tokenization strategy. Argv should contain the command line
1910 /// before expansion and will be modified in place. If requested, Argv will
1911 /// also be populated with nullptrs indicating where each response file line
1912 /// ends, which is useful for the "/link" argument that needs to consume all
1913 /// remaining arguments only until the next end of line, when in a response
1914 /// file.
1916 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1917 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1918 /// \param [in,out] Argv Command line into which to expand response files.
1919 /// \param [in] MarkEOLs Mark end of lines and the end of the response file
1920 /// with nullptrs in the Argv vector.
1921 /// \param [in] RelativeNames true if names of nested response files must be
1922 /// resolved relative to including file.
1923 /// \return true if all @files were expanded successfully or there were none.
1924 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1925 SmallVectorImpl<const char *> &Argv,
1926 bool MarkEOLs = false, bool RelativeNames = false);
1928 /// Mark all options not part of this category as cl::ReallyHidden.
1930 /// \param Category the category of options to keep displaying
1932 /// Some tools (like clang-format) like to be able to hide all options that are
1933 /// not specific to the tool. This function allows a tool to specify a single
1934 /// option category to display in the -help output.
1935 void HideUnrelatedOptions(cl::OptionCategory &Category,
1936 SubCommand &Sub = *TopLevelSubCommand);
1938 /// Mark all options not part of the categories as cl::ReallyHidden.
1940 /// \param Categories the categories of options to keep displaying.
1942 /// Some tools (like clang-format) like to be able to hide all options that are
1943 /// not specific to the tool. This function allows a tool to specify a single
1944 /// option category to display in the -help output.
1945 void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
1946 SubCommand &Sub = *TopLevelSubCommand);
1948 /// Reset all command line options to a state that looks as if they have
1949 /// never appeared on the command line. This is useful for being able to parse
1950 /// a command line multiple times (especially useful for writing tests).
1951 void ResetAllOptionOccurrences();
1953 /// Reset the command line parser back to its initial state. This
1954 /// removes
1955 /// all options, categories, and subcommands and returns the parser to a state
1956 /// where no options are supported.
1957 void ResetCommandLineParser();
1959 } // end namespace cl
1961 } // end namespace llvm
1963 #endif // LLVM_SUPPORT_COMMANDLINE_H