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