CommandLine.h 75 KB

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