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