CommandLine.h 73 KB

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