Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:29

0001 //===- llvm/Support/CommandLine.h - Command line handler --------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This class implements a command line argument processor that is useful when
0010 // creating a tool.  It provides a simple, minimalistic interface that is easily
0011 // extensible and supports nonlocal (library) command line options.
0012 //
0013 // Note that rather than trying to figure out what this code does, you should
0014 // read the library documentation located in docs/CommandLine.html or looks at
0015 // the many example usages in tools/*/*.cpp
0016 //
0017 //===----------------------------------------------------------------------===//
0018 
0019 #ifndef LLVM_SUPPORT_COMMANDLINE_H
0020 #define LLVM_SUPPORT_COMMANDLINE_H
0021 
0022 #include "llvm/ADT/ArrayRef.h"
0023 #include "llvm/ADT/STLExtras.h"
0024 #include "llvm/ADT/SmallPtrSet.h"
0025 #include "llvm/ADT/SmallVector.h"
0026 #include "llvm/ADT/StringMap.h"
0027 #include "llvm/ADT/StringRef.h"
0028 #include "llvm/ADT/Twine.h"
0029 #include "llvm/ADT/iterator_range.h"
0030 #include "llvm/Support/ErrorHandling.h"
0031 #include "llvm/Support/StringSaver.h"
0032 #include "llvm/Support/raw_ostream.h"
0033 #include <cassert>
0034 #include <climits>
0035 #include <cstddef>
0036 #include <functional>
0037 #include <initializer_list>
0038 #include <string>
0039 #include <type_traits>
0040 #include <vector>
0041 
0042 namespace llvm {
0043 
0044 namespace vfs {
0045 class FileSystem;
0046 }
0047 
0048 class StringSaver;
0049 
0050 /// This namespace contains all of the command line option processing machinery.
0051 /// It is intentionally a short name to make qualified usage concise.
0052 namespace cl {
0053 
0054 //===----------------------------------------------------------------------===//
0055 // Command line option processing entry point.
0056 //
0057 // Returns true on success. Otherwise, this will print the error message to
0058 // stderr and exit if \p Errs is not set (nullptr by default), or print the
0059 // error message to \p Errs and return false if \p Errs is provided.
0060 //
0061 // If EnvVar is not nullptr, command-line options are also parsed from the
0062 // environment variable named by EnvVar.  Precedence is given to occurrences
0063 // from argv.  This precedence is currently implemented by parsing argv after
0064 // the environment variable, so it is only implemented correctly for options
0065 // that give precedence to later occurrences.  If your program supports options
0066 // that give precedence to earlier occurrences, you will need to extend this
0067 // function to support it correctly.
0068 bool ParseCommandLineOptions(int argc, const char *const *argv,
0069                              StringRef Overview = "",
0070                              raw_ostream *Errs = nullptr,
0071                              const char *EnvVar = nullptr,
0072                              bool LongOptionsUseDoubleDash = false);
0073 
0074 // Function pointer type for printing version information.
0075 using VersionPrinterTy = std::function<void(raw_ostream &)>;
0076 
0077 ///===---------------------------------------------------------------------===//
0078 /// Override the default (LLVM specific) version printer used to print out the
0079 /// version when --version is given on the command line. This allows other
0080 /// systems using the CommandLine utilities to print their own version string.
0081 void SetVersionPrinter(VersionPrinterTy func);
0082 
0083 ///===---------------------------------------------------------------------===//
0084 /// Add an extra printer to use in addition to the default one. This can be
0085 /// called multiple times, and each time it adds a new function to the list
0086 /// which will be called after the basic LLVM version printing is complete.
0087 /// Each can then add additional information specific to the tool.
0088 void AddExtraVersionPrinter(VersionPrinterTy func);
0089 
0090 // Print option values.
0091 // With -print-options print the difference between option values and defaults.
0092 // With -print-all-options print all option values.
0093 // (Currently not perfect, but best-effort.)
0094 void PrintOptionValues();
0095 
0096 // Forward declaration - AddLiteralOption needs to be up here to make gcc happy.
0097 class Option;
0098 
0099 /// Adds a new option for parsing and provides the option it refers to.
0100 ///
0101 /// \param O pointer to the option
0102 /// \param Name the string name for the option to handle during parsing
0103 ///
0104 /// Literal options are used by some parsers to register special option values.
0105 /// This is how the PassNameParser registers pass names for opt.
0106 void AddLiteralOption(Option &O, StringRef Name);
0107 
0108 //===----------------------------------------------------------------------===//
0109 // Flags permitted to be passed to command line arguments
0110 //
0111 
0112 enum NumOccurrencesFlag { // Flags for the number of occurrences allowed
0113   Optional = 0x00,        // Zero or One occurrence
0114   ZeroOrMore = 0x01,      // Zero or more occurrences allowed
0115   Required = 0x02,        // One occurrence required
0116   OneOrMore = 0x03,       // One or more occurrences required
0117 
0118   // Indicates that this option is fed anything that follows the last positional
0119   // argument required by the application (it is an error if there are zero
0120   // positional arguments, and a ConsumeAfter option is used).
0121   // Thus, for example, all arguments to LLI are processed until a filename is
0122   // found.  Once a filename is found, all of the succeeding arguments are
0123   // passed, unprocessed, to the ConsumeAfter option.
0124   //
0125   ConsumeAfter = 0x04
0126 };
0127 
0128 enum ValueExpected { // Is a value required for the option?
0129   // zero reserved for the unspecified value
0130   ValueOptional = 0x01,  // The value can appear... or not
0131   ValueRequired = 0x02,  // The value is required to appear!
0132   ValueDisallowed = 0x03 // A value may not be specified (for flags)
0133 };
0134 
0135 enum OptionHidden {   // Control whether -help shows this option
0136   NotHidden = 0x00,   // Option included in -help & -help-hidden
0137   Hidden = 0x01,      // -help doesn't, but -help-hidden does
0138   ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg
0139 };
0140 
0141 // This controls special features that the option might have that cause it to be
0142 // parsed differently...
0143 //
0144 // Prefix - This option allows arguments that are otherwise unrecognized to be
0145 // matched by options that are a prefix of the actual value.  This is useful for
0146 // cases like a linker, where options are typically of the form '-lfoo' or
0147 // '-L../../include' where -l or -L are the actual flags.  When prefix is
0148 // enabled, and used, the value for the flag comes from the suffix of the
0149 // argument.
0150 //
0151 // AlwaysPrefix - Only allow the behavior enabled by the Prefix flag and reject
0152 // the Option=Value form.
0153 //
0154 
0155 enum FormattingFlags {
0156   NormalFormatting = 0x00, // Nothing special
0157   Positional = 0x01,       // Is a positional argument, no '-' required
0158   Prefix = 0x02,           // Can this option directly prefix its value?
0159   AlwaysPrefix = 0x03      // Can this option only directly prefix its value?
0160 };
0161 
0162 enum MiscFlags {             // Miscellaneous flags to adjust argument
0163   CommaSeparated = 0x01,     // Should this cl::list split between commas?
0164   PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args?
0165   Sink = 0x04,               // Should this cl::list eat all unknown options?
0166 
0167   // Can this option group with other options?
0168   // If this is enabled, multiple letter options are allowed to bunch together
0169   // with only a single hyphen for the whole group.  This allows emulation
0170   // of the behavior that ls uses for example: ls -la === ls -l -a
0171   Grouping = 0x08,
0172 
0173   // Default option
0174   DefaultOption = 0x10
0175 };
0176 
0177 //===----------------------------------------------------------------------===//
0178 //
0179 class OptionCategory {
0180 private:
0181   StringRef const Name;
0182   StringRef const Description;
0183 
0184   void registerCategory();
0185 
0186 public:
0187   OptionCategory(StringRef const Name,
0188                  StringRef const Description = "")
0189       : Name(Name), Description(Description) {
0190     registerCategory();
0191   }
0192 
0193   StringRef getName() const { return Name; }
0194   StringRef getDescription() const { return Description; }
0195 };
0196 
0197 // The general Option Category (used as default category).
0198 OptionCategory &getGeneralCategory();
0199 
0200 //===----------------------------------------------------------------------===//
0201 //
0202 class SubCommand {
0203 private:
0204   StringRef Name;
0205   StringRef Description;
0206 
0207 protected:
0208   void registerSubCommand();
0209   void unregisterSubCommand();
0210 
0211 public:
0212   SubCommand(StringRef Name, StringRef Description = "")
0213       : Name(Name), Description(Description) {
0214         registerSubCommand();
0215   }
0216   SubCommand() = default;
0217 
0218   // Get the special subcommand representing no subcommand.
0219   static SubCommand &getTopLevel();
0220 
0221   // Get the special subcommand that can be used to put an option into all
0222   // subcommands.
0223   static SubCommand &getAll();
0224 
0225   void reset();
0226 
0227   explicit operator bool() const;
0228 
0229   StringRef getName() const { return Name; }
0230   StringRef getDescription() const { return Description; }
0231 
0232   SmallVector<Option *, 4> PositionalOpts;
0233   SmallVector<Option *, 4> SinkOpts;
0234   StringMap<Option *> OptionsMap;
0235 
0236   Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists.
0237 };
0238 
0239 class SubCommandGroup {
0240   SmallVector<SubCommand *, 4> Subs;
0241 
0242 public:
0243   SubCommandGroup(std::initializer_list<SubCommand *> IL) : Subs(IL) {}
0244 
0245   ArrayRef<SubCommand *> getSubCommands() const { return Subs; }
0246 };
0247 
0248 //===----------------------------------------------------------------------===//
0249 //
0250 class Option {
0251   friend class alias;
0252 
0253   // Overriden by subclasses to handle the value passed into an argument. Should
0254   // return true if there was an error processing the argument and the program
0255   // should exit.
0256   //
0257   virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
0258                                 StringRef Arg) = 0;
0259 
0260   virtual enum ValueExpected getValueExpectedFlagDefault() const {
0261     return ValueOptional;
0262   }
0263 
0264   // Out of line virtual function to provide home for the class.
0265   virtual void anchor();
0266 
0267   uint16_t NumOccurrences; // The number of times specified
0268   // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
0269   // problems with signed enums in bitfields.
0270   uint16_t Occurrences : 3; // enum NumOccurrencesFlag
0271   // not using the enum type for 'Value' because zero is an implementation
0272   // detail representing the non-value
0273   uint16_t Value : 2;
0274   uint16_t HiddenFlag : 2; // enum OptionHidden
0275   uint16_t Formatting : 2; // enum FormattingFlags
0276   uint16_t Misc : 5;
0277   uint16_t FullyInitialized : 1; // Has addArgument been called?
0278   uint16_t Position;             // Position of last occurrence of the option
0279   uint16_t AdditionalVals;       // Greater than 0 for multi-valued option.
0280 
0281 public:
0282   StringRef ArgStr;   // The argument string itself (ex: "help", "o")
0283   StringRef HelpStr;  // The descriptive text message for -help
0284   StringRef ValueStr; // String describing what the value of this option is
0285   SmallVector<OptionCategory *, 1>
0286       Categories;                    // The Categories this option belongs to
0287   SmallPtrSet<SubCommand *, 1> Subs; // The subcommands this option belongs to.
0288 
0289   inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
0290     return (enum NumOccurrencesFlag)Occurrences;
0291   }
0292 
0293   inline enum ValueExpected getValueExpectedFlag() const {
0294     return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
0295   }
0296 
0297   inline enum OptionHidden getOptionHiddenFlag() const {
0298     return (enum OptionHidden)HiddenFlag;
0299   }
0300 
0301   inline enum FormattingFlags getFormattingFlag() const {
0302     return (enum FormattingFlags)Formatting;
0303   }
0304 
0305   inline unsigned getMiscFlags() const { return Misc; }
0306   inline unsigned getPosition() const { return Position; }
0307   inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
0308 
0309   // Return true if the argstr != ""
0310   bool hasArgStr() const { return !ArgStr.empty(); }
0311   bool isPositional() const { return getFormattingFlag() == cl::Positional; }
0312   bool isSink() const { return getMiscFlags() & cl::Sink; }
0313   bool isDefaultOption() const { return getMiscFlags() & cl::DefaultOption; }
0314 
0315   bool isConsumeAfter() const {
0316     return getNumOccurrencesFlag() == cl::ConsumeAfter;
0317   }
0318 
0319   //-------------------------------------------------------------------------===
0320   // Accessor functions set by OptionModifiers
0321   //
0322   void setArgStr(StringRef S);
0323   void setDescription(StringRef S) { HelpStr = S; }
0324   void setValueStr(StringRef S) { ValueStr = S; }
0325   void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
0326   void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
0327   void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
0328   void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
0329   void setMiscFlag(enum MiscFlags M) { Misc |= M; }
0330   void setPosition(unsigned pos) { Position = pos; }
0331   void addCategory(OptionCategory &C);
0332   void addSubCommand(SubCommand &S) { Subs.insert(&S); }
0333 
0334 protected:
0335   explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
0336                   enum OptionHidden Hidden)
0337       : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
0338         HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0),
0339         FullyInitialized(false), Position(0), AdditionalVals(0) {
0340     Categories.push_back(&getGeneralCategory());
0341   }
0342 
0343   inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
0344 
0345 public:
0346   virtual ~Option() = default;
0347 
0348   // Register this argument with the commandline system.
0349   //
0350   void addArgument();
0351 
0352   /// Unregisters this option from the CommandLine system.
0353   ///
0354   /// This option must have been the last option registered.
0355   /// For testing purposes only.
0356   void removeArgument();
0357 
0358   // Return the width of the option tag for printing...
0359   virtual size_t getOptionWidth() const = 0;
0360 
0361   // Print out information about this option. The to-be-maintained width is
0362   // specified.
0363   //
0364   virtual void printOptionInfo(size_t GlobalWidth) const = 0;
0365 
0366   virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
0367 
0368   virtual void setDefault() = 0;
0369 
0370   // Prints the help string for an option.
0371   //
0372   // This maintains the Indent for multi-line descriptions.
0373   // FirstLineIndentedBy is the count of chars of the first line
0374   //      i.e. the one containing the --<option name>.
0375   static void printHelpStr(StringRef HelpStr, size_t Indent,
0376                            size_t FirstLineIndentedBy);
0377 
0378   // Prints the help string for an enum value.
0379   //
0380   // This maintains the Indent for multi-line descriptions.
0381   // FirstLineIndentedBy is the count of chars of the first line
0382   //      i.e. the one containing the =<value>.
0383   static void printEnumValHelpStr(StringRef HelpStr, size_t Indent,
0384                                   size_t FirstLineIndentedBy);
0385 
0386   virtual void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
0387 
0388   // Wrapper around handleOccurrence that enforces Flags.
0389   //
0390   virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
0391                              bool MultiArg = false);
0392 
0393   // Prints option name followed by message.  Always returns true.
0394   bool error(const Twine &Message, StringRef ArgName = StringRef(), raw_ostream &Errs = llvm::errs());
0395   bool error(const Twine &Message, raw_ostream &Errs) {
0396     return error(Message, StringRef(), Errs);
0397   }
0398 
0399   inline int getNumOccurrences() const { return NumOccurrences; }
0400   void reset();
0401 };
0402 
0403 //===----------------------------------------------------------------------===//
0404 // Command line option modifiers that can be used to modify the behavior of
0405 // command line option parsers...
0406 //
0407 
0408 // Modifier to set the description shown in the -help output...
0409 struct desc {
0410   StringRef Desc;
0411 
0412   desc(StringRef Str) : Desc(Str) {}
0413 
0414   void apply(Option &O) const { O.setDescription(Desc); }
0415 };
0416 
0417 // Modifier to set the value description shown in the -help output...
0418 struct value_desc {
0419   StringRef Desc;
0420 
0421   value_desc(StringRef Str) : Desc(Str) {}
0422 
0423   void apply(Option &O) const { O.setValueStr(Desc); }
0424 };
0425 
0426 // Specify a default (initial) value for the command line argument, if the
0427 // default constructor for the argument type does not give you what you want.
0428 // This is only valid on "opt" arguments, not on "list" arguments.
0429 template <class Ty> struct initializer {
0430   const Ty &Init;
0431   initializer(const Ty &Val) : Init(Val) {}
0432 
0433   template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
0434 };
0435 
0436 template <class Ty> struct list_initializer {
0437   ArrayRef<Ty> Inits;
0438   list_initializer(ArrayRef<Ty> Vals) : Inits(Vals) {}
0439 
0440   template <class Opt> void apply(Opt &O) const { O.setInitialValues(Inits); }
0441 };
0442 
0443 template <class Ty> initializer<Ty> init(const Ty &Val) {
0444   return initializer<Ty>(Val);
0445 }
0446 
0447 template <class Ty>
0448 list_initializer<Ty> list_init(ArrayRef<Ty> Vals) {
0449   return list_initializer<Ty>(Vals);
0450 }
0451 
0452 // Allow the user to specify which external variable they want to store the
0453 // results of the command line argument processing into, if they don't want to
0454 // store it in the option itself.
0455 template <class Ty> struct LocationClass {
0456   Ty &Loc;
0457 
0458   LocationClass(Ty &L) : Loc(L) {}
0459 
0460   template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
0461 };
0462 
0463 template <class Ty> LocationClass<Ty> location(Ty &L) {
0464   return LocationClass<Ty>(L);
0465 }
0466 
0467 // Specify the Option category for the command line argument to belong to.
0468 struct cat {
0469   OptionCategory &Category;
0470 
0471   cat(OptionCategory &c) : Category(c) {}
0472 
0473   template <class Opt> void apply(Opt &O) const { O.addCategory(Category); }
0474 };
0475 
0476 // Specify the subcommand that this option belongs to.
0477 struct sub {
0478   SubCommand *Sub = nullptr;
0479   SubCommandGroup *Group = nullptr;
0480 
0481   sub(SubCommand &S) : Sub(&S) {}
0482   sub(SubCommandGroup &G) : Group(&G) {}
0483 
0484   template <class Opt> void apply(Opt &O) const {
0485     if (Sub)
0486       O.addSubCommand(*Sub);
0487     else if (Group)
0488       for (SubCommand *SC : Group->getSubCommands())
0489         O.addSubCommand(*SC);
0490   }
0491 };
0492 
0493 // Specify a callback function to be called when an option is seen.
0494 // Can be used to set other options automatically.
0495 template <typename R, typename Ty> struct cb {
0496   std::function<R(Ty)> CB;
0497 
0498   cb(std::function<R(Ty)> CB) : CB(CB) {}
0499 
0500   template <typename Opt> void apply(Opt &O) const { O.setCallback(CB); }
0501 };
0502 
0503 namespace detail {
0504 template <typename F>
0505 struct callback_traits : public callback_traits<decltype(&F::operator())> {};
0506 
0507 template <typename R, typename C, typename... Args>
0508 struct callback_traits<R (C::*)(Args...) const> {
0509   using result_type = R;
0510   using arg_type = std::tuple_element_t<0, std::tuple<Args...>>;
0511   static_assert(sizeof...(Args) == 1, "callback function must have one and only one parameter");
0512   static_assert(std::is_same_v<result_type, void>,
0513                 "callback return type must be void");
0514   static_assert(std::is_lvalue_reference_v<arg_type> &&
0515                     std::is_const_v<std::remove_reference_t<arg_type>>,
0516                 "callback arg_type must be a const lvalue reference");
0517 };
0518 } // namespace detail
0519 
0520 template <typename F>
0521 cb<typename detail::callback_traits<F>::result_type,
0522    typename detail::callback_traits<F>::arg_type>
0523 callback(F CB) {
0524   using result_type = typename detail::callback_traits<F>::result_type;
0525   using arg_type = typename detail::callback_traits<F>::arg_type;
0526   return cb<result_type, arg_type>(CB);
0527 }
0528 
0529 //===----------------------------------------------------------------------===//
0530 
0531 // Support value comparison outside the template.
0532 struct GenericOptionValue {
0533   virtual bool compare(const GenericOptionValue &V) const = 0;
0534 
0535 protected:
0536   GenericOptionValue() = default;
0537   GenericOptionValue(const GenericOptionValue&) = default;
0538   GenericOptionValue &operator=(const GenericOptionValue &) = default;
0539   ~GenericOptionValue() = default;
0540 
0541 private:
0542   virtual void anchor();
0543 };
0544 
0545 template <class DataType> struct OptionValue;
0546 
0547 // The default value safely does nothing. Option value printing is only
0548 // best-effort.
0549 template <class DataType, bool isClass>
0550 struct OptionValueBase : public GenericOptionValue {
0551   // Temporary storage for argument passing.
0552   using WrapperType = OptionValue<DataType>;
0553 
0554   bool hasValue() const { return false; }
0555 
0556   const DataType &getValue() const { llvm_unreachable("no default value"); }
0557 
0558   // Some options may take their value from a different data type.
0559   template <class DT> void setValue(const DT & /*V*/) {}
0560 
0561   // Returns whether this instance matches the argument.
0562   bool compare(const DataType & /*V*/) const { return false; }
0563 
0564   bool compare(const GenericOptionValue & /*V*/) const override {
0565     return false;
0566   }
0567 
0568 protected:
0569   ~OptionValueBase() = default;
0570 };
0571 
0572 // Simple copy of the option value.
0573 template <class DataType> class OptionValueCopy : public GenericOptionValue {
0574   DataType Value;
0575   bool Valid = false;
0576 
0577 protected:
0578   OptionValueCopy(const OptionValueCopy&) = default;
0579   OptionValueCopy &operator=(const OptionValueCopy &) = default;
0580   ~OptionValueCopy() = default;
0581 
0582 public:
0583   OptionValueCopy() = default;
0584 
0585   bool hasValue() const { return Valid; }
0586 
0587   const DataType &getValue() const {
0588     assert(Valid && "invalid option value");
0589     return Value;
0590   }
0591 
0592   void setValue(const DataType &V) {
0593     Valid = true;
0594     Value = V;
0595   }
0596 
0597   // Returns whether this instance matches V.
0598   bool compare(const DataType &V) const { return Valid && (Value == V); }
0599 
0600   bool compare(const GenericOptionValue &V) const override {
0601     const OptionValueCopy<DataType> &VC =
0602         static_cast<const OptionValueCopy<DataType> &>(V);
0603     if (!VC.hasValue())
0604       return false;
0605     return compare(VC.getValue());
0606   }
0607 };
0608 
0609 // Non-class option values.
0610 template <class DataType>
0611 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
0612   using WrapperType = DataType;
0613 
0614 protected:
0615   OptionValueBase() = default;
0616   OptionValueBase(const OptionValueBase&) = default;
0617   OptionValueBase &operator=(const OptionValueBase &) = default;
0618   ~OptionValueBase() = default;
0619 };
0620 
0621 // Top-level option class.
0622 template <class DataType>
0623 struct OptionValue final
0624     : OptionValueBase<DataType, std::is_class_v<DataType>> {
0625   OptionValue() = default;
0626 
0627   OptionValue(const DataType &V) { this->setValue(V); }
0628 
0629   // Some options may take their value from a different data type.
0630   template <class DT> OptionValue<DataType> &operator=(const DT &V) {
0631     this->setValue(V);
0632     return *this;
0633   }
0634 };
0635 
0636 // Other safe-to-copy-by-value common option types.
0637 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
0638 template <>
0639 struct OptionValue<cl::boolOrDefault> final
0640     : OptionValueCopy<cl::boolOrDefault> {
0641   using WrapperType = cl::boolOrDefault;
0642 
0643   OptionValue() = default;
0644 
0645   OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
0646 
0647   OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
0648     setValue(V);
0649     return *this;
0650   }
0651 
0652 private:
0653   void anchor() override;
0654 };
0655 
0656 template <>
0657 struct OptionValue<std::string> final : OptionValueCopy<std::string> {
0658   using WrapperType = StringRef;
0659 
0660   OptionValue() = default;
0661 
0662   OptionValue(const std::string &V) { this->setValue(V); }
0663 
0664   OptionValue<std::string> &operator=(const std::string &V) {
0665     setValue(V);
0666     return *this;
0667   }
0668 
0669 private:
0670   void anchor() override;
0671 };
0672 
0673 //===----------------------------------------------------------------------===//
0674 // Enum valued command line option
0675 //
0676 
0677 // This represents a single enum value, using "int" as the underlying type.
0678 struct OptionEnumValue {
0679   StringRef Name;
0680   int Value;
0681   StringRef Description;
0682 };
0683 
0684 #define clEnumVal(ENUMVAL, DESC)                                               \
0685   llvm::cl::OptionEnumValue { #ENUMVAL, int(ENUMVAL), DESC }
0686 #define clEnumValN(ENUMVAL, FLAGNAME, DESC)                                    \
0687   llvm::cl::OptionEnumValue { FLAGNAME, int(ENUMVAL), DESC }
0688 
0689 // For custom data types, allow specifying a group of values together as the
0690 // values that go into the mapping that the option handler uses.
0691 //
0692 class ValuesClass {
0693   // Use a vector instead of a map, because the lists should be short,
0694   // the overhead is less, and most importantly, it keeps them in the order
0695   // inserted so we can print our option out nicely.
0696   SmallVector<OptionEnumValue, 4> Values;
0697 
0698 public:
0699   ValuesClass(std::initializer_list<OptionEnumValue> Options)
0700       : Values(Options) {}
0701 
0702   template <class Opt> void apply(Opt &O) const {
0703     for (const auto &Value : Values)
0704       O.getParser().addLiteralOption(Value.Name, Value.Value,
0705                                      Value.Description);
0706   }
0707 };
0708 
0709 /// Helper to build a ValuesClass by forwarding a variable number of arguments
0710 /// as an initializer list to the ValuesClass constructor.
0711 template <typename... OptsTy> ValuesClass values(OptsTy... Options) {
0712   return ValuesClass({Options...});
0713 }
0714 
0715 //===----------------------------------------------------------------------===//
0716 // Parameterizable parser for different data types. By default, known data types
0717 // (string, int, bool) have specialized parsers, that do what you would expect.
0718 // The default parser, used for data types that are not built-in, uses a mapping
0719 // table to map specific options to values, which is used, among other things,
0720 // to handle enum types.
0721 
0722 //--------------------------------------------------
0723 // This class holds all the non-generic code that we do not need replicated for
0724 // every instance of the generic parser.  This also allows us to put stuff into
0725 // CommandLine.cpp
0726 //
0727 class generic_parser_base {
0728 protected:
0729   class GenericOptionInfo {
0730   public:
0731     GenericOptionInfo(StringRef name, StringRef helpStr)
0732         : Name(name), HelpStr(helpStr) {}
0733     StringRef Name;
0734     StringRef HelpStr;
0735   };
0736 
0737 public:
0738   generic_parser_base(Option &O) : Owner(O) {}
0739 
0740   virtual ~generic_parser_base() = default;
0741   // Base class should have virtual-destructor
0742 
0743   // Virtual function implemented by generic subclass to indicate how many
0744   // entries are in Values.
0745   //
0746   virtual unsigned getNumOptions() const = 0;
0747 
0748   // Return option name N.
0749   virtual StringRef getOption(unsigned N) const = 0;
0750 
0751   // Return description N
0752   virtual StringRef getDescription(unsigned N) const = 0;
0753 
0754   // Return the width of the option tag for printing...
0755   virtual size_t getOptionWidth(const Option &O) const;
0756 
0757   virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
0758 
0759   // Print out information about this option. The to-be-maintained width is
0760   // specified.
0761   //
0762   virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
0763 
0764   void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
0765                               const GenericOptionValue &Default,
0766                               size_t GlobalWidth) const;
0767 
0768   // Print the value of an option and it's default.
0769   //
0770   // Template definition ensures that the option and default have the same
0771   // DataType (via the same AnyOptionValue).
0772   template <class AnyOptionValue>
0773   void printOptionDiff(const Option &O, const AnyOptionValue &V,
0774                        const AnyOptionValue &Default,
0775                        size_t GlobalWidth) const {
0776     printGenericOptionDiff(O, V, Default, GlobalWidth);
0777   }
0778 
0779   void initialize() {}
0780 
0781   void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) {
0782     // If there has been no argstr specified, that means that we need to add an
0783     // argument for every possible option.  This ensures that our options are
0784     // vectored to us.
0785     if (!Owner.hasArgStr())
0786       for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
0787         OptionNames.push_back(getOption(i));
0788   }
0789 
0790   enum ValueExpected getValueExpectedFlagDefault() const {
0791     // If there is an ArgStr specified, then we are of the form:
0792     //
0793     //    -opt=O2   or   -opt O2  or  -optO2
0794     //
0795     // In which case, the value is required.  Otherwise if an arg str has not
0796     // been specified, we are of the form:
0797     //
0798     //    -O2 or O2 or -la (where -l and -a are separate options)
0799     //
0800     // If this is the case, we cannot allow a value.
0801     //
0802     if (Owner.hasArgStr())
0803       return ValueRequired;
0804     else
0805       return ValueDisallowed;
0806   }
0807 
0808   // Return the option number corresponding to the specified
0809   // argument string.  If the option is not found, getNumOptions() is returned.
0810   //
0811   unsigned findOption(StringRef Name);
0812 
0813 protected:
0814   Option &Owner;
0815 };
0816 
0817 // Default parser implementation - This implementation depends on having a
0818 // mapping of recognized options to values of some sort.  In addition to this,
0819 // each entry in the mapping also tracks a help message that is printed with the
0820 // command line option for -help.  Because this is a simple mapping parser, the
0821 // data type can be any unsupported type.
0822 //
0823 template <class DataType> class parser : public generic_parser_base {
0824 protected:
0825   class OptionInfo : public GenericOptionInfo {
0826   public:
0827     OptionInfo(StringRef name, DataType v, StringRef helpStr)
0828         : GenericOptionInfo(name, helpStr), V(v) {}
0829 
0830     OptionValue<DataType> V;
0831   };
0832   SmallVector<OptionInfo, 8> Values;
0833 
0834 public:
0835   parser(Option &O) : generic_parser_base(O) {}
0836 
0837   using parser_data_type = DataType;
0838 
0839   // Implement virtual functions needed by generic_parser_base
0840   unsigned getNumOptions() const override { return unsigned(Values.size()); }
0841   StringRef getOption(unsigned N) const override { return Values[N].Name; }
0842   StringRef getDescription(unsigned N) const override {
0843     return Values[N].HelpStr;
0844   }
0845 
0846   // Return the value of option name N.
0847   const GenericOptionValue &getOptionValue(unsigned N) const override {
0848     return Values[N].V;
0849   }
0850 
0851   // Return true on error.
0852   bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
0853     StringRef ArgVal;
0854     if (Owner.hasArgStr())
0855       ArgVal = Arg;
0856     else
0857       ArgVal = ArgName;
0858 
0859     for (size_t i = 0, e = Values.size(); i != e; ++i)
0860       if (Values[i].Name == ArgVal) {
0861         V = Values[i].V.getValue();
0862         return false;
0863       }
0864 
0865     return O.error("Cannot find option named '" + ArgVal + "'!");
0866   }
0867 
0868   /// Add an entry to the mapping table.
0869   ///
0870   template <class DT>
0871   void addLiteralOption(StringRef Name, const DT &V, StringRef HelpStr) {
0872 #ifndef NDEBUG
0873     if (findOption(Name) != Values.size())
0874       report_fatal_error("Option '" + Name + "' already exists!");
0875 #endif
0876     OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
0877     Values.push_back(X);
0878     AddLiteralOption(Owner, Name);
0879   }
0880 
0881   /// Remove the specified option.
0882   ///
0883   void removeLiteralOption(StringRef Name) {
0884     unsigned N = findOption(Name);
0885     assert(N != Values.size() && "Option not found!");
0886     Values.erase(Values.begin() + N);
0887   }
0888 };
0889 
0890 //--------------------------------------------------
0891 // Super class of parsers to provide boilerplate code
0892 //
0893 class basic_parser_impl { // non-template implementation of basic_parser<t>
0894 public:
0895   basic_parser_impl(Option &) {}
0896 
0897   virtual ~basic_parser_impl() = default;
0898 
0899   enum ValueExpected getValueExpectedFlagDefault() const {
0900     return ValueRequired;
0901   }
0902 
0903   void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
0904 
0905   void initialize() {}
0906 
0907   // Return the width of the option tag for printing...
0908   size_t getOptionWidth(const Option &O) const;
0909 
0910   // Print out information about this option. The to-be-maintained width is
0911   // specified.
0912   //
0913   void printOptionInfo(const Option &O, size_t GlobalWidth) const;
0914 
0915   // Print a placeholder for options that don't yet support printOptionDiff().
0916   void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
0917 
0918   // Overload in subclass to provide a better default value.
0919   virtual StringRef getValueName() const { return "value"; }
0920 
0921   // An out-of-line virtual method to provide a 'home' for this class.
0922   virtual void anchor();
0923 
0924 protected:
0925   // A helper for basic_parser::printOptionDiff.
0926   void printOptionName(const Option &O, size_t GlobalWidth) const;
0927 };
0928 
0929 // The real basic parser is just a template wrapper that provides a typedef for
0930 // the provided data type.
0931 //
0932 template <class DataType> class basic_parser : public basic_parser_impl {
0933 public:
0934   using parser_data_type = DataType;
0935   using OptVal = OptionValue<DataType>;
0936 
0937   basic_parser(Option &O) : basic_parser_impl(O) {}
0938 };
0939 
0940 //--------------------------------------------------
0941 
0942 extern template class basic_parser<bool>;
0943 
0944 template <> class parser<bool> : public basic_parser<bool> {
0945 public:
0946   parser(Option &O) : basic_parser(O) {}
0947 
0948   // Return true on error.
0949   bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
0950 
0951   void initialize() {}
0952 
0953   enum ValueExpected getValueExpectedFlagDefault() const {
0954     return ValueOptional;
0955   }
0956 
0957   // Do not print =<value> at all.
0958   StringRef getValueName() const override { return StringRef(); }
0959 
0960   void printOptionDiff(const Option &O, bool V, OptVal Default,
0961                        size_t GlobalWidth) const;
0962 
0963   // An out-of-line virtual method to provide a 'home' for this class.
0964   void anchor() override;
0965 };
0966 
0967 //--------------------------------------------------
0968 
0969 extern template class basic_parser<boolOrDefault>;
0970 
0971 template <> class parser<boolOrDefault> : public basic_parser<boolOrDefault> {
0972 public:
0973   parser(Option &O) : basic_parser(O) {}
0974 
0975   // Return true on error.
0976   bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
0977 
0978   enum ValueExpected getValueExpectedFlagDefault() const {
0979     return ValueOptional;
0980   }
0981 
0982   // Do not print =<value> at all.
0983   StringRef getValueName() const override { return StringRef(); }
0984 
0985   void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
0986                        size_t GlobalWidth) const;
0987 
0988   // An out-of-line virtual method to provide a 'home' for this class.
0989   void anchor() override;
0990 };
0991 
0992 //--------------------------------------------------
0993 
0994 extern template class basic_parser<int>;
0995 
0996 template <> class parser<int> : public basic_parser<int> {
0997 public:
0998   parser(Option &O) : basic_parser(O) {}
0999 
1000   // Return true on error.
1001   bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
1002 
1003   // Overload in subclass to provide a better default value.
1004   StringRef getValueName() const override { return "int"; }
1005 
1006   void printOptionDiff(const Option &O, int V, OptVal Default,
1007                        size_t GlobalWidth) const;
1008 
1009   // An out-of-line virtual method to provide a 'home' for this class.
1010   void anchor() override;
1011 };
1012 
1013 //--------------------------------------------------
1014 
1015 extern template class basic_parser<long>;
1016 
1017 template <> class parser<long> final : public basic_parser<long> {
1018 public:
1019   parser(Option &O) : basic_parser(O) {}
1020 
1021   // Return true on error.
1022   bool parse(Option &O, StringRef ArgName, StringRef Arg, long &Val);
1023 
1024   // Overload in subclass to provide a better default value.
1025   StringRef getValueName() const override { return "long"; }
1026 
1027   void printOptionDiff(const Option &O, long V, OptVal Default,
1028                        size_t GlobalWidth) const;
1029 
1030   // An out-of-line virtual method to provide a 'home' for this class.
1031   void anchor() override;
1032 };
1033 
1034 //--------------------------------------------------
1035 
1036 extern template class basic_parser<long long>;
1037 
1038 template <> class parser<long long> : public basic_parser<long long> {
1039 public:
1040   parser(Option &O) : basic_parser(O) {}
1041 
1042   // Return true on error.
1043   bool parse(Option &O, StringRef ArgName, StringRef Arg, long long &Val);
1044 
1045   // Overload in subclass to provide a better default value.
1046   StringRef getValueName() const override { return "long"; }
1047 
1048   void printOptionDiff(const Option &O, long long V, OptVal Default,
1049                        size_t GlobalWidth) const;
1050 
1051   // An out-of-line virtual method to provide a 'home' for this class.
1052   void anchor() override;
1053 };
1054 
1055 //--------------------------------------------------
1056 
1057 extern template class basic_parser<unsigned>;
1058 
1059 template <> class parser<unsigned> : public basic_parser<unsigned> {
1060 public:
1061   parser(Option &O) : basic_parser(O) {}
1062 
1063   // Return true on error.
1064   bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
1065 
1066   // Overload in subclass to provide a better default value.
1067   StringRef getValueName() const override { return "uint"; }
1068 
1069   void printOptionDiff(const Option &O, unsigned V, OptVal Default,
1070                        size_t GlobalWidth) const;
1071 
1072   // An out-of-line virtual method to provide a 'home' for this class.
1073   void anchor() override;
1074 };
1075 
1076 //--------------------------------------------------
1077 
1078 extern template class basic_parser<unsigned long>;
1079 
1080 template <>
1081 class parser<unsigned long> final : public basic_parser<unsigned long> {
1082 public:
1083   parser(Option &O) : basic_parser(O) {}
1084 
1085   // Return true on error.
1086   bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned long &Val);
1087 
1088   // Overload in subclass to provide a better default value.
1089   StringRef getValueName() const override { return "ulong"; }
1090 
1091   void printOptionDiff(const Option &O, unsigned long V, OptVal Default,
1092                        size_t GlobalWidth) const;
1093 
1094   // An out-of-line virtual method to provide a 'home' for this class.
1095   void anchor() override;
1096 };
1097 
1098 //--------------------------------------------------
1099 
1100 extern template class basic_parser<unsigned long long>;
1101 
1102 template <>
1103 class parser<unsigned long long> : public basic_parser<unsigned long long> {
1104 public:
1105   parser(Option &O) : basic_parser(O) {}
1106 
1107   // Return true on error.
1108   bool parse(Option &O, StringRef ArgName, StringRef Arg,
1109              unsigned long long &Val);
1110 
1111   // Overload in subclass to provide a better default value.
1112   StringRef getValueName() const override { return "ulong"; }
1113 
1114   void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
1115                        size_t GlobalWidth) const;
1116 
1117   // An out-of-line virtual method to provide a 'home' for this class.
1118   void anchor() override;
1119 };
1120 
1121 //--------------------------------------------------
1122 
1123 extern template class basic_parser<double>;
1124 
1125 template <> class parser<double> : public basic_parser<double> {
1126 public:
1127   parser(Option &O) : basic_parser(O) {}
1128 
1129   // Return true on error.
1130   bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
1131 
1132   // Overload in subclass to provide a better default value.
1133   StringRef getValueName() const override { return "number"; }
1134 
1135   void printOptionDiff(const Option &O, double V, OptVal Default,
1136                        size_t GlobalWidth) const;
1137 
1138   // An out-of-line virtual method to provide a 'home' for this class.
1139   void anchor() override;
1140 };
1141 
1142 //--------------------------------------------------
1143 
1144 extern template class basic_parser<float>;
1145 
1146 template <> class parser<float> : public basic_parser<float> {
1147 public:
1148   parser(Option &O) : basic_parser(O) {}
1149 
1150   // Return true on error.
1151   bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
1152 
1153   // Overload in subclass to provide a better default value.
1154   StringRef getValueName() const override { return "number"; }
1155 
1156   void printOptionDiff(const Option &O, float V, OptVal Default,
1157                        size_t GlobalWidth) const;
1158 
1159   // An out-of-line virtual method to provide a 'home' for this class.
1160   void anchor() override;
1161 };
1162 
1163 //--------------------------------------------------
1164 
1165 extern template class basic_parser<std::string>;
1166 
1167 template <> class parser<std::string> : public basic_parser<std::string> {
1168 public:
1169   parser(Option &O) : basic_parser(O) {}
1170 
1171   // Return true on error.
1172   bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
1173     Value = Arg.str();
1174     return false;
1175   }
1176 
1177   // Overload in subclass to provide a better default value.
1178   StringRef getValueName() const override { return "string"; }
1179 
1180   void printOptionDiff(const Option &O, StringRef V, const OptVal &Default,
1181                        size_t GlobalWidth) const;
1182 
1183   // An out-of-line virtual method to provide a 'home' for this class.
1184   void anchor() override;
1185 };
1186 
1187 //--------------------------------------------------
1188 
1189 extern template class basic_parser<char>;
1190 
1191 template <> class parser<char> : public basic_parser<char> {
1192 public:
1193   parser(Option &O) : basic_parser(O) {}
1194 
1195   // Return true on error.
1196   bool parse(Option &, StringRef, StringRef Arg, char &Value) {
1197     Value = Arg[0];
1198     return false;
1199   }
1200 
1201   // Overload in subclass to provide a better default value.
1202   StringRef getValueName() const override { return "char"; }
1203 
1204   void printOptionDiff(const Option &O, char V, OptVal Default,
1205                        size_t GlobalWidth) const;
1206 
1207   // An out-of-line virtual method to provide a 'home' for this class.
1208   void anchor() override;
1209 };
1210 
1211 //--------------------------------------------------
1212 // This collection of wrappers is the intermediary between class opt and class
1213 // parser to handle all the template nastiness.
1214 
1215 // This overloaded function is selected by the generic parser.
1216 template <class ParserClass, class DT>
1217 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
1218                      const OptionValue<DT> &Default, size_t GlobalWidth) {
1219   OptionValue<DT> OV = V;
1220   P.printOptionDiff(O, OV, Default, GlobalWidth);
1221 }
1222 
1223 // This is instantiated for basic parsers when the parsed value has a different
1224 // type than the option value. e.g. HelpPrinter.
1225 template <class ParserDT, class ValDT> struct OptionDiffPrinter {
1226   void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/,
1227              const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
1228     P.printOptionNoValue(O, GlobalWidth);
1229   }
1230 };
1231 
1232 // This is instantiated for basic parsers when the parsed value has the same
1233 // type as the option value.
1234 template <class DT> struct OptionDiffPrinter<DT, DT> {
1235   void print(const Option &O, const parser<DT> &P, const DT &V,
1236              const OptionValue<DT> &Default, size_t GlobalWidth) {
1237     P.printOptionDiff(O, V, Default, GlobalWidth);
1238   }
1239 };
1240 
1241 // This overloaded function is selected by the basic parser, which may parse a
1242 // different type than the option type.
1243 template <class ParserClass, class ValDT>
1244 void printOptionDiff(
1245     const Option &O,
1246     const basic_parser<typename ParserClass::parser_data_type> &P,
1247     const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
1248 
1249   OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
1250   printer.print(O, static_cast<const ParserClass &>(P), V, Default,
1251                 GlobalWidth);
1252 }
1253 
1254 //===----------------------------------------------------------------------===//
1255 // This class is used because we must use partial specialization to handle
1256 // literal string arguments specially (const char* does not correctly respond to
1257 // the apply method). Because the syntax to use this is a pain, we have the
1258 // 'apply' method below to handle the nastiness...
1259 //
1260 template <class Mod> struct applicator {
1261   template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1262 };
1263 
1264 // Handle const char* as a special case...
1265 template <unsigned n> struct applicator<char[n]> {
1266   template <class Opt> static void opt(StringRef Str, Opt &O) {
1267     O.setArgStr(Str);
1268   }
1269 };
1270 template <unsigned n> struct applicator<const char[n]> {
1271   template <class Opt> static void opt(StringRef Str, Opt &O) {
1272     O.setArgStr(Str);
1273   }
1274 };
1275 template <> struct applicator<StringRef > {
1276   template <class Opt> static void opt(StringRef Str, Opt &O) {
1277     O.setArgStr(Str);
1278   }
1279 };
1280 
1281 template <> struct applicator<NumOccurrencesFlag> {
1282   static void opt(NumOccurrencesFlag N, Option &O) {
1283     O.setNumOccurrencesFlag(N);
1284   }
1285 };
1286 
1287 template <> struct applicator<ValueExpected> {
1288   static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1289 };
1290 
1291 template <> struct applicator<OptionHidden> {
1292   static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1293 };
1294 
1295 template <> struct applicator<FormattingFlags> {
1296   static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1297 };
1298 
1299 template <> struct applicator<MiscFlags> {
1300   static void opt(MiscFlags MF, Option &O) {
1301     assert((MF != Grouping || O.ArgStr.size() == 1) &&
1302            "cl::Grouping can only apply to single character Options.");
1303     O.setMiscFlag(MF);
1304   }
1305 };
1306 
1307 // Apply modifiers to an option in a type safe way.
1308 template <class Opt, class Mod, class... Mods>
1309 void apply(Opt *O, const Mod &M, const Mods &... Ms) {
1310   applicator<Mod>::opt(M, *O);
1311   apply(O, Ms...);
1312 }
1313 
1314 template <class Opt, class Mod> void apply(Opt *O, const Mod &M) {
1315   applicator<Mod>::opt(M, *O);
1316 }
1317 
1318 //===----------------------------------------------------------------------===//
1319 // Default storage class definition: external storage.  This implementation
1320 // assumes the user will specify a variable to store the data into with the
1321 // cl::location(x) modifier.
1322 //
1323 template <class DataType, bool ExternalStorage, bool isClass>
1324 class opt_storage {
1325   DataType *Location = nullptr; // Where to store the object...
1326   OptionValue<DataType> Default;
1327 
1328   void check_location() const {
1329     assert(Location && "cl::location(...) not specified for a command "
1330                        "line option with external storage, "
1331                        "or cl::init specified before cl::location()!!");
1332   }
1333 
1334 public:
1335   opt_storage() = default;
1336 
1337   bool setLocation(Option &O, DataType &L) {
1338     if (Location)
1339       return O.error("cl::location(x) specified more than once!");
1340     Location = &L;
1341     Default = L;
1342     return false;
1343   }
1344 
1345   template <class T> void setValue(const T &V, bool initial = false) {
1346     check_location();
1347     *Location = V;
1348     if (initial)
1349       Default = V;
1350   }
1351 
1352   DataType &getValue() {
1353     check_location();
1354     return *Location;
1355   }
1356   const DataType &getValue() const {
1357     check_location();
1358     return *Location;
1359   }
1360 
1361   operator DataType() const { return this->getValue(); }
1362 
1363   const OptionValue<DataType> &getDefault() const { return Default; }
1364 };
1365 
1366 // Define how to hold a class type object, such as a string.  Since we can
1367 // inherit from a class, we do so.  This makes us exactly compatible with the
1368 // object in all cases that it is used.
1369 //
1370 template <class DataType>
1371 class opt_storage<DataType, false, true> : public DataType {
1372 public:
1373   OptionValue<DataType> Default;
1374 
1375   template <class T> void setValue(const T &V, bool initial = false) {
1376     DataType::operator=(V);
1377     if (initial)
1378       Default = V;
1379   }
1380 
1381   DataType &getValue() { return *this; }
1382   const DataType &getValue() const { return *this; }
1383 
1384   const OptionValue<DataType> &getDefault() const { return Default; }
1385 };
1386 
1387 // Define a partial specialization to handle things we cannot inherit from.  In
1388 // this case, we store an instance through containment, and overload operators
1389 // to get at the value.
1390 //
1391 template <class DataType> class opt_storage<DataType, false, false> {
1392 public:
1393   DataType Value;
1394   OptionValue<DataType> Default;
1395 
1396   // Make sure we initialize the value with the default constructor for the
1397   // type.
1398   opt_storage() : Value(DataType()), Default() {}
1399 
1400   template <class T> void setValue(const T &V, bool initial = false) {
1401     Value = V;
1402     if (initial)
1403       Default = V;
1404   }
1405   DataType &getValue() { return Value; }
1406   DataType getValue() const { return Value; }
1407 
1408   const OptionValue<DataType> &getDefault() const { return Default; }
1409 
1410   operator DataType() const { return getValue(); }
1411 
1412   // If the datatype is a pointer, support -> on it.
1413   DataType operator->() const { return Value; }
1414 };
1415 
1416 //===----------------------------------------------------------------------===//
1417 // A scalar command line option.
1418 //
1419 template <class DataType, bool ExternalStorage = false,
1420           class ParserClass = parser<DataType>>
1421 class opt
1422     : public Option,
1423       public opt_storage<DataType, ExternalStorage, std::is_class_v<DataType>> {
1424   ParserClass Parser;
1425 
1426   bool handleOccurrence(unsigned pos, StringRef ArgName,
1427                         StringRef Arg) override {
1428     typename ParserClass::parser_data_type Val =
1429         typename ParserClass::parser_data_type();
1430     if (Parser.parse(*this, ArgName, Arg, Val))
1431       return true; // Parse error!
1432     this->setValue(Val);
1433     this->setPosition(pos);
1434     Callback(Val);
1435     return false;
1436   }
1437 
1438   enum ValueExpected getValueExpectedFlagDefault() const override {
1439     return Parser.getValueExpectedFlagDefault();
1440   }
1441 
1442   void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1443     return Parser.getExtraOptionNames(OptionNames);
1444   }
1445 
1446   // Forward printing stuff to the parser...
1447   size_t getOptionWidth() const override {
1448     return Parser.getOptionWidth(*this);
1449   }
1450 
1451   void printOptionInfo(size_t GlobalWidth) const override {
1452     Parser.printOptionInfo(*this, GlobalWidth);
1453   }
1454 
1455   void printOptionValue(size_t GlobalWidth, bool Force) const override {
1456     if (Force || !this->getDefault().compare(this->getValue())) {
1457       cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1458                                        this->getDefault(), GlobalWidth);
1459     }
1460   }
1461 
1462   template <class T, class = std::enable_if_t<std::is_assignable_v<T &, T>>>
1463   void setDefaultImpl() {
1464     const OptionValue<DataType> &V = this->getDefault();
1465     if (V.hasValue())
1466       this->setValue(V.getValue());
1467     else
1468       this->setValue(T());
1469   }
1470 
1471   template <class T, class = std::enable_if_t<!std::is_assignable_v<T &, T>>>
1472   void setDefaultImpl(...) {}
1473 
1474   void setDefault() override { setDefaultImpl<DataType>(); }
1475 
1476   void done() {
1477     addArgument();
1478     Parser.initialize();
1479   }
1480 
1481 public:
1482   // Command line options should not be copyable
1483   opt(const opt &) = delete;
1484   opt &operator=(const opt &) = delete;
1485 
1486   // setInitialValue - Used by the cl::init modifier...
1487   void setInitialValue(const DataType &V) { this->setValue(V, true); }
1488 
1489   ParserClass &getParser() { return Parser; }
1490 
1491   template <class T> DataType &operator=(const T &Val) {
1492     this->setValue(Val);
1493     Callback(Val);
1494     return this->getValue();
1495   }
1496 
1497   template <class... Mods>
1498   explicit opt(const Mods &... Ms)
1499       : Option(llvm::cl::Optional, NotHidden), Parser(*this) {
1500     apply(this, Ms...);
1501     done();
1502   }
1503 
1504   void setCallback(
1505       std::function<void(const typename ParserClass::parser_data_type &)> CB) {
1506     Callback = CB;
1507   }
1508 
1509   std::function<void(const typename ParserClass::parser_data_type &)> Callback =
1510       [](const typename ParserClass::parser_data_type &) {};
1511 };
1512 
1513 extern template class opt<unsigned>;
1514 extern template class opt<int>;
1515 extern template class opt<std::string>;
1516 extern template class opt<char>;
1517 extern template class opt<bool>;
1518 
1519 //===----------------------------------------------------------------------===//
1520 // Default storage class definition: external storage.  This implementation
1521 // assumes the user will specify a variable to store the data into with the
1522 // cl::location(x) modifier.
1523 //
1524 template <class DataType, class StorageClass> class list_storage {
1525   StorageClass *Location = nullptr; // Where to store the object...
1526   std::vector<OptionValue<DataType>> Default =
1527       std::vector<OptionValue<DataType>>();
1528   bool DefaultAssigned = false;
1529 
1530 public:
1531   list_storage() = default;
1532 
1533   void clear() {}
1534 
1535   bool setLocation(Option &O, StorageClass &L) {
1536     if (Location)
1537       return O.error("cl::location(x) specified more than once!");
1538     Location = &L;
1539     return false;
1540   }
1541 
1542   template <class T> void addValue(const T &V, bool initial = false) {
1543     assert(Location != nullptr &&
1544            "cl::location(...) not specified for a command "
1545            "line option with external storage!");
1546     Location->push_back(V);
1547     if (initial)
1548       Default.push_back(V);
1549   }
1550 
1551   const std::vector<OptionValue<DataType>> &getDefault() const {
1552     return Default;
1553   }
1554 
1555   void assignDefault() { DefaultAssigned = true; }
1556   void overwriteDefault() { DefaultAssigned = false; }
1557   bool isDefaultAssigned() { return DefaultAssigned; }
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   std::vector<OptionValue<DataType>> Default;
1571   bool DefaultAssigned = false;
1572 
1573 public:
1574   using iterator = typename std::vector<DataType>::iterator;
1575 
1576   iterator begin() { return Storage.begin(); }
1577   iterator end() { return Storage.end(); }
1578 
1579   using const_iterator = typename std::vector<DataType>::const_iterator;
1580 
1581   const_iterator begin() const { return Storage.begin(); }
1582   const_iterator end() const { return Storage.end(); }
1583 
1584   using size_type = typename std::vector<DataType>::size_type;
1585 
1586   size_type size() const { return Storage.size(); }
1587 
1588   bool empty() const { return Storage.empty(); }
1589 
1590   void push_back(const DataType &value) { Storage.push_back(value); }
1591   void push_back(DataType &&value) { Storage.push_back(value); }
1592 
1593   using reference = typename std::vector<DataType>::reference;
1594   using const_reference = typename std::vector<DataType>::const_reference;
1595 
1596   reference operator[](size_type pos) { return Storage[pos]; }
1597   const_reference operator[](size_type pos) const { return Storage[pos]; }
1598 
1599   void clear() {
1600     Storage.clear();
1601   }
1602 
1603   iterator erase(const_iterator pos) { return Storage.erase(pos); }
1604   iterator erase(const_iterator first, const_iterator last) {
1605     return Storage.erase(first, last);
1606   }
1607 
1608   iterator erase(iterator pos) { return Storage.erase(pos); }
1609   iterator erase(iterator first, iterator last) {
1610     return Storage.erase(first, last);
1611   }
1612 
1613   iterator insert(const_iterator pos, const DataType &value) {
1614     return Storage.insert(pos, value);
1615   }
1616   iterator insert(const_iterator pos, DataType &&value) {
1617     return Storage.insert(pos, value);
1618   }
1619 
1620   iterator insert(iterator pos, const DataType &value) {
1621     return Storage.insert(pos, value);
1622   }
1623   iterator insert(iterator pos, DataType &&value) {
1624     return Storage.insert(pos, value);
1625   }
1626 
1627   reference front() { return Storage.front(); }
1628   const_reference front() const { return Storage.front(); }
1629 
1630   operator std::vector<DataType> &() { return Storage; }
1631   operator ArrayRef<DataType>() const { return Storage; }
1632   std::vector<DataType> *operator&() { return &Storage; }
1633   const std::vector<DataType> *operator&() const { return &Storage; }
1634 
1635   template <class T> void addValue(const T &V, bool initial = false) {
1636     Storage.push_back(V);
1637     if (initial)
1638       Default.push_back(OptionValue<DataType>(V));
1639   }
1640 
1641   const std::vector<OptionValue<DataType>> &getDefault() const {
1642     return Default;
1643   }
1644 
1645   void assignDefault() { DefaultAssigned = true; }
1646   void overwriteDefault() { DefaultAssigned = false; }
1647   bool isDefaultAssigned() { return DefaultAssigned; }
1648 };
1649 
1650 //===----------------------------------------------------------------------===//
1651 // A list of command line options.
1652 //
1653 template <class DataType, class StorageClass = bool,
1654           class ParserClass = parser<DataType>>
1655 class list : public Option, public list_storage<DataType, StorageClass> {
1656   std::vector<unsigned> Positions;
1657   ParserClass Parser;
1658 
1659   enum ValueExpected getValueExpectedFlagDefault() const override {
1660     return Parser.getValueExpectedFlagDefault();
1661   }
1662 
1663   void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1664     return Parser.getExtraOptionNames(OptionNames);
1665   }
1666 
1667   bool handleOccurrence(unsigned pos, StringRef ArgName,
1668                         StringRef Arg) override {
1669     typename ParserClass::parser_data_type Val =
1670         typename ParserClass::parser_data_type();
1671     if (list_storage<DataType, StorageClass>::isDefaultAssigned()) {
1672       clear();
1673       list_storage<DataType, StorageClass>::overwriteDefault();
1674     }
1675     if (Parser.parse(*this, ArgName, Arg, Val))
1676       return true; // Parse Error!
1677     list_storage<DataType, StorageClass>::addValue(Val);
1678     setPosition(pos);
1679     Positions.push_back(pos);
1680     Callback(Val);
1681     return false;
1682   }
1683 
1684   // Forward printing stuff to the parser...
1685   size_t getOptionWidth() const override {
1686     return Parser.getOptionWidth(*this);
1687   }
1688 
1689   void printOptionInfo(size_t GlobalWidth) const override {
1690     Parser.printOptionInfo(*this, GlobalWidth);
1691   }
1692 
1693   // Unimplemented: list options don't currently store their default value.
1694   void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1695   }
1696 
1697   void setDefault() override {
1698     Positions.clear();
1699     list_storage<DataType, StorageClass>::clear();
1700     for (auto &Val : list_storage<DataType, StorageClass>::getDefault())
1701       list_storage<DataType, StorageClass>::addValue(Val.getValue());
1702   }
1703 
1704   void done() {
1705     addArgument();
1706     Parser.initialize();
1707   }
1708 
1709 public:
1710   // Command line options should not be copyable
1711   list(const list &) = delete;
1712   list &operator=(const list &) = delete;
1713 
1714   ParserClass &getParser() { return Parser; }
1715 
1716   unsigned getPosition(unsigned optnum) const {
1717     assert(optnum < this->size() && "Invalid option index");
1718     return Positions[optnum];
1719   }
1720 
1721   void clear() {
1722     Positions.clear();
1723     list_storage<DataType, StorageClass>::clear();
1724   }
1725 
1726   // setInitialValues - Used by the cl::list_init modifier...
1727   void setInitialValues(ArrayRef<DataType> Vs) {
1728     assert(!(list_storage<DataType, StorageClass>::isDefaultAssigned()) &&
1729            "Cannot have two default values");
1730     list_storage<DataType, StorageClass>::assignDefault();
1731     for (auto &Val : Vs)
1732       list_storage<DataType, StorageClass>::addValue(Val, true);
1733   }
1734 
1735   void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
1736 
1737   template <class... Mods>
1738   explicit list(const Mods &... Ms)
1739       : Option(ZeroOrMore, NotHidden), Parser(*this) {
1740     apply(this, Ms...);
1741     done();
1742   }
1743 
1744   void setCallback(
1745       std::function<void(const typename ParserClass::parser_data_type &)> CB) {
1746     Callback = CB;
1747   }
1748 
1749   std::function<void(const typename ParserClass::parser_data_type &)> Callback =
1750       [](const typename ParserClass::parser_data_type &) {};
1751 };
1752 
1753 // Modifier to set the number of additional values.
1754 struct multi_val {
1755   unsigned AdditionalVals;
1756   explicit multi_val(unsigned N) : AdditionalVals(N) {}
1757 
1758   template <typename D, typename S, typename P>
1759   void apply(list<D, S, P> &L) const {
1760     L.setNumAdditionalVals(AdditionalVals);
1761   }
1762 };
1763 
1764 //===----------------------------------------------------------------------===//
1765 // Default storage class definition: external storage.  This implementation
1766 // assumes the user will specify a variable to store the data into with the
1767 // cl::location(x) modifier.
1768 //
1769 template <class DataType, class StorageClass> class bits_storage {
1770   unsigned *Location = nullptr; // Where to store the bits...
1771 
1772   template <class T> static unsigned Bit(const T &V) {
1773     unsigned BitPos = static_cast<unsigned>(V);
1774     assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1775            "enum exceeds width of bit vector!");
1776     return 1 << BitPos;
1777   }
1778 
1779 public:
1780   bits_storage() = default;
1781 
1782   bool setLocation(Option &O, unsigned &L) {
1783     if (Location)
1784       return O.error("cl::location(x) specified more than once!");
1785     Location = &L;
1786     return false;
1787   }
1788 
1789   template <class T> void addValue(const T &V) {
1790     assert(Location != nullptr &&
1791            "cl::location(...) not specified for a command "
1792            "line option with external storage!");
1793     *Location |= Bit(V);
1794   }
1795 
1796   unsigned getBits() { return *Location; }
1797 
1798   void clear() {
1799     if (Location)
1800       *Location = 0;
1801   }
1802 
1803   template <class T> bool isSet(const T &V) {
1804     return (*Location & Bit(V)) != 0;
1805   }
1806 };
1807 
1808 // Define how to hold bits.  Since we can inherit from a class, we do so.
1809 // This makes us exactly compatible with the bits in all cases that it is used.
1810 //
1811 template <class DataType> class bits_storage<DataType, bool> {
1812   unsigned Bits{0}; // Where to store the bits...
1813 
1814   template <class T> static unsigned Bit(const T &V) {
1815     unsigned BitPos = static_cast<unsigned>(V);
1816     assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1817            "enum exceeds width of bit vector!");
1818     return 1 << BitPos;
1819   }
1820 
1821 public:
1822   template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1823 
1824   unsigned getBits() { return Bits; }
1825 
1826   void clear() { Bits = 0; }
1827 
1828   template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1829 };
1830 
1831 //===----------------------------------------------------------------------===//
1832 // A bit vector of command options.
1833 //
1834 template <class DataType, class Storage = bool,
1835           class ParserClass = parser<DataType>>
1836 class bits : public Option, public bits_storage<DataType, Storage> {
1837   std::vector<unsigned> Positions;
1838   ParserClass Parser;
1839 
1840   enum ValueExpected getValueExpectedFlagDefault() const override {
1841     return Parser.getValueExpectedFlagDefault();
1842   }
1843 
1844   void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1845     return Parser.getExtraOptionNames(OptionNames);
1846   }
1847 
1848   bool handleOccurrence(unsigned pos, StringRef ArgName,
1849                         StringRef Arg) override {
1850     typename ParserClass::parser_data_type Val =
1851         typename ParserClass::parser_data_type();
1852     if (Parser.parse(*this, ArgName, Arg, Val))
1853       return true; // Parse Error!
1854     this->addValue(Val);
1855     setPosition(pos);
1856     Positions.push_back(pos);
1857     Callback(Val);
1858     return false;
1859   }
1860 
1861   // Forward printing stuff to the parser...
1862   size_t getOptionWidth() const override {
1863     return Parser.getOptionWidth(*this);
1864   }
1865 
1866   void printOptionInfo(size_t GlobalWidth) const override {
1867     Parser.printOptionInfo(*this, GlobalWidth);
1868   }
1869 
1870   // Unimplemented: bits options don't currently store their default values.
1871   void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1872   }
1873 
1874   void setDefault() override { bits_storage<DataType, Storage>::clear(); }
1875 
1876   void done() {
1877     addArgument();
1878     Parser.initialize();
1879   }
1880 
1881 public:
1882   // Command line options should not be copyable
1883   bits(const bits &) = delete;
1884   bits &operator=(const bits &) = delete;
1885 
1886   ParserClass &getParser() { return Parser; }
1887 
1888   unsigned getPosition(unsigned optnum) const {
1889     assert(optnum < this->size() && "Invalid option index");
1890     return Positions[optnum];
1891   }
1892 
1893   template <class... Mods>
1894   explicit bits(const Mods &... Ms)
1895       : Option(ZeroOrMore, NotHidden), Parser(*this) {
1896     apply(this, Ms...);
1897     done();
1898   }
1899 
1900   void setCallback(
1901       std::function<void(const typename ParserClass::parser_data_type &)> CB) {
1902     Callback = CB;
1903   }
1904 
1905   std::function<void(const typename ParserClass::parser_data_type &)> Callback =
1906       [](const typename ParserClass::parser_data_type &) {};
1907 };
1908 
1909 //===----------------------------------------------------------------------===//
1910 // Aliased command line option (alias this name to a preexisting name)
1911 //
1912 
1913 class alias : public Option {
1914   Option *AliasFor;
1915 
1916   bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1917                         StringRef Arg) override {
1918     return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1919   }
1920 
1921   bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1922                      bool MultiArg = false) override {
1923     return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1924   }
1925 
1926   // Handle printing stuff...
1927   size_t getOptionWidth() const override;
1928   void printOptionInfo(size_t GlobalWidth) const override;
1929 
1930   // Aliases do not need to print their values.
1931   void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1932   }
1933 
1934   void setDefault() override { AliasFor->setDefault(); }
1935 
1936   ValueExpected getValueExpectedFlagDefault() const override {
1937     return AliasFor->getValueExpectedFlag();
1938   }
1939 
1940   void done() {
1941     if (!hasArgStr())
1942       error("cl::alias must have argument name specified!");
1943     if (!AliasFor)
1944       error("cl::alias must have an cl::aliasopt(option) specified!");
1945     if (!Subs.empty())
1946       error("cl::alias must not have cl::sub(), aliased option's cl::sub() will be used!");
1947     Subs = AliasFor->Subs;
1948     Categories = AliasFor->Categories;
1949     addArgument();
1950   }
1951 
1952 public:
1953   // Command line options should not be copyable
1954   alias(const alias &) = delete;
1955   alias &operator=(const alias &) = delete;
1956 
1957   void setAliasFor(Option &O) {
1958     if (AliasFor)
1959       error("cl::alias must only have one cl::aliasopt(...) specified!");
1960     AliasFor = &O;
1961   }
1962 
1963   template <class... Mods>
1964   explicit alias(const Mods &... Ms)
1965       : Option(Optional, Hidden), AliasFor(nullptr) {
1966     apply(this, Ms...);
1967     done();
1968   }
1969 };
1970 
1971 // Modifier to set the option an alias aliases.
1972 struct aliasopt {
1973   Option &Opt;
1974 
1975   explicit aliasopt(Option &O) : Opt(O) {}
1976 
1977   void apply(alias &A) const { A.setAliasFor(Opt); }
1978 };
1979 
1980 // Provide additional help at the end of the normal help output. All occurrences
1981 // of cl::extrahelp will be accumulated and printed to stderr at the end of the
1982 // regular help, just before exit is called.
1983 struct extrahelp {
1984   StringRef morehelp;
1985 
1986   explicit extrahelp(StringRef help);
1987 };
1988 
1989 void PrintVersionMessage();
1990 
1991 /// This function just prints the help message, exactly the same way as if the
1992 /// -help or -help-hidden option had been given on the command line.
1993 ///
1994 /// \param Hidden if true will print hidden options
1995 /// \param Categorized if true print options in categories
1996 void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
1997 
1998 /// An array of optional enabled settings in the LLVM build configuration,
1999 /// which may be of interest to compiler developers. For example, includes
2000 /// "+assertions" if assertions are enabled. Used by printBuildConfig.
2001 ArrayRef<StringRef> getCompilerBuildConfig();
2002 
2003 /// Prints the compiler build configuration.
2004 /// Designed for compiler developers, not compiler end-users.
2005 /// Intended to be used in --version output when enabled.
2006 void printBuildConfig(raw_ostream &OS);
2007 
2008 //===----------------------------------------------------------------------===//
2009 // Public interface for accessing registered options.
2010 //
2011 
2012 /// Use this to get a StringMap to all registered named options
2013 /// (e.g. -help).
2014 ///
2015 /// \return A reference to the StringMap used by the cl APIs to parse options.
2016 ///
2017 /// Access to unnamed arguments (i.e. positional) are not provided because
2018 /// it is expected that the client already has access to these.
2019 ///
2020 /// Typical usage:
2021 /// \code
2022 /// main(int argc,char* argv[]) {
2023 /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions();
2024 /// assert(opts.count("help") == 1)
2025 /// opts["help"]->setDescription("Show alphabetical help information")
2026 /// // More code
2027 /// llvm::cl::ParseCommandLineOptions(argc,argv);
2028 /// //More code
2029 /// }
2030 /// \endcode
2031 ///
2032 /// This interface is useful for modifying options in libraries that are out of
2033 /// the control of the client. The options should be modified before calling
2034 /// llvm::cl::ParseCommandLineOptions().
2035 ///
2036 /// Hopefully this API can be deprecated soon. Any situation where options need
2037 /// to be modified by tools or libraries should be handled by sane APIs rather
2038 /// than just handing around a global list.
2039 StringMap<Option *> &
2040 getRegisteredOptions(SubCommand &Sub = SubCommand::getTopLevel());
2041 
2042 /// Use this to get all registered SubCommands from the provided parser.
2043 ///
2044 /// \return A range of all SubCommand pointers registered with the parser.
2045 ///
2046 /// Typical usage:
2047 /// \code
2048 /// main(int argc, char* argv[]) {
2049 ///   llvm::cl::ParseCommandLineOptions(argc, argv);
2050 ///   for (auto* S : llvm::cl::getRegisteredSubcommands()) {
2051 ///     if (*S) {
2052 ///       std::cout << "Executing subcommand: " << S->getName() << std::endl;
2053 ///       // Execute some function based on the name...
2054 ///     }
2055 ///   }
2056 /// }
2057 /// \endcode
2058 ///
2059 /// This interface is useful for defining subcommands in libraries and
2060 /// the dispatch from a single point (like in the main function).
2061 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2062 getRegisteredSubcommands();
2063 
2064 //===----------------------------------------------------------------------===//
2065 // Standalone command line processing utilities.
2066 //
2067 
2068 /// Tokenizes a command line that can contain escapes and quotes.
2069 //
2070 /// The quoting rules match those used by GCC and other tools that use
2071 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
2072 /// They differ from buildargv() on treatment of backslashes that do not escape
2073 /// a special character to make it possible to accept most Windows file paths.
2074 ///
2075 /// \param [in] Source The string to be split on whitespace with quotes.
2076 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
2077 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
2078 /// lines and end of the response file to be marked with a nullptr string.
2079 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
2080 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
2081                             SmallVectorImpl<const char *> &NewArgv,
2082                             bool MarkEOLs = false);
2083 
2084 /// Tokenizes a string of Windows command line arguments, which may contain
2085 /// quotes and escaped quotes.
2086 ///
2087 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
2088 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
2089 ///
2090 /// For handling a full Windows command line including the executable name at
2091 /// the start, see TokenizeWindowsCommandLineFull below.
2092 ///
2093 /// \param [in] Source The string to be split on whitespace with quotes.
2094 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
2095 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
2096 /// lines and end of the response file to be marked with a nullptr string.
2097 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
2098 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
2099                                 SmallVectorImpl<const char *> &NewArgv,
2100                                 bool MarkEOLs = false);
2101 
2102 /// Tokenizes a Windows command line while attempting to avoid copies. If no
2103 /// quoting or escaping was used, this produces substrings of the original
2104 /// string. If a token requires unquoting, it will be allocated with the
2105 /// StringSaver.
2106 void TokenizeWindowsCommandLineNoCopy(StringRef Source, StringSaver &Saver,
2107                                       SmallVectorImpl<StringRef> &NewArgv);
2108 
2109 /// Tokenizes a Windows full command line, including command name at the start.
2110 ///
2111 /// This uses the same syntax rules as TokenizeWindowsCommandLine for all but
2112 /// the first token. But the first token is expected to be parsed as the
2113 /// executable file name in the way CreateProcess would do it, rather than the
2114 /// way the C library startup code would do it: CreateProcess does not consider
2115 /// that \ is ever an escape character (because " is not a valid filename char,
2116 /// hence there's never a need to escape it to be used literally).
2117 ///
2118 /// Parameters are the same as for TokenizeWindowsCommandLine. In particular,
2119 /// if you set MarkEOLs = true, then the first word of every line will be
2120 /// parsed using the special rules for command names, making this function
2121 /// suitable for parsing a file full of commands to execute.
2122 void TokenizeWindowsCommandLineFull(StringRef Source, StringSaver &Saver,
2123                                     SmallVectorImpl<const char *> &NewArgv,
2124                                     bool MarkEOLs = false);
2125 
2126 /// String tokenization function type.  Should be compatible with either
2127 /// Windows or Unix command line tokenizers.
2128 using TokenizerCallback = void (*)(StringRef Source, StringSaver &Saver,
2129                                    SmallVectorImpl<const char *> &NewArgv,
2130                                    bool MarkEOLs);
2131 
2132 /// Tokenizes content of configuration file.
2133 ///
2134 /// \param [in] Source The string representing content of config file.
2135 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
2136 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
2137 /// \param [in] MarkEOLs Added for compatibility with TokenizerCallback.
2138 ///
2139 /// It works like TokenizeGNUCommandLine with ability to skip comment lines.
2140 ///
2141 void tokenizeConfigFile(StringRef Source, StringSaver &Saver,
2142                         SmallVectorImpl<const char *> &NewArgv,
2143                         bool MarkEOLs = false);
2144 
2145 /// Contains options that control response file expansion.
2146 class ExpansionContext {
2147   /// Provides persistent storage for parsed strings.
2148   StringSaver Saver;
2149 
2150   /// Tokenization strategy. Typically Unix or Windows.
2151   TokenizerCallback Tokenizer;
2152 
2153   /// File system used for all file access when running the expansion.
2154   vfs::FileSystem *FS;
2155 
2156   /// Path used to resolve relative rsp files. If empty, the file system
2157   /// current directory is used instead.
2158   StringRef CurrentDir;
2159 
2160   /// Directories used for search of config files.
2161   ArrayRef<StringRef> SearchDirs;
2162 
2163   /// True if names of nested response files must be resolved relative to
2164   /// including file.
2165   bool RelativeNames = false;
2166 
2167   /// If true, mark end of lines and the end of the response file with nullptrs
2168   /// in the Argv vector.
2169   bool MarkEOLs = false;
2170 
2171   /// If true, body of config file is expanded.
2172   bool InConfigFile = false;
2173 
2174   llvm::Error expandResponseFile(StringRef FName,
2175                                  SmallVectorImpl<const char *> &NewArgv);
2176 
2177 public:
2178   ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T);
2179 
2180   ExpansionContext &setMarkEOLs(bool X) {
2181     MarkEOLs = X;
2182     return *this;
2183   }
2184 
2185   ExpansionContext &setRelativeNames(bool X) {
2186     RelativeNames = X;
2187     return *this;
2188   }
2189 
2190   ExpansionContext &setCurrentDir(StringRef X) {
2191     CurrentDir = X;
2192     return *this;
2193   }
2194 
2195   ExpansionContext &setSearchDirs(ArrayRef<StringRef> X) {
2196     SearchDirs = X;
2197     return *this;
2198   }
2199 
2200   ExpansionContext &setVFS(vfs::FileSystem *X) {
2201     FS = X;
2202     return *this;
2203   }
2204 
2205   /// Looks for the specified configuration file.
2206   ///
2207   /// \param[in]  FileName Name of the file to search for.
2208   /// \param[out] FilePath File absolute path, if it was found.
2209   /// \return True if file was found.
2210   ///
2211   /// If the specified file name contains a directory separator, it is searched
2212   /// for by its absolute path. Otherwise looks for file sequentially in
2213   /// directories specified by SearchDirs field.
2214   bool findConfigFile(StringRef FileName, SmallVectorImpl<char> &FilePath);
2215 
2216   /// Reads command line options from the given configuration file.
2217   ///
2218   /// \param [in] CfgFile Path to configuration file.
2219   /// \param [out] Argv Array to which the read options are added.
2220   /// \return true if the file was successfully read.
2221   ///
2222   /// It reads content of the specified file, tokenizes it and expands "@file"
2223   /// commands resolving file names in them relative to the directory where
2224   /// CfgFilename resides. It also expands "<CFGDIR>" to the base path of the
2225   /// current config file.
2226   Error readConfigFile(StringRef CfgFile, SmallVectorImpl<const char *> &Argv);
2227 
2228   /// Expands constructs "@file" in the provided array of arguments recursively.
2229   Error expandResponseFiles(SmallVectorImpl<const char *> &Argv);
2230 };
2231 
2232 /// A convenience helper which concatenates the options specified by the
2233 /// environment variable EnvVar and command line options, then expands
2234 /// response files recursively.
2235 /// \return true if all @files were expanded successfully or there were none.
2236 bool expandResponseFiles(int Argc, const char *const *Argv, const char *EnvVar,
2237                          SmallVectorImpl<const char *> &NewArgv);
2238 
2239 /// A convenience helper which supports the typical use case of expansion
2240 /// function call.
2241 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
2242                          SmallVectorImpl<const char *> &Argv);
2243 
2244 /// A convenience helper which concatenates the options specified by the
2245 /// environment variable EnvVar and command line options, then expands response
2246 /// files recursively. The tokenizer is a predefined GNU or Windows one.
2247 /// \return true if all @files were expanded successfully or there were none.
2248 bool expandResponseFiles(int Argc, const char *const *Argv, const char *EnvVar,
2249                          StringSaver &Saver,
2250                          SmallVectorImpl<const char *> &NewArgv);
2251 
2252 /// Mark all options not part of this category as cl::ReallyHidden.
2253 ///
2254 /// \param Category the category of options to keep displaying
2255 ///
2256 /// Some tools (like clang-format) like to be able to hide all options that are
2257 /// not specific to the tool. This function allows a tool to specify a single
2258 /// option category to display in the -help output.
2259 void HideUnrelatedOptions(cl::OptionCategory &Category,
2260                           SubCommand &Sub = SubCommand::getTopLevel());
2261 
2262 /// Mark all options not part of the categories as cl::ReallyHidden.
2263 ///
2264 /// \param Categories the categories of options to keep displaying.
2265 ///
2266 /// Some tools (like clang-format) like to be able to hide all options that are
2267 /// not specific to the tool. This function allows a tool to specify a single
2268 /// option category to display in the -help output.
2269 void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2270                           SubCommand &Sub = SubCommand::getTopLevel());
2271 
2272 /// Reset all command line options to a state that looks as if they have
2273 /// never appeared on the command line.  This is useful for being able to parse
2274 /// a command line multiple times (especially useful for writing tests).
2275 void ResetAllOptionOccurrences();
2276 
2277 /// Reset the command line parser back to its initial state.  This
2278 /// removes
2279 /// all options, categories, and subcommands and returns the parser to a state
2280 /// where no options are supported.
2281 void ResetCommandLineParser();
2282 
2283 /// Parses `Arg` into the option handler `Handler`.
2284 bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i);
2285 
2286 } // end namespace cl
2287 
2288 } // end namespace llvm
2289 
2290 #endif // LLVM_SUPPORT_COMMANDLINE_H