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