CommandLine.h 72 KB

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