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