CommandLine.h 60 KB

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