1 //===- llvm/Support/CommandLine.h - Command line handler --------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
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
17 //
18 //===----------------------------------------------------------------------===//
19
20 #ifndef LLVM_SUPPORT_COMMANDLINE_H
21 #define LLVM_SUPPORT_COMMANDLINE_H
22
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/ADT/iterator_range.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <cassert>
35 #include <climits>
36 #include <cstddef>
37 #include <functional>
38 #include <initializer_list>
39 #include <string>
40 #include <type_traits>
41 #include <vector>
42
43 namespace llvm {
44
45 class StringSaver;
46 class raw_ostream;
47
48 /// cl Namespace - This namespace contains all of the command line option
49 /// processing machinery. It is intentionally a short name to make qualified
50 /// usage concise.
51 namespace cl {
52
53 //===----------------------------------------------------------------------===//
54 // ParseCommandLineOptions - Command line option processing entry point.
55 //
56 // Returns true on success. Otherwise, this will print the error message to
57 // stderr and exit if \p Errs is not set (nullptr by default), or print the
58 // error message to \p Errs and return false if \p Errs is provided.
59 bool ParseCommandLineOptions(int argc, const char *const *argv,
60 StringRef Overview = "",
61 raw_ostream *Errs = nullptr);
62
63 //===----------------------------------------------------------------------===//
64 // ParseEnvironmentOptions - Environment variable option processing alternate
65 // entry point.
66 //
67 void ParseEnvironmentOptions(const char *progName, const char *envvar,
68 const char *Overview = "");
69
70 // Function pointer type for printing version information.
71 using VersionPrinterTy = std::function<void(raw_ostream &)>;
72
73 ///===---------------------------------------------------------------------===//
74 /// SetVersionPrinter - Override the default (LLVM specific) version printer
75 /// used to print out the version when --version is given
76 /// on the command line. This allows other systems using the
77 /// CommandLine utilities to print their own version string.
78 void SetVersionPrinter(VersionPrinterTy func);
79
80 ///===---------------------------------------------------------------------===//
81 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
82 /// default one. This can be called multiple times,
83 /// and each time it adds a new function to the list
84 /// which will be called after the basic LLVM version
85 /// printing is complete. Each can then add additional
86 /// information specific to the tool.
87 void AddExtraVersionPrinter(VersionPrinterTy func);
88
89 // PrintOptionValues - Print option values.
90 // With -print-options print the difference between option values and defaults.
91 // With -print-all-options print all option values.
92 // (Currently not perfect, but best-effort.)
93 void PrintOptionValues();
94
95 // Forward declaration - AddLiteralOption needs to be up here to make gcc happy.
96 class Option;
97
98 /// Adds a new option for parsing and provides the option it refers to.
99 ///
100 /// \param O pointer to the option
101 /// \param Name the string name for the option to handle during parsing
102 ///
103 /// Literal options are used by some parsers to register special option values.
104 /// This is how the PassNameParser registers pass names for opt.
105 void AddLiteralOption(Option &O, StringRef Name);
106
107 //===----------------------------------------------------------------------===//
108 // Flags permitted to be passed to command line arguments
109 //
110
111 enum NumOccurrencesFlag { // Flags for the number of occurrences allowed
112 Optional = 0x00, // Zero or One occurrence
113 ZeroOrMore = 0x01, // Zero or more occurrences allowed
114 Required = 0x02, // One occurrence required
115 OneOrMore = 0x03, // One or more occurrences required
116
117 // ConsumeAfter - Indicates that this option is fed anything that follows the
118 // last positional argument required by the application (it is an error if
119 // there are zero positional arguments, and a ConsumeAfter option is used).
120 // Thus, for example, all arguments to LLI are processed until a filename is
121 // found. Once a filename is found, all of the succeeding arguments are
122 // passed, unprocessed, to the ConsumeAfter option.
123 //
124 ConsumeAfter = 0x04
125 };
126
127 enum ValueExpected { // Is a value required for the option?
128 // zero reserved for the unspecified value
129 ValueOptional = 0x01, // The value can appear... or not
130 ValueRequired = 0x02, // The value is required to appear!
131 ValueDisallowed = 0x03 // A value may not be specified (for flags)
132 };
133
134 enum OptionHidden { // Control whether -help shows this option
135 NotHidden = 0x00, // Option included in -help & -help-hidden
136 Hidden = 0x01, // -help doesn't, but -help-hidden does
137 ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg
138 };
139
140 // Formatting flags - This controls special features that the option might have
141 // that cause it to be parsed differently...
142 //
143 // Prefix - This option allows arguments that are otherwise unrecognized to be
144 // matched by options that are a prefix of the actual value. This is useful for
145 // cases like a linker, where options are typically of the form '-lfoo' or
146 // '-L../../include' where -l or -L are the actual flags. When prefix is
147 // enabled, and used, the value for the flag comes from the suffix of the
148 // argument.
149 //
150 // Grouping - With this option enabled, multiple letter options are allowed to
151 // bunch together with only a single hyphen for the whole group. This allows
152 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
153 //
154
155 enum FormattingFlags {
156 NormalFormatting = 0x00, // Nothing special
157 Positional = 0x01, // Is a positional argument, no '-' required
158 Prefix = 0x02, // Can this option directly prefix its value?
159 Grouping = 0x03 // Can this option group with other options?
160 };
161
162 enum MiscFlags { // Miscellaneous flags to adjust argument
163 CommaSeparated = 0x01, // Should this cl::list split between commas?
164 PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args?
165 Sink = 0x04 // Should this cl::list eat all unknown options?
166 };
167
168 //===----------------------------------------------------------------------===//
169 // Option Category class
170 //
171 class OptionCategory {
172 private:
173 StringRef const Name;
174 StringRef const Description;
175
176 void registerCategory();
177
178 public:
179 OptionCategory(StringRef const Name,
180 StringRef const Description = "")
Name(Name)181 : Name(Name), Description(Description) {
182 registerCategory();
183 }
184
getName()185 StringRef getName() const { return Name; }
getDescription()186 StringRef getDescription() const { return Description; }
187 };
188
189 // The general Option Category (used as default category).
190 extern OptionCategory GeneralCategory;
191
192 //===----------------------------------------------------------------------===//
193 // SubCommand class
194 //
195 class SubCommand {
196 private:
197 StringRef Name;
198 StringRef Description;
199
200 protected:
201 void registerSubCommand();
202 void unregisterSubCommand();
203
204 public:
205 SubCommand(StringRef Name, StringRef Description = "")
Name(Name)206 : Name(Name), Description(Description) {
207 registerSubCommand();
208 }
209 SubCommand() = default;
210
211 void reset();
212
213 explicit operator bool() const;
214
getName()215 StringRef getName() const { return Name; }
getDescription()216 StringRef getDescription() const { return Description; }
217
218 SmallVector<Option *, 4> PositionalOpts;
219 SmallVector<Option *, 4> SinkOpts;
220 StringMap<Option *> OptionsMap;
221
222 Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists.
223 };
224
225 // A special subcommand representing no subcommand
226 extern ManagedStatic<SubCommand> TopLevelSubCommand;
227
228 // A special subcommand that can be used to put an option into all subcommands.
229 extern ManagedStatic<SubCommand> AllSubCommands;
230
231 //===----------------------------------------------------------------------===//
232 // Option Base class
233 //
234 class Option {
235 friend class alias;
236
237 // handleOccurrences - Overriden by subclasses to handle the value passed into
238 // an argument. Should return true if there was an error processing the
239 // argument and the program should exit.
240 //
241 virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
242 StringRef Arg) = 0;
243
getValueExpectedFlagDefault()244 virtual enum ValueExpected getValueExpectedFlagDefault() const {
245 return ValueOptional;
246 }
247
248 // Out of line virtual function to provide home for the class.
249 virtual void anchor();
250
251 int NumOccurrences = 0; // The number of times specified
252 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
253 // problems with signed enums in bitfields.
254 unsigned Occurrences : 3; // enum NumOccurrencesFlag
255 // not using the enum type for 'Value' because zero is an implementation
256 // detail representing the non-value
257 unsigned Value : 2;
258 unsigned HiddenFlag : 2; // enum OptionHidden
259 unsigned Formatting : 2; // enum FormattingFlags
260 unsigned Misc : 3;
261 unsigned Position = 0; // Position of last occurrence of the option
262 unsigned AdditionalVals = 0; // Greater than 0 for multi-valued option.
263
264 public:
265 StringRef ArgStr; // The argument string itself (ex: "help", "o")
266 StringRef HelpStr; // The descriptive text message for -help
267 StringRef ValueStr; // String describing what the value of this option is
268 OptionCategory *Category; // The Category this option belongs to
269 SmallPtrSet<SubCommand *, 4> Subs; // The subcommands this option belongs to.
270 bool FullyInitialized = false; // Has addArgument been called?
271
getNumOccurrencesFlag()272 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
273 return (enum NumOccurrencesFlag)Occurrences;
274 }
275
getValueExpectedFlag()276 inline enum ValueExpected getValueExpectedFlag() const {
277 return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
278 }
279
getOptionHiddenFlag()280 inline enum OptionHidden getOptionHiddenFlag() const {
281 return (enum OptionHidden)HiddenFlag;
282 }
283
getFormattingFlag()284 inline enum FormattingFlags getFormattingFlag() const {
285 return (enum FormattingFlags)Formatting;
286 }
287
getMiscFlags()288 inline unsigned getMiscFlags() const { return Misc; }
getPosition()289 inline unsigned getPosition() const { return Position; }
getNumAdditionalVals()290 inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
291
292 // hasArgStr - Return true if the argstr != ""
hasArgStr()293 bool hasArgStr() const { return !ArgStr.empty(); }
isPositional()294 bool isPositional() const { return getFormattingFlag() == cl::Positional; }
isSink()295 bool isSink() const { return getMiscFlags() & cl::Sink; }
296
isConsumeAfter()297 bool isConsumeAfter() const {
298 return getNumOccurrencesFlag() == cl::ConsumeAfter;
299 }
300
isInAllSubCommands()301 bool isInAllSubCommands() const {
302 return any_of(Subs, [](const SubCommand *SC) {
303 return SC == &*AllSubCommands;
304 });
305 }
306
307 //-------------------------------------------------------------------------===
308 // Accessor functions set by OptionModifiers
309 //
310 void setArgStr(StringRef S);
setDescription(StringRef S)311 void setDescription(StringRef S) { HelpStr = S; }
setValueStr(StringRef S)312 void setValueStr(StringRef S) { ValueStr = S; }
setNumOccurrencesFlag(enum NumOccurrencesFlag Val)313 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
setValueExpectedFlag(enum ValueExpected Val)314 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
setHiddenFlag(enum OptionHidden Val)315 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
setFormattingFlag(enum FormattingFlags V)316 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
setMiscFlag(enum MiscFlags M)317 void setMiscFlag(enum MiscFlags M) { Misc |= M; }
setPosition(unsigned pos)318 void setPosition(unsigned pos) { Position = pos; }
setCategory(OptionCategory & C)319 void setCategory(OptionCategory &C) { Category = &C; }
addSubCommand(SubCommand & S)320 void addSubCommand(SubCommand &S) { Subs.insert(&S); }
321
322 protected:
Option(enum NumOccurrencesFlag OccurrencesFlag,enum OptionHidden Hidden)323 explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
324 enum OptionHidden Hidden)
325 : Occurrences(OccurrencesFlag), Value(0), HiddenFlag(Hidden),
326 Formatting(NormalFormatting), Misc(0), Category(&GeneralCategory) {}
327
setNumAdditionalVals(unsigned n)328 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
329
330 public:
331 virtual ~Option() = default;
332
333 // addArgument - Register this argument with the commandline system.
334 //
335 void addArgument();
336
337 /// Unregisters this option from the CommandLine system.
338 ///
339 /// This option must have been the last option registered.
340 /// For testing purposes only.
341 void removeArgument();
342
343 // Return the width of the option tag for printing...
344 virtual size_t getOptionWidth() const = 0;
345
346 // printOptionInfo - Print out information about this option. The
347 // to-be-maintained width is specified.
348 //
349 virtual void printOptionInfo(size_t GlobalWidth) const = 0;
350
351 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
352
353 virtual void setDefault() = 0;
354
355 static void printHelpStr(StringRef HelpStr, size_t Indent,
356 size_t FirstLineIndentedBy);
357
getExtraOptionNames(SmallVectorImpl<StringRef> &)358 virtual void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
359
360 // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
361 //
362 virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
363 bool MultiArg = false);
364
365 // Prints option name followed by message. Always returns true.
366 bool error(const Twine &Message, StringRef ArgName = StringRef(), raw_ostream &Errs = llvm::errs());
error(const Twine & Message,raw_ostream & Errs)367 bool error(const Twine &Message, raw_ostream &Errs) {
368 return error(Message, StringRef(), Errs);
369 }
370
getNumOccurrences()371 inline int getNumOccurrences() const { return NumOccurrences; }
reset()372 inline void reset() { NumOccurrences = 0; }
373 };
374
375 //===----------------------------------------------------------------------===//
376 // Command line option modifiers that can be used to modify the behavior of
377 // command line option parsers...
378 //
379
380 // desc - Modifier to set the description shown in the -help output...
381 struct desc {
382 StringRef Desc;
383
descdesc384 desc(StringRef Str) : Desc(Str) {}
385
applydesc386 void apply(Option &O) const { O.setDescription(Desc); }
387 };
388
389 // value_desc - Modifier to set the value description shown in the -help
390 // output...
391 struct value_desc {
392 StringRef Desc;
393
value_descvalue_desc394 value_desc(StringRef Str) : Desc(Str) {}
395
applyvalue_desc396 void apply(Option &O) const { O.setValueStr(Desc); }
397 };
398
399 // init - Specify a default (initial) value for the command line argument, if
400 // the default constructor for the argument type does not give you what you
401 // want. This is only valid on "opt" arguments, not on "list" arguments.
402 //
403 template <class Ty> struct initializer {
404 const Ty &Init;
initializerinitializer405 initializer(const Ty &Val) : Init(Val) {}
406
applyinitializer407 template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
408 };
409
init(const Ty & Val)410 template <class Ty> initializer<Ty> init(const Ty &Val) {
411 return initializer<Ty>(Val);
412 }
413
414 // location - Allow the user to specify which external variable they want to
415 // store the results of the command line argument processing into, if they don't
416 // want to store it in the option itself.
417 //
418 template <class Ty> struct LocationClass {
419 Ty &Loc;
420
LocationClassLocationClass421 LocationClass(Ty &L) : Loc(L) {}
422
applyLocationClass423 template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
424 };
425
location(Ty & L)426 template <class Ty> LocationClass<Ty> location(Ty &L) {
427 return LocationClass<Ty>(L);
428 }
429
430 // cat - Specifiy the Option category for the command line argument to belong
431 // to.
432 struct cat {
433 OptionCategory &Category;
434
catcat435 cat(OptionCategory &c) : Category(c) {}
436
applycat437 template <class Opt> void apply(Opt &O) const { O.setCategory(Category); }
438 };
439
440 // sub - Specify the subcommand that this option belongs to.
441 struct sub {
442 SubCommand ⋐
443
subsub444 sub(SubCommand &S) : Sub(S) {}
445
applysub446 template <class Opt> void apply(Opt &O) const { O.addSubCommand(Sub); }
447 };
448
449 //===----------------------------------------------------------------------===//
450 // OptionValue class
451
452 // Support value comparison outside the template.
453 struct GenericOptionValue {
454 virtual bool compare(const GenericOptionValue &V) const = 0;
455
456 protected:
457 GenericOptionValue() = default;
458 GenericOptionValue(const GenericOptionValue&) = default;
459 GenericOptionValue &operator=(const GenericOptionValue &) = default;
460 ~GenericOptionValue() = default;
461
462 private:
463 virtual void anchor();
464 };
465
466 template <class DataType> struct OptionValue;
467
468 // The default value safely does nothing. Option value printing is only
469 // best-effort.
470 template <class DataType, bool isClass>
471 struct OptionValueBase : public GenericOptionValue {
472 // Temporary storage for argument passing.
473 using WrapperType = OptionValue<DataType>;
474
hasValueOptionValueBase475 bool hasValue() const { return false; }
476
getValueOptionValueBase477 const DataType &getValue() const { llvm_unreachable("no default value"); }
478
479 // Some options may take their value from a different data type.
setValueOptionValueBase480 template <class DT> void setValue(const DT & /*V*/) {}
481
compareOptionValueBase482 bool compare(const DataType & /*V*/) const { return false; }
483
compareOptionValueBase484 bool compare(const GenericOptionValue & /*V*/) const override {
485 return false;
486 }
487
488 protected:
489 ~OptionValueBase() = default;
490 };
491
492 // Simple copy of the option value.
493 template <class DataType> class OptionValueCopy : public GenericOptionValue {
494 DataType Value;
495 bool Valid = false;
496
497 protected:
498 OptionValueCopy(const OptionValueCopy&) = default;
499 OptionValueCopy &operator=(const OptionValueCopy &) = default;
500 ~OptionValueCopy() = default;
501
502 public:
503 OptionValueCopy() = default;
504
hasValue()505 bool hasValue() const { return Valid; }
506
getValue()507 const DataType &getValue() const {
508 assert(Valid && "invalid option value");
509 return Value;
510 }
511
setValue(const DataType & V)512 void setValue(const DataType &V) {
513 Valid = true;
514 Value = V;
515 }
516
compare(const DataType & V)517 bool compare(const DataType &V) const { return Valid && (Value != V); }
518
compare(const GenericOptionValue & V)519 bool compare(const GenericOptionValue &V) const override {
520 const OptionValueCopy<DataType> &VC =
521 static_cast<const OptionValueCopy<DataType> &>(V);
522 if (!VC.hasValue())
523 return false;
524 return compare(VC.getValue());
525 }
526 };
527
528 // Non-class option values.
529 template <class DataType>
530 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
531 using WrapperType = DataType;
532
533 protected:
534 OptionValueBase() = default;
535 OptionValueBase(const OptionValueBase&) = default;
536 OptionValueBase &operator=(const OptionValueBase &) = default;
537 ~OptionValueBase() = default;
538 };
539
540 // Top-level option class.
541 template <class DataType>
542 struct OptionValue final
543 : OptionValueBase<DataType, std::is_class<DataType>::value> {
544 OptionValue() = default;
545
546 OptionValue(const DataType &V) { this->setValue(V); }
547
548 // Some options may take their value from a different data type.
549 template <class DT> OptionValue<DataType> &operator=(const DT &V) {
550 this->setValue(V);
551 return *this;
552 }
553 };
554
555 // Other safe-to-copy-by-value common option types.
556 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
557 template <>
558 struct OptionValue<cl::boolOrDefault> final
559 : OptionValueCopy<cl::boolOrDefault> {
560 using WrapperType = cl::boolOrDefault;
561
562 OptionValue() = default;
563
564 OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
565
566 OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
567 setValue(V);
568 return *this;
569 }
570
571 private:
572 void anchor() override;
573 };
574
575 template <>
576 struct OptionValue<std::string> final : OptionValueCopy<std::string> {
577 using WrapperType = StringRef;
578
579 OptionValue() = default;
580
581 OptionValue(const std::string &V) { this->setValue(V); }
582
583 OptionValue<std::string> &operator=(const std::string &V) {
584 setValue(V);
585 return *this;
586 }
587
588 private:
589 void anchor() override;
590 };
591
592 //===----------------------------------------------------------------------===//
593 // Enum valued command line option
594 //
595
596 // This represents a single enum value, using "int" as the underlying type.
597 struct OptionEnumValue {
598 StringRef Name;
599 int Value;
600 StringRef Description;
601 };
602
603 #define clEnumVal(ENUMVAL, DESC) \
604 llvm::cl::OptionEnumValue { #ENUMVAL, int(ENUMVAL), DESC }
605 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) \
606 llvm::cl::OptionEnumValue { FLAGNAME, int(ENUMVAL), DESC }
607
608 // values - For custom data types, allow specifying a group of values together
609 // as the values that go into the mapping that the option handler uses.
610 //
611 class ValuesClass {
612 // Use a vector instead of a map, because the lists should be short,
613 // the overhead is less, and most importantly, it keeps them in the order
614 // inserted so we can print our option out nicely.
615 SmallVector<OptionEnumValue, 4> Values;
616
617 public:
618 ValuesClass(std::initializer_list<OptionEnumValue> Options)
619 : Values(Options) {}
620
621 template <class Opt> void apply(Opt &O) const {
622 for (auto Value : Values)
623 O.getParser().addLiteralOption(Value.Name, Value.Value,
624 Value.Description);
625 }
626 };
627
628 /// Helper to build a ValuesClass by forwarding a variable number of arguments
629 /// as an initializer list to the ValuesClass constructor.
630 template <typename... OptsTy> ValuesClass values(OptsTy... Options) {
631 return ValuesClass({Options...});
632 }
633
634 //===----------------------------------------------------------------------===//
635 // parser class - Parameterizable parser for different data types. By default,
636 // known data types (string, int, bool) have specialized parsers, that do what
637 // you would expect. The default parser, used for data types that are not
638 // built-in, uses a mapping table to map specific options to values, which is
639 // used, among other things, to handle enum types.
640
641 //--------------------------------------------------
642 // generic_parser_base - This class holds all the non-generic code that we do
643 // not need replicated for every instance of the generic parser. This also
644 // allows us to put stuff into CommandLine.cpp
645 //
646 class generic_parser_base {
647 protected:
648 class GenericOptionInfo {
649 public:
650 GenericOptionInfo(StringRef name, StringRef helpStr)
651 : Name(name), HelpStr(helpStr) {}
652 StringRef Name;
653 StringRef HelpStr;
654 };
655
656 public:
657 generic_parser_base(Option &O) : Owner(O) {}
658
659 virtual ~generic_parser_base() = default;
660 // Base class should have virtual-destructor
661
662 // getNumOptions - Virtual function implemented by generic subclass to
663 // indicate how many entries are in Values.
664 //
665 virtual unsigned getNumOptions() const = 0;
666
667 // getOption - Return option name N.
668 virtual StringRef getOption(unsigned N) const = 0;
669
670 // getDescription - Return description N
671 virtual StringRef getDescription(unsigned N) const = 0;
672
673 // Return the width of the option tag for printing...
674 virtual size_t getOptionWidth(const Option &O) const;
675
676 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
677
678 // printOptionInfo - Print out information about this option. The
679 // to-be-maintained width is specified.
680 //
681 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
682
683 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
684 const GenericOptionValue &Default,
685 size_t GlobalWidth) const;
686
687 // printOptionDiff - print the value of an option and it's default.
688 //
689 // Template definition ensures that the option and default have the same
690 // DataType (via the same AnyOptionValue).
691 template <class AnyOptionValue>
692 void printOptionDiff(const Option &O, const AnyOptionValue &V,
693 const AnyOptionValue &Default,
694 size_t GlobalWidth) const {
695 printGenericOptionDiff(O, V, Default, GlobalWidth);
696 }
697
698 void initialize() {}
699
700 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) {
701 // If there has been no argstr specified, that means that we need to add an
702 // argument for every possible option. This ensures that our options are
703 // vectored to us.
704 if (!Owner.hasArgStr())
705 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
706 OptionNames.push_back(getOption(i));
707 }
708
709 enum ValueExpected getValueExpectedFlagDefault() const {
710 // If there is an ArgStr specified, then we are of the form:
711 //
712 // -opt=O2 or -opt O2 or -optO2
713 //
714 // In which case, the value is required. Otherwise if an arg str has not
715 // been specified, we are of the form:
716 //
717 // -O2 or O2 or -la (where -l and -a are separate options)
718 //
719 // If this is the case, we cannot allow a value.
720 //
721 if (Owner.hasArgStr())
722 return ValueRequired;
723 else
724 return ValueDisallowed;
725 }
726
727 // findOption - Return the option number corresponding to the specified
728 // argument string. If the option is not found, getNumOptions() is returned.
729 //
730 unsigned findOption(StringRef Name);
731
732 protected:
733 Option &Owner;
734 };
735
736 // Default parser implementation - This implementation depends on having a
737 // mapping of recognized options to values of some sort. In addition to this,
738 // each entry in the mapping also tracks a help message that is printed with the
739 // command line option for -help. Because this is a simple mapping parser, the
740 // data type can be any unsupported type.
741 //
742 template <class DataType> class parser : public generic_parser_base {
743 protected:
744 class OptionInfo : public GenericOptionInfo {
745 public:
746 OptionInfo(StringRef name, DataType v, StringRef helpStr)
747 : GenericOptionInfo(name, helpStr), V(v) {}
748
749 OptionValue<DataType> V;
750 };
751 SmallVector<OptionInfo, 8> Values;
752
753 public:
754 parser(Option &O) : generic_parser_base(O) {}
755
756 using parser_data_type = DataType;
757
758 // Implement virtual functions needed by generic_parser_base
759 unsigned getNumOptions() const override { return unsigned(Values.size()); }
760 StringRef getOption(unsigned N) const override { return Values[N].Name; }
761 StringRef getDescription(unsigned N) const override {
762 return Values[N].HelpStr;
763 }
764
765 // getOptionValue - Return the value of option name N.
766 const GenericOptionValue &getOptionValue(unsigned N) const override {
767 return Values[N].V;
768 }
769
770 // parse - Return true on error.
771 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
772 StringRef ArgVal;
773 if (Owner.hasArgStr())
774 ArgVal = Arg;
775 else
776 ArgVal = ArgName;
777
778 for (size_t i = 0, e = Values.size(); i != e; ++i)
779 if (Values[i].Name == ArgVal) {
780 V = Values[i].V.getValue();
781 return false;
782 }
783
784 return O.error("Cannot find option named '" + ArgVal + "'!");
785 }
786
787 /// addLiteralOption - Add an entry to the mapping table.
788 ///
789 template <class DT>
790 void addLiteralOption(StringRef Name, const DT &V, StringRef HelpStr) {
791 assert(findOption(Name) == Values.size() && "Option already exists!");
792 OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
793 Values.push_back(X);
794 AddLiteralOption(Owner, Name);
795 }
796
797 /// removeLiteralOption - Remove the specified option.
798 ///
799 void removeLiteralOption(StringRef Name) {
800 unsigned N = findOption(Name);
801 assert(N != Values.size() && "Option not found!");
802 Values.erase(Values.begin() + N);
803 }
804 };
805
806 //--------------------------------------------------
807 // basic_parser - Super class of parsers to provide boilerplate code
808 //
809 class basic_parser_impl { // non-template implementation of basic_parser<t>
810 public:
811 basic_parser_impl(Option &) {}
812
813 enum ValueExpected getValueExpectedFlagDefault() const {
814 return ValueRequired;
815 }
816
817 void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
818
819 void initialize() {}
820
821 // Return the width of the option tag for printing...
822 size_t getOptionWidth(const Option &O) const;
823
824 // printOptionInfo - Print out information about this option. The
825 // to-be-maintained width is specified.
826 //
827 void printOptionInfo(const Option &O, size_t GlobalWidth) const;
828
829 // printOptionNoValue - Print a placeholder for options that don't yet support
830 // printOptionDiff().
831 void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
832
833 // getValueName - Overload in subclass to provide a better default value.
834 virtual StringRef getValueName() const { return "value"; }
835
836 // An out-of-line virtual method to provide a 'home' for this class.
837 virtual void anchor();
838
839 protected:
840 ~basic_parser_impl() = default;
841
842 // A helper for basic_parser::printOptionDiff.
843 void printOptionName(const Option &O, size_t GlobalWidth) const;
844 };
845
846 // basic_parser - The real basic parser is just a template wrapper that provides
847 // a typedef for the provided data type.
848 //
849 template <class DataType> class basic_parser : public basic_parser_impl {
850 public:
851 using parser_data_type = DataType;
852 using OptVal = OptionValue<DataType>;
853
854 basic_parser(Option &O) : basic_parser_impl(O) {}
855
856 protected:
857 ~basic_parser() = default;
858 };
859
860 //--------------------------------------------------
861 // parser<bool>
862 //
863 template <> class parser<bool> final : public basic_parser<bool> {
864 public:
865 parser(Option &O) : basic_parser(O) {}
866
867 // parse - Return true on error.
868 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
869
870 void initialize() {}
871
872 enum ValueExpected getValueExpectedFlagDefault() const {
873 return ValueOptional;
874 }
875
876 // getValueName - Do not print =<value> at all.
877 StringRef getValueName() const override { return StringRef(); }
878
879 void printOptionDiff(const Option &O, bool V, OptVal Default,
880 size_t GlobalWidth) const;
881
882 // An out-of-line virtual method to provide a 'home' for this class.
883 void anchor() override;
884 };
885
886 extern template class basic_parser<bool>;
887
888 //--------------------------------------------------
889 // parser<boolOrDefault>
890 template <>
891 class parser<boolOrDefault> final : public basic_parser<boolOrDefault> {
892 public:
893 parser(Option &O) : basic_parser(O) {}
894
895 // parse - Return true on error.
896 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
897
898 enum ValueExpected getValueExpectedFlagDefault() const {
899 return ValueOptional;
900 }
901
902 // getValueName - Do not print =<value> at all.
903 StringRef getValueName() const override { return StringRef(); }
904
905 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
906 size_t GlobalWidth) const;
907
908 // An out-of-line virtual method to provide a 'home' for this class.
909 void anchor() override;
910 };
911
912 extern template class basic_parser<boolOrDefault>;
913
914 //--------------------------------------------------
915 // parser<int>
916 //
917 template <> class parser<int> final : public basic_parser<int> {
918 public:
919 parser(Option &O) : basic_parser(O) {}
920
921 // parse - Return true on error.
922 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
923
924 // getValueName - Overload in subclass to provide a better default value.
925 StringRef getValueName() const override { return "int"; }
926
927 void printOptionDiff(const Option &O, int V, OptVal Default,
928 size_t GlobalWidth) const;
929
930 // An out-of-line virtual method to provide a 'home' for this class.
931 void anchor() override;
932 };
933
934 extern template class basic_parser<int>;
935
936 //--------------------------------------------------
937 // parser<unsigned>
938 //
939 template <> class parser<unsigned> final : public basic_parser<unsigned> {
940 public:
941 parser(Option &O) : basic_parser(O) {}
942
943 // parse - Return true on error.
944 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
945
946 // getValueName - Overload in subclass to provide a better default value.
947 StringRef getValueName() const override { return "uint"; }
948
949 void printOptionDiff(const Option &O, unsigned V, OptVal Default,
950 size_t GlobalWidth) const;
951
952 // An out-of-line virtual method to provide a 'home' for this class.
953 void anchor() override;
954 };
955
956 extern template class basic_parser<unsigned>;
957
958 //--------------------------------------------------
959 // parser<unsigned long long>
960 //
961 template <>
962 class parser<unsigned long long> final
963 : public basic_parser<unsigned long long> {
964 public:
965 parser(Option &O) : basic_parser(O) {}
966
967 // parse - Return true on error.
968 bool parse(Option &O, StringRef ArgName, StringRef Arg,
969 unsigned long long &Val);
970
971 // getValueName - Overload in subclass to provide a better default value.
972 StringRef getValueName() const override { return "uint"; }
973
974 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
975 size_t GlobalWidth) const;
976
977 // An out-of-line virtual method to provide a 'home' for this class.
978 void anchor() override;
979 };
980
981 extern template class basic_parser<unsigned long long>;
982
983 //--------------------------------------------------
984 // parser<double>
985 //
986 template <> class parser<double> final : public basic_parser<double> {
987 public:
988 parser(Option &O) : basic_parser(O) {}
989
990 // parse - Return true on error.
991 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
992
993 // getValueName - Overload in subclass to provide a better default value.
994 StringRef getValueName() const override { return "number"; }
995
996 void printOptionDiff(const Option &O, double V, OptVal Default,
997 size_t GlobalWidth) const;
998
999 // An out-of-line virtual method to provide a 'home' for this class.
1000 void anchor() override;
1001 };
1002
1003 extern template class basic_parser<double>;
1004
1005 //--------------------------------------------------
1006 // parser<float>
1007 //
1008 template <> class parser<float> final : public basic_parser<float> {
1009 public:
1010 parser(Option &O) : basic_parser(O) {}
1011
1012 // parse - Return true on error.
1013 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
1014
1015 // getValueName - Overload in subclass to provide a better default value.
1016 StringRef getValueName() const override { return "number"; }
1017
1018 void printOptionDiff(const Option &O, float V, OptVal Default,
1019 size_t GlobalWidth) const;
1020
1021 // An out-of-line virtual method to provide a 'home' for this class.
1022 void anchor() override;
1023 };
1024
1025 extern template class basic_parser<float>;
1026
1027 //--------------------------------------------------
1028 // parser<std::string>
1029 //
1030 template <> class parser<std::string> final : public basic_parser<std::string> {
1031 public:
1032 parser(Option &O) : basic_parser(O) {}
1033
1034 // parse - Return true on error.
1035 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
1036 Value = Arg.str();
1037 return false;
1038 }
1039
1040 // getValueName - Overload in subclass to provide a better default value.
1041 StringRef getValueName() const override { return "string"; }
1042
1043 void printOptionDiff(const Option &O, StringRef V, const OptVal &Default,
1044 size_t GlobalWidth) const;
1045
1046 // An out-of-line virtual method to provide a 'home' for this class.
1047 void anchor() override;
1048 };
1049
1050 extern template class basic_parser<std::string>;
1051
1052 //--------------------------------------------------
1053 // parser<char>
1054 //
1055 template <> class parser<char> final : public basic_parser<char> {
1056 public:
1057 parser(Option &O) : basic_parser(O) {}
1058
1059 // parse - Return true on error.
1060 bool parse(Option &, StringRef, StringRef Arg, char &Value) {
1061 Value = Arg[0];
1062 return false;
1063 }
1064
1065 // getValueName - Overload in subclass to provide a better default value.
1066 StringRef getValueName() const override { return "char"; }
1067
1068 void printOptionDiff(const Option &O, char V, OptVal Default,
1069 size_t GlobalWidth) const;
1070
1071 // An out-of-line virtual method to provide a 'home' for this class.
1072 void anchor() override;
1073 };
1074
1075 extern template class basic_parser<char>;
1076
1077 //--------------------------------------------------
1078 // PrintOptionDiff
1079 //
1080 // This collection of wrappers is the intermediary between class opt and class
1081 // parser to handle all the template nastiness.
1082
1083 // This overloaded function is selected by the generic parser.
1084 template <class ParserClass, class DT>
1085 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
1086 const OptionValue<DT> &Default, size_t GlobalWidth) {
1087 OptionValue<DT> OV = V;
1088 P.printOptionDiff(O, OV, Default, GlobalWidth);
1089 }
1090
1091 // This is instantiated for basic parsers when the parsed value has a different
1092 // type than the option value. e.g. HelpPrinter.
1093 template <class ParserDT, class ValDT> struct OptionDiffPrinter {
1094 void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/,
1095 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
1096 P.printOptionNoValue(O, GlobalWidth);
1097 }
1098 };
1099
1100 // This is instantiated for basic parsers when the parsed value has the same
1101 // type as the option value.
1102 template <class DT> struct OptionDiffPrinter<DT, DT> {
1103 void print(const Option &O, const parser<DT> &P, const DT &V,
1104 const OptionValue<DT> &Default, size_t GlobalWidth) {
1105 P.printOptionDiff(O, V, Default, GlobalWidth);
1106 }
1107 };
1108
1109 // This overloaded function is selected by the basic parser, which may parse a
1110 // different type than the option type.
1111 template <class ParserClass, class ValDT>
1112 void printOptionDiff(
1113 const Option &O,
1114 const basic_parser<typename ParserClass::parser_data_type> &P,
1115 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
1116
1117 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
1118 printer.print(O, static_cast<const ParserClass &>(P), V, Default,
1119 GlobalWidth);
1120 }
1121
1122 //===----------------------------------------------------------------------===//
1123 // applicator class - This class is used because we must use partial
1124 // specialization to handle literal string arguments specially (const char* does
1125 // not correctly respond to the apply method). Because the syntax to use this
1126 // is a pain, we have the 'apply' method below to handle the nastiness...
1127 //
1128 template <class Mod> struct applicator {
1129 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1130 };
1131
1132 // Handle const char* as a special case...
1133 template <unsigned n> struct applicator<char[n]> {
1134 template <class Opt> static void opt(StringRef Str, Opt &O) {
1135 O.setArgStr(Str);
1136 }
1137 };
1138 template <unsigned n> struct applicator<const char[n]> {
1139 template <class Opt> static void opt(StringRef Str, Opt &O) {
1140 O.setArgStr(Str);
1141 }
1142 };
1143 template <> struct applicator<StringRef > {
1144 template <class Opt> static void opt(StringRef Str, Opt &O) {
1145 O.setArgStr(Str);
1146 }
1147 };
1148
1149 template <> struct applicator<NumOccurrencesFlag> {
1150 static void opt(NumOccurrencesFlag N, Option &O) {
1151 O.setNumOccurrencesFlag(N);
1152 }
1153 };
1154
1155 template <> struct applicator<ValueExpected> {
1156 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1157 };
1158
1159 template <> struct applicator<OptionHidden> {
1160 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1161 };
1162
1163 template <> struct applicator<FormattingFlags> {
1164 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1165 };
1166
1167 template <> struct applicator<MiscFlags> {
1168 static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1169 };
1170
1171 // apply method - Apply modifiers to an option in a type safe way.
1172 template <class Opt, class Mod, class... Mods>
1173 void apply(Opt *O, const Mod &M, const Mods &... Ms) {
1174 applicator<Mod>::opt(M, *O);
1175 apply(O, Ms...);
1176 }
1177
1178 template <class Opt, class Mod> void apply(Opt *O, const Mod &M) {
1179 applicator<Mod>::opt(M, *O);
1180 }
1181
1182 //===----------------------------------------------------------------------===//
1183 // opt_storage class
1184
1185 // Default storage class definition: external storage. This implementation
1186 // assumes the user will specify a variable to store the data into with the
1187 // cl::location(x) modifier.
1188 //
1189 template <class DataType, bool ExternalStorage, bool isClass>
1190 class opt_storage {
1191 DataType *Location = nullptr; // Where to store the object...
1192 OptionValue<DataType> Default;
1193
1194 void check_location() const {
1195 assert(Location && "cl::location(...) not specified for a command "
1196 "line option with external storage, "
1197 "or cl::init specified before cl::location()!!");
1198 }
1199
1200 public:
1201 opt_storage() = default;
1202
1203 bool setLocation(Option &O, DataType &L) {
1204 if (Location)
1205 return O.error("cl::location(x) specified more than once!");
1206 Location = &L;
1207 Default = L;
1208 return false;
1209 }
1210
1211 template <class T> void setValue(const T &V, bool initial = false) {
1212 check_location();
1213 *Location = V;
1214 if (initial)
1215 Default = V;
1216 }
1217
1218 DataType &getValue() {
1219 check_location();
1220 return *Location;
1221 }
1222 const DataType &getValue() const {
1223 check_location();
1224 return *Location;
1225 }
1226
1227 operator DataType() const { return this->getValue(); }
1228
1229 const OptionValue<DataType> &getDefault() const { return Default; }
1230 };
1231
1232 // Define how to hold a class type object, such as a string. Since we can
1233 // inherit from a class, we do so. This makes us exactly compatible with the
1234 // object in all cases that it is used.
1235 //
1236 template <class DataType>
1237 class opt_storage<DataType, false, true> : public DataType {
1238 public:
1239 OptionValue<DataType> Default;
1240
1241 template <class T> void setValue(const T &V, bool initial = false) {
1242 DataType::operator=(V);
1243 if (initial)
1244 Default = V;
1245 }
1246
1247 DataType &getValue() { return *this; }
1248 const DataType &getValue() const { return *this; }
1249
1250 const OptionValue<DataType> &getDefault() const { return Default; }
1251 };
1252
1253 // Define a partial specialization to handle things we cannot inherit from. In
1254 // this case, we store an instance through containment, and overload operators
1255 // to get at the value.
1256 //
1257 template <class DataType> class opt_storage<DataType, false, false> {
1258 public:
1259 DataType Value;
1260 OptionValue<DataType> Default;
1261
1262 // Make sure we initialize the value with the default constructor for the
1263 // type.
1264 opt_storage() : Value(DataType()), Default(DataType()) {}
1265
1266 template <class T> void setValue(const T &V, bool initial = false) {
1267 Value = V;
1268 if (initial)
1269 Default = V;
1270 }
1271 DataType &getValue() { return Value; }
1272 DataType getValue() const { return Value; }
1273
1274 const OptionValue<DataType> &getDefault() const { return Default; }
1275
1276 operator DataType() const { return getValue(); }
1277
1278 // If the datatype is a pointer, support -> on it.
1279 DataType operator->() const { return Value; }
1280 };
1281
1282 //===----------------------------------------------------------------------===//
1283 // opt - A scalar command line option.
1284 //
1285 template <class DataType, bool ExternalStorage = false,
1286 class ParserClass = parser<DataType>>
1287 class opt : public Option,
1288 public opt_storage<DataType, ExternalStorage,
1289 std::is_class<DataType>::value> {
1290 ParserClass Parser;
1291
1292 bool handleOccurrence(unsigned pos, StringRef ArgName,
1293 StringRef Arg) override {
1294 typename ParserClass::parser_data_type Val =
1295 typename ParserClass::parser_data_type();
1296 if (Parser.parse(*this, ArgName, Arg, Val))
1297 return true; // Parse error!
1298 this->setValue(Val);
1299 this->setPosition(pos);
1300 return false;
1301 }
1302
1303 enum ValueExpected getValueExpectedFlagDefault() const override {
1304 return Parser.getValueExpectedFlagDefault();
1305 }
1306
1307 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1308 return Parser.getExtraOptionNames(OptionNames);
1309 }
1310
1311 // Forward printing stuff to the parser...
1312 size_t getOptionWidth() const override {
1313 return Parser.getOptionWidth(*this);
1314 }
1315
1316 void printOptionInfo(size_t GlobalWidth) const override {
1317 Parser.printOptionInfo(*this, GlobalWidth);
1318 }
1319
1320 void printOptionValue(size_t GlobalWidth, bool Force) const override {
1321 if (Force || this->getDefault().compare(this->getValue())) {
1322 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1323 this->getDefault(), GlobalWidth);
1324 }
1325 }
1326
1327 template <class T, class = typename std::enable_if<
1328 std::is_assignable<T&, T>::value>::type>
1329 void setDefaultImpl() {
1330 const OptionValue<DataType> &V = this->getDefault();
1331 if (V.hasValue())
1332 this->setValue(V.getValue());
1333 }
1334
1335 template <class T, class = typename std::enable_if<
1336 !std::is_assignable<T&, T>::value>::type>
1337 void setDefaultImpl(...) {}
1338
1339 void setDefault() override { setDefaultImpl<DataType>(); }
1340
1341 void done() {
1342 addArgument();
1343 Parser.initialize();
1344 }
1345
1346 public:
1347 // Command line options should not be copyable
1348 opt(const opt &) = delete;
1349 opt &operator=(const opt &) = delete;
1350
1351 // setInitialValue - Used by the cl::init modifier...
1352 void setInitialValue(const DataType &V) { this->setValue(V, true); }
1353
1354 ParserClass &getParser() { return Parser; }
1355
1356 template <class T> DataType &operator=(const T &Val) {
1357 this->setValue(Val);
1358 return this->getValue();
1359 }
1360
1361 template <class... Mods>
1362 explicit opt(const Mods &... Ms)
1363 : Option(Optional, NotHidden), Parser(*this) {
1364 apply(this, Ms...);
1365 done();
1366 }
1367 };
1368
1369 extern template class opt<unsigned>;
1370 extern template class opt<int>;
1371 extern template class opt<std::string>;
1372 extern template class opt<char>;
1373 extern template class opt<bool>;
1374
1375 //===----------------------------------------------------------------------===//
1376 // list_storage class
1377
1378 // Default storage class definition: external storage. This implementation
1379 // assumes the user will specify a variable to store the data into with the
1380 // cl::location(x) modifier.
1381 //
1382 template <class DataType, class StorageClass> class list_storage {
1383 StorageClass *Location = nullptr; // Where to store the object...
1384
1385 public:
1386 list_storage() = default;
1387
1388 bool setLocation(Option &O, StorageClass &L) {
1389 if (Location)
1390 return O.error("cl::location(x) specified more than once!");
1391 Location = &L;
1392 return false;
1393 }
1394
1395 template <class T> void addValue(const T &V) {
1396 assert(Location != 0 && "cl::location(...) not specified for a command "
1397 "line option with external storage!");
1398 Location->push_back(V);
1399 }
1400 };
1401
1402 // Define how to hold a class type object, such as a string.
1403 // Originally this code inherited from std::vector. In transitioning to a new
1404 // API for command line options we should change this. The new implementation
1405 // of this list_storage specialization implements the minimum subset of the
1406 // std::vector API required for all the current clients.
1407 //
1408 // FIXME: Reduce this API to a more narrow subset of std::vector
1409 //
1410 template <class DataType> class list_storage<DataType, bool> {
1411 std::vector<DataType> Storage;
1412
1413 public:
1414 using iterator = typename std::vector<DataType>::iterator;
1415
1416 iterator begin() { return Storage.begin(); }
1417 iterator end() { return Storage.end(); }
1418
1419 using const_iterator = typename std::vector<DataType>::const_iterator;
1420
1421 const_iterator begin() const { return Storage.begin(); }
1422 const_iterator end() const { return Storage.end(); }
1423
1424 using size_type = typename std::vector<DataType>::size_type;
1425
1426 size_type size() const { return Storage.size(); }
1427
1428 bool empty() const { return Storage.empty(); }
1429
1430 void push_back(const DataType &value) { Storage.push_back(value); }
1431 void push_back(DataType &&value) { Storage.push_back(value); }
1432
1433 using reference = typename std::vector<DataType>::reference;
1434 using const_reference = typename std::vector<DataType>::const_reference;
1435
1436 reference operator[](size_type pos) { return Storage[pos]; }
1437 const_reference operator[](size_type pos) const { return Storage[pos]; }
1438
1439 iterator erase(const_iterator pos) { return Storage.erase(pos); }
1440 iterator erase(const_iterator first, const_iterator last) {
1441 return Storage.erase(first, last);
1442 }
1443
1444 iterator erase(iterator pos) { return Storage.erase(pos); }
1445 iterator erase(iterator first, iterator last) {
1446 return Storage.erase(first, last);
1447 }
1448
1449 iterator insert(const_iterator pos, const DataType &value) {
1450 return Storage.insert(pos, value);
1451 }
1452 iterator insert(const_iterator pos, DataType &&value) {
1453 return Storage.insert(pos, value);
1454 }
1455
1456 iterator insert(iterator pos, const DataType &value) {
1457 return Storage.insert(pos, value);
1458 }
1459 iterator insert(iterator pos, DataType &&value) {
1460 return Storage.insert(pos, value);
1461 }
1462
1463 reference front() { return Storage.front(); }
1464 const_reference front() const { return Storage.front(); }
1465
1466 operator std::vector<DataType>&() { return Storage; }
1467 operator ArrayRef<DataType>() { return Storage; }
1468 std::vector<DataType> *operator&() { return &Storage; }
1469 const std::vector<DataType> *operator&() const { return &Storage; }
1470
1471 template <class T> void addValue(const T &V) { Storage.push_back(V); }
1472 };
1473
1474 //===----------------------------------------------------------------------===//
1475 // list - A list of command line options.
1476 //
1477 template <class DataType, class StorageClass = bool,
1478 class ParserClass = parser<DataType>>
1479 class list : public Option, public list_storage<DataType, StorageClass> {
1480 std::vector<unsigned> Positions;
1481 ParserClass Parser;
1482
1483 enum ValueExpected getValueExpectedFlagDefault() const override {
1484 return Parser.getValueExpectedFlagDefault();
1485 }
1486
1487 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1488 return Parser.getExtraOptionNames(OptionNames);
1489 }
1490
1491 bool handleOccurrence(unsigned pos, StringRef ArgName,
1492 StringRef Arg) override {
1493 typename ParserClass::parser_data_type Val =
1494 typename ParserClass::parser_data_type();
1495 if (Parser.parse(*this, ArgName, Arg, Val))
1496 return true; // Parse Error!
1497 list_storage<DataType, StorageClass>::addValue(Val);
1498 setPosition(pos);
1499 Positions.push_back(pos);
1500 return false;
1501 }
1502
1503 // Forward printing stuff to the parser...
1504 size_t getOptionWidth() const override {
1505 return Parser.getOptionWidth(*this);
1506 }
1507
1508 void printOptionInfo(size_t GlobalWidth) const override {
1509 Parser.printOptionInfo(*this, GlobalWidth);
1510 }
1511
1512 // Unimplemented: list options don't currently store their default value.
1513 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1514 }
1515
1516 void setDefault() override {}
1517
1518 void done() {
1519 addArgument();
1520 Parser.initialize();
1521 }
1522
1523 public:
1524 // Command line options should not be copyable
1525 list(const list &) = delete;
1526 list &operator=(const list &) = delete;
1527
1528 ParserClass &getParser() { return Parser; }
1529
1530 unsigned getPosition(unsigned optnum) const {
1531 assert(optnum < this->size() && "Invalid option index");
1532 return Positions[optnum];
1533 }
1534
1535 void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
1536
1537 template <class... Mods>
1538 explicit list(const Mods &... Ms)
1539 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1540 apply(this, Ms...);
1541 done();
1542 }
1543 };
1544
1545 // multi_val - Modifier to set the number of additional values.
1546 struct multi_val {
1547 unsigned AdditionalVals;
1548 explicit multi_val(unsigned N) : AdditionalVals(N) {}
1549
1550 template <typename D, typename S, typename P>
1551 void apply(list<D, S, P> &L) const {
1552 L.setNumAdditionalVals(AdditionalVals);
1553 }
1554 };
1555
1556 //===----------------------------------------------------------------------===//
1557 // bits_storage class
1558
1559 // Default storage class definition: external storage. This implementation
1560 // assumes the user will specify a variable to store the data into with the
1561 // cl::location(x) modifier.
1562 //
1563 template <class DataType, class StorageClass> class bits_storage {
1564 unsigned *Location = nullptr; // Where to store the bits...
1565
1566 template <class T> static unsigned Bit(const T &V) {
1567 unsigned BitPos = reinterpret_cast<unsigned>(V);
1568 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1569 "enum exceeds width of bit vector!");
1570 return 1 << BitPos;
1571 }
1572
1573 public:
1574 bits_storage() = default;
1575
1576 bool setLocation(Option &O, unsigned &L) {
1577 if (Location)
1578 return O.error("cl::location(x) specified more than once!");
1579 Location = &L;
1580 return false;
1581 }
1582
1583 template <class T> void addValue(const T &V) {
1584 assert(Location != 0 && "cl::location(...) not specified for a command "
1585 "line option with external storage!");
1586 *Location |= Bit(V);
1587 }
1588
1589 unsigned getBits() { return *Location; }
1590
1591 template <class T> bool isSet(const T &V) {
1592 return (*Location & Bit(V)) != 0;
1593 }
1594 };
1595
1596 // Define how to hold bits. Since we can inherit from a class, we do so.
1597 // This makes us exactly compatible with the bits in all cases that it is used.
1598 //
1599 template <class DataType> class bits_storage<DataType, bool> {
1600 unsigned Bits; // Where to store the bits...
1601
1602 template <class T> static unsigned Bit(const T &V) {
1603 unsigned BitPos = (unsigned)V;
1604 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1605 "enum exceeds width of bit vector!");
1606 return 1 << BitPos;
1607 }
1608
1609 public:
1610 template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1611
1612 unsigned getBits() { return Bits; }
1613
1614 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1615 };
1616
1617 //===----------------------------------------------------------------------===//
1618 // bits - A bit vector of command options.
1619 //
1620 template <class DataType, class Storage = bool,
1621 class ParserClass = parser<DataType>>
1622 class bits : public Option, public bits_storage<DataType, Storage> {
1623 std::vector<unsigned> Positions;
1624 ParserClass Parser;
1625
1626 enum ValueExpected getValueExpectedFlagDefault() const override {
1627 return Parser.getValueExpectedFlagDefault();
1628 }
1629
1630 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1631 return Parser.getExtraOptionNames(OptionNames);
1632 }
1633
1634 bool handleOccurrence(unsigned pos, StringRef ArgName,
1635 StringRef Arg) override {
1636 typename ParserClass::parser_data_type Val =
1637 typename ParserClass::parser_data_type();
1638 if (Parser.parse(*this, ArgName, Arg, Val))
1639 return true; // Parse Error!
1640 this->addValue(Val);
1641 setPosition(pos);
1642 Positions.push_back(pos);
1643 return false;
1644 }
1645
1646 // Forward printing stuff to the parser...
1647 size_t getOptionWidth() const override {
1648 return Parser.getOptionWidth(*this);
1649 }
1650
1651 void printOptionInfo(size_t GlobalWidth) const override {
1652 Parser.printOptionInfo(*this, GlobalWidth);
1653 }
1654
1655 // Unimplemented: bits options don't currently store their default values.
1656 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1657 }
1658
1659 void setDefault() override {}
1660
1661 void done() {
1662 addArgument();
1663 Parser.initialize();
1664 }
1665
1666 public:
1667 // Command line options should not be copyable
1668 bits(const bits &) = delete;
1669 bits &operator=(const bits &) = delete;
1670
1671 ParserClass &getParser() { return Parser; }
1672
1673 unsigned getPosition(unsigned optnum) const {
1674 assert(optnum < this->size() && "Invalid option index");
1675 return Positions[optnum];
1676 }
1677
1678 template <class... Mods>
1679 explicit bits(const Mods &... Ms)
1680 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1681 apply(this, Ms...);
1682 done();
1683 }
1684 };
1685
1686 //===----------------------------------------------------------------------===//
1687 // Aliased command line option (alias this name to a preexisting name)
1688 //
1689
1690 class alias : public Option {
1691 Option *AliasFor;
1692
1693 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1694 StringRef Arg) override {
1695 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1696 }
1697
1698 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1699 bool MultiArg = false) override {
1700 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1701 }
1702
1703 // Handle printing stuff...
1704 size_t getOptionWidth() const override;
1705 void printOptionInfo(size_t GlobalWidth) const override;
1706
1707 // Aliases do not need to print their values.
1708 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1709 }
1710
1711 void setDefault() override { AliasFor->setDefault(); }
1712
1713 ValueExpected getValueExpectedFlagDefault() const override {
1714 return AliasFor->getValueExpectedFlag();
1715 }
1716
1717 void done() {
1718 if (!hasArgStr())
1719 error("cl::alias must have argument name specified!");
1720 if (!AliasFor)
1721 error("cl::alias must have an cl::aliasopt(option) specified!");
1722 Subs = AliasFor->Subs;
1723 addArgument();
1724 }
1725
1726 public:
1727 // Command line options should not be copyable
1728 alias(const alias &) = delete;
1729 alias &operator=(const alias &) = delete;
1730
1731 void setAliasFor(Option &O) {
1732 if (AliasFor)
1733 error("cl::alias must only have one cl::aliasopt(...) specified!");
1734 AliasFor = &O;
1735 }
1736
1737 template <class... Mods>
1738 explicit alias(const Mods &... Ms)
1739 : Option(Optional, Hidden), AliasFor(nullptr) {
1740 apply(this, Ms...);
1741 done();
1742 }
1743 };
1744
1745 // aliasfor - Modifier to set the option an alias aliases.
1746 struct aliasopt {
1747 Option &Opt;
1748
1749 explicit aliasopt(Option &O) : Opt(O) {}
1750
1751 void apply(alias &A) const { A.setAliasFor(Opt); }
1752 };
1753
1754 // extrahelp - provide additional help at the end of the normal help
1755 // output. All occurrences of cl::extrahelp will be accumulated and
1756 // printed to stderr at the end of the regular help, just before
1757 // exit is called.
1758 struct extrahelp {
1759 StringRef morehelp;
1760
1761 explicit extrahelp(StringRef help);
1762 };
1763
1764 void PrintVersionMessage();
1765
1766 /// This function just prints the help message, exactly the same way as if the
1767 /// -help or -help-hidden option had been given on the command line.
1768 ///
1769 /// \param Hidden if true will print hidden options
1770 /// \param Categorized if true print options in categories
1771 void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
1772
1773 //===----------------------------------------------------------------------===//
1774 // Public interface for accessing registered options.
1775 //
1776
1777 /// Use this to get a StringMap to all registered named options
1778 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1779 ///
1780 /// \return A reference to the StringMap used by the cl APIs to parse options.
1781 ///
1782 /// Access to unnamed arguments (i.e. positional) are not provided because
1783 /// it is expected that the client already has access to these.
1784 ///
1785 /// Typical usage:
1786 /// \code
1787 /// main(int argc,char* argv[]) {
1788 /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions();
1789 /// assert(opts.count("help") == 1)
1790 /// opts["help"]->setDescription("Show alphabetical help information")
1791 /// // More code
1792 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1793 /// //More code
1794 /// }
1795 /// \endcode
1796 ///
1797 /// This interface is useful for modifying options in libraries that are out of
1798 /// the control of the client. The options should be modified before calling
1799 /// llvm::cl::ParseCommandLineOptions().
1800 ///
1801 /// Hopefully this API can be deprecated soon. Any situation where options need
1802 /// to be modified by tools or libraries should be handled by sane APIs rather
1803 /// than just handing around a global list.
1804 StringMap<Option *> &getRegisteredOptions(SubCommand &Sub = *TopLevelSubCommand);
1805
1806 /// Use this to get all registered SubCommands from the provided parser.
1807 ///
1808 /// \return A range of all SubCommand pointers registered with the parser.
1809 ///
1810 /// Typical usage:
1811 /// \code
1812 /// main(int argc, char* argv[]) {
1813 /// llvm::cl::ParseCommandLineOptions(argc, argv);
1814 /// for (auto* S : llvm::cl::getRegisteredSubcommands()) {
1815 /// if (*S) {
1816 /// std::cout << "Executing subcommand: " << S->getName() << std::endl;
1817 /// // Execute some function based on the name...
1818 /// }
1819 /// }
1820 /// }
1821 /// \endcode
1822 ///
1823 /// This interface is useful for defining subcommands in libraries and
1824 /// the dispatch from a single point (like in the main function).
1825 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
1826 getRegisteredSubcommands();
1827
1828 //===----------------------------------------------------------------------===//
1829 // Standalone command line processing utilities.
1830 //
1831
1832 /// Tokenizes a command line that can contain escapes and quotes.
1833 //
1834 /// The quoting rules match those used by GCC and other tools that use
1835 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1836 /// They differ from buildargv() on treatment of backslashes that do not escape
1837 /// a special character to make it possible to accept most Windows file paths.
1838 ///
1839 /// \param [in] Source The string to be split on whitespace with quotes.
1840 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1841 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1842 /// lines and end of the response file to be marked with a nullptr string.
1843 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1844 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
1845 SmallVectorImpl<const char *> &NewArgv,
1846 bool MarkEOLs = false);
1847
1848 /// Tokenizes a Windows command line which may contain quotes and escaped
1849 /// quotes.
1850 ///
1851 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1852 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1853 ///
1854 /// \param [in] Source The string to be split on whitespace with quotes.
1855 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1856 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1857 /// lines and end of the response file to be marked with a nullptr string.
1858 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1859 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
1860 SmallVectorImpl<const char *> &NewArgv,
1861 bool MarkEOLs = false);
1862
1863 /// String tokenization function type. Should be compatible with either
1864 /// Windows or Unix command line tokenizers.
1865 using TokenizerCallback = void (*)(StringRef Source, StringSaver &Saver,
1866 SmallVectorImpl<const char *> &NewArgv,
1867 bool MarkEOLs);
1868
1869 /// Tokenizes content of configuration file.
1870 ///
1871 /// \param [in] Source The string representing content of config file.
1872 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1873 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1874 /// \param [in] MarkEOLs Added for compatibility with TokenizerCallback.
1875 ///
1876 /// It works like TokenizeGNUCommandLine with ability to skip comment lines.
1877 ///
1878 void tokenizeConfigFile(StringRef Source, StringSaver &Saver,
1879 SmallVectorImpl<const char *> &NewArgv,
1880 bool MarkEOLs = false);
1881
1882 /// Reads command line options from the given configuration file.
1883 ///
1884 /// \param [in] CfgFileName Path to configuration file.
1885 /// \param [in] Saver Objects that saves allocated strings.
1886 /// \param [out] Argv Array to which the read options are added.
1887 /// \return true if the file was successfully read.
1888 ///
1889 /// It reads content of the specified file, tokenizes it and expands "@file"
1890 /// commands resolving file names in them relative to the directory where
1891 /// CfgFilename resides.
1892 ///
1893 bool readConfigFile(StringRef CfgFileName, StringSaver &Saver,
1894 SmallVectorImpl<const char *> &Argv);
1895
1896 /// Expand response files on a command line recursively using the given
1897 /// StringSaver and tokenization strategy. Argv should contain the command line
1898 /// before expansion and will be modified in place. If requested, Argv will
1899 /// also be populated with nullptrs indicating where each response file line
1900 /// ends, which is useful for the "/link" argument that needs to consume all
1901 /// remaining arguments only until the next end of line, when in a response
1902 /// file.
1903 ///
1904 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1905 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1906 /// \param [in,out] Argv Command line into which to expand response files.
1907 /// \param [in] MarkEOLs Mark end of lines and the end of the response file
1908 /// with nullptrs in the Argv vector.
1909 /// \param [in] RelativeNames true if names of nested response files must be
1910 /// resolved relative to including file.
1911 /// \return true if all @files were expanded successfully or there were none.
1912 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1913 SmallVectorImpl<const char *> &Argv,
1914 bool MarkEOLs = false, bool RelativeNames = false);
1915
1916 /// Mark all options not part of this category as cl::ReallyHidden.
1917 ///
1918 /// \param Category the category of options to keep displaying
1919 ///
1920 /// Some tools (like clang-format) like to be able to hide all options that are
1921 /// not specific to the tool. This function allows a tool to specify a single
1922 /// option category to display in the -help output.
1923 void HideUnrelatedOptions(cl::OptionCategory &Category,
1924 SubCommand &Sub = *TopLevelSubCommand);
1925
1926 /// Mark all options not part of the categories as cl::ReallyHidden.
1927 ///
1928 /// \param Categories the categories of options to keep displaying.
1929 ///
1930 /// Some tools (like clang-format) like to be able to hide all options that are
1931 /// not specific to the tool. This function allows a tool to specify a single
1932 /// option category to display in the -help output.
1933 void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
1934 SubCommand &Sub = *TopLevelSubCommand);
1935
1936 /// Reset all command line options to a state that looks as if they have
1937 /// never appeared on the command line. This is useful for being able to parse
1938 /// a command line multiple times (especially useful for writing tests).
1939 void ResetAllOptionOccurrences();
1940
1941 /// Reset the command line parser back to its initial state. This
1942 /// removes
1943 /// all options, categories, and subcommands and returns the parser to a state
1944 /// where no options are supported.
1945 void ResetCommandLineParser();
1946
1947 } // end namespace cl
1948
1949 } // end namespace llvm
1950
1951 #endif // LLVM_SUPPORT_COMMANDLINE_H
1952