CommandLine.rst 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752
  1. ==============================
  2. CommandLine 2.0 Library Manual
  3. ==============================
  4. .. contents::
  5. :local:
  6. Introduction
  7. ============
  8. This document describes the CommandLine argument processing library. It will
  9. show you how to use it, and what it can do. The CommandLine library uses a
  10. declarative approach to specifying the command line options that your program
  11. takes. By default, these options declarations implicitly hold the value parsed
  12. for the option declared (of course this `can be changed`_).
  13. Although there are a **lot** of command line argument parsing libraries out
  14. there in many different languages, none of them fit well with what I needed. By
  15. looking at the features and problems of other libraries, I designed the
  16. CommandLine library to have the following features:
  17. #. Speed: The CommandLine library is very quick and uses little resources. The
  18. parsing time of the library is directly proportional to the number of
  19. arguments parsed, not the number of options recognized. Additionally,
  20. command line argument values are captured transparently into user defined
  21. global variables, which can be accessed like any other variable (and with the
  22. same performance).
  23. #. Type Safe: As a user of CommandLine, you don't have to worry about
  24. remembering the type of arguments that you want (is it an int? a string? a
  25. bool? an enum?) and keep casting it around. Not only does this help prevent
  26. error prone constructs, it also leads to dramatically cleaner source code.
  27. #. No subclasses required: To use CommandLine, you instantiate variables that
  28. correspond to the arguments that you would like to capture, you don't
  29. subclass a parser. This means that you don't have to write **any**
  30. boilerplate code.
  31. #. Globally accessible: Libraries can specify command line arguments that are
  32. automatically enabled in any tool that links to the library. This is
  33. possible because the application doesn't have to keep a list of arguments to
  34. pass to the parser. This also makes supporting `dynamically loaded options`_
  35. trivial.
  36. #. Cleaner: CommandLine supports enum and other types directly, meaning that
  37. there is less error and more security built into the library. You don't have
  38. to worry about whether your integral command line argument accidentally got
  39. assigned a value that is not valid for your enum type.
  40. #. Powerful: The CommandLine library supports many different types of arguments,
  41. from simple `boolean flags`_ to `scalars arguments`_ (`strings`_,
  42. `integers`_, `enums`_, `doubles`_), to `lists of arguments`_. This is
  43. possible because CommandLine is...
  44. #. Extensible: It is very simple to add a new argument type to CommandLine.
  45. Simply specify the parser that you want to use with the command line option
  46. when you declare it. `Custom parsers`_ are no problem.
  47. #. Labor Saving: The CommandLine library cuts down on the amount of grunt work
  48. that you, the user, have to do. For example, it automatically provides a
  49. ``-help`` option that shows the available command line options for your tool.
  50. Additionally, it does most of the basic correctness checking for you.
  51. #. Capable: The CommandLine library can handle lots of different forms of
  52. options often found in real programs. For example, `positional`_ arguments,
  53. ``ls`` style `grouping`_ options (to allow processing '``ls -lad``'
  54. naturally), ``ld`` style `prefix`_ options (to parse '``-lmalloc
  55. -L/usr/lib``'), and interpreter style options.
  56. This document will hopefully let you jump in and start using CommandLine in your
  57. utility quickly and painlessly. Additionally it should be a simple reference
  58. manual to figure out how stuff works.
  59. Quick Start Guide
  60. =================
  61. This section of the manual runs through a simple CommandLine'ification of a
  62. basic compiler tool. This is intended to show you how to jump into using the
  63. CommandLine library in your own program, and show you some of the cool things it
  64. can do.
  65. To start out, you need to include the CommandLine header file into your program:
  66. .. code-block:: c++
  67. #include "llvm/Support/CommandLine.h"
  68. Additionally, you need to add this as the first line of your main program:
  69. .. code-block:: c++
  70. int main(int argc, char **argv) {
  71. cl::ParseCommandLineOptions(argc, argv);
  72. ...
  73. }
  74. ... which actually parses the arguments and fills in the variable declarations.
  75. Now that you are ready to support command line arguments, we need to tell the
  76. system which ones we want, and what type of arguments they are. The CommandLine
  77. library uses a declarative syntax to model command line arguments with the
  78. global variable declarations that capture the parsed values. This means that
  79. for every command line option that you would like to support, there should be a
  80. global variable declaration to capture the result. For example, in a compiler,
  81. we would like to support the Unix-standard '``-o <filename>``' option to specify
  82. where to put the output. With the CommandLine library, this is represented like
  83. this:
  84. .. _scalars arguments:
  85. .. _here:
  86. .. code-block:: c++
  87. cl::opt<string> OutputFilename("o", cl::desc("Specify output filename"), cl::value_desc("filename"));
  88. This declares a global variable "``OutputFilename``" that is used to capture the
  89. result of the "``o``" argument (first parameter). We specify that this is a
  90. simple scalar option by using the "``cl::opt``" template (as opposed to the
  91. "``cl::list``" template), and tell the CommandLine library that the data
  92. type that we are parsing is a string.
  93. The second and third parameters (which are optional) are used to specify what to
  94. output for the "``-help``" option. In this case, we get a line that looks like
  95. this:
  96. ::
  97. USAGE: compiler [options]
  98. OPTIONS:
  99. -h - Alias for -help
  100. -help - display available options (-help-hidden for more)
  101. -o <filename> - Specify output filename
  102. Because we specified that the command line option should parse using the
  103. ``string`` data type, the variable declared is automatically usable as a real
  104. string in all contexts that a normal C++ string object may be used. For
  105. example:
  106. .. code-block:: c++
  107. ...
  108. std::ofstream Output(OutputFilename.c_str());
  109. if (Output.good()) ...
  110. ...
  111. There are many different options that you can use to customize the command line
  112. option handling library, but the above example shows the general interface to
  113. these options. The options can be specified in any order, and are specified
  114. with helper functions like `cl::desc(...)`_, so there are no positional
  115. dependencies to remember. The available options are discussed in detail in the
  116. `Reference Guide`_.
  117. Continuing the example, we would like to have our compiler take an input
  118. filename as well as an output filename, but we do not want the input filename to
  119. be specified with a hyphen (ie, not ``-filename.c``). To support this style of
  120. argument, the CommandLine library allows for `positional`_ arguments to be
  121. specified for the program. These positional arguments are filled with command
  122. line parameters that are not in option form. We use this feature like this:
  123. .. code-block:: c++
  124. cl::opt<string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
  125. This declaration indicates that the first positional argument should be treated
  126. as the input filename. Here we use the `cl::init`_ option to specify an initial
  127. value for the command line option, which is used if the option is not specified
  128. (if you do not specify a `cl::init`_ modifier for an option, then the default
  129. constructor for the data type is used to initialize the value). Command line
  130. options default to being optional, so if we would like to require that the user
  131. always specify an input filename, we would add the `cl::Required`_ flag, and we
  132. could eliminate the `cl::init`_ modifier, like this:
  133. .. code-block:: c++
  134. cl::opt<string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::Required);
  135. Again, the CommandLine library does not require the options to be specified in
  136. any particular order, so the above declaration is equivalent to:
  137. .. code-block:: c++
  138. cl::opt<string> InputFilename(cl::Positional, cl::Required, cl::desc("<input file>"));
  139. By simply adding the `cl::Required`_ flag, the CommandLine library will
  140. automatically issue an error if the argument is not specified, which shifts all
  141. of the command line option verification code out of your application into the
  142. library. This is just one example of how using flags can alter the default
  143. behaviour of the library, on a per-option basis. By adding one of the
  144. declarations above, the ``-help`` option synopsis is now extended to:
  145. ::
  146. USAGE: compiler [options] <input file>
  147. OPTIONS:
  148. -h - Alias for -help
  149. -help - display available options (-help-hidden for more)
  150. -o <filename> - Specify output filename
  151. ... indicating that an input filename is expected.
  152. Boolean Arguments
  153. -----------------
  154. In addition to input and output filenames, we would like the compiler example to
  155. support three boolean flags: "``-f``" to force writing binary output to a
  156. terminal, "``--quiet``" to enable quiet mode, and "``-q``" for backwards
  157. compatibility with some of our users. We can support these by declaring options
  158. of boolean type like this:
  159. .. code-block:: c++
  160. cl::opt<bool> Force ("f", cl::desc("Enable binary output on terminals"));
  161. cl::opt<bool> Quiet ("quiet", cl::desc("Don't print informational messages"));
  162. cl::opt<bool> Quiet2("q", cl::desc("Don't print informational messages"), cl::Hidden);
  163. This does what you would expect: it declares three boolean variables
  164. ("``Force``", "``Quiet``", and "``Quiet2``") to recognize these options. Note
  165. that the "``-q``" option is specified with the "`cl::Hidden`_" flag. This
  166. modifier prevents it from being shown by the standard "``-help``" output (note
  167. that it is still shown in the "``-help-hidden``" output).
  168. The CommandLine library uses a `different parser`_ for different data types.
  169. For example, in the string case, the argument passed to the option is copied
  170. literally into the content of the string variable... we obviously cannot do that
  171. in the boolean case, however, so we must use a smarter parser. In the case of
  172. the boolean parser, it allows no options (in which case it assigns the value of
  173. true to the variable), or it allows the values "``true``" or "``false``" to be
  174. specified, allowing any of the following inputs:
  175. ::
  176. compiler -f # No value, 'Force' == true
  177. compiler -f=true # Value specified, 'Force' == true
  178. compiler -f=TRUE # Value specified, 'Force' == true
  179. compiler -f=FALSE # Value specified, 'Force' == false
  180. ... you get the idea. The `bool parser`_ just turns the string values into
  181. boolean values, and rejects things like '``compiler -f=foo``'. Similarly, the
  182. `float`_, `double`_, and `int`_ parsers work like you would expect, using the
  183. '``strtol``' and '``strtod``' C library calls to parse the string value into the
  184. specified data type.
  185. With the declarations above, "``compiler -help``" emits this:
  186. ::
  187. USAGE: compiler [options] <input file>
  188. OPTIONS:
  189. -f - Enable binary output on terminals
  190. -o - Override output filename
  191. -quiet - Don't print informational messages
  192. -help - display available options (-help-hidden for more)
  193. and "``compiler -help-hidden``" prints this:
  194. ::
  195. USAGE: compiler [options] <input file>
  196. OPTIONS:
  197. -f - Enable binary output on terminals
  198. -o - Override output filename
  199. -q - Don't print informational messages
  200. -quiet - Don't print informational messages
  201. -help - display available options (-help-hidden for more)
  202. This brief example has shown you how to use the '`cl::opt`_' class to parse
  203. simple scalar command line arguments. In addition to simple scalar arguments,
  204. the CommandLine library also provides primitives to support CommandLine option
  205. `aliases`_, and `lists`_ of options.
  206. .. _aliases:
  207. Argument Aliases
  208. ----------------
  209. So far, the example works well, except for the fact that we need to check the
  210. quiet condition like this now:
  211. .. code-block:: c++
  212. ...
  213. if (!Quiet && !Quiet2) printInformationalMessage(...);
  214. ...
  215. ... which is a real pain! Instead of defining two values for the same
  216. condition, we can use the "`cl::alias`_" class to make the "``-q``" option an
  217. **alias** for the "``-quiet``" option, instead of providing a value itself:
  218. .. code-block:: c++
  219. cl::opt<bool> Force ("f", cl::desc("Overwrite output files"));
  220. cl::opt<bool> Quiet ("quiet", cl::desc("Don't print informational messages"));
  221. cl::alias QuietA("q", cl::desc("Alias for -quiet"), cl::aliasopt(Quiet));
  222. The third line (which is the only one we modified from above) defines a "``-q``"
  223. alias that updates the "``Quiet``" variable (as specified by the `cl::aliasopt`_
  224. modifier) whenever it is specified. Because aliases do not hold state, the only
  225. thing the program has to query is the ``Quiet`` variable now. Another nice
  226. feature of aliases is that they automatically hide themselves from the ``-help``
  227. output (although, again, they are still visible in the ``-help-hidden output``).
  228. Now the application code can simply use:
  229. .. code-block:: c++
  230. ...
  231. if (!Quiet) printInformationalMessage(...);
  232. ...
  233. ... which is much nicer! The "`cl::alias`_" can be used to specify an
  234. alternative name for any variable type, and has many uses.
  235. .. _unnamed alternatives using the generic parser:
  236. Selecting an alternative from a set of possibilities
  237. ----------------------------------------------------
  238. So far we have seen how the CommandLine library handles builtin types like
  239. ``std::string``, ``bool`` and ``int``, but how does it handle things it doesn't
  240. know about, like enums or '``int*``'s?
  241. The answer is that it uses a table-driven generic parser (unless you specify
  242. your own parser, as described in the `Extension Guide`_). This parser maps
  243. literal strings to whatever type is required, and requires you to tell it what
  244. this mapping should be.
  245. Let's say that we would like to add four optimization levels to our optimizer,
  246. using the standard flags "``-g``", "``-O0``", "``-O1``", and "``-O2``". We
  247. could easily implement this with boolean options like above, but there are
  248. several problems with this strategy:
  249. #. A user could specify more than one of the options at a time, for example,
  250. "``compiler -O3 -O2``". The CommandLine library would not be able to catch
  251. this erroneous input for us.
  252. #. We would have to test 4 different variables to see which ones are set.
  253. #. This doesn't map to the numeric levels that we want... so we cannot easily
  254. see if some level >= "``-O1``" is enabled.
  255. To cope with these problems, we can use an enum value, and have the CommandLine
  256. library fill it in with the appropriate level directly, which is used like this:
  257. .. code-block:: c++
  258. enum OptLevel {
  259. g, O1, O2, O3
  260. };
  261. cl::opt<OptLevel> OptimizationLevel(cl::desc("Choose optimization level:"),
  262. cl::values(
  263. clEnumVal(g , "No optimizations, enable debugging"),
  264. clEnumVal(O1, "Enable trivial optimizations"),
  265. clEnumVal(O2, "Enable default optimizations"),
  266. clEnumVal(O3, "Enable expensive optimizations")));
  267. ...
  268. if (OptimizationLevel >= O2) doPartialRedundancyElimination(...);
  269. ...
  270. This declaration defines a variable "``OptimizationLevel``" of the
  271. "``OptLevel``" enum type. This variable can be assigned any of the values that
  272. are listed in the declaration. The CommandLine library enforces that
  273. the user can only specify one of the options, and it ensure that only valid enum
  274. values can be specified. The "``clEnumVal``" macros ensure that the command
  275. line arguments matched the enum values. With this option added, our help output
  276. now is:
  277. ::
  278. USAGE: compiler [options] <input file>
  279. OPTIONS:
  280. Choose optimization level:
  281. -g - No optimizations, enable debugging
  282. -O1 - Enable trivial optimizations
  283. -O2 - Enable default optimizations
  284. -O3 - Enable expensive optimizations
  285. -f - Enable binary output on terminals
  286. -help - display available options (-help-hidden for more)
  287. -o <filename> - Specify output filename
  288. -quiet - Don't print informational messages
  289. In this case, it is sort of awkward that flag names correspond directly to enum
  290. names, because we probably don't want a enum definition named "``g``" in our
  291. program. Because of this, we can alternatively write this example like this:
  292. .. code-block:: c++
  293. enum OptLevel {
  294. Debug, O1, O2, O3
  295. };
  296. cl::opt<OptLevel> OptimizationLevel(cl::desc("Choose optimization level:"),
  297. cl::values(
  298. clEnumValN(Debug, "g", "No optimizations, enable debugging"),
  299. clEnumVal(O1 , "Enable trivial optimizations"),
  300. clEnumVal(O2 , "Enable default optimizations"),
  301. clEnumVal(O3 , "Enable expensive optimizations")));
  302. ...
  303. if (OptimizationLevel == Debug) outputDebugInfo(...);
  304. ...
  305. By using the "``clEnumValN``" macro instead of "``clEnumVal``", we can directly
  306. specify the name that the flag should get. In general a direct mapping is nice,
  307. but sometimes you can't or don't want to preserve the mapping, which is when you
  308. would use it.
  309. Named Alternatives
  310. ------------------
  311. Another useful argument form is a named alternative style. We shall use this
  312. style in our compiler to specify different debug levels that can be used.
  313. Instead of each debug level being its own switch, we want to support the
  314. following options, of which only one can be specified at a time:
  315. "``--debug-level=none``", "``--debug-level=quick``",
  316. "``--debug-level=detailed``". To do this, we use the exact same format as our
  317. optimization level flags, but we also specify an option name. For this case,
  318. the code looks like this:
  319. .. code-block:: c++
  320. enum DebugLev {
  321. nodebuginfo, quick, detailed
  322. };
  323. // Enable Debug Options to be specified on the command line
  324. cl::opt<DebugLev> DebugLevel("debug_level", cl::desc("Set the debugging level:"),
  325. cl::values(
  326. clEnumValN(nodebuginfo, "none", "disable debug information"),
  327. clEnumVal(quick, "enable quick debug information"),
  328. clEnumVal(detailed, "enable detailed debug information")));
  329. This definition defines an enumerated command line variable of type "``enum
  330. DebugLev``", which works exactly the same way as before. The difference here is
  331. just the interface exposed to the user of your program and the help output by
  332. the "``-help``" option:
  333. ::
  334. USAGE: compiler [options] <input file>
  335. OPTIONS:
  336. Choose optimization level:
  337. -g - No optimizations, enable debugging
  338. -O1 - Enable trivial optimizations
  339. -O2 - Enable default optimizations
  340. -O3 - Enable expensive optimizations
  341. -debug_level - Set the debugging level:
  342. =none - disable debug information
  343. =quick - enable quick debug information
  344. =detailed - enable detailed debug information
  345. -f - Enable binary output on terminals
  346. -help - display available options (-help-hidden for more)
  347. -o <filename> - Specify output filename
  348. -quiet - Don't print informational messages
  349. Again, the only structural difference between the debug level declaration and
  350. the optimization level declaration is that the debug level declaration includes
  351. an option name (``"debug_level"``), which automatically changes how the library
  352. processes the argument. The CommandLine library supports both forms so that you
  353. can choose the form most appropriate for your application.
  354. .. _lists:
  355. Parsing a list of options
  356. -------------------------
  357. Now that we have the standard run-of-the-mill argument types out of the way,
  358. lets get a little wild and crazy. Lets say that we want our optimizer to accept
  359. a **list** of optimizations to perform, allowing duplicates. For example, we
  360. might want to run: "``compiler -dce -constprop -inline -dce -strip``". In this
  361. case, the order of the arguments and the number of appearances is very
  362. important. This is what the "``cl::list``" template is for. First, start by
  363. defining an enum of the optimizations that you would like to perform:
  364. .. code-block:: c++
  365. enum Opts {
  366. // 'inline' is a C++ keyword, so name it 'inlining'
  367. dce, constprop, inlining, strip
  368. };
  369. Then define your "``cl::list``" variable:
  370. .. code-block:: c++
  371. cl::list<Opts> OptimizationList(cl::desc("Available Optimizations:"),
  372. cl::values(
  373. clEnumVal(dce , "Dead Code Elimination"),
  374. clEnumVal(constprop , "Constant Propagation"),
  375. clEnumValN(inlining, "inline", "Procedure Integration"),
  376. clEnumVal(strip , "Strip Symbols")));
  377. This defines a variable that is conceptually of the type
  378. "``std::vector<enum Opts>``". Thus, you can access it with standard vector
  379. methods:
  380. .. code-block:: c++
  381. for (unsigned i = 0; i != OptimizationList.size(); ++i)
  382. switch (OptimizationList[i])
  383. ...
  384. ... to iterate through the list of options specified.
  385. Note that the "``cl::list``" template is completely general and may be used with
  386. any data types or other arguments that you can use with the "``cl::opt``"
  387. template. One especially useful way to use a list is to capture all of the
  388. positional arguments together if there may be more than one specified. In the
  389. case of a linker, for example, the linker takes several '``.o``' files, and
  390. needs to capture them into a list. This is naturally specified as:
  391. .. code-block:: c++
  392. ...
  393. cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<Input files>"), cl::OneOrMore);
  394. ...
  395. This variable works just like a "``vector<string>``" object. As such, accessing
  396. the list is simple, just like above. In this example, we used the
  397. `cl::OneOrMore`_ modifier to inform the CommandLine library that it is an error
  398. if the user does not specify any ``.o`` files on our command line. Again, this
  399. just reduces the amount of checking we have to do.
  400. Collecting options as a set of flags
  401. ------------------------------------
  402. Instead of collecting sets of options in a list, it is also possible to gather
  403. information for enum values in a **bit vector**. The representation used by the
  404. `cl::bits`_ class is an ``unsigned`` integer. An enum value is represented by a
  405. 0/1 in the enum's ordinal value bit position. 1 indicating that the enum was
  406. specified, 0 otherwise. As each specified value is parsed, the resulting enum's
  407. bit is set in the option's bit vector:
  408. .. code-block:: c++
  409. bits |= 1 << (unsigned)enum;
  410. Options that are specified multiple times are redundant. Any instances after
  411. the first are discarded.
  412. Reworking the above list example, we could replace `cl::list`_ with `cl::bits`_:
  413. .. code-block:: c++
  414. cl::bits<Opts> OptimizationBits(cl::desc("Available Optimizations:"),
  415. cl::values(
  416. clEnumVal(dce , "Dead Code Elimination"),
  417. clEnumVal(constprop , "Constant Propagation"),
  418. clEnumValN(inlining, "inline", "Procedure Integration"),
  419. clEnumVal(strip , "Strip Symbols")));
  420. To test to see if ``constprop`` was specified, we can use the ``cl:bits::isSet``
  421. function:
  422. .. code-block:: c++
  423. if (OptimizationBits.isSet(constprop)) {
  424. ...
  425. }
  426. It's also possible to get the raw bit vector using the ``cl::bits::getBits``
  427. function:
  428. .. code-block:: c++
  429. unsigned bits = OptimizationBits.getBits();
  430. Finally, if external storage is used, then the location specified must be of
  431. **type** ``unsigned``. In all other ways a `cl::bits`_ option is equivalent to a
  432. `cl::list`_ option.
  433. .. _additional extra text:
  434. Adding freeform text to help output
  435. -----------------------------------
  436. As our program grows and becomes more mature, we may decide to put summary
  437. information about what it does into the help output. The help output is styled
  438. to look similar to a Unix ``man`` page, providing concise information about a
  439. program. Unix ``man`` pages, however often have a description about what the
  440. program does. To add this to your CommandLine program, simply pass a third
  441. argument to the `cl::ParseCommandLineOptions`_ call in main. This additional
  442. argument is then printed as the overview information for your program, allowing
  443. you to include any additional information that you want. For example:
  444. .. code-block:: c++
  445. int main(int argc, char **argv) {
  446. cl::ParseCommandLineOptions(argc, argv, " CommandLine compiler example\n\n"
  447. " This program blah blah blah...\n");
  448. ...
  449. }
  450. would yield the help output:
  451. ::
  452. **OVERVIEW: CommandLine compiler example
  453. This program blah blah blah...**
  454. USAGE: compiler [options] <input file>
  455. OPTIONS:
  456. ...
  457. -help - display available options (-help-hidden for more)
  458. -o <filename> - Specify output filename
  459. .. _grouping options into categories:
  460. Grouping options into categories
  461. --------------------------------
  462. If our program has a large number of options it may become difficult for users
  463. of our tool to navigate the output of ``-help``. To alleviate this problem we
  464. can put our options into categories. This can be done by declaring option
  465. categories (`cl::OptionCategory`_ objects) and then placing our options into
  466. these categories using the `cl::cat`_ option attribute. For example:
  467. .. code-block:: c++
  468. cl::OptionCategory StageSelectionCat("Stage Selection Options",
  469. "These control which stages are run.");
  470. cl::opt<bool> Preprocessor("E",cl::desc("Run preprocessor stage."),
  471. cl::cat(StageSelectionCat));
  472. cl::opt<bool> NoLink("c",cl::desc("Run all stages except linking."),
  473. cl::cat(StageSelectionCat));
  474. The output of ``-help`` will become categorized if an option category is
  475. declared. The output looks something like ::
  476. OVERVIEW: This is a small program to demo the LLVM CommandLine API
  477. USAGE: Sample [options]
  478. OPTIONS:
  479. General options:
  480. -help - Display available options (-help-hidden for more)
  481. -help-list - Display list of available options (-help-list-hidden for more)
  482. Stage Selection Options:
  483. These control which stages are run.
  484. -E - Run preprocessor stage.
  485. -c - Run all stages except linking.
  486. In addition to the behaviour of ``-help`` changing when an option category is
  487. declared, the command line option ``-help-list`` becomes visible which will
  488. print the command line options as uncategorized list.
  489. Note that Options that are not explicitly categorized will be placed in the
  490. ``cl::GeneralCategory`` category.
  491. .. _Reference Guide:
  492. Reference Guide
  493. ===============
  494. Now that you know the basics of how to use the CommandLine library, this section
  495. will give you the detailed information you need to tune how command line options
  496. work, as well as information on more "advanced" command line option processing
  497. capabilities.
  498. .. _positional:
  499. .. _positional argument:
  500. .. _Positional Arguments:
  501. .. _Positional arguments section:
  502. .. _positional options:
  503. Positional Arguments
  504. --------------------
  505. Positional arguments are those arguments that are not named, and are not
  506. specified with a hyphen. Positional arguments should be used when an option is
  507. specified by its position alone. For example, the standard Unix ``grep`` tool
  508. takes a regular expression argument, and an optional filename to search through
  509. (which defaults to standard input if a filename is not specified). Using the
  510. CommandLine library, this would be specified as:
  511. .. code-block:: c++
  512. cl::opt<string> Regex (cl::Positional, cl::desc("<regular expression>"), cl::Required);
  513. cl::opt<string> Filename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
  514. Given these two option declarations, the ``-help`` output for our grep
  515. replacement would look like this:
  516. ::
  517. USAGE: spiffygrep [options] <regular expression> <input file>
  518. OPTIONS:
  519. -help - display available options (-help-hidden for more)
  520. ... and the resultant program could be used just like the standard ``grep``
  521. tool.
  522. Positional arguments are sorted by their order of construction. This means that
  523. command line options will be ordered according to how they are listed in a .cpp
  524. file, but will not have an ordering defined if the positional arguments are
  525. defined in multiple .cpp files. The fix for this problem is simply to define
  526. all of your positional arguments in one .cpp file.
  527. Specifying positional options with hyphens
  528. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  529. Sometimes you may want to specify a value to your positional argument that
  530. starts with a hyphen (for example, searching for '``-foo``' in a file). At
  531. first, you will have trouble doing this, because it will try to find an argument
  532. named '``-foo``', and will fail (and single quotes will not save you). Note
  533. that the system ``grep`` has the same problem:
  534. ::
  535. $ spiffygrep '-foo' test.txt
  536. Unknown command line argument '-foo'. Try: spiffygrep -help'
  537. $ grep '-foo' test.txt
  538. grep: illegal option -- f
  539. grep: illegal option -- o
  540. grep: illegal option -- o
  541. Usage: grep -hblcnsviw pattern file . . .
  542. The solution for this problem is the same for both your tool and the system
  543. version: use the '``--``' marker. When the user specifies '``--``' on the
  544. command line, it is telling the program that all options after the '``--``'
  545. should be treated as positional arguments, not options. Thus, we can use it
  546. like this:
  547. ::
  548. $ spiffygrep -- -foo test.txt
  549. ...output...
  550. Determining absolute position with getPosition()
  551. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  552. Sometimes an option can affect or modify the meaning of another option. For
  553. example, consider ``gcc``'s ``-x LANG`` option. This tells ``gcc`` to ignore the
  554. suffix of subsequent positional arguments and force the file to be interpreted
  555. as if it contained source code in language ``LANG``. In order to handle this
  556. properly, you need to know the absolute position of each argument, especially
  557. those in lists, so their interaction(s) can be applied correctly. This is also
  558. useful for options like ``-llibname`` which is actually a positional argument
  559. that starts with a dash.
  560. So, generally, the problem is that you have two ``cl::list`` variables that
  561. interact in some way. To ensure the correct interaction, you can use the
  562. ``cl::list::getPosition(optnum)`` method. This method returns the absolute
  563. position (as found on the command line) of the ``optnum`` item in the
  564. ``cl::list``.
  565. The idiom for usage is like this:
  566. .. code-block:: c++
  567. static cl::list<std::string> Files(cl::Positional, cl::OneOrMore);
  568. static cl::list<std::string> Libraries("l", cl::ZeroOrMore);
  569. int main(int argc, char**argv) {
  570. // ...
  571. std::vector<std::string>::iterator fileIt = Files.begin();
  572. std::vector<std::string>::iterator libIt = Libraries.begin();
  573. unsigned libPos = 0, filePos = 0;
  574. while ( 1 ) {
  575. if ( libIt != Libraries.end() )
  576. libPos = Libraries.getPosition( libIt - Libraries.begin() );
  577. else
  578. libPos = 0;
  579. if ( fileIt != Files.end() )
  580. filePos = Files.getPosition( fileIt - Files.begin() );
  581. else
  582. filePos = 0;
  583. if ( filePos != 0 && (libPos == 0 || filePos < libPos) ) {
  584. // Source File Is next
  585. ++fileIt;
  586. }
  587. else if ( libPos != 0 && (filePos == 0 || libPos < filePos) ) {
  588. // Library is next
  589. ++libIt;
  590. }
  591. else
  592. break; // we're done with the list
  593. }
  594. }
  595. Note that, for compatibility reasons, the ``cl::opt`` also supports an
  596. ``unsigned getPosition()`` option that will provide the absolute position of
  597. that option. You can apply the same approach as above with a ``cl::opt`` and a
  598. ``cl::list`` option as you can with two lists.
  599. .. _interpreter style options:
  600. .. _cl::ConsumeAfter:
  601. .. _this section for more information:
  602. The ``cl::ConsumeAfter`` modifier
  603. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  604. The ``cl::ConsumeAfter`` `formatting option`_ is used to construct programs that
  605. use "interpreter style" option processing. With this style of option
  606. processing, all arguments specified after the last positional argument are
  607. treated as special interpreter arguments that are not interpreted by the command
  608. line argument.
  609. As a concrete example, lets say we are developing a replacement for the standard
  610. Unix Bourne shell (``/bin/sh``). To run ``/bin/sh``, first you specify options
  611. to the shell itself (like ``-x`` which turns on trace output), then you specify
  612. the name of the script to run, then you specify arguments to the script. These
  613. arguments to the script are parsed by the Bourne shell command line option
  614. processor, but are not interpreted as options to the shell itself. Using the
  615. CommandLine library, we would specify this as:
  616. .. code-block:: c++
  617. cl::opt<string> Script(cl::Positional, cl::desc("<input script>"), cl::init("-"));
  618. cl::list<string> Argv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
  619. cl::opt<bool> Trace("x", cl::desc("Enable trace output"));
  620. which automatically provides the help output:
  621. ::
  622. USAGE: spiffysh [options] <input script> <program arguments>...
  623. OPTIONS:
  624. -help - display available options (-help-hidden for more)
  625. -x - Enable trace output
  626. At runtime, if we run our new shell replacement as ```spiffysh -x test.sh -a -x
  627. -y bar``', the ``Trace`` variable will be set to true, the ``Script`` variable
  628. will be set to "``test.sh``", and the ``Argv`` list will contain ``["-a", "-x",
  629. "-y", "bar"]``, because they were specified after the last positional argument
  630. (which is the script name).
  631. There are several limitations to when ``cl::ConsumeAfter`` options can be
  632. specified. For example, only one ``cl::ConsumeAfter`` can be specified per
  633. program, there must be at least one `positional argument`_ specified, there must
  634. not be any `cl::list`_ positional arguments, and the ``cl::ConsumeAfter`` option
  635. should be a `cl::list`_ option.
  636. .. _can be changed:
  637. .. _Internal vs External Storage:
  638. Internal vs External Storage
  639. ----------------------------
  640. By default, all command line options automatically hold the value that they
  641. parse from the command line. This is very convenient in the common case,
  642. especially when combined with the ability to define command line options in the
  643. files that use them. This is called the internal storage model.
  644. Sometimes, however, it is nice to separate the command line option processing
  645. code from the storage of the value parsed. For example, lets say that we have a
  646. '``-debug``' option that we would like to use to enable debug information across
  647. the entire body of our program. In this case, the boolean value controlling the
  648. debug code should be globally accessible (in a header file, for example) yet the
  649. command line option processing code should not be exposed to all of these
  650. clients (requiring lots of .cpp files to ``#include CommandLine.h``).
  651. To do this, set up your .h file with your option, like this for example:
  652. .. code-block:: c++
  653. // DebugFlag.h - Get access to the '-debug' command line option
  654. //
  655. // DebugFlag - This boolean is set to true if the '-debug' command line option
  656. // is specified. This should probably not be referenced directly, instead, use
  657. // the DEBUG macro below.
  658. //
  659. extern bool DebugFlag;
  660. // DEBUG macro - This macro should be used by code to emit debug information.
  661. // In the '-debug' option is specified on the command line, and if this is a
  662. // debug build, then the code specified as the option to the macro will be
  663. // executed. Otherwise it will not be.
  664. #ifdef NDEBUG
  665. #define LLVM_DEBUG(X)
  666. #else
  667. #define LLVM_DEBUG(X) do { if (DebugFlag) { X; } } while (0)
  668. #endif
  669. This allows clients to blissfully use the ``LLVM_DEBUG()`` macro, or the
  670. ``DebugFlag`` explicitly if they want to. Now we just need to be able to set
  671. the ``DebugFlag`` boolean when the option is set. To do this, we pass an
  672. additional argument to our command line argument processor, and we specify where
  673. to fill in with the `cl::location`_ attribute:
  674. .. code-block:: c++
  675. bool DebugFlag; // the actual value
  676. static cl::opt<bool, true> // The parser
  677. Debug("debug", cl::desc("Enable debug output"), cl::Hidden, cl::location(DebugFlag));
  678. In the above example, we specify "``true``" as the second argument to the
  679. `cl::opt`_ template, indicating that the template should not maintain a copy of
  680. the value itself. In addition to this, we specify the `cl::location`_
  681. attribute, so that ``DebugFlag`` is automatically set.
  682. Option Attributes
  683. -----------------
  684. This section describes the basic attributes that you can specify on options.
  685. * The option name attribute (which is required for all options, except
  686. `positional options`_) specifies what the option name is. This option is
  687. specified in simple double quotes:
  688. .. code-block:: c++
  689. cl::opt<bool> Quiet("quiet");
  690. .. _cl::desc(...):
  691. * The **cl::desc** attribute specifies a description for the option to be
  692. shown in the ``-help`` output for the program. This attribute supports
  693. multi-line descriptions with lines separated by '\n'.
  694. .. _cl::value_desc:
  695. * The **cl::value_desc** attribute specifies a string that can be used to
  696. fine tune the ``-help`` output for a command line option. Look `here`_ for an
  697. example.
  698. .. _cl::init:
  699. * The **cl::init** attribute specifies an initial value for a `scalar`_
  700. option. If this attribute is not specified then the command line option value
  701. defaults to the value created by the default constructor for the
  702. type.
  703. .. warning::
  704. If you specify both **cl::init** and **cl::location** for an option, you
  705. must specify **cl::location** first, so that when the command-line parser
  706. sees **cl::init**, it knows where to put the initial value. (You will get an
  707. error at runtime if you don't put them in the right order.)
  708. .. _cl::location:
  709. * The **cl::location** attribute where to store the value for a parsed command
  710. line option if using external storage. See the section on `Internal vs
  711. External Storage`_ for more information.
  712. .. _cl::aliasopt:
  713. * The **cl::aliasopt** attribute specifies which option a `cl::alias`_ option is
  714. an alias for.
  715. .. _cl::values:
  716. * The **cl::values** attribute specifies the string-to-value mapping to be used
  717. by the generic parser. It takes a list of (option, value, description)
  718. triplets that specify the option name, the value mapped to, and the
  719. description shown in the ``-help`` for the tool. Because the generic parser
  720. is used most frequently with enum values, two macros are often useful:
  721. #. The **clEnumVal** macro is used as a nice simple way to specify a triplet
  722. for an enum. This macro automatically makes the option name be the same as
  723. the enum name. The first option to the macro is the enum, the second is
  724. the description for the command line option.
  725. #. The **clEnumValN** macro is used to specify macro options where the option
  726. name doesn't equal the enum name. For this macro, the first argument is
  727. the enum value, the second is the flag name, and the second is the
  728. description.
  729. You will get a compile time error if you try to use cl::values with a parser
  730. that does not support it.
  731. .. _cl::multi_val:
  732. * The **cl::multi_val** attribute specifies that this option takes has multiple
  733. values (example: ``-sectalign segname sectname sectvalue``). This attribute
  734. takes one unsigned argument - the number of values for the option. This
  735. attribute is valid only on ``cl::list`` options (and will fail with compile
  736. error if you try to use it with other option types). It is allowed to use all
  737. of the usual modifiers on multi-valued options (besides
  738. ``cl::ValueDisallowed``, obviously).
  739. .. _cl::cat:
  740. * The **cl::cat** attribute specifies the option category that the option
  741. belongs to. The category should be a `cl::OptionCategory`_ object.
  742. Option Modifiers
  743. ----------------
  744. Option modifiers are the flags and expressions that you pass into the
  745. constructors for `cl::opt`_ and `cl::list`_. These modifiers give you the
  746. ability to tweak how options are parsed and how ``-help`` output is generated to
  747. fit your application well.
  748. These options fall into five main categories:
  749. #. Hiding an option from ``-help`` output
  750. #. Controlling the number of occurrences required and allowed
  751. #. Controlling whether or not a value must be specified
  752. #. Controlling other formatting options
  753. #. Miscellaneous option modifiers
  754. It is not possible to specify two options from the same category (you'll get a
  755. runtime error) to a single option, except for options in the miscellaneous
  756. category. The CommandLine library specifies defaults for all of these settings
  757. that are the most useful in practice and the most common, which mean that you
  758. usually shouldn't have to worry about these.
  759. Hiding an option from ``-help`` output
  760. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  761. The ``cl::NotHidden``, ``cl::Hidden``, and ``cl::ReallyHidden`` modifiers are
  762. used to control whether or not an option appears in the ``-help`` and
  763. ``-help-hidden`` output for the compiled program:
  764. .. _cl::NotHidden:
  765. * The **cl::NotHidden** modifier (which is the default for `cl::opt`_ and
  766. `cl::list`_ options) indicates the option is to appear in both help
  767. listings.
  768. .. _cl::Hidden:
  769. * The **cl::Hidden** modifier (which is the default for `cl::alias`_ options)
  770. indicates that the option should not appear in the ``-help`` output, but
  771. should appear in the ``-help-hidden`` output.
  772. .. _cl::ReallyHidden:
  773. * The **cl::ReallyHidden** modifier indicates that the option should not appear
  774. in any help output.
  775. Controlling the number of occurrences required and allowed
  776. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  777. This group of options is used to control how many time an option is allowed (or
  778. required) to be specified on the command line of your program. Specifying a
  779. value for this setting allows the CommandLine library to do error checking for
  780. you.
  781. The allowed values for this option group are:
  782. .. _cl::Optional:
  783. * The **cl::Optional** modifier (which is the default for the `cl::opt`_ and
  784. `cl::alias`_ classes) indicates that your program will allow either zero or
  785. one occurrence of the option to be specified.
  786. .. _cl::ZeroOrMore:
  787. * The **cl::ZeroOrMore** modifier (which is the default for the `cl::list`_
  788. class) indicates that your program will allow the option to be specified zero
  789. or more times.
  790. .. _cl::Required:
  791. * The **cl::Required** modifier indicates that the specified option must be
  792. specified exactly one time.
  793. .. _cl::OneOrMore:
  794. * The **cl::OneOrMore** modifier indicates that the option must be specified at
  795. least one time.
  796. * The **cl::ConsumeAfter** modifier is described in the `Positional arguments
  797. section`_.
  798. If an option is not specified, then the value of the option is equal to the
  799. value specified by the `cl::init`_ attribute. If the ``cl::init`` attribute is
  800. not specified, the option value is initialized with the default constructor for
  801. the data type.
  802. If an option is specified multiple times for an option of the `cl::opt`_ class,
  803. only the last value will be retained.
  804. Controlling whether or not a value must be specified
  805. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  806. This group of options is used to control whether or not the option allows a
  807. value to be present. In the case of the CommandLine library, a value is either
  808. specified with an equal sign (e.g. '``-index-depth=17``') or as a trailing
  809. string (e.g. '``-o a.out``').
  810. The allowed values for this option group are:
  811. .. _cl::ValueOptional:
  812. * The **cl::ValueOptional** modifier (which is the default for ``bool`` typed
  813. options) specifies that it is acceptable to have a value, or not. A boolean
  814. argument can be enabled just by appearing on the command line, or it can have
  815. an explicit '``-foo=true``'. If an option is specified with this mode, it is
  816. illegal for the value to be provided without the equal sign. Therefore
  817. '``-foo true``' is illegal. To get this behavior, you must use
  818. the `cl::ValueRequired`_ modifier.
  819. .. _cl::ValueRequired:
  820. * The **cl::ValueRequired** modifier (which is the default for all other types
  821. except for `unnamed alternatives using the generic parser`_) specifies that a
  822. value must be provided. This mode informs the command line library that if an
  823. option is not provides with an equal sign, that the next argument provided
  824. must be the value. This allows things like '``-o a.out``' to work.
  825. .. _cl::ValueDisallowed:
  826. * The **cl::ValueDisallowed** modifier (which is the default for `unnamed
  827. alternatives using the generic parser`_) indicates that it is a runtime error
  828. for the user to specify a value. This can be provided to disallow users from
  829. providing options to boolean options (like '``-foo=true``').
  830. In general, the default values for this option group work just like you would
  831. want them to. As mentioned above, you can specify the `cl::ValueDisallowed`_
  832. modifier to a boolean argument to restrict your command line parser. These
  833. options are mostly useful when `extending the library`_.
  834. .. _formatting option:
  835. Controlling other formatting options
  836. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  837. The formatting option group is used to specify that the command line option has
  838. special abilities and is otherwise different from other command line arguments.
  839. As usual, you can only specify one of these arguments at most.
  840. .. _cl::NormalFormatting:
  841. * The **cl::NormalFormatting** modifier (which is the default all options)
  842. specifies that this option is "normal".
  843. .. _cl::Positional:
  844. * The **cl::Positional** modifier specifies that this is a positional argument
  845. that does not have a command line option associated with it. See the
  846. `Positional Arguments`_ section for more information.
  847. * The **cl::ConsumeAfter** modifier specifies that this option is used to
  848. capture "interpreter style" arguments. See `this section for more
  849. information`_.
  850. .. _prefix:
  851. .. _cl::Prefix:
  852. * The **cl::Prefix** modifier specifies that this option prefixes its value.
  853. With 'Prefix' options, the equal sign does not separate the value from the
  854. option name specified. Instead, the value is everything after the prefix,
  855. including any equal sign if present. This is useful for processing odd
  856. arguments like ``-lmalloc`` and ``-L/usr/lib`` in a linker tool or
  857. ``-DNAME=value`` in a compiler tool. Here, the '``l``', '``D``' and '``L``'
  858. options are normal string (or list) options, that have the **cl::Prefix**
  859. modifier added to allow the CommandLine library to recognize them. Note that
  860. **cl::Prefix** options must not have the **cl::ValueDisallowed** modifier
  861. specified.
  862. .. _grouping:
  863. .. _cl::Grouping:
  864. Controlling options grouping
  865. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  866. The **cl::Grouping** modifier can be combined with any formatting types except
  867. for `cl::Positional`_. It is used to implement Unix-style tools (like ``ls``)
  868. that have lots of single letter arguments, but only require a single dash.
  869. For example, the '``ls -labF``' command actually enables four different options,
  870. all of which are single letters.
  871. Note that **cl::Grouping** options can have values only if they are used
  872. separately or at the end of the groups. For `cl::ValueRequired`_, it is
  873. a runtime error if such an option is used elsewhere in the group.
  874. The CommandLine library does not restrict how you use the **cl::Prefix** or
  875. **cl::Grouping** modifiers, but it is possible to specify ambiguous argument
  876. settings. Thus, it is possible to have multiple letter options that are prefix
  877. or grouping options, and they will still work as designed.
  878. To do this, the CommandLine library uses a greedy algorithm to parse the input
  879. option into (potentially multiple) prefix and grouping options. The strategy
  880. basically looks like this:
  881. ::
  882. parse(string OrigInput) {
  883. 1. string Input = OrigInput;
  884. 2. if (isOption(Input)) return getOption(Input).parse(); // Normal option
  885. 3. while (!Input.empty() && !isOption(Input)) Input.pop_back(); // Remove the last letter
  886. 4. while (!Input.empty()) {
  887. string MaybeValue = OrigInput.substr(Input.length())
  888. if (getOption(Input).isPrefix())
  889. return getOption(Input).parse(MaybeValue)
  890. if (!MaybeValue.empty() && MaybeValue[0] == '=')
  891. return getOption(Input).parse(MaybeValue.substr(1))
  892. if (!getOption(Input).isGrouping())
  893. return error()
  894. getOption(Input).parse()
  895. Input = OrigInput = MaybeValue
  896. while (!Input.empty() && !isOption(Input)) Input.pop_back();
  897. if (!Input.empty() && !getOption(Input).isGrouping())
  898. return error()
  899. }
  900. 5. 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::DefaultOption:
  916. * The **cl::DefaultOption** modifier is used to specify that the option is a
  917. default that can be overridden by application specific parsers. For example,
  918. the ``-help`` alias, ``-h``, is registered this way, so it can be overridden
  919. by applications that need to use the ``-h`` option for another purpose,
  920. either as a regular option or an alias for another option.
  921. .. _cl::PositionalEatsArgs:
  922. * The **cl::PositionalEatsArgs** modifier (which only applies to positional
  923. arguments, and only makes sense for lists) indicates that positional argument
  924. should consume any strings after it (including strings that start with a "-")
  925. up until another recognized positional argument. For example, if you have two
  926. "eating" positional arguments, "``pos1``" and "``pos2``", the string "``-pos1
  927. -foo -bar baz -pos2 -bork``" would cause the "``-foo -bar -baz``" strings to
  928. be applied to the "``-pos1``" option and the "``-bork``" string to be applied
  929. to the "``-pos2``" option.
  930. .. _cl::Sink:
  931. * The **cl::Sink** modifier is used to handle unknown options. If there is at
  932. least one option with ``cl::Sink`` modifier specified, the parser passes
  933. unrecognized option strings to it as values instead of signaling an error. As
  934. with ``cl::CommaSeparated``, this modifier only makes sense with a `cl::list`_
  935. option.
  936. .. _response files:
  937. Response files
  938. ^^^^^^^^^^^^^^
  939. Some systems, such as certain variants of Microsoft Windows and some older
  940. Unices have a relatively low limit on command-line length. It is therefore
  941. customary to use the so-called 'response files' to circumvent this
  942. restriction. These files are mentioned on the command-line (using the "@file")
  943. syntax. The program reads these files and inserts the contents into argv,
  944. thereby working around the command-line length limits.
  945. Top-Level Classes and Functions
  946. -------------------------------
  947. Despite all of the built-in flexibility, the CommandLine option library really
  948. only consists of one function `cl::ParseCommandLineOptions`_) and three main
  949. classes: `cl::opt`_, `cl::list`_, and `cl::alias`_. This section describes
  950. these three classes in detail.
  951. .. _cl::getRegisteredOptions:
  952. The ``cl::getRegisteredOptions`` function
  953. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  954. The ``cl::getRegisteredOptions`` function is designed to give a programmer
  955. access to declared non-positional command line options so that how they appear
  956. in ``-help`` can be modified prior to calling `cl::ParseCommandLineOptions`_.
  957. Note this method should not be called during any static initialisation because
  958. it cannot be guaranteed that all options will have been initialised. Hence it
  959. should be called from ``main``.
  960. This function can be used to gain access to options declared in libraries that
  961. the tool writer may not have direct access to.
  962. The function retrieves a :ref:`StringMap <dss_stringmap>` that maps the option
  963. string (e.g. ``-help``) to an ``Option*``.
  964. Here is an example of how the function could be used:
  965. .. code-block:: c++
  966. using namespace llvm;
  967. int main(int argc, char **argv) {
  968. cl::OptionCategory AnotherCategory("Some options");
  969. StringMap<cl::Option*> &Map = cl::getRegisteredOptions();
  970. //Unhide useful option and put it in a different category
  971. assert(Map.count("print-all-options") > 0);
  972. Map["print-all-options"]->setHiddenFlag(cl::NotHidden);
  973. Map["print-all-options"]->setCategory(AnotherCategory);
  974. //Hide an option we don't want to see
  975. assert(Map.count("enable-no-infs-fp-math") > 0);
  976. Map["enable-no-infs-fp-math"]->setHiddenFlag(cl::Hidden);
  977. //Change --version to --show-version
  978. assert(Map.count("version") > 0);
  979. Map["version"]->setArgStr("show-version");
  980. //Change --help description
  981. assert(Map.count("help") > 0);
  982. Map["help"]->setDescription("Shows help");
  983. cl::ParseCommandLineOptions(argc, argv, "This is a small program to demo the LLVM CommandLine API");
  984. ...
  985. }
  986. .. _cl::ParseCommandLineOptions:
  987. The ``cl::ParseCommandLineOptions`` function
  988. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  989. The ``cl::ParseCommandLineOptions`` function is designed to be called directly
  990. from ``main``, and is used to fill in the values of all of the command line
  991. option variables once ``argc`` and ``argv`` are available.
  992. The ``cl::ParseCommandLineOptions`` function requires two parameters (``argc``
  993. and ``argv``), but may also take an optional third parameter which holds
  994. `additional extra text`_ to emit when the ``-help`` option is invoked.
  995. .. _cl::ParseEnvironmentOptions:
  996. The ``cl::ParseEnvironmentOptions`` function
  997. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  998. The ``cl::ParseEnvironmentOptions`` function has mostly the same effects as
  999. `cl::ParseCommandLineOptions`_, except that it is designed to take values for
  1000. options from an environment variable, for those cases in which reading the
  1001. command line is not convenient or desired. It fills in the values of all the
  1002. command line option variables just like `cl::ParseCommandLineOptions`_ does.
  1003. It takes four parameters: the name of the program (since ``argv`` may not be
  1004. available, it can't just look in ``argv[0]``), the name of the environment
  1005. variable to examine, and the optional `additional extra text`_ to emit when the
  1006. ``-help`` option is invoked.
  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/IR/PassManager.cpp`` file.
  1291. .. todo::
  1292. TODO: complete this section
  1293. .. _dynamically loaded options:
  1294. Dynamically adding command line options
  1295. ---------------------------------------
  1296. .. todo::
  1297. TODO: fill in this section