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