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