CommandLine.rst 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749
  1. ==============================
  2. CommandLine 2.0 Library Manual
  3. ==============================
  4. .. contents::
  5. :local:
  6. Introduction
  7. ============
  8. NOTE: This document describes the CommandLine library as used for the original
  9. LLVM project, not the DirectX Compiler. For the DirectX Compiler project, we
  10. prefer to avoid globals for a few reasons: thread-safety, control over
  11. initialization and cleanup timing (explicit vs. runtime/linker-determined) and
  12. ability to control memory allocations.
  13. This document describes the CommandLine argument processing library. It will
  14. show you how to use it, and what it can do. The CommandLine library uses a
  15. declarative approach to specifying the command line options that your program
  16. takes. By default, these options declarations implicitly hold the value parsed
  17. for the option declared (of course this `can be changed`_).
  18. Although there are a **lot** of command line argument parsing libraries out
  19. there in many different languages, none of them fit well with what I needed. By
  20. looking at the features and problems of other libraries, I designed the
  21. CommandLine library to have the following features:
  22. #. Speed: The CommandLine library is very quick and uses little resources. The
  23. parsing time of the library is directly proportional to the number of
  24. arguments parsed, not the number of options recognized. Additionally,
  25. command line argument values are captured transparently into user defined
  26. global variables, which can be accessed like any other variable (and with the
  27. same performance).
  28. #. Type Safe: As a user of CommandLine, you don't have to worry about
  29. remembering the type of arguments that you want (is it an int? a string? a
  30. bool? an enum?) and keep casting it around. Not only does this help prevent
  31. error prone constructs, it also leads to dramatically cleaner source code.
  32. #. No subclasses required: To use CommandLine, you instantiate variables that
  33. correspond to the arguments that you would like to capture, you don't
  34. subclass a parser. This means that you don't have to write **any**
  35. boilerplate code.
  36. #. Globally accessible: Libraries can specify command line arguments that are
  37. automatically enabled in any tool that links to the library. This is
  38. possible because the application doesn't have to keep a list of arguments to
  39. pass to the parser. This also makes supporting `dynamically loaded options`_
  40. trivial.
  41. #. Cleaner: CommandLine supports enum and other types directly, meaning that
  42. there is less error and more security built into the library. You don't have
  43. to worry about whether your integral command line argument accidentally got
  44. assigned a value that is not valid for your enum type.
  45. #. Powerful: The CommandLine library supports many different types of arguments,
  46. from simple `boolean flags`_ to `scalars arguments`_ (`strings`_,
  47. `integers`_, `enums`_, `doubles`_), to `lists of arguments`_. This is
  48. possible because CommandLine is...
  49. #. Extensible: It is very simple to add a new argument type to CommandLine.
  50. Simply specify the parser that you want to use with the command line option
  51. when you declare it. `Custom parsers`_ are no problem.
  52. #. Labor Saving: The CommandLine library cuts down on the amount of grunt work
  53. that you, the user, have to do. For example, it automatically provides a
  54. ``-help`` option that shows the available command line options for your tool.
  55. Additionally, it does most of the basic correctness checking for you.
  56. #. Capable: The CommandLine library can handle lots of different forms of
  57. options often found in real programs. For example, `positional`_ arguments,
  58. ``ls`` style `grouping`_ options (to allow processing '``ls -lad``'
  59. naturally), ``ld`` style `prefix`_ options (to parse '``-lmalloc
  60. -L/usr/lib``'), and interpreter style options.
  61. This document will hopefully let you jump in and start using CommandLine in your
  62. utility quickly and painlessly. Additionally it should be a simple reference
  63. manual to figure out how stuff works.
  64. Quick Start Guide
  65. =================
  66. This section of the manual runs through a simple CommandLine'ification of a
  67. basic compiler tool. This is intended to show you how to jump into using the
  68. CommandLine library in your own program, and show you some of the cool things it
  69. can do.
  70. To start out, you need to include the CommandLine header file into your program:
  71. .. code-block:: c++
  72. #include "llvm/Support/CommandLine.h"
  73. Additionally, you need to add this as the first line of your main program:
  74. .. code-block:: c++
  75. int main(int argc, char **argv) {
  76. cl::ParseCommandLineOptions(argc, argv);
  77. ...
  78. }
  79. ... which actually parses the arguments and fills in the variable declarations.
  80. Now that you are ready to support command line arguments, we need to tell the
  81. system which ones we want, and what type of arguments they are. The CommandLine
  82. library uses a declarative syntax to model command line arguments with the
  83. global variable declarations that capture the parsed values. This means that
  84. for every command line option that you would like to support, there should be a
  85. global variable declaration to capture the result. For example, in a compiler,
  86. we would like to support the Unix-standard '``-o <filename>``' option to specify
  87. where to put the output. With the CommandLine library, this is represented like
  88. this:
  89. .. _scalars arguments:
  90. .. _here:
  91. .. code-block:: c++
  92. cl::opt<string> OutputFilename("o", cl::desc("Specify output filename"), cl::value_desc("filename"));
  93. This declares a global variable "``OutputFilename``" that is used to capture the
  94. result of the "``o``" argument (first parameter). We specify that this is a
  95. simple scalar option by using the "``cl::opt``" template (as opposed to the
  96. "``cl::list``" template), and tell the CommandLine library that the data
  97. type that we are parsing is a string.
  98. The second and third parameters (which are optional) are used to specify what to
  99. output for the "``-help``" option. In this case, we get a line that looks like
  100. this:
  101. ::
  102. USAGE: compiler [options]
  103. OPTIONS:
  104. -help - display available options (-help-hidden for more)
  105. -o <filename> - Specify output filename
  106. Because we specified that the command line option should parse using the
  107. ``string`` data type, the variable declared is automatically usable as a real
  108. string in all contexts that a normal C++ string object may be used. For
  109. example:
  110. .. code-block:: c++
  111. ...
  112. std::ofstream Output(OutputFilename.c_str());
  113. if (Output.good()) ...
  114. ...
  115. There are many different options that you can use to customize the command line
  116. option handling library, but the above example shows the general interface to
  117. these options. The options can be specified in any order, and are specified
  118. with helper functions like `cl::desc(...)`_, so there are no positional
  119. dependencies to remember. The available options are discussed in detail in the
  120. `Reference Guide`_.
  121. Continuing the example, we would like to have our compiler take an input
  122. filename as well as an output filename, but we do not want the input filename to
  123. be specified with a hyphen (ie, not ``-filename.c``). To support this style of
  124. argument, the CommandLine library allows for `positional`_ arguments to be
  125. specified for the program. These positional arguments are filled with command
  126. line parameters that are not in option form. We use this feature like this:
  127. .. code-block:: c++
  128. cl::opt<string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
  129. This declaration indicates that the first positional argument should be treated
  130. as the input filename. Here we use the `cl::init`_ option to specify an initial
  131. value for the command line option, which is used if the option is not specified
  132. (if you do not specify a `cl::init`_ modifier for an option, then the default
  133. constructor for the data type is used to initialize the value). Command line
  134. options default to being optional, so if we would like to require that the user
  135. always specify an input filename, we would add the `cl::Required`_ flag, and we
  136. could eliminate the `cl::init`_ modifier, like this:
  137. .. code-block:: c++
  138. cl::opt<string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::Required);
  139. Again, the CommandLine library does not require the options to be specified in
  140. any particular order, so the above declaration is equivalent to:
  141. .. code-block:: c++
  142. cl::opt<string> InputFilename(cl::Positional, cl::Required, cl::desc("<input file>"));
  143. By simply adding the `cl::Required`_ flag, the CommandLine library will
  144. automatically issue an error if the argument is not specified, which shifts all
  145. of the command line option verification code out of your application into the
  146. library. This is just one example of how using flags can alter the default
  147. behaviour of the library, on a per-option basis. By adding one of the
  148. declarations above, the ``-help`` option synopsis is now extended to:
  149. ::
  150. USAGE: compiler [options] <input file>
  151. OPTIONS:
  152. -help - display available options (-help-hidden for more)
  153. -o <filename> - Specify output filename
  154. ... indicating that an input filename is expected.
  155. Boolean Arguments
  156. -----------------
  157. In addition to input and output filenames, we would like the compiler example to
  158. support three boolean flags: "``-f``" to force writing binary output to a
  159. terminal, "``--quiet``" to enable quiet mode, and "``-q``" for backwards
  160. compatibility with some of our users. We can support these by declaring options
  161. of boolean type like this:
  162. .. code-block:: c++
  163. cl::opt<bool> Force ("f", cl::desc("Enable binary output on terminals"));
  164. cl::opt<bool> Quiet ("quiet", cl::desc("Don't print informational messages"));
  165. cl::opt<bool> Quiet2("q", cl::desc("Don't print informational messages"), cl::Hidden);
  166. This does what you would expect: it declares three boolean variables
  167. ("``Force``", "``Quiet``", and "``Quiet2``") to recognize these options. Note
  168. that the "``-q``" option is specified with the "`cl::Hidden`_" flag. This
  169. modifier prevents it from being shown by the standard "``-help``" output (note
  170. that it is still shown in the "``-help-hidden``" output).
  171. The CommandLine library uses a `different parser`_ for different data types.
  172. For example, in the string case, the argument passed to the option is copied
  173. literally into the content of the string variable... we obviously cannot do that
  174. in the boolean case, however, so we must use a smarter parser. In the case of
  175. the boolean parser, it allows no options (in which case it assigns the value of
  176. true to the variable), or it allows the values "``true``" or "``false``" to be
  177. specified, allowing any of the following inputs:
  178. ::
  179. compiler -f # No value, 'Force' == true
  180. compiler -f=true # Value specified, 'Force' == true
  181. compiler -f=TRUE # Value specified, 'Force' == true
  182. compiler -f=FALSE # Value specified, 'Force' == false
  183. ... you get the idea. The `bool parser`_ just turns the string values into
  184. boolean values, and rejects things like '``compiler -f=foo``'. Similarly, the
  185. `float`_, `double`_, and `int`_ parsers work like you would expect, using the
  186. '``strtol``' and '``strtod``' C library calls to parse the string value into the
  187. specified data type.
  188. With the declarations above, "``compiler -help``" emits this:
  189. ::
  190. USAGE: compiler [options] <input file>
  191. OPTIONS:
  192. -f - Enable binary output on terminals
  193. -o - Override output filename
  194. -quiet - Don't print informational messages
  195. -help - display available options (-help-hidden for more)
  196. and "``compiler -help-hidden``" prints this:
  197. ::
  198. USAGE: compiler [options] <input file>
  199. OPTIONS:
  200. -f - Enable binary output on terminals
  201. -o - Override output filename
  202. -q - Don't print informational messages
  203. -quiet - Don't print informational messages
  204. -help - display available options (-help-hidden for more)
  205. This brief example has shown you how to use the '`cl::opt`_' class to parse
  206. simple scalar command line arguments. In addition to simple scalar arguments,
  207. the CommandLine library also provides primitives to support CommandLine option
  208. `aliases`_, and `lists`_ of options.
  209. .. _aliases:
  210. Argument Aliases
  211. ----------------
  212. So far, the example works well, except for the fact that we need to check the
  213. quiet condition like this now:
  214. .. code-block:: c++
  215. ...
  216. if (!Quiet && !Quiet2) printInformationalMessage(...);
  217. ...
  218. ... which is a real pain! Instead of defining two values for the same
  219. condition, we can use the "`cl::alias`_" class to make the "``-q``" option an
  220. **alias** for the "``-quiet``" option, instead of providing a value itself:
  221. .. code-block:: c++
  222. cl::opt<bool> Force ("f", cl::desc("Overwrite output files"));
  223. cl::opt<bool> Quiet ("quiet", cl::desc("Don't print informational messages"));
  224. cl::alias QuietA("q", cl::desc("Alias for -quiet"), cl::aliasopt(Quiet));
  225. The third line (which is the only one we modified from above) defines a "``-q``"
  226. alias that updates the "``Quiet``" variable (as specified by the `cl::aliasopt`_
  227. modifier) whenever it is specified. Because aliases do not hold state, the only
  228. thing the program has to query is the ``Quiet`` variable now. Another nice
  229. feature of aliases is that they automatically hide themselves from the ``-help``
  230. output (although, again, they are still visible in the ``-help-hidden output``).
  231. Now the application code can simply use:
  232. .. code-block:: c++
  233. ...
  234. if (!Quiet) printInformationalMessage(...);
  235. ...
  236. ... which is much nicer! The "`cl::alias`_" can be used to specify an
  237. alternative name for any variable type, and has many uses.
  238. .. _unnamed alternatives using the generic parser:
  239. Selecting an alternative from a set of possibilities
  240. ----------------------------------------------------
  241. So far we have seen how the CommandLine library handles builtin types like
  242. ``std::string``, ``bool`` and ``int``, but how does it handle things it doesn't
  243. know about, like enums or '``int*``'s?
  244. The answer is that it uses a table-driven generic parser (unless you specify
  245. your own parser, as described in the `Extension Guide`_). This parser maps
  246. literal strings to whatever type is required, and requires you to tell it what
  247. this mapping should be.
  248. Let's say that we would like to add four optimization levels to our optimizer,
  249. using the standard flags "``-g``", "``-O0``", "``-O1``", and "``-O2``". We
  250. could easily implement this with boolean options like above, but there are
  251. several problems with this strategy:
  252. #. A user could specify more than one of the options at a time, for example,
  253. "``compiler -O3 -O2``". The CommandLine library would not be able to catch
  254. this erroneous input for us.
  255. #. We would have to test 4 different variables to see which ones are set.
  256. #. This doesn't map to the numeric levels that we want... so we cannot easily
  257. see if some level >= "``-O1``" is enabled.
  258. To cope with these problems, we can use an enum value, and have the CommandLine
  259. library fill it in with the appropriate level directly, which is used like this:
  260. .. code-block:: c++
  261. enum OptLevel {
  262. g, O1, O2, O3
  263. };
  264. cl::opt<OptLevel> OptimizationLevel(cl::desc("Choose optimization level:"),
  265. cl::values(
  266. clEnumVal(g , "No optimizations, enable debugging"),
  267. clEnumVal(O1, "Enable trivial optimizations"),
  268. clEnumVal(O2, "Enable default optimizations"),
  269. clEnumVal(O3, "Enable expensive optimizations"),
  270. clEnumValEnd));
  271. ...
  272. if (OptimizationLevel >= O2) doPartialRedundancyElimination(...);
  273. ...
  274. This declaration defines a variable "``OptimizationLevel``" of the
  275. "``OptLevel``" enum type. This variable can be assigned any of the values that
  276. are listed in the declaration (Note that the declaration list must be terminated
  277. with the "``clEnumValEnd``" argument!). The CommandLine library enforces that
  278. the user can only specify one of the options, and it ensure that only valid enum
  279. values can be specified. The "``clEnumVal``" macros ensure that the command
  280. line arguments matched the enum values. With this option added, our help output
  281. now is:
  282. ::
  283. USAGE: compiler [options] <input file>
  284. OPTIONS:
  285. Choose optimization level:
  286. -g - No optimizations, enable debugging
  287. -O1 - Enable trivial optimizations
  288. -O2 - Enable default optimizations
  289. -O3 - Enable expensive optimizations
  290. -f - Enable binary output on terminals
  291. -help - display available options (-help-hidden for more)
  292. -o <filename> - Specify output filename
  293. -quiet - Don't print informational messages
  294. In this case, it is sort of awkward that flag names correspond directly to enum
  295. names, because we probably don't want a enum definition named "``g``" in our
  296. program. Because of this, we can alternatively write this example like this:
  297. .. code-block:: c++
  298. enum OptLevel {
  299. Debug, O1, O2, O3
  300. };
  301. cl::opt<OptLevel> OptimizationLevel(cl::desc("Choose optimization level:"),
  302. cl::values(
  303. clEnumValN(Debug, "g", "No optimizations, enable debugging"),
  304. clEnumVal(O1 , "Enable trivial optimizations"),
  305. clEnumVal(O2 , "Enable default optimizations"),
  306. clEnumVal(O3 , "Enable expensive optimizations"),
  307. clEnumValEnd));
  308. ...
  309. if (OptimizationLevel == Debug) outputDebugInfo(...);
  310. ...
  311. By using the "``clEnumValN``" macro instead of "``clEnumVal``", we can directly
  312. specify the name that the flag should get. In general a direct mapping is nice,
  313. but sometimes you can't or don't want to preserve the mapping, which is when you
  314. would use it.
  315. Named Alternatives
  316. ------------------
  317. Another useful argument form is a named alternative style. We shall use this
  318. style in our compiler to specify different debug levels that can be used.
  319. Instead of each debug level being its own switch, we want to support the
  320. following options, of which only one can be specified at a time:
  321. "``--debug-level=none``", "``--debug-level=quick``",
  322. "``--debug-level=detailed``". To do this, we use the exact same format as our
  323. optimization level flags, but we also specify an option name. For this case,
  324. the code looks like this:
  325. .. code-block:: c++
  326. enum DebugLev {
  327. nodebuginfo, quick, detailed
  328. };
  329. // Enable Debug Options to be specified on the command line
  330. cl::opt<DebugLev> DebugLevel("debug_level", cl::desc("Set the debugging level:"),
  331. cl::values(
  332. clEnumValN(nodebuginfo, "none", "disable debug information"),
  333. clEnumVal(quick, "enable quick debug information"),
  334. clEnumVal(detailed, "enable detailed debug information"),
  335. clEnumValEnd));
  336. This definition defines an enumerated command line variable of type "``enum
  337. DebugLev``", which works exactly the same way as before. The difference here is
  338. just the interface exposed to the user of your program and the help output by
  339. the "``-help``" option:
  340. ::
  341. USAGE: compiler [options] <input file>
  342. OPTIONS:
  343. Choose optimization level:
  344. -g - No optimizations, enable debugging
  345. -O1 - Enable trivial optimizations
  346. -O2 - Enable default optimizations
  347. -O3 - Enable expensive optimizations
  348. -debug_level - Set the debugging level:
  349. =none - disable debug information
  350. =quick - enable quick debug information
  351. =detailed - enable detailed debug information
  352. -f - Enable binary output on terminals
  353. -help - display available options (-help-hidden for more)
  354. -o <filename> - Specify output filename
  355. -quiet - Don't print informational messages
  356. Again, the only structural difference between the debug level declaration and
  357. the optimization level declaration is that the debug level declaration includes
  358. an option name (``"debug_level"``), which automatically changes how the library
  359. processes the argument. The CommandLine library supports both forms so that you
  360. can choose the form most appropriate for your application.
  361. .. _lists:
  362. Parsing a list of options
  363. -------------------------
  364. Now that we have the standard run-of-the-mill argument types out of the way,
  365. lets get a little wild and crazy. Lets say that we want our optimizer to accept
  366. a **list** of optimizations to perform, allowing duplicates. For example, we
  367. might want to run: "``compiler -dce -constprop -inline -dce -strip``". In this
  368. case, the order of the arguments and the number of appearances is very
  369. important. This is what the "``cl::list``" template is for. First, start by
  370. defining an enum of the optimizations that you would like to perform:
  371. .. code-block:: c++
  372. enum Opts {
  373. // 'inline' is a C++ keyword, so name it 'inlining'
  374. dce, constprop, inlining, strip
  375. };
  376. Then define your "``cl::list``" variable:
  377. .. code-block:: c++
  378. cl::list<Opts> OptimizationList(cl::desc("Available Optimizations:"),
  379. cl::values(
  380. clEnumVal(dce , "Dead Code Elimination"),
  381. clEnumVal(constprop , "Constant Propagation"),
  382. clEnumValN(inlining, "inline", "Procedure Integration"),
  383. clEnumVal(strip , "Strip Symbols"),
  384. clEnumValEnd));
  385. This defines a variable that is conceptually of the type
  386. "``std::vector<enum Opts>``". Thus, you can access it with standard vector
  387. methods:
  388. .. code-block:: c++
  389. for (unsigned i = 0; i != OptimizationList.size(); ++i)
  390. switch (OptimizationList[i])
  391. ...
  392. ... to iterate through the list of options specified.
  393. Note that the "``cl::list``" template is completely general and may be used with
  394. any data types or other arguments that you can use with the "``cl::opt``"
  395. template. One especially useful way to use a list is to capture all of the
  396. positional arguments together if there may be more than one specified. In the
  397. case of a linker, for example, the linker takes several '``.o``' files, and
  398. needs to capture them into a list. This is naturally specified as:
  399. .. code-block:: c++
  400. ...
  401. cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<Input files>"), cl::OneOrMore);
  402. ...
  403. This variable works just like a "``vector<string>``" object. As such, accessing
  404. the list is simple, just like above. In this example, we used the
  405. `cl::OneOrMore`_ modifier to inform the CommandLine library that it is an error
  406. if the user does not specify any ``.o`` files on our command line. Again, this
  407. just reduces the amount of checking we have to do.
  408. Collecting options as a set of flags
  409. ------------------------------------
  410. Instead of collecting sets of options in a list, it is also possible to gather
  411. information for enum values in a **bit vector**. The representation used by the
  412. `cl::bits`_ class is an ``unsigned`` integer. An enum value is represented by a
  413. 0/1 in the enum's ordinal value bit position. 1 indicating that the enum was
  414. specified, 0 otherwise. As each specified value is parsed, the resulting enum's
  415. bit is set in the option's bit vector:
  416. .. code-block:: c++
  417. bits |= 1 << (unsigned)enum;
  418. Options that are specified multiple times are redundant. Any instances after
  419. the first are discarded.
  420. Reworking the above list example, we could replace `cl::list`_ with `cl::bits`_:
  421. .. code-block:: c++
  422. cl::bits<Opts> OptimizationBits(cl::desc("Available Optimizations:"),
  423. cl::values(
  424. clEnumVal(dce , "Dead Code Elimination"),
  425. clEnumVal(constprop , "Constant Propagation"),
  426. clEnumValN(inlining, "inline", "Procedure Integration"),
  427. clEnumVal(strip , "Strip Symbols"),
  428. clEnumValEnd));
  429. To test to see if ``constprop`` was specified, we can use the ``cl:bits::isSet``
  430. function:
  431. .. code-block:: c++
  432. if (OptimizationBits.isSet(constprop)) {
  433. ...
  434. }
  435. It's also possible to get the raw bit vector using the ``cl::bits::getBits``
  436. function:
  437. .. code-block:: c++
  438. unsigned bits = OptimizationBits.getBits();
  439. Finally, if external storage is used, then the location specified must be of
  440. **type** ``unsigned``. In all other ways a `cl::bits`_ option is equivalent to a
  441. `cl::list`_ option.
  442. .. _additional extra text:
  443. Adding freeform text to help output
  444. -----------------------------------
  445. As our program grows and becomes more mature, we may decide to put summary
  446. information about what it does into the help output. The help output is styled
  447. to look similar to a Unix ``man`` page, providing concise information about a
  448. program. Unix ``man`` pages, however often have a description about what the
  449. program does. To add this to your CommandLine program, simply pass a third
  450. argument to the `cl::ParseCommandLineOptions`_ call in main. This additional
  451. argument is then printed as the overview information for your program, allowing
  452. you to include any additional information that you want. For example:
  453. .. code-block:: c++
  454. int main(int argc, char **argv) {
  455. cl::ParseCommandLineOptions(argc, argv, " CommandLine compiler example\n\n"
  456. " This program blah blah blah...\n");
  457. ...
  458. }
  459. would yield the help output:
  460. ::
  461. **OVERVIEW: CommandLine compiler example
  462. This program blah blah blah...**
  463. USAGE: compiler [options] <input file>
  464. OPTIONS:
  465. ...
  466. -help - display available options (-help-hidden for more)
  467. -o <filename> - Specify output filename
  468. .. _grouping options into categories:
  469. Grouping options into categories
  470. --------------------------------
  471. If our program has a large number of options it may become difficult for users
  472. of our tool to navigate the output of ``-help``. To alleviate this problem we
  473. can put our options into categories. This can be done by declaring option
  474. categories (`cl::OptionCategory`_ objects) and then placing our options into
  475. these categories using the `cl::cat`_ option attribute. For example:
  476. .. code-block:: c++
  477. cl::OptionCategory StageSelectionCat("Stage Selection Options",
  478. "These control which stages are run.");
  479. cl::opt<bool> Preprocessor("E",cl::desc("Run preprocessor stage."),
  480. cl::cat(StageSelectionCat));
  481. cl::opt<bool> NoLink("c",cl::desc("Run all stages except linking."),
  482. cl::cat(StageSelectionCat));
  483. The output of ``-help`` will become categorized if an option category is
  484. declared. The output looks something like ::
  485. OVERVIEW: This is a small program to demo the LLVM CommandLine API
  486. USAGE: Sample [options]
  487. OPTIONS:
  488. General options:
  489. -help - Display available options (-help-hidden for more)
  490. -help-list - Display list of available options (-help-list-hidden for more)
  491. Stage Selection Options:
  492. These control which stages are run.
  493. -E - Run preprocessor stage.
  494. -c - Run all stages except linking.
  495. In addition to the behaviour of ``-help`` changing when an option category is
  496. declared, the command line option ``-help-list`` becomes visible which will
  497. print the command line options as uncategorized list.
  498. Note that Options that are not explicitly categorized will be placed in the
  499. ``cl::GeneralCategory`` category.
  500. .. _Reference Guide:
  501. Reference Guide
  502. ===============
  503. Now that you know the basics of how to use the CommandLine library, this section
  504. will give you the detailed information you need to tune how command line options
  505. work, as well as information on more "advanced" command line option processing
  506. capabilities.
  507. .. _positional:
  508. .. _positional argument:
  509. .. _Positional Arguments:
  510. .. _Positional arguments section:
  511. .. _positional options:
  512. Positional Arguments
  513. --------------------
  514. Positional arguments are those arguments that are not named, and are not
  515. specified with a hyphen. Positional arguments should be used when an option is
  516. specified by its position alone. For example, the standard Unix ``grep`` tool
  517. takes a regular expression argument, and an optional filename to search through
  518. (which defaults to standard input if a filename is not specified). Using the
  519. CommandLine library, this would be specified as:
  520. .. code-block:: c++
  521. cl::opt<string> Regex (cl::Positional, cl::desc("<regular expression>"), cl::Required);
  522. cl::opt<string> Filename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
  523. Given these two option declarations, the ``-help`` output for our grep
  524. replacement would look like this:
  525. ::
  526. USAGE: spiffygrep [options] <regular expression> <input file>
  527. OPTIONS:
  528. -help - display available options (-help-hidden for more)
  529. ... and the resultant program could be used just like the standard ``grep``
  530. tool.
  531. Positional arguments are sorted by their order of construction. This means that
  532. command line options will be ordered according to how they are listed in a .cpp
  533. file, but will not have an ordering defined if the positional arguments are
  534. defined in multiple .cpp files. The fix for this problem is simply to define
  535. all of your positional arguments in one .cpp file.
  536. Specifying positional options with hyphens
  537. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  538. Sometimes you may want to specify a value to your positional argument that
  539. starts with a hyphen (for example, searching for '``-foo``' in a file). At
  540. first, you will have trouble doing this, because it will try to find an argument
  541. named '``-foo``', and will fail (and single quotes will not save you). Note
  542. that the system ``grep`` has the same problem:
  543. ::
  544. $ spiffygrep '-foo' test.txt
  545. Unknown command line argument '-foo'. Try: spiffygrep -help'
  546. $ grep '-foo' test.txt
  547. grep: illegal option -- f
  548. grep: illegal option -- o
  549. grep: illegal option -- o
  550. Usage: grep -hblcnsviw pattern file . . .
  551. The solution for this problem is the same for both your tool and the system
  552. version: use the '``--``' marker. When the user specifies '``--``' on the
  553. command line, it is telling the program that all options after the '``--``'
  554. should be treated as positional arguments, not options. Thus, we can use it
  555. like this:
  556. ::
  557. $ spiffygrep -- -foo test.txt
  558. ...output...
  559. Determining absolute position with getPosition()
  560. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  561. Sometimes an option can affect or modify the meaning of another option. For
  562. example, consider ``gcc``'s ``-x LANG`` option. This tells ``gcc`` to ignore the
  563. suffix of subsequent positional arguments and force the file to be interpreted
  564. as if it contained source code in language ``LANG``. In order to handle this
  565. properly, you need to know the absolute position of each argument, especially
  566. those in lists, so their interaction(s) can be applied correctly. This is also
  567. useful for options like ``-llibname`` which is actually a positional argument
  568. that starts with a dash.
  569. So, generally, the problem is that you have two ``cl::list`` variables that
  570. interact in some way. To ensure the correct interaction, you can use the
  571. ``cl::list::getPosition(optnum)`` method. This method returns the absolute
  572. position (as found on the command line) of the ``optnum`` item in the
  573. ``cl::list``.
  574. The idiom for usage is like this:
  575. .. code-block:: c++
  576. static cl::list<std::string> Files(cl::Positional, cl::OneOrMore);
  577. static cl::list<std::string> Libraries("l", cl::ZeroOrMore);
  578. int main(int argc, char**argv) {
  579. // ...
  580. std::vector<std::string>::iterator fileIt = Files.begin();
  581. std::vector<std::string>::iterator libIt = Libraries.begin();
  582. unsigned libPos = 0, filePos = 0;
  583. while ( 1 ) {
  584. if ( libIt != Libraries.end() )
  585. libPos = Libraries.getPosition( libIt - Libraries.begin() );
  586. else
  587. libPos = 0;
  588. if ( fileIt != Files.end() )
  589. filePos = Files.getPosition( fileIt - Files.begin() );
  590. else
  591. filePos = 0;
  592. if ( filePos != 0 && (libPos == 0 || filePos < libPos) ) {
  593. // Source File Is next
  594. ++fileIt;
  595. }
  596. else if ( libPos != 0 && (filePos == 0 || libPos < filePos) ) {
  597. // Library is next
  598. ++libIt;
  599. }
  600. else
  601. break; // we're done with the list
  602. }
  603. }
  604. Note that, for compatibility reasons, the ``cl::opt`` also supports an
  605. ``unsigned getPosition()`` option that will provide the absolute position of
  606. that option. You can apply the same approach as above with a ``cl::opt`` and a
  607. ``cl::list`` option as you can with two lists.
  608. .. _interpreter style options:
  609. .. _cl::ConsumeAfter:
  610. .. _this section for more information:
  611. The ``cl::ConsumeAfter`` modifier
  612. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  613. The ``cl::ConsumeAfter`` `formatting option`_ is used to construct programs that
  614. use "interpreter style" option processing. With this style of option
  615. processing, all arguments specified after the last positional argument are
  616. treated as special interpreter arguments that are not interpreted by the command
  617. line argument.
  618. As a concrete example, lets say we are developing a replacement for the standard
  619. Unix Bourne shell (``/bin/sh``). To run ``/bin/sh``, first you specify options
  620. to the shell itself (like ``-x`` which turns on trace output), then you specify
  621. the name of the script to run, then you specify arguments to the script. These
  622. arguments to the script are parsed by the Bourne shell command line option
  623. processor, but are not interpreted as options to the shell itself. Using the
  624. CommandLine library, we would specify this as:
  625. .. code-block:: c++
  626. cl::opt<string> Script(cl::Positional, cl::desc("<input script>"), cl::init("-"));
  627. cl::list<string> Argv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
  628. cl::opt<bool> Trace("x", cl::desc("Enable trace output"));
  629. which automatically provides the help output:
  630. ::
  631. USAGE: spiffysh [options] <input script> <program arguments>...
  632. OPTIONS:
  633. -help - display available options (-help-hidden for more)
  634. -x - Enable trace output
  635. At runtime, if we run our new shell replacement as ```spiffysh -x test.sh -a -x
  636. -y bar``', the ``Trace`` variable will be set to true, the ``Script`` variable
  637. will be set to "``test.sh``", and the ``Argv`` list will contain ``["-a", "-x",
  638. "-y", "bar"]``, because they were specified after the last positional argument
  639. (which is the script name).
  640. There are several limitations to when ``cl::ConsumeAfter`` options can be
  641. specified. For example, only one ``cl::ConsumeAfter`` can be specified per
  642. program, there must be at least one `positional argument`_ specified, there must
  643. not be any `cl::list`_ positional arguments, and the ``cl::ConsumeAfter`` option
  644. should be a `cl::list`_ option.
  645. .. _can be changed:
  646. .. _Internal vs External Storage:
  647. Internal vs External Storage
  648. ----------------------------
  649. By default, all command line options automatically hold the value that they
  650. parse from the command line. This is very convenient in the common case,
  651. especially when combined with the ability to define command line options in the
  652. files that use them. This is called the internal storage model.
  653. Sometimes, however, it is nice to separate the command line option processing
  654. code from the storage of the value parsed. For example, lets say that we have a
  655. '``-debug``' option that we would like to use to enable debug information across
  656. the entire body of our program. In this case, the boolean value controlling the
  657. debug code should be globally accessible (in a header file, for example) yet the
  658. command line option processing code should not be exposed to all of these
  659. clients (requiring lots of .cpp files to ``#include CommandLine.h``).
  660. To do this, set up your .h file with your option, like this for example:
  661. .. code-block:: c++
  662. // DebugFlag.h - Get access to the '-debug' command line option
  663. //
  664. // DebugFlag - This boolean is set to true if the '-debug' command line option
  665. // is specified. This should probably not be referenced directly, instead, use
  666. // the DEBUG macro below.
  667. //
  668. extern bool DebugFlag;
  669. // DEBUG macro - This macro should be used by code to emit debug information.
  670. // In the '-debug' option is specified on the command line, and if this is a
  671. // debug build, then the code specified as the option to the macro will be
  672. // executed. Otherwise it will not be.
  673. #ifdef NDEBUG
  674. #define DEBUG(X)
  675. #else
  676. #define DEBUG(X) do { if (DebugFlag) { X; } } while (0)
  677. #endif
  678. This allows clients to blissfully use the ``DEBUG()`` macro, or the
  679. ``DebugFlag`` explicitly if they want to. Now we just need to be able to set
  680. the ``DebugFlag`` boolean when the option is set. To do this, we pass an
  681. additional argument to our command line argument processor, and we specify where
  682. to fill in with the `cl::location`_ attribute:
  683. .. code-block:: c++
  684. bool DebugFlag; // the actual value
  685. static cl::opt<bool, true> // The parser
  686. Debug("debug", cl::desc("Enable debug output"), cl::Hidden, cl::location(DebugFlag));
  687. In the above example, we specify "``true``" as the second argument to the
  688. `cl::opt`_ template, indicating that the template should not maintain a copy of
  689. the value itself. In addition to this, we specify the `cl::location`_
  690. attribute, so that ``DebugFlag`` is automatically set.
  691. Option Attributes
  692. -----------------
  693. This section describes the basic attributes that you can specify on options.
  694. * The option name attribute (which is required for all options, except
  695. `positional options`_) specifies what the option name is. This option is
  696. specified in simple double quotes:
  697. .. code-block:: c++
  698. cl::opt<bool> Quiet("quiet");
  699. .. _cl::desc(...):
  700. * The **cl::desc** attribute specifies a description for the option to be
  701. shown in the ``-help`` output for the program. This attribute supports
  702. multi-line descriptions with lines separated by '\n'.
  703. .. _cl::value_desc:
  704. * The **cl::value_desc** attribute specifies a string that can be used to
  705. fine tune the ``-help`` output for a command line option. Look `here`_ for an
  706. example.
  707. .. _cl::init:
  708. * The **cl::init** attribute specifies an initial value for a `scalar`_
  709. option. If this attribute is not specified then the command line option value
  710. defaults to the value created by the default constructor for the
  711. type.
  712. .. warning::
  713. If you specify both **cl::init** and **cl::location** for an option, you
  714. must specify **cl::location** first, so that when the command-line parser
  715. sees **cl::init**, it knows where to put the initial value. (You will get an
  716. error at runtime if you don't put them in the right order.)
  717. .. _cl::location:
  718. * The **cl::location** attribute where to store the value for a parsed command
  719. line option if using external storage. See the section on `Internal vs
  720. External Storage`_ for more information.
  721. .. _cl::aliasopt:
  722. * The **cl::aliasopt** attribute specifies which option a `cl::alias`_ option is
  723. an alias for.
  724. .. _cl::values:
  725. * The **cl::values** attribute specifies the string-to-value mapping to be used
  726. by the generic parser. It takes a **clEnumValEnd terminated** list of
  727. (option, value, description) triplets that specify the option name, the value
  728. mapped to, and the description shown in the ``-help`` for the tool. Because
  729. the generic parser is used most frequently with enum values, two macros are
  730. often useful:
  731. #. The **clEnumVal** macro is used as a nice simple way to specify a triplet
  732. for an enum. This macro automatically makes the option name be the same as
  733. the enum name. The first option to the macro is the enum, the second is
  734. the description for the command line option.
  735. #. The **clEnumValN** macro is used to specify macro options where the option
  736. name doesn't equal the enum name. For this macro, the first argument is
  737. the enum value, the second is the flag name, and the second is the
  738. description.
  739. You will get a compile time error if you try to use cl::values with a parser
  740. that does not support it.
  741. .. _cl::multi_val:
  742. * The **cl::multi_val** attribute specifies that this option takes has multiple
  743. values (example: ``-sectalign segname sectname sectvalue``). This attribute
  744. takes one unsigned argument - the number of values for the option. This
  745. attribute is valid only on ``cl::list`` options (and will fail with compile
  746. error if you try to use it with other option types). It is allowed to use all
  747. of the usual modifiers on multi-valued options (besides
  748. ``cl::ValueDisallowed``, obviously).
  749. .. _cl::cat:
  750. * The **cl::cat** attribute specifies the option category that the option
  751. belongs to. The category should be a `cl::OptionCategory`_ object.
  752. Option Modifiers
  753. ----------------
  754. Option modifiers are the flags and expressions that you pass into the
  755. constructors for `cl::opt`_ and `cl::list`_. These modifiers give you the
  756. ability to tweak how options are parsed and how ``-help`` output is generated to
  757. fit your application well.
  758. These options fall into five main categories:
  759. #. Hiding an option from ``-help`` output
  760. #. Controlling the number of occurrences required and allowed
  761. #. Controlling whether or not a value must be specified
  762. #. Controlling other formatting options
  763. #. Miscellaneous option modifiers
  764. It is not possible to specify two options from the same category (you'll get a
  765. runtime error) to a single option, except for options in the miscellaneous
  766. category. The CommandLine library specifies defaults for all of these settings
  767. that are the most useful in practice and the most common, which mean that you
  768. usually shouldn't have to worry about these.
  769. Hiding an option from ``-help`` output
  770. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  771. The ``cl::NotHidden``, ``cl::Hidden``, and ``cl::ReallyHidden`` modifiers are
  772. used to control whether or not an option appears in the ``-help`` and
  773. ``-help-hidden`` output for the compiled program:
  774. .. _cl::NotHidden:
  775. * The **cl::NotHidden** modifier (which is the default for `cl::opt`_ and
  776. `cl::list`_ options) indicates the option is to appear in both help
  777. listings.
  778. .. _cl::Hidden:
  779. * The **cl::Hidden** modifier (which is the default for `cl::alias`_ options)
  780. indicates that the option should not appear in the ``-help`` output, but
  781. should appear in the ``-help-hidden`` output.
  782. .. _cl::ReallyHidden:
  783. * The **cl::ReallyHidden** modifier indicates that the option should not appear
  784. in any help output.
  785. Controlling the number of occurrences required and allowed
  786. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  787. This group of options is used to control how many time an option is allowed (or
  788. required) to be specified on the command line of your program. Specifying a
  789. value for this setting allows the CommandLine library to do error checking for
  790. you.
  791. The allowed values for this option group are:
  792. .. _cl::Optional:
  793. * The **cl::Optional** modifier (which is the default for the `cl::opt`_ and
  794. `cl::alias`_ classes) indicates that your program will allow either zero or
  795. one occurrence of the option to be specified.
  796. .. _cl::ZeroOrMore:
  797. * The **cl::ZeroOrMore** modifier (which is the default for the `cl::list`_
  798. class) indicates that your program will allow the option to be specified zero
  799. or more times.
  800. .. _cl::Required:
  801. * The **cl::Required** modifier indicates that the specified option must be
  802. specified exactly one time.
  803. .. _cl::OneOrMore:
  804. * The **cl::OneOrMore** modifier indicates that the option must be specified at
  805. least one time.
  806. * The **cl::ConsumeAfter** modifier is described in the `Positional arguments
  807. section`_.
  808. If an option is not specified, then the value of the option is equal to the
  809. value specified by the `cl::init`_ attribute. If the ``cl::init`` attribute is
  810. not specified, the option value is initialized with the default constructor for
  811. the data type.
  812. If an option is specified multiple times for an option of the `cl::opt`_ class,
  813. only the last value will be retained.
  814. Controlling whether or not a value must be specified
  815. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  816. This group of options is used to control whether or not the option allows a
  817. value to be present. In the case of the CommandLine library, a value is either
  818. specified with an equal sign (e.g. '``-index-depth=17``') or as a trailing
  819. string (e.g. '``-o a.out``').
  820. The allowed values for this option group are:
  821. .. _cl::ValueOptional:
  822. * The **cl::ValueOptional** modifier (which is the default for ``bool`` typed
  823. options) specifies that it is acceptable to have a value, or not. A boolean
  824. argument can be enabled just by appearing on the command line, or it can have
  825. an explicit '``-foo=true``'. If an option is specified with this mode, it is
  826. illegal for the value to be provided without the equal sign. Therefore
  827. '``-foo true``' is illegal. To get this behavior, you must use
  828. the `cl::ValueRequired`_ modifier.
  829. .. _cl::ValueRequired:
  830. * The **cl::ValueRequired** modifier (which is the default for all other types
  831. except for `unnamed alternatives using the generic parser`_) specifies that a
  832. value must be provided. This mode informs the command line library that if an
  833. option is not provides with an equal sign, that the next argument provided
  834. must be the value. This allows things like '``-o a.out``' to work.
  835. .. _cl::ValueDisallowed:
  836. * The **cl::ValueDisallowed** modifier (which is the default for `unnamed
  837. alternatives using the generic parser`_) indicates that it is a runtime error
  838. for the user to specify a value. This can be provided to disallow users from
  839. providing options to boolean options (like '``-foo=true``').
  840. In general, the default values for this option group work just like you would
  841. want them to. As mentioned above, you can specify the `cl::ValueDisallowed`_
  842. modifier to a boolean argument to restrict your command line parser. These
  843. options are mostly useful when `extending the library`_.
  844. .. _formatting option:
  845. Controlling other formatting options
  846. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  847. The formatting option group is used to specify that the command line option has
  848. special abilities and is otherwise different from other command line arguments.
  849. As usual, you can only specify one of these arguments at most.
  850. .. _cl::NormalFormatting:
  851. * The **cl::NormalFormatting** modifier (which is the default all options)
  852. specifies that this option is "normal".
  853. .. _cl::Positional:
  854. * The **cl::Positional** modifier specifies that this is a positional argument
  855. that does not have a command line option associated with it. See the
  856. `Positional Arguments`_ section for more information.
  857. * The **cl::ConsumeAfter** modifier specifies that this option is used to
  858. capture "interpreter style" arguments. See `this section for more
  859. information`_.
  860. .. _prefix:
  861. .. _cl::Prefix:
  862. * The **cl::Prefix** modifier specifies that this option prefixes its value.
  863. With 'Prefix' options, the equal sign does not separate the value from the
  864. option name specified. Instead, the value is everything after the prefix,
  865. including any equal sign if present. This is useful for processing odd
  866. arguments like ``-lmalloc`` and ``-L/usr/lib`` in a linker tool or
  867. ``-DNAME=value`` in a compiler tool. Here, the '``l``', '``D``' and '``L``'
  868. options are normal string (or list) options, that have the **cl::Prefix**
  869. modifier added to allow the CommandLine library to recognize them. Note that
  870. **cl::Prefix** options must not have the **cl::ValueDisallowed** modifier
  871. specified.
  872. .. _grouping:
  873. .. _cl::Grouping:
  874. * The **cl::Grouping** modifier is used to implement Unix-style tools (like
  875. ``ls``) that have lots of single letter arguments, but only require a single
  876. dash. For example, the '``ls -labF``' command actually enables four different
  877. options, all of which are single letters. Note that **cl::Grouping** options
  878. cannot have values.
  879. The CommandLine library does not restrict how you use the **cl::Prefix** or
  880. **cl::Grouping** modifiers, but it is possible to specify ambiguous argument
  881. settings. Thus, it is possible to have multiple letter options that are prefix
  882. or grouping options, and they will still work as designed.
  883. To do this, the CommandLine library uses a greedy algorithm to parse the input
  884. option into (potentially multiple) prefix and grouping options. The strategy
  885. basically looks like this:
  886. ::
  887. parse(string OrigInput) {
  888. 1. string input = OrigInput;
  889. 2. if (isOption(input)) return getOption(input).parse(); // Normal option
  890. 3. while (!isOption(input) && !input.empty()) input.pop_back(); // Remove the last letter
  891. 4. if (input.empty()) return error(); // No matching option
  892. 5. if (getOption(input).isPrefix())
  893. return getOption(input).parse(input);
  894. 6. while (!input.empty()) { // Must be grouping options
  895. getOption(input).parse();
  896. OrigInput.erase(OrigInput.begin(), OrigInput.begin()+input.length());
  897. input = OrigInput;
  898. while (!isOption(input) && !input.empty()) input.pop_back();
  899. }
  900. 7. if (!OrigInput.empty()) error();
  901. }
  902. Miscellaneous option modifiers
  903. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  904. The miscellaneous option modifiers are the only flags where you can specify more
  905. than one flag from the set: they are not mutually exclusive. These flags
  906. specify boolean properties that modify the option.
  907. .. _cl::CommaSeparated:
  908. * The **cl::CommaSeparated** modifier indicates that any commas specified for an
  909. option's value should be used to split the value up into multiple values for
  910. the option. For example, these two options are equivalent when
  911. ``cl::CommaSeparated`` is specified: "``-foo=a -foo=b -foo=c``" and
  912. "``-foo=a,b,c``". This option only makes sense to be used in a case where the
  913. option is allowed to accept one or more values (i.e. it is a `cl::list`_
  914. option).
  915. .. _cl::PositionalEatsArgs:
  916. * The **cl::PositionalEatsArgs** modifier (which only applies to positional
  917. arguments, and only makes sense for lists) indicates that positional argument
  918. should consume any strings after it (including strings that start with a "-")
  919. up until another recognized positional argument. For example, if you have two
  920. "eating" positional arguments, "``pos1``" and "``pos2``", the string "``-pos1
  921. -foo -bar baz -pos2 -bork``" would cause the "``-foo -bar -baz``" strings to
  922. be applied to the "``-pos1``" option and the "``-bork``" string to be applied
  923. to the "``-pos2``" option.
  924. .. _cl::Sink:
  925. * The **cl::Sink** modifier is used to handle unknown options. If there is at
  926. least one option with ``cl::Sink`` modifier specified, the parser passes
  927. unrecognized option strings to it as values instead of signaling an error. As
  928. with ``cl::CommaSeparated``, this modifier only makes sense with a `cl::list`_
  929. option.
  930. So far, these are the only three miscellaneous option modifiers.
  931. .. _response files:
  932. Response files
  933. ^^^^^^^^^^^^^^
  934. Some systems, such as certain variants of Microsoft Windows and some older
  935. Unices have a relatively low limit on command-line length. It is therefore
  936. customary to use the so-called 'response files' to circumvent this
  937. restriction. These files are mentioned on the command-line (using the "@file")
  938. syntax. The program reads these files and inserts the contents into argv,
  939. thereby working around the command-line length limits. Response files are
  940. enabled by an optional fourth argument to `cl::ParseEnvironmentOptions`_ and
  941. `cl::ParseCommandLineOptions`_.
  942. Top-Level Classes and Functions
  943. -------------------------------
  944. Despite all of the built-in flexibility, the CommandLine option library really
  945. only consists of one function `cl::ParseCommandLineOptions`_) and three main
  946. classes: `cl::opt`_, `cl::list`_, and `cl::alias`_. This section describes
  947. these three classes in detail.
  948. .. _cl::getRegisteredOptions:
  949. The ``cl::getRegisteredOptions`` function
  950. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  951. The ``cl::getRegisteredOptions`` function is designed to give a programmer
  952. access to declared non-positional command line options so that how they appear
  953. in ``-help`` can be modified prior to calling `cl::ParseCommandLineOptions`_.
  954. Note this method should not be called during any static initialisation because
  955. it cannot be guaranteed that all options will have been initialised. Hence it
  956. should be called from ``main``.
  957. This function can be used to gain access to options declared in libraries that
  958. the tool writter may not have direct access to.
  959. The function retrieves a :ref:`StringMap <dss_stringmap>` that maps the option
  960. string (e.g. ``-help``) to an ``Option*``.
  961. Here is an example of how the function could be used:
  962. .. code-block:: c++
  963. using namespace llvm;
  964. int main(int argc, char **argv) {
  965. cl::OptionCategory AnotherCategory("Some options");
  966. StringMap<cl::Option*> Map;
  967. cl::getRegisteredOptions(Map);
  968. //Unhide useful option and put it in a different category
  969. assert(Map.count("print-all-options") > 0);
  970. Map["print-all-options"]->setHiddenFlag(cl::NotHidden);
  971. Map["print-all-options"]->setCategory(AnotherCategory);
  972. //Hide an option we don't want to see
  973. assert(Map.count("enable-no-infs-fp-math") > 0);
  974. Map["enable-no-infs-fp-math"]->setHiddenFlag(cl::Hidden);
  975. //Change --version to --show-version
  976. assert(Map.count("version") > 0);
  977. Map["version"]->setArgStr("show-version");
  978. //Change --help description
  979. assert(Map.count("help") > 0);
  980. Map["help"]->setDescription("Shows help");
  981. cl::ParseCommandLineOptions(argc, argv, "This is a small program to demo the LLVM CommandLine API");
  982. ...
  983. }
  984. .. _cl::ParseCommandLineOptions:
  985. The ``cl::ParseCommandLineOptions`` function
  986. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  987. The ``cl::ParseCommandLineOptions`` function is designed to be called directly
  988. from ``main``, and is used to fill in the values of all of the command line
  989. option variables once ``argc`` and ``argv`` are available.
  990. The ``cl::ParseCommandLineOptions`` function requires two parameters (``argc``
  991. and ``argv``), but may also take an optional third parameter which holds
  992. `additional extra text`_ to emit when the ``-help`` option is invoked, and a
  993. fourth boolean parameter that enables `response files`_.
  994. .. _cl::ParseEnvironmentOptions:
  995. The ``cl::ParseEnvironmentOptions`` function
  996. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  997. The ``cl::ParseEnvironmentOptions`` function has mostly the same effects as
  998. `cl::ParseCommandLineOptions`_, except that it is designed to take values for
  999. options from an environment variable, for those cases in which reading the
  1000. command line is not convenient or desired. It fills in the values of all the
  1001. command line option variables just like `cl::ParseCommandLineOptions`_ does.
  1002. It takes four parameters: the name of the program (since ``argv`` may not be
  1003. available, it can't just look in ``argv[0]``), the name of the environment
  1004. variable to examine, the optional `additional extra text`_ to emit when the
  1005. ``-help`` option is invoked, and the boolean switch that controls whether
  1006. `response files`_ should be read.
  1007. ``cl::ParseEnvironmentOptions`` will break the environment variable's value up
  1008. into words and then process them using `cl::ParseCommandLineOptions`_.
  1009. **Note:** Currently ``cl::ParseEnvironmentOptions`` does not support quoting, so
  1010. an environment variable containing ``-option "foo bar"`` will be parsed as three
  1011. words, ``-option``, ``"foo``, and ``bar"``, which is different from what you
  1012. would get from the shell with the same input.
  1013. The ``cl::SetVersionPrinter`` function
  1014. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1015. The ``cl::SetVersionPrinter`` function is designed to be called directly from
  1016. ``main`` and *before* ``cl::ParseCommandLineOptions``. Its use is optional. It
  1017. simply arranges for a function to be called in response to the ``--version``
  1018. option instead of having the ``CommandLine`` library print out the usual version
  1019. string for LLVM. This is useful for programs that are not part of LLVM but wish
  1020. to use the ``CommandLine`` facilities. Such programs should just define a small
  1021. function that takes no arguments and returns ``void`` and that prints out
  1022. whatever version information is appropriate for the program. Pass the address of
  1023. that function to ``cl::SetVersionPrinter`` to arrange for it to be called when
  1024. the ``--version`` option is given by the user.
  1025. .. _cl::opt:
  1026. .. _scalar:
  1027. The ``cl::opt`` class
  1028. ^^^^^^^^^^^^^^^^^^^^^
  1029. The ``cl::opt`` class is the class used to represent scalar command line
  1030. options, and is the one used most of the time. It is a templated class which
  1031. can take up to three arguments (all except for the first have default values
  1032. though):
  1033. .. code-block:: c++
  1034. namespace cl {
  1035. template <class DataType, bool ExternalStorage = false,
  1036. class ParserClass = parser<DataType> >
  1037. class opt;
  1038. }
  1039. The first template argument specifies what underlying data type the command line
  1040. argument is, and is used to select a default parser implementation. The second
  1041. template argument is used to specify whether the option should contain the
  1042. storage for the option (the default) or whether external storage should be used
  1043. to contain the value parsed for the option (see `Internal vs External Storage`_
  1044. for more information).
  1045. The third template argument specifies which parser to use. The default value
  1046. selects an instantiation of the ``parser`` class based on the underlying data
  1047. type of the option. In general, this default works well for most applications,
  1048. so this option is only used when using a `custom parser`_.
  1049. .. _lists of arguments:
  1050. .. _cl::list:
  1051. The ``cl::list`` class
  1052. ^^^^^^^^^^^^^^^^^^^^^^
  1053. The ``cl::list`` class is the class used to represent a list of command line
  1054. options. It too is a templated class which can take up to three arguments:
  1055. .. code-block:: c++
  1056. namespace cl {
  1057. template <class DataType, class Storage = bool,
  1058. class ParserClass = parser<DataType> >
  1059. class list;
  1060. }
  1061. This class works the exact same as the `cl::opt`_ class, except that the second
  1062. argument is the **type** of the external storage, not a boolean value. For this
  1063. class, the marker type '``bool``' is used to indicate that internal storage
  1064. should be used.
  1065. .. _cl::bits:
  1066. The ``cl::bits`` class
  1067. ^^^^^^^^^^^^^^^^^^^^^^
  1068. The ``cl::bits`` class is the class used to represent a list of command line
  1069. options in the form of a bit vector. It is also a templated class which can
  1070. take up to three arguments:
  1071. .. code-block:: c++
  1072. namespace cl {
  1073. template <class DataType, class Storage = bool,
  1074. class ParserClass = parser<DataType> >
  1075. class bits;
  1076. }
  1077. This class works the exact same as the `cl::list`_ class, except that the second
  1078. argument must be of **type** ``unsigned`` if external storage is used.
  1079. .. _cl::alias:
  1080. The ``cl::alias`` class
  1081. ^^^^^^^^^^^^^^^^^^^^^^^
  1082. The ``cl::alias`` class is a nontemplated class that is used to form aliases for
  1083. other arguments.
  1084. .. code-block:: c++
  1085. namespace cl {
  1086. class alias;
  1087. }
  1088. The `cl::aliasopt`_ attribute should be used to specify which option this is an
  1089. alias for. Alias arguments default to being `cl::Hidden`_, and use the aliased
  1090. options parser to do the conversion from string to data.
  1091. .. _cl::extrahelp:
  1092. The ``cl::extrahelp`` class
  1093. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1094. The ``cl::extrahelp`` class is a nontemplated class that allows extra help text
  1095. to be printed out for the ``-help`` option.
  1096. .. code-block:: c++
  1097. namespace cl {
  1098. struct extrahelp;
  1099. }
  1100. To use the extrahelp, simply construct one with a ``const char*`` parameter to
  1101. the constructor. The text passed to the constructor will be printed at the
  1102. bottom of the help message, verbatim. Note that multiple ``cl::extrahelp``
  1103. **can** be used, but this practice is discouraged. If your tool needs to print
  1104. additional help information, put all that help into a single ``cl::extrahelp``
  1105. instance.
  1106. For example:
  1107. .. code-block:: c++
  1108. cl::extrahelp("\nADDITIONAL HELP:\n\n This is the extra help\n");
  1109. .. _cl::OptionCategory:
  1110. The ``cl::OptionCategory`` class
  1111. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1112. The ``cl::OptionCategory`` class is a simple class for declaring
  1113. option categories.
  1114. .. code-block:: c++
  1115. namespace cl {
  1116. class OptionCategory;
  1117. }
  1118. An option category must have a name and optionally a description which are
  1119. passed to the constructor as ``const char*``.
  1120. Note that declaring an option category and associating it with an option before
  1121. parsing options (e.g. statically) will change the output of ``-help`` from
  1122. uncategorized to categorized. If an option category is declared but not
  1123. associated with an option then it will be hidden from the output of ``-help``
  1124. but will be shown in the output of ``-help-hidden``.
  1125. .. _different parser:
  1126. .. _discussed previously:
  1127. Builtin parsers
  1128. ---------------
  1129. Parsers control how the string value taken from the command line is translated
  1130. into a typed value, suitable for use in a C++ program. By default, the
  1131. CommandLine library uses an instance of ``parser<type>`` if the command line
  1132. option specifies that it uses values of type '``type``'. Because of this,
  1133. custom option processing is specified with specializations of the '``parser``'
  1134. class.
  1135. The CommandLine library provides the following builtin parser specializations,
  1136. which are sufficient for most applications. It can, however, also be extended to
  1137. work with new data types and new ways of interpreting the same data. See the
  1138. `Writing a Custom Parser`_ for more details on this type of library extension.
  1139. .. _enums:
  1140. .. _cl::parser:
  1141. * The generic ``parser<t>`` parser can be used to map strings values to any data
  1142. type, through the use of the `cl::values`_ property, which specifies the
  1143. mapping information. The most common use of this parser is for parsing enum
  1144. values, which allows you to use the CommandLine library for all of the error
  1145. checking to make sure that only valid enum values are specified (as opposed to
  1146. accepting arbitrary strings). Despite this, however, the generic parser class
  1147. can be used for any data type.
  1148. .. _boolean flags:
  1149. .. _bool parser:
  1150. * The **parser<bool> specialization** is used to convert boolean strings to a
  1151. boolean value. Currently accepted strings are "``true``", "``TRUE``",
  1152. "``True``", "``1``", "``false``", "``FALSE``", "``False``", and "``0``".
  1153. * The **parser<boolOrDefault> specialization** is used for cases where the value
  1154. is boolean, but we also need to know whether the option was specified at all.
  1155. boolOrDefault is an enum with 3 values, BOU_UNSET, BOU_TRUE and BOU_FALSE.
  1156. This parser accepts the same strings as **``parser<bool>``**.
  1157. .. _strings:
  1158. * The **parser<string> specialization** simply stores the parsed string into the
  1159. string value specified. No conversion or modification of the data is
  1160. performed.
  1161. .. _integers:
  1162. .. _int:
  1163. * The **parser<int> specialization** uses the C ``strtol`` function to parse the
  1164. string input. As such, it will accept a decimal number (with an optional '+'
  1165. or '-' prefix) which must start with a non-zero digit. It accepts octal
  1166. numbers, which are identified with a '``0``' prefix digit, and hexadecimal
  1167. numbers with a prefix of '``0x``' or '``0X``'.
  1168. .. _doubles:
  1169. .. _float:
  1170. .. _double:
  1171. * The **parser<double>** and **parser<float> specializations** use the standard
  1172. C ``strtod`` function to convert floating point strings into floating point
  1173. values. As such, a broad range of string formats is supported, including
  1174. exponential notation (ex: ``1.7e15``) and properly supports locales.
  1175. .. _Extension Guide:
  1176. .. _extending the library:
  1177. Extension Guide
  1178. ===============
  1179. Although the CommandLine library has a lot of functionality built into it
  1180. already (as discussed previously), one of its true strengths lie in its
  1181. extensibility. This section discusses how the CommandLine library works under
  1182. the covers and illustrates how to do some simple, common, extensions.
  1183. .. _Custom parsers:
  1184. .. _custom parser:
  1185. .. _Writing a Custom Parser:
  1186. Writing a custom parser
  1187. -----------------------
  1188. One of the simplest and most common extensions is the use of a custom parser.
  1189. As `discussed previously`_, parsers are the portion of the CommandLine library
  1190. that turns string input from the user into a particular parsed data type,
  1191. validating the input in the process.
  1192. There are two ways to use a new parser:
  1193. #. Specialize the `cl::parser`_ template for your custom data type.
  1194. This approach has the advantage that users of your custom data type will
  1195. automatically use your custom parser whenever they define an option with a
  1196. value type of your data type. The disadvantage of this approach is that it
  1197. doesn't work if your fundamental data type is something that is already
  1198. supported.
  1199. #. Write an independent class, using it explicitly from options that need it.
  1200. This approach works well in situations where you would line to parse an
  1201. option using special syntax for a not-very-special data-type. The drawback
  1202. of this approach is that users of your parser have to be aware that they are
  1203. using your parser instead of the builtin ones.
  1204. To guide the discussion, we will discuss a custom parser that accepts file
  1205. sizes, specified with an optional unit after the numeric size. For example, we
  1206. would like to parse "102kb", "41M", "1G" into the appropriate integer value. In
  1207. this case, the underlying data type we want to parse into is '``unsigned``'. We
  1208. choose approach #2 above because we don't want to make this the default for all
  1209. ``unsigned`` options.
  1210. To start out, we declare our new ``FileSizeParser`` class:
  1211. .. code-block:: c++
  1212. struct FileSizeParser : public cl::parser<unsigned> {
  1213. // parse - Return true on error.
  1214. bool parse(cl::Option &O, StringRef ArgName, const std::string &ArgValue,
  1215. unsigned &Val);
  1216. };
  1217. Our new class inherits from the ``cl::parser`` template class to fill in
  1218. the default, boiler plate code for us. We give it the data type that we parse
  1219. into, the last argument to the ``parse`` method, so that clients of our custom
  1220. parser know what object type to pass in to the parse method. (Here we declare
  1221. that we parse into '``unsigned``' variables.)
  1222. For most purposes, the only method that must be implemented in a custom parser
  1223. is the ``parse`` method. The ``parse`` method is called whenever the option is
  1224. invoked, passing in the option itself, the option name, the string to parse, and
  1225. a reference to a return value. If the string to parse is not well-formed, the
  1226. parser should output an error message and return true. Otherwise it should
  1227. return false and set '``Val``' to the parsed value. In our example, we
  1228. implement ``parse`` as:
  1229. .. code-block:: c++
  1230. bool FileSizeParser::parse(cl::Option &O, StringRef ArgName,
  1231. const std::string &Arg, unsigned &Val) {
  1232. const char *ArgStart = Arg.c_str();
  1233. char *End;
  1234. // Parse integer part, leaving 'End' pointing to the first non-integer char
  1235. Val = (unsigned)strtol(ArgStart, &End, 0);
  1236. while (1) {
  1237. switch (*End++) {
  1238. case 0: return false; // No error
  1239. case 'i': // Ignore the 'i' in KiB if people use that
  1240. case 'b': case 'B': // Ignore B suffix
  1241. break;
  1242. case 'g': case 'G': Val *= 1024*1024*1024; break;
  1243. case 'm': case 'M': Val *= 1024*1024; break;
  1244. case 'k': case 'K': Val *= 1024; break;
  1245. default:
  1246. // Print an error message if unrecognized character!
  1247. return O.error("'" + Arg + "' value invalid for file size argument!");
  1248. }
  1249. }
  1250. }
  1251. This function implements a very simple parser for the kinds of strings we are
  1252. interested in. Although it has some holes (it allows "``123KKK``" for example),
  1253. it is good enough for this example. Note that we use the option itself to print
  1254. out the error message (the ``error`` method always returns true) in order to get
  1255. a nice error message (shown below). Now that we have our parser class, we can
  1256. use it like this:
  1257. .. code-block:: c++
  1258. static cl::opt<unsigned, false, FileSizeParser>
  1259. MFS("max-file-size", cl::desc("Maximum file size to accept"),
  1260. cl::value_desc("size"));
  1261. Which adds this to the output of our program:
  1262. ::
  1263. OPTIONS:
  1264. -help - display available options (-help-hidden for more)
  1265. ...
  1266. -max-file-size=<size> - Maximum file size to accept
  1267. And we can test that our parse works correctly now (the test program just prints
  1268. out the max-file-size argument value):
  1269. ::
  1270. $ ./test
  1271. MFS: 0
  1272. $ ./test -max-file-size=123MB
  1273. MFS: 128974848
  1274. $ ./test -max-file-size=3G
  1275. MFS: 3221225472
  1276. $ ./test -max-file-size=dog
  1277. -max-file-size option: 'dog' value invalid for file size argument!
  1278. It looks like it works. The error message that we get is nice and helpful, and
  1279. we seem to accept reasonable file sizes. This wraps up the "custom parser"
  1280. tutorial.
  1281. Exploiting external storage
  1282. ---------------------------
  1283. Several of the LLVM libraries define static ``cl::opt`` instances that will
  1284. automatically be included in any program that links with that library. This is
  1285. a feature. However, sometimes it is necessary to know the value of the command
  1286. line option outside of the library. In these cases the library does or should
  1287. provide an external storage location that is accessible to users of the
  1288. library. Examples of this include the ``llvm::DebugFlag`` exported by the
  1289. ``lib/Support/Debug.cpp`` file and the ``llvm::TimePassesIsEnabled`` flag
  1290. exported by the ``lib/VMCore/PassManager.cpp`` file.
  1291. .. todo::
  1292. TODO: complete this section
  1293. .. _dynamically loaded options:
  1294. Dynamically adding command line options
  1295. .. todo::
  1296. TODO: fill in this section