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