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