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

source code of llvm/include/llvm/Support/CommandLine.h