Adding additional license information to these files.
[oota-llvm.git] / docs / CommandLine.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html><head><title>CommandLine 2.0 Library Manual</title></head>
3 <body bgcolor=white>
4
5 <table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
6 <tr><td>&nbsp; <font size=+3 color="#EEEEFF" face="Georgia,Palatino,Times,Roman"><b>CommandLine 2.0 Library Manual</b></font></td>
7 </tr></table>
8
9 <ol>
10   <li><a href="#introduction">Introduction</a>
11   <li><a href="#quickstart">Quick Start Guide</a>
12     <ol>
13       <li><a href="#bool">Boolean Arguments</a>
14       <li><a href="#alias">Argument Aliases</a>
15       <li><a href="#onealternative">Selecting an alternative from a
16                                     set of possibilities</a>
17       <li><a href="#namedalternatives">Named alternatives</a>
18       <li><a href="#list">Parsing a list of options</a>
19       <li><a href="#description">Adding freeform text to help output</a>
20     </ol>
21   <li><a href="#referenceguide">Reference Guide</a>
22     <ol>
23       <li><a href="#positional">Positional Arguments</a>
24         <ul>
25         <li><a href="#--">Specifying positional options with hyphens</a>
26         <li><a href="#cl::ConsumeAfter">The <tt>cl::ConsumeAfter</tt>
27              modifier</a>
28         </ul>
29       <li><a href="#storage">Internal vs External Storage</a>
30       <li><a href="#attributes">Option Attributes</a>
31       <li><a href="#modifiers">Option Modifiers</a>
32         <ul>
33         <li><a href="#hiding">Hiding an option from <tt>--help</tt> output</a>
34         <li><a href="#numoccurances">Controlling the number of occurances
35                                      required and allowed</a>
36         <li><a href="#valrequired">Controlling whether or not a value must be
37                                    specified</a>
38         <li><a href="#formatting">Controlling other formatting options</a>
39         <li><a href="#misc">Miscellaneous option modifiers</a>
40         </ul>
41       <li><a href="#toplevel">Top-Level Classes and Functions</a>
42         <ul>
43       <li><a href="#cl::ParseCommandLineOptions">The 
44             <tt>cl::ParseCommandLineOptions</tt> function</a>
45       <li><a href="#cl::ParseEnvironmentOptions">The 
46             <tt>cl::ParseEnvironmentOptions</tt> function</a>
47         <li><a href="#cl::opt">The <tt>cl::opt</tt> class</a>
48         <li><a href="#cl::list">The <tt>cl::list</tt> class</a>
49         <li><a href="#cl::alias">The <tt>cl::alias</tt> class</a>
50         </ul>
51       <li><a href="#builtinparsers">Builtin parsers</a>
52         <ul>
53         <li><a href="#genericparser">The Generic <tt>parser&lt;t&gt;</tt>
54             parser</a>
55         <li><a href="#boolparser">The <tt>parser&lt;bool&gt;</tt>
56             specialization</a>
57         <li><a href="#stringparser">The <tt>parser&lt;string&gt;</tt>
58             specialization</a>
59         <li><a href="#intparser">The <tt>parser&lt;int&gt;</tt>
60             specialization</a>
61         <li><a href="#doubleparser">The <tt>parser&lt;double&gt;</tt> and
62             <tt>parser&lt;float&gt;</tt> specializations</a>
63         </ul>
64     </ol>
65   <li><a href="#extensionguide">Extension Guide</a>
66     <ol>
67       <li><a href="#customparser">Writing a custom parser</a>
68       <li><a href="#explotingexternal">Exploiting external storage</a>
69       <li><a href="#dynamicopts">Dynamically adding command line options</a>
70     </ol>
71
72   <p><b>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></b><p>
73 </ol><p>
74
75
76 <!-- *********************************************************************** -->
77 <table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
78 <tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
79 <a name="introduction">Introduction
80 </b></font></td></tr></table><ul>
81 <!-- *********************************************************************** -->
82
83 This document describes the CommandLine argument processing library.  It will
84 show you how to use it, and what it can do.  The CommandLine library uses a
85 declarative approach to specifying the command line options that your program
86 takes.  By default, these options declarations implicitly hold the value parsed
87 for the option declared (of course this <a href="#storage">can be
88 changed</a>).<p>
89
90 Although there are a <b>lot</b> of command line argument parsing libraries out
91 there in many different languages, none of them fit well with what I needed.  By
92 looking at the features and problems of other libraries, I designed the
93 CommandLine library to have the following features:<p>
94
95 <ol>
96 <li>Speed: The CommandLine library is very quick and uses little resources.  The
97 parsing time of the library is directly proportional to the number of arguments
98 parsed, not the the number of options recognized.  Additionally, command line
99 argument values are captured transparently into user defined global variables,
100 which can be accessed like any other variable (and with the same
101 performance).<p>
102
103 <li>Type Safe: As a user of CommandLine, you don't have to worry about
104 remembering the type of arguments that you want (is it an int?  a string? a
105 bool? an enum?) and keep casting it around.  Not only does this help prevent
106 error prone constructs, it also leads to dramatically cleaner source code.<p>
107
108 <li>No subclasses required: To use CommandLine, you instantiate variables that
109 correspond to the arguments that you would like to capture, you don't subclass a
110 parser.  This means that you don't have to write <b>any</b> boilerplate code.<p>
111
112 <li>Globally accessible: Libraries can specify command line arguments that are
113 automatically enabled in any tool that links to the library.  This is possible
114 because the application doesn't have to keep a "list" of arguments to pass to
115 the parser.  This also makes supporting <a href="#dynamicopts">dynamically
116 loaded options</a> trivial.<p>
117
118 <li>Cleaner: CommandLine supports enum and other types directly, meaning that
119 there is less error and more security built into the library.  You don't have to
120 worry about whether your integral command line argument accidentally got
121 assigned a value that is not valid for your enum type.<p>
122
123 <li>Powerful: The CommandLine library supports many different types of
124 arguments, from simple <a href="#boolparser">boolean flags</a> to <a
125 href="#cl::opt">scalars arguments</a> (<a href="#stringparser">strings</a>, <a
126 href="#intparser">integers</a>, <a href="#genericparser">enums</a>, <a
127 href="#doubleparser">doubles</a>), to <a href="#cl::list">lists of
128 arguments</a>.  This is possible because CommandLine is...<p>
129
130 <li>Extensible: It is very simple to add a new argument type to CommandLine.
131 Simply specify the parser that you want to use with the command line option when
132 you declare it.  <a href="#customparser">Custom parsers</a> are no problem.<p>
133
134 <li>Labor Saving: The CommandLine library cuts down on the amount of grunt work
135 that you, the user, have to do.  For example, it automatically provides a
136 <tt>--help</tt> option that shows the available command line options for your
137 tool.  Additionally, it does most of the basic correctness checking for you.<p>
138
139 <li>Capable: The CommandLine library can handle lots of different forms of
140 options often found in real programs.  For example, <a
141 href="#positional">positional</a> arguments, <tt>ls</tt> style <a
142 href="#cl::Grouping">grouping</a> options (to allow processing '<tt>ls
143 -lad</tt>' naturally), <tt>ld</tt> style <a href="#cl::Prefix">prefix</a>
144 options (to parse '<tt>-lmalloc -L/usr/lib</tt>'), and <a
145 href="#cl::ConsumeAfter">interpreter style options</a>.<p>
146
147 </ol>
148
149 This document will hopefully let you jump in and start using CommandLine in your
150 utility quickly and painlessly.  Additionally it should be a simple reference
151 manual to figure out how stuff works.  If it is failing in some area (or you
152 want an extension to the library), nag the author, <a
153 href="mailto:sabre@nondot.org">Chris Lattner</a>.<p>
154
155
156
157 <!-- *********************************************************************** -->
158 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0><tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
159 <a name="quickstart">Quick Start Guide
160 </b></font></td></tr></table><ul>
161 <!-- *********************************************************************** -->
162
163 This section of the manual runs through a simple CommandLine'ification of a
164 basic compiler tool.  This is intended to show you how to jump into using the
165 CommandLine library in your own program, and show you some of the cool things it
166 can do.<p>
167
168 To start out, you need to include the CommandLine header file into your
169 program:<p>
170
171 <pre>
172   #include "Support/CommandLine.h"
173 </pre><p>
174
175 Additionally, you need to add this as the first line of your main program:<p>
176
177 <pre>
178 int main(int argc, char **argv) {
179   <a href="#cl::ParseCommandLineOptions">cl::ParseCommandLineOptions</a>(argc, argv);
180   ...
181 }
182 </pre><p>
183
184 ... which actually parses the arguments and fills in the variable
185 declarations.<p>
186
187 Now that you are ready to support command line arguments, we need to tell the
188 system which ones we want, and what type of argument they are.  The CommandLine
189 library uses a declarative syntax to model command line arguments with the
190 global variable declarations that capture the parsed values.  This means that
191 for every command line option that you would like to support, there should be a
192 global variable declaration to capture the result.  For example, in a compiler,
193 we would like to support the unix standard '<tt>-o &lt;filename&gt;</tt>' option
194 to specify where to put the output.  With the CommandLine library, this is
195 represented like this:<p>
196
197 <pre><a name="value_desc_example">
198 <a href="#cl::opt">cl::opt</a>&lt;string&gt; OutputFilename("<i>o</i>", <a href="#cl::desc">cl::desc</a>("<i>Specify output filename</i>"), <a href="#cl::value_desc">cl::value_desc</a>("<i>filename</i>"));
199 </pre><p>
200
201 This declares a global variable "<tt>OutputFilename</tt>" that is used to
202 capture the result of the "<tt>o</tt>" argument (first parameter).  We specify
203 that this is a simple scalar option by using the "<tt><a
204 href="#cl::opt">cl::opt</a></tt>" template (as opposed to the <a
205 href="#list">"<tt>cl::list</tt> template</a>), and tell the CommandLine library
206 that the data type that we are parsing is a string.<p>
207
208 The second and third parameters (which are optional) are used to specify what to
209 output for the "<tt>--help</tt>" option.  In this case, we get a line that looks
210 like this:<p>
211
212 <pre>
213 USAGE: compiler [options]
214
215 OPTIONS:
216   -help             - display available options (--help-hidden for more)
217   <b>-o &lt;filename&gt;     - Specify output filename</b>
218 </pre>
219
220 Because we specified that the command line option should parse using the
221 <tt>string</tt> data type, the variable declared is automatically usable as a
222 real string in all contexts that a normal C++ string object may be used.  For
223 example:<p>
224
225 <pre>
226   ...
227   ofstream Output(OutputFilename.c_str());
228   if (Out.good()) ...
229   ...
230 </pre><p>
231
232 There are many different options that you can use to customize the command line
233 option handling library, but the above example shows the general interface to
234 these options.  The options can be specified in any order, and are specified
235 with helper functions like <a href="#cl::desc"><tt>cl::desc(...)</tt></a>, so
236 there are no positional dependencies to remember.  The available options are
237 discussed in detail in the <a href="#referenceguide">Reference Guide</a>.<p>
238
239
240 Continuing the example, we would like to have our compiler take an input
241 filename as well as an output filename, but we do not want the input filename to
242 be specified with a hyphen (ie, not <tt>-filename.c</tt>).  To support this
243 style of argument, the CommandLine library allows for <a
244 href="#positional">positional</a> arguments to be specified for the program.
245 These positional arguments are filled with command line parameters that are not
246 in option form.  We use this feature like this:<p>
247
248 <pre>
249 <a href="#cl::opt">cl::opt</a>&lt;string&gt; InputFilename(<a href="#cl::Positional">cl::Positional</a>, <a href="#cl::desc">cl::desc</a>("<i>&lt;input file&gt;</i>"), <a href="#cl::init">cl::init</a>("<i>-</i>"));
250 </pre>
251
252 This declaration indicates that the first positional argument should be treated
253 as the input filename.  Here we use the <tt><a
254 href="#cl::init">cl::init</a></tt> option to specify an initial value for the
255 command line option, which is used if the option is not specified (if you do not
256 specify a <tt><a href="#cl::init">cl::init</a></tt> modifier for an option, then
257 the default constructor for the data type is used to initialize the value).
258 Command line options default to being optional, so if we would like to require
259 that the user always specify an input filename, we would add the <tt><a
260 href="#cl::Required">cl::Required</a></tt> flag, and we could eliminate the
261 <tt><a href="#cl::init">cl::init</a></tt> modifier, like this:<p>
262
263 <pre>
264 <a href="#cl::opt">cl::opt</a>&lt;string&gt; InputFilename(<a href="#cl::Positional">cl::Positional</a>, <a href="#cl::desc">cl::desc</a>("<i>&lt;input file&gt;</i>"), <b><a href="#cl::Required">cl::Required</a></b>);
265 </pre>
266
267 Again, the CommandLine library does not require the options to be specified in
268 any particular order, so the above declaration is equivalent to:<p>
269
270 <pre>
271 <a href="#cl::opt">cl::opt</a>&lt;string&gt; InputFilename(<a href="#cl::Positional">cl::Positional</a>, <a href="#cl::Required">cl::Required</a>, <a href="#cl::desc">cl::desc</a>("<i>&lt;input file&gt;</i>"));
272 </pre>
273
274 By simply adding the <tt><a href="#cl::Required">cl::Required</a></tt> flag, the
275 CommandLine library will automatically issue an error if the argument is not
276 specified, which shifts all of the command line option verification code out of
277 your application into the library.  This is just one example of how using flags
278 can alter the default behaviour of the library, on a per-option basis.  By
279 adding one of the declarations above, the <tt>--help</tt> option synopsis is now
280 extended to:<p>
281
282 <pre>
283 USAGE: compiler [options] <b>&lt;input file&gt;</b>
284
285 OPTIONS:
286   -help             - display available options (--help-hidden for more)
287   -o &lt;filename&gt;     - Specify output filename
288 </pre>
289
290 ... indicating that an input filename is expected.<p>
291
292
293
294 <!-- ======================================================================= -->
295 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
296 <a name="bool">Boolean Arguments
297 </b></font></td></tr></table><ul>
298
299 In addition to input and output filenames, we would like the compiler example to
300 support three boolean flags: "<tt>-f</tt>" to force overwriting of the output
301 file, "<tt>--quiet</tt>" to enable quiet mode, and "<tt>-q</tt>" for backwards
302 compatibility with some of our users.  We can support these by declaring options
303 of boolean type like this:<p>
304
305 <pre>
306 <a href="#cl::opt">cl::opt</a>&lt;bool&gt; Force ("<i>f</i>", <a href="#cl::desc">cl::desc</a>("<i>Overwrite output files</i>"));
307 <a href="#cl::opt">cl::opt</a>&lt;bool&gt; Quiet ("<i>quiet</i>", <a href="#cl::desc">cl::desc</a>("<i>Don't print informational messages</i>"));
308 <a href="#cl::opt">cl::opt</a>&lt;bool&gt; Quiet2("<i>q</i>", <a href="#cl::desc">cl::desc</a>("<i>Don't print informational messages</i>"), <a href="#cl::Hidden">cl::Hidden</a>);
309 </pre><p>
310
311 This does what you would expect: it declares three boolean variables
312 ("<tt>Force</tt>", "<tt>Quiet</tt>", and "<tt>Quiet2</tt>") to recognize these
313 options.  Note that the "<tt>-q</tt>" option is specified with the "<a
314 href="#cl::Hidden"><tt>cl::Hidden</tt></a>" flag.  This modifier prevents it
315 from being shown by the standard "<tt>--help</tt>" output (note that it is still
316 shown in the "<tt>--help-hidden</tt>" output).<p>
317
318 The CommandLine library uses a <a href="#builtinparsers">different parser</a>
319 for different data types.  For example, in the string case, the argument passed
320 to the option is copied literally into the content of the string variable... we
321 obviously cannot do that in the boolean case, however, so we must use a smarter
322 parser.  In the case of the boolean parser, it allows no options (in which case
323 it assigns the value of true to the variable), or it allows the values
324 "<tt>true</tt>" or "<tt>false</tt>" to be specified, allowing any of the
325 following inputs:<p>
326
327 <pre>
328  compiler -f          # No value, 'Force' == true
329  compiler -f=true     # Value specified, 'Force' == true
330  compiler -f=TRUE     # Value specified, 'Force' == true
331  compiler -f=FALSE    # Value specified, 'Force' == false
332 </pre>
333
334 ... you get the idea.  The <a href="#boolparser">bool parser</a> just turns the
335 string values into boolean values, and rejects things like '<tt>compiler
336 -f=foo</tt>'.  Similarly, the <a href="#doubleparser">float</a>, <a
337 href="#doubleparser">double</a>, and <a href="#intparser">int</a> parsers work
338 like you would expect, using the '<tt>strtol</tt>' and '<tt>strtod</tt>' C
339 library calls to parse the string value into the specified data type.<p>
340
341 With the declarations above, "<tt>compiler --help</tt>" emits this:<p>
342
343 <pre>
344 USAGE: compiler [options] &lt;input file&gt;
345
346 OPTIONS:
347   <b>-f     - Overwrite output files</b>
348   -o     - Override output filename
349   <b>-quiet - Don't print informational messages</b>
350   -help  - display available options (--help-hidden for more)
351 </pre><p>
352
353 and "<tt>opt --help-hidden</tt>" prints this:<p>
354
355 <pre>
356 USAGE: compiler [options] &lt;input file&gt;
357
358 OPTIONS:
359   -f     - Overwrite output files
360   -o     - Override output filename
361   <b>-q     - Don't print informational messages</b>
362   -quiet - Don't print informational messages
363   -help  - display available options (--help-hidden for more)
364 </pre><p>
365
366 This brief example has shown you how to use the '<tt><a
367 href="#cl::opt">cl::opt</a></tt>' class to parse simple scalar command line
368 arguments.  In addition to simple scalar arguments, the CommandLine library also
369 provides primitives to support CommandLine option <a href="#alias">aliases</a>,
370 and <a href="#list">lists</a> of options.<p>
371
372
373 <!-- ======================================================================= -->
374 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
375 <a name="alias">Argument Aliases
376 </b></font></td></tr></table><ul>
377
378 So far, the example works well, except for the fact that we need to check the
379 quiet condition like this now:<p>
380
381 <pre>
382 ...
383   if (!Quiet &amp;&amp; !Quiet2) printInformationalMessage(...);
384 ...
385 </pre><p>
386
387 ... which is a real pain!  Instead of defining two values for the same
388 condition, we can use the "<tt><a href="#cl::alias">cl::alias</a></tt>" class to make the "<tt>-q</tt>"
389 option an <b>alias</b> for the "<tt>-quiet</tt>" option, instead of providing
390 a value itself:<p>
391
392 <pre>
393 <a href="#cl::opt">cl::opt</a>&lt;bool&gt; Force ("<i>f</i>", <a href="#cl::desc">cl::desc</a>("<i>Overwrite output files</i>"));
394 <a href="#cl::opt">cl::opt</a>&lt;bool&gt; Quiet ("<i>quiet</i>", <a href="#cl::desc">cl::desc</a>("<i>Don't print informational messages</i>"));
395 <a href="#cl::alias">cl::alias</a>     QuietA("<i>q</i>", <a href="#cl::desc">cl::desc</a>("<i>Alias for -quiet</i>"), <a href="#cl::aliasopt">cl::aliasopt</a>(Quiet));
396 </pre><p>
397
398 The third line (which is the only one we modified from above) defines a
399 "<tt>-q</tt> alias that updates the "<tt>Quiet</tt>" variable (as specified by
400 the <tt><a href="#cl::aliasopt">cl::aliasopt</a></tt> modifier) whenever it is
401 specified.  Because aliases do not hold state, the only thing the program has to
402 query is the <tt>Quiet</tt> variable now.  Another nice feature of aliases is
403 that they automatically hide themselves from the <tt>-help</tt> output
404 (although, again, they are still visible in the <tt>--help-hidden
405 output</tt>).<p>
406
407 Now the application code can simply use:<p>
408
409 <pre>
410 ...
411   if (!Quiet) printInformationalMessage(...);
412 ...
413 </pre><p>
414
415 ... which is much nicer!  The "<tt><a href="#cl::alias">cl::alias</a></tt>" can be used to specify an
416 alternative name for any variable type, and has many uses.<p>
417
418
419
420 <!-- ======================================================================= -->
421 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
422 <a name="onealternative">Selecting an alternative from a set of possibilities
423 </b></font></td></tr></table><ul>
424
425 So far, we have seen how the CommandLine library handles builtin types like
426 <tt>std::string</tt>, <tt>bool</tt> and <tt>int</tt>, but how does it handle
427 things it doesn't know about, like enums or '<tt>int*</tt>'s?<p>
428
429 The answer is that it uses a table driven generic parser (unless you specify
430 your own parser, as described in the <a href="#extensionguide">Extension
431 Guide</a>).  This parser maps literal strings to whatever type is required, are
432 requires you to tell it what this mapping should be.<p>
433
434 Lets say that we would like to add four optimizations levels to our optimizer,
435 using the standard flags "<tt>-g</tt>", "<tt>-O0</tt>", "<tt>-O1</tt>", and
436 "<tt>-O2</tt>".  We could easily implement this with boolean options like above,
437 but there are several problems with this strategy:<p>
438
439 <ol>
440 <li>A user could specify more than one of the options at a time, for example,
441 "<tt>opt -O3 -O2</tt>".  The CommandLine library would not be able to catch this
442 erroneous input for us.
443
444 <li>We would have to test 4 different variables to see which ones are set.
445
446 <li>This doesn't map to the numeric levels that we want... so we cannot easily
447 see if some level &gt;= "<tt>-O1</tt>" is enabled.
448
449 </ol><p>
450
451 To cope with these problems, we can use an enum value, and have the CommandLine
452 library fill it in with the appropriate level directly, which is used like
453 this:<p>
454
455 <pre>
456 enum OptLevel {
457   g, O1, O2, O3
458 };
459
460 <a href="#cl::opt">cl::opt</a>&lt;OptLevel&gt; OptimizationLevel(<a href="#cl::desc">cl::desc</a>("<i>Choose optimization level:</i>"),
461   <a href="#cl::values">cl::values</a>(
462     clEnumVal(g , "<i>No optimizations, enable debugging</i>"),
463     clEnumVal(O1, "<i>Enable trivial optimizations</i>"),
464     clEnumVal(O2, "<i>Enable default optimizations</i>"),
465     clEnumVal(O3, "<i>Enable expensive optimizations</i>"),
466    0));
467
468 ...
469   if (OptimizationLevel &gt;= O2) doPartialRedundancyElimination(...);
470 ...
471 </pre><p>
472
473 This declaration defines a variable "<tt>OptimizationLevel</tt>" of the
474 "<tt>OptLevel</tt>" enum type.  This variable can be assigned any of the values
475 that are listed in the declaration (Note that the declaration list must be
476 terminated with the "<tt>0</tt>" argument!).  The CommandLine library enforces
477 that the user can only specify one of the options, and it ensure that only valid
478 enum values can be specified.  The "<tt>clEnumVal</tt>" macros ensure that the
479 command line arguments matched the enum values.  With this option added, our
480 help output now is:<p>
481
482 <pre>
483 USAGE: compiler [options] &lt;input file&gt;
484
485 OPTIONS:
486   <b>Choose optimization level:
487     -g          - No optimizations, enable debugging
488     -O1         - Enable trivial optimizations
489     -O2         - Enable default optimizations
490     -O3         - Enable expensive optimizations</b>
491   -f            - Overwrite output files
492   -help         - display available options (--help-hidden for more)
493   -o &lt;filename&gt; - Specify output filename
494   -quiet        - Don't print informational messages
495 </pre>
496
497 In this case, it is sort of awkward that flag names correspond directly to enum
498 names, because we probably don't want a enum definition named "<tt>g</tt>" in
499 our program.  Because of this, we can alternatively write this example like
500 this:<p>
501
502 <pre>
503 enum OptLevel {
504   Debug, O1, O2, O3
505 };
506
507 <a href="#cl::opt">cl::opt</a>&lt;OptLevel&gt; OptimizationLevel(<a href="#cl::desc">cl::desc</a>("<i>Choose optimization level:</i>"),
508   <a href="#cl::values">cl::values</a>(
509    clEnumValN(Debug, "g", "<i>No optimizations, enable debugging</i>"),
510     clEnumVal(O1        , "<i>Enable trivial optimizations</i>"),
511     clEnumVal(O2        , "<i>Enable default optimizations</i>"),
512     clEnumVal(O3        , "<i>Enable expensive optimizations</i>"),
513    0));
514
515 ...
516   if (OptimizationLevel == Debug) outputDebugInfo(...);
517 ...
518 </pre><p>
519
520 By using the "<tt>clEnumValN</tt>" macro instead of "<tt>clEnumVal</tt>", we can
521 directly specify the name that the flag should get.  In general a direct mapping
522 is nice, but sometimes you can't or don't want to preserve the mapping, which is
523 when you would use it.<p>
524
525
526
527 <!-- ======================================================================= -->
528 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
529 <a name="namedalternatives">Named Alternatives
530 </b></font></td></tr></table><ul>
531
532 Another useful argument form is a named alternative style.  We shall use this
533 style in our compiler to specify different debug levels that can be used.
534 Instead of each debug level being its own switch, we want to support the
535 following options, of which only one can be specified at a time:
536 "<tt>--debug-level=none</tt>", "<tt>--debug-level=quick</tt>",
537 "<tt>--debug-level=detailed</tt>".  To do this, we use the exact same format as
538 our optimization level flags, but we also specify an option name.  For this
539 case, the code looks like this:<p>
540
541 <pre>
542 enum DebugLev {
543   nodebuginfo, quick, detailed
544 };
545
546 // Enable Debug Options to be specified on the command line
547 <a href="#cl::opt">cl::opt</a>&lt;DebugLev&gt; DebugLevel("<i>debug_level</i>", <a href="#cl::desc">cl::desc</a>("<i>Set the debugging level:</i>"),
548   <a href="#cl::values">cl::values</a>(
549     clEnumValN(nodebuginfo, "none", "<i>disable debug information</i>"),
550      clEnumVal(quick,               "<i>enable quick debug information</i>"),
551      clEnumVal(detailed,            "<i>enable detailed debug information</i>"),
552     0));
553 </pre>
554
555 This definition defines an enumerated command line variable of type "<tt>enum
556 DebugLev</tt>", which works exactly the same way as before.  The difference here
557 is just the interface exposed to the user of your program and the help output by
558 the "<tt>--help</tt>" option:<p>
559
560 <pre>
561 USAGE: compiler [options] &lt;input file&gt;
562
563 OPTIONS:
564   Choose optimization level:
565     -g          - No optimizations, enable debugging
566     -O1         - Enable trivial optimizations
567     -O2         - Enable default optimizations
568     -O3         - Enable expensive optimizations
569   <b>-debug_level  - Set the debugging level:
570     =none       - disable debug information
571     =quick      - enable quick debug information
572     =detailed   - enable detailed debug information</b>
573   -f            - Overwrite output files
574   -help         - display available options (--help-hidden for more)
575   -o &lt;filename&gt; - Specify output filename
576   -quiet        - Don't print informational messages
577 </pre><p>
578
579 Again, the only structural difference between the debug level declaration and
580 the optimiation level declaration is that the debug level declaration includes
581 an option name (<tt>"debug_level"</tt>), which automatically changes how the
582 library processes the argument.  The CommandLine library supports both forms so
583 that you can choose the form most appropriate for your application.<p>
584
585
586
587 <!-- ======================================================================= -->
588 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
589 <a name="list">Parsing a list of options
590 </b></font></td></tr></table><ul>
591
592 Now that we have the standard run of the mill argument types out of the way,
593 lets get a little wild and crazy.  Lets say that we want our optimizer to accept
594 a <b>list</b> of optimizations to perform, allowing duplicates.  For example, we
595 might want to run: "<tt>compiler -dce -constprop -inline -dce -strip</tt>".  In
596 this case, the order of the arguments and the number of appearances is very
597 important.  This is what the "<tt><a href="#cl::list">cl::list</a></tt>"
598 template is for.  First, start by defining an enum of the optimizations that you
599 would like to perform:<p>
600
601 <pre>
602 enum Opts {
603   // 'inline' is a C++ keyword, so name it 'inlining'
604   dce, constprop, inlining, strip
605 };
606 </pre><p>
607
608 Then define your "<tt><a href="#cl::list">cl::list</a></tt>" variable:<p>
609
610 <pre>
611 <a href="#cl::list">cl::list</a>&lt;Opts&gt; OptimizationList(<a href="#cl::desc">cl::desc</a>("<i>Available Optimizations:</i>"),
612   <a href="#cl::values">cl::values</a>(
613     clEnumVal(dce               , "<i>Dead Code Elimination</i>"),
614     clEnumVal(constprop         , "<i>Constant Propagation</i>"),
615    clEnumValN(inlining, "<i>inline</i>", "<i>Procedure Integration</i>"),
616     clEnumVal(strip             , "<i>Strip Symbols</i>"),
617   0));
618 </pre><p>
619
620 This defines a variable that is conceptually of the type
621 "<tt>std::vector&lt;enum Opts&gt;</tt>".  Thus, you can access it with standard
622 vector methods:<p>
623
624 <pre>
625   for (unsigned i = 0; i != OptimizationList.size(); ++i)
626     switch (OptimizationList[i])
627        ...
628 </pre>
629
630 ... to iterate through the list of options specified.<p>
631
632 Note that the "<tt><a href="#cl::list">cl::list</a></tt>" template is completely general and may be used
633 with any data types or other arguments that you can use with the
634 "<tt><a href="#cl::opt">cl::opt</a></tt>" template.  One especially useful way to use a list is to
635 capture all of the positional arguments together if there may be more than one
636 specified.  In the case of a linker, for example, the linker takes several
637 '<tt>.o</tt>' files, and needs to capture them into a list.  This is naturally
638 specified as:<p>
639
640 <pre>
641 ...
642 <a href="#cl::list">cl::list</a>&lt;std::string&gt; InputFilenames(<a href="#cl::Positional">cl::Positional</a>, <a href="#cl::desc">cl::desc</a>("&lt;Input files&gt;"), <a href="#cl::OneOrMore">cl::OneOrMore</a>);
643 ...
644 </pre><p>
645
646 This variable works just like a "<tt>vector&lt;string&gt;</tt>" object.  As
647 such, accessing the list is simple, just like above.  In this example, we used
648 the <tt><a href="#cl::OneOrMore">cl::OneOrMore</a></tt> modifier to inform the
649 CommandLine library that it is an error if the user does not specify any
650 <tt>.o</tt> files on our command line.  Again, this just reduces the amount of
651 checking we have to do.<p>
652
653
654
655 <!-- ======================================================================= -->
656 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
657 <a name="description">Adding freeform text to help output
658 </b></font></td></tr></table><ul>
659
660 As our program grows and becomes more mature, we may decide to put summary
661 information about what it does into the help output.  The help output is styled
662 to look similar to a Unix <tt>man</tt> page, providing concise information about
663 a program.  Unix <tt>man</tt> pages, however often have a description about what
664 the program does.  To add this to your CommandLine program, simply pass a third
665 argument to the <a
666 href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>
667 call in main.  This additional argument is then printed as the overview
668 information for your program, allowing you to include any additional information
669 that you want.  For example:<p>
670
671 <pre>
672 int main(int argc, char **argv) {
673   <a href="#cl::ParseCommandLineOptions">cl::ParseCommandLineOptions</a>(argc, argv, " CommandLine compiler example\n\n"
674                               "  This program blah blah blah...\n");
675   ...
676 }
677 </pre><p>
678
679 Would yield the help output:
680
681 <pre>
682 <b>OVERVIEW: CommandLine compiler example
683
684   This program blah blah blah...</b>
685
686 USAGE: compiler [options] &lt;input file&gt;
687
688 OPTIONS:
689   ...
690   -help             - display available options (--help-hidden for more)
691   -o &lt;filename&gt;     - Specify output filename
692 </pre><p>
693
694
695
696
697 <!-- *********************************************************************** -->
698 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0><tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
699 <a name="referenceguide">Reference Guide
700 </b></font></td></tr></table><ul>
701 <!-- *********************************************************************** -->
702
703 Now that you know the basics of how to use the CommandLine library, this section
704 will give you the detailed information you need to tune how command line options
705 work, as well as information on more "advanced" command line option processing
706 capabilities.<p>
707
708
709 <!-- ======================================================================= -->
710 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
711 <a name="positional">Positional Arguments
712 </b></font></td></tr></table><ul>
713
714 Positional arguments are those arguments that are not named, and are not
715 specified with a hyphen.  Positional arguments should be used when an option is
716 specified by its position alone.  For example, the standard Unix <tt>grep</tt>
717 tool takes a regular expression argument, and an optional filename to search
718 through (which defaults to standard input if a filename is not specified).
719 Using the CommandLine library, this would be specified as:<p>
720
721 <pre>
722 <a href="#cl::opt">cl::opt</a>&lt;string&gt; Regex   (<a href="#cl::Positional">cl::Positional</a>, <a href="#cl::desc">cl::desc</a>("<i>&lt;regular expression&gt;</i>"), <a href="#cl::Required">cl::Required</a>);
723 <a href="#cl::opt">cl::opt</a>&lt;string&gt; Filename(<a href="#cl::Positional">cl::Positional</a>, <a href="#cl::desc">cl::desc</a>("<i>&lt;input file&gt;</i>"), <a href="#cl::init">cl::init</a>("<i>-</i>"));
724 </pre>
725
726 Given these two option declarations, the <tt>--help</tt> output for our grep
727 replacement would look like this:<p>
728
729 <pre>
730 USAGE: spiffygrep [options] <b>&lt;regular expression&gt; &lt;input file&gt;</b>
731
732 OPTIONS:
733   -help - display available options (--help-hidden for more)
734 </pre>
735
736 ... and the resultant program could be used just like the standard <tt>grep</tt>
737 tool.<p>
738
739 Positional arguments are sorted by their order of construction.  This means that
740 command line options will be ordered according to how they are listed in a .cpp
741 file, but will not have an ordering defined if they positional arguments are
742 defined in multiple .cpp files.  The fix for this problem is simply to define
743 all of your positional arguments in one .cpp file.<p>
744
745
746
747 <!-- _______________________________________________________________________ -->
748 </ul><a name="--"><h4><hr size=0>Specifying positional options with hyphens</h4><ul>
749
750 Sometimes you may want to specify a value to your positional argument that
751 starts with a hyphen (for example, searching for '<tt>-foo</tt>' in a file).  At
752 first, you will have trouble doing this, because it will try to find an argument
753 named '<tt>-foo</tt>', and will fail (and single quotes will not save you).
754 Note that the system <tt>grep</tt> has the same problem:<p>
755
756 <pre>
757   $ spiffygrep '-foo' test.txt
758   Unknown command line argument '-foo'.  Try: spiffygrep --help'
759
760   $ grep '-foo' test.txt
761   grep: illegal option -- f
762   grep: illegal option -- o
763   grep: illegal option -- o
764   Usage: grep -hblcnsviw pattern file . . .
765 </pre><p>
766
767 The solution for this problem is the same for both your tool and the system
768 version: use the '<tt>--</tt>' marker.  When the user specifies '<tt>--</tt>' on
769 the command line, it is telling the program that all options after the
770 '<tt>--</tt>' should be treated as positional arguments, not options.  Thus, we
771 can use it like this:<p>
772
773 <pre>
774   $ spiffygrep -- -foo test.txt
775     ...output...
776 </pre><p>
777
778
779
780 <!-- _______________________________________________________________________ -->
781 </ul><a name="cl::ConsumeAfter"><h4><hr size=0>The <tt>cl::ConsumeAfter</tt> modifier</h4><ul>
782
783 The <tt>cl::ConsumeAfter</tt> <a href="#formatting">formatting option</a> is
784 used to construct programs that use "interpreter style" option processing.  With
785 this style of option processing, all arguments specified after the last
786 positional argument are treated as special interpreter arguments that are not
787 interpreted by the command line argument.<p>
788
789 As a concrete example, lets say we are developing a replacement for the standard
790 Unix Bourne shell (<tt>/bin/sh</tt>).  To run <tt>/bin/sh</tt>, first you
791 specify options to the shell itself (like <tt>-x</tt> which turns on trace
792 output), then you specify the name of the script to run, then you specify
793 arguments to the script.  These arguments to the script are parsed by the bourne
794 shell command line option processor, but are not interpreted as options to the
795 shell itself.  Using the CommandLine library, we would specify this as:<p>
796
797 <pre>
798 <a href="#cl::opt">cl::opt</a>&lt;string&gt; Script(<a href="#cl::Positional">cl::Positional</a>, <a href="#cl::desc">cl::desc</a>("<i>&lt;input script&gt;</i>"), <a href="#cl::init">cl::init</a>("-"));
799 <a href="#cl::list">cl::list</a>&lt;string&gt;  Argv(<a href="#cl::ConsumeAfter">cl::ConsumeAfter</a>, <a href="#cl::desc">cl::desc</a>("<i>&lt;program arguments&gt;...</i>"));
800 <a href="#cl::opt">cl::opt</a>&lt;bool&gt;    Trace("<i>x</i>", <a href="#cl::desc">cl::desc</a>("<i>Enable trace output</i>"));
801 </pre><p>
802
803 which automatically provides the help output:<p>
804
805 <pre>
806 USAGE: spiffysh [options] <b>&lt;input script&gt; &lt;program arguments&gt;...</b>
807
808 OPTIONS:
809   -help - display available options (--help-hidden for more)
810   <b>-x    - Enable trace output</b>
811 </pre><p>
812
813 At runtime, if we run our new shell replacement as '<tt>spiffysh -x test.sh -a
814 -x -y bar</tt>', the <tt>Trace</tt> variable will be set to true, the
815 <tt>Script</tt> variable will be set to "<tt>test.sh</tt>", and the
816 <tt>Argv</tt> list will contain <tt>["-a", "-x", "-y", "bar"]</tt>, because
817 they were specified after the last positional argument (which is the script
818 name).<p>
819
820 There are several limitations to when <tt>cl::ConsumeAfter</tt> options can be
821 specified.  For example, only one <tt>cl::ConsumeAfter</tt> can be specified per
822 program, there must be at least one <a href="#positional">positional
823 argument</a> specified, and the <tt>cl::ConsumeAfter</tt> option should be a <a
824 href="#cl::list">cl::list</a> option.<p>
825
826
827
828 <!-- ======================================================================= -->
829 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
830 <a name="storage">Internal vs External Storage
831 </b></font></td></tr></table><ul>
832
833 By default, all command line options automatically hold the value that they
834 parse from the command line.  This is very convenient in the common case,
835 especially when combined with the ability to define command line options in the
836 files that use them.  This is called the internal storage model.<p>
837
838 Sometimes, however, it is nice to separate the command line option processing
839 code from the storage of the value parsed.  For example, lets say that we have a
840 '<tt>-debug</tt>' option that we would like to use to enable debug information
841 across the entire body of our program.  In this case, the boolean value
842 controlling the debug code should be globally accessable (in a header file, for
843 example) yet the command line option processing code should not be exposed to
844 all of these clients (requiring lots of .cpp files to #include
845 <tt>CommandLine.h</tt>).<p>
846
847 To do this, set up your .h file with your option, like this for example:<p>
848
849 <pre>
850 <i>// DebugFlag.h - Get access to the '-debug' command line option
851 //
852
853 // DebugFlag - This boolean is set to true if the '-debug' command line option
854 // is specified.  This should probably not be referenced directly, instead, use
855 // the DEBUG macro below.
856 //</i>
857 extern bool DebugFlag;
858
859 <i>// DEBUG macro - This macro should be used by code to emit debug information.
860 // In the '-debug' option is specified on the command line, and if this is a
861 // debug build, then the code specified as the option to the macro will be
862 // executed.  Otherwise it will not be.  Example:
863 //
864 // DEBUG(cerr << "Bitset contains: " << Bitset << "\n");
865 //</i>
866 <font color=red>#ifdef NDEBUG
867 #define DEBUG(X)
868 #else
869 #define DEBUG(X)</font> \
870   do { if (DebugFlag) { X; } } while (0)
871 <font color=red>#endif</font>
872 </pre>
873
874 This allows clients to blissfully use the <tt>DEBUG()</tt> macro, or the
875 <tt>DebugFlag</tt> explicitly if they want to.  Now we just need to be able to
876 set the <tt>DebugFlag</tt> boolean when the option is set.  To do this, we pass
877 an additial argument to our command line argument processor, and we specify
878 where to fill in with the <a href="#cl::location">cl::location</a> attribute:<p>
879
880 <pre>
881 bool DebugFlag;      <i>// the actual value</i>
882 static <a href="#cl::opt">cl::opt</a>&lt;bool, true&gt;       <i>// The parser</i>
883 Debug("<i>debug</i>", <a href="#cl::desc">cl::desc</a>("<i>Enable debug output</i>")</a>, <a href="#cl::Hidden">cl::Hidden</a>,
884       <a href="#cl::location">cl::location</a>(DebugFlag));
885 </pre>
886
887 In the above example, we specify "<tt>true</tt>" as the second argument to the
888 <a href="#cl::opt">cl::opt</a> template, indicating that the template should not
889 maintain a copy of the value itself.  In addition to this, we specify the <a
890 href="#cl::location">cl::location</a> attribute, so that <tt>DebugFlag</tt> is
891 automatically set.<p>
892
893
894
895 <!-- ======================================================================= -->
896 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
897 <a name="attributes">Option Attributes
898 </b></font></td></tr></table><ul>
899
900 This section describes the basic attributes that you can specify on options.<p>
901
902 <ul>
903
904 <li>The option name attribute (which is required for all options, except <a
905 href="#positional">positional options</a>) specifies what the option name is.
906 This option is specified in simple double quotes:<p>
907
908 <pre>
909 <a href="#cl::opt">cl::opt</a>&lt;<b>bool</b>&gt; Quiet("<i>quiet</i>");
910 </pre><p>
911
912 <li><a name="cl::desc">The <b><tt>cl::desc</tt></b> attribute specifies a
913 description for the option to be shown in the <tt>--help</tt> output for the
914 program.<p>
915
916 <li><a name="cl::value_desc">The <b><tt>cl::value_desc</tt></b> attribute
917 specifies a string that can be used to fine tune the <tt>--help</tt> output for
918 a command line option.  Look <a href="#value_desc_example">here</a> for an
919 example.<p>
920
921 <li><a name="cl::init">The <b><tt>cl::init</tt></b> attribute specifies an
922 inital value for a <a href="#cl::opt">scalar</a> option.  If this attribute is
923 not specified then the command line option value defaults to the value created
924 by the default constructor for the type. <b>Warning</b>: If you specify both
925 <b><tt>cl::init</tt></b> and <b><tt>cl::location</tt></b> for an option,
926 you must specify <b><tt>cl::location</tt></b> first, so that when the
927 command-line parser sees <b><tt>cl::init</tt></b>, it knows where to put the
928 initial value. (You will get an error at runtime if you don't put them in
929 the right order.)<p>
930
931 <li><a name="cl::location">The <b><tt>cl::location</tt></b> attribute where to
932 store the value for a parsed command line option if using external storage.  See
933 the section on <a href="#storage">Internal vs External Storage</a> for more
934 information.<p>
935
936 <li><a name="cl::aliasopt">The <b><tt>cl::aliasopt</tt></b> attribute specifies
937 which option a <a href="#cl::alias">cl::alias</a> option is an alias for.<p>
938
939 <li><a name="cl::values">The <b><tt>cl::values</tt></b> attribute specifies the
940 string-to-value mapping to be used by the generic parser.  It takes a <b>null
941 terminated</b> list of (option, value, description) triplets that specify the
942 option name, the value mapped to, and the description shown in the
943 <tt>--help</tt> for the tool.  Because the generic parser is used most frequently with enum values, two macros are often useful:<p>
944 <ol>
945 <li><a name="clEnumVal">The <b><tt>clEnumVal</tt></b> macro is used as a nice
946 simple way to specify a triplet for an enum.  This macro automatically makes the
947 option name be the same as the enum name.  The first option to the macro is the
948 enum, the second is the description for the command line option.<p> <li><a
949 name="clEnumValN">The <b><tt>clEnumValN</tt></b> macro is used to specify macro
950 options where the option name doesn't equal the enum name.  For this macro, the
951 first argument is the enum value, the second is the flag name, and the second is
952 the description.<p>
953 </ol>
954
955 You will get a compile time error if you try to use cl::values with a parser
956 that does not support it.<p>
957
958 </ul>
959
960
961
962 <!-- ======================================================================= -->
963 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
964 <a name="modifiers">Option Modifiers
965 </b></font></td></tr></table><ul>
966
967 Option modifiers are the flags and expressions that you pass into the
968 constructors for <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
969 href="#cl::list">cl::list</a></tt>.  These modifiers give you the ability to
970 tweak how options are parsed and how <tt>--help</tt> output is generated to fit
971 your application well.<p>
972
973 These options fall into five main catagories:<p>
974
975 <ol>
976 <li><a href="#hiding">Hiding an option from <tt>--help</tt> output</a>
977 <li><a href="#numoccurances">Controlling the number of occurances
978                              required and allowed</a>
979 <li><a href="#valrequired">Controlling whether or not a value must be
980                            specified</a>
981 <li><a href="#formatting">Controlling other formatting options</a>
982 <li><a href="#misc">Miscellaneous option modifiers</a>
983 </ol><p>
984
985 It is not possible to specify two options from the same catagory (you'll get a
986 runtime error) to a single option, except for options in the miscellaneous
987 catagory.  The CommandLine library specifies defaults for all of these settings
988 that are the most useful in practice and the most common, which mean that you
989 usually shouldn't have to worry about these.<p>
990
991
992 <!-- _______________________________________________________________________ -->
993 </ul><a name="hiding"><h4><hr size=0>Hiding an option from <tt>--help</tt> output</h4><ul>
994
995 The <tt>cl::NotHidden</tt>, <tt>cl::Hidden</tt>, and <tt>cl::ReallyHidden</tt>
996 modifiers are used to control whether or not an option appears in the
997 <tt>--help</tt> and <tt>--help-hidden</tt> output for the compiled program:<p>
998
999 <ul>
1000
1001 <a name="cl::NotHidden">The <b><tt>cl::NotHidden</tt></b> modifier (which is the
1002 default for <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
1003 href="#cl::list">cl::list</a></tt> options), indicates the option is to appear
1004 in both help listings.<p>
1005
1006 <a name="cl::Hidden">The <b><tt>cl::Hidden</tt></b> modifier (which is the
1007 default for <tt><a href="#cl::alias">cl::alias</a></tt> options), indicates that
1008 the option should not appear in the <tt>--help</tt> output, but should appear in
1009 the <tt>--help-hidden</tt> output.<p>
1010
1011 <a name="cl::ReallyHidden">The <b><tt>cl::ReallyHidden</tt></b> modifier,
1012 indicates that the option should not appear in any help output.<p>
1013 </ul>
1014
1015 <!-- _______________________________________________________________________ -->
1016 </ul><a name="numoccurances"><h4><hr size=0>Controlling the number of occurances required and allowed</h4><ul>
1017
1018 This group of options is used to control how many time an option is allowed (or
1019 required) to be specified on the command line of your program.  Specifying a
1020 value for this setting allows the CommandLine library to do error checking for
1021 you.<p>
1022
1023 The allowed values for this option group are:<p>
1024
1025 <ul>
1026 <a name="cl::Optional">The <b><tt>cl::Optional</tt></b> modifier (which is the
1027 default for the <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
1028 href="#cl::alias">cl::alias</a></tt> classes) indicates that your program will
1029 allow either zero or one occurance of the option to be specified.<p>
1030
1031 <a name="cl::ZeroOrMore">The <b><tt>cl::ZeroOrMore</tt></b> modifier (which is
1032 the default for the <tt><a href="#cl::list">cl::list</a></tt> class) indicates
1033 that your program will allow the option to be specified zero or more times.<p>
1034
1035 <a name="cl::Required">The <b><tt>cl::Required</tt></b> modifier indicates that
1036 the specified option must be specified exactly one time.<p>
1037
1038 <a name="cl::OneOrMore">The <b><tt>cl::OneOrMore</tt></b> modifier indicates
1039 that the option must be specified at least one time.<p>
1040
1041 The <b><tt>cl::ConsumeAfter</tt></b> modifier is described in the <a
1042 href="#positional">Positional arguments section</a><p>
1043
1044 </ul>
1045
1046 If an option is not specified, then the value of the option is equal to the
1047 value specified by the <tt><a href="#cl::init">cl::init</a></tt> attribute.  If
1048 the <tt><a href="#cl::init">cl::init</a></tt> attribute is not specified, the
1049 option value is initialized with the default constructor for the data type.<p>
1050
1051 If an option is specified multiple times for an option of the <tt><a
1052 href="#cl::opt">cl::opt</a></tt> class, only the last value will be retained.<p>
1053
1054
1055 <!-- _______________________________________________________________________ -->
1056 </ul><a name="valrequired"><h4><hr size=0>Controlling whether or not a value must be specified</h4><ul>
1057
1058 This group of options is used to control whether or not the option allows a
1059 value to be present.  In the case of the CommandLine library, a value is either
1060 specified with an equal sign (e.g. '<tt>-index-depth=17</tt>') or as a trailing
1061 string (e.g. '<tt>-o a.out</tt>').<p>
1062
1063 The allowed values for this option group are:<p>
1064
1065 <ul>
1066 <a name="cl::ValueOptional">The <b><tt>cl::ValueOptional</tt></b> modifier
1067 (which is the default for <tt>bool</tt> typed options) specifies that it is
1068 acceptable to have a value, or not.  A boolean argument can be enabled just by
1069 appearing on the command line, or it can have an explicit '<tt>-foo=true</tt>'.
1070 If an option is specified with this mode, it is illegal for the value to be
1071 provided without the equal sign.  Therefore '<tt>-foo true</tt>' is illegal.  To
1072 get this behavior, you must use the <a
1073 href="#cl::ValueRequired">cl::ValueRequired</a> modifier.<p>
1074
1075 <a name="cl::ValueRequired">The <b><tt>cl::ValueRequired</tt></b> modifier
1076 (which is the default for all other types except for <a
1077 href="#onealternative">unnamed alternatives using the generic parser</a>)
1078 specifies that a value must be provided.  This mode informs the command line
1079 library that if an option is not provides with an equal sign, that the next
1080 argument provided must be the value.  This allows things like '<tt>-o
1081 a.out</tt>' to work.<p>
1082
1083 <a name="cl::ValueDisallowed">The <b><tt>cl::ValueDisallowed</tt></b> modifier
1084 (which is the default for <a href="#onealternative">unnamed alternatives using
1085 the generic parser</a>) indicates that it is a runtime error for the user to specify a value.  This can be provided to disallow users from providing options to boolean options (like '<tt>-foo=true</tt>').<p>
1086
1087 </ul>
1088
1089 In general, the default values for this option group work just like you would
1090 want them to.  As mentioned above, you can specify the <a
1091 href="#cl::ValueDisallowed">cl::ValueDisallowed</a> modifier to a boolean
1092 argument to restrict your command line parser.  These options are mostly useful
1093 when <a href="#extensionguide">extending the library</a>.<p>
1094
1095
1096
1097 <!-- _______________________________________________________________________ -->
1098 </ul><a name="formatting"><h4><hr size=0>Controlling other formatting options</h4><ul>
1099
1100 The formatting option group is used to specify that the command line option has
1101 special abilities and is otherwise different from other command line arguments.
1102 As usual, you can only specify at most one of these arguments.<p>
1103
1104 <ul>
1105 <a name="cl::NormalFormatting">The <b><tt>cl::NormalFormatting</tt></b> modifier
1106 (which is the default all options) specifies that this option is "normal".<p>
1107
1108 <a name="cl::Positional">The <b><tt>cl::Positional</tt></b> modifier specifies
1109 that this is a positional argument, that does not have a command line option
1110 associated with it.  See the <a href="#positional">Positional Arguments</a>
1111 section for more information.<p>
1112
1113 The <b><a href="#cl::ConsumeAfter"><tt>cl::ConsumeAfter</tt></a></b> modifier
1114 specifies that this option is used to capture "interpreter style" arguments.  See <a href="#cl::ConsumeAfter">this section for more information</a>.<p>
1115
1116
1117 <a name="cl::Prefix">The <b><tt>cl::Prefix</tt></b> modifier specifies that this
1118 option prefixes its value.  With 'Prefix' options, there is no equal sign that
1119 separates the value from the option name specified.  This is useful for
1120 processing odd arguments like '<tt>-lmalloc -L/usr/lib'</tt> in a linker tool.
1121 Here, the '<tt>l</tt>' and '<tt>L</tt>' options are normal string (list)
1122 options, that have the <a href="#cl::Prefix">cl::Prefix</a> modifier added to
1123 allow the CommandLine library to recognize them.  Note that <a
1124 href="#cl::Prefix">cl::Prefix</a> options must not have the <a
1125 href="#cl::ValueDisallowed">cl::ValueDisallowed</a> modifier specified.<p>
1126
1127 <a name="cl::Grouping">The <b><tt>cl::Grouping</tt></b> modifier is used to
1128 implement unix style tools (like <tt>ls</tt>) that have lots of single letter
1129 arguments, but only require a single dash.  For example, the '<tt>ls -labF</tt>'
1130 command actually enables four different options, all of which are single
1131 letters.  Note that <a href="#cl::Grouping">cl::Grouping</a> options cannot have
1132 values.<p>
1133
1134 </ul>
1135
1136 The CommandLine library does not restrict how you use the <a
1137 href="#cl::Prefix">cl::Prefix</a> or <a href="#cl::Grouping">cl::Grouping</a>
1138 modifiers, but it is possible to specify ambiguous argument settings.  Thus, it
1139 is possible to have multiple letter options that are prefix or grouping options,
1140 and they will still work as designed.<p>
1141
1142 To do this, the CommandLine library uses a greedy algorithm to parse the input
1143 option into (potentially multiple) prefix and grouping options.  The strategy
1144 basically looks like this:<p>
1145
1146 <tt>parse(string OrigInput) {</tt>
1147 <ol>
1148 <li><tt>string input = OrigInput;</tt>
1149 <li><tt>if (isOption(input)) return getOption(input).parse();</tt>&nbsp;&nbsp;&nbsp;&nbsp;<i>// Normal option</i>
1150 <li><tt>while (!isOption(input) &amp;&amp; !input.empty()) input.pop_back();</tt>&nbsp;&nbsp;&nbsp;&nbsp;<i>// Remove the last letter</i>
1151 <li><tt>if (input.empty()) return error();</tt>&nbsp;&nbsp;&nbsp;&nbsp;<i>// No matching option</i>
1152 <li><tt>if (getOption(input).isPrefix())<br>
1153 &nbsp;&nbsp;return getOption(input).parse(input);</tt>
1154 <li><tt>while (!input.empty()) {&nbsp;&nbsp;&nbsp;&nbsp;<i>// Must be grouping options</i><br>
1155 &nbsp;&nbsp;getOption(input).parse();<br>
1156 &nbsp;&nbsp;OrigInput.erase(OrigInput.begin(), OrigInput.begin()+input.length());<br>
1157 &nbsp;&nbsp;input = OrigInput;<br>
1158 &nbsp;&nbsp;while (!isOption(input) &amp;&amp; !input.empty()) input.pop_back();<br>
1159 }</tt>
1160 <li><tt>if (!OrigInput.empty()) error();</tt>
1161 </tt>
1162
1163 </ol>
1164 <tt>}</tt><p>
1165
1166
1167
1168 <!-- _______________________________________________________________________ -->
1169 </ul><a name="misc"><h4><hr size=0>Miscellaneous option modifiers</h4><ul>
1170
1171 The miscellaneous option modifiers are the only flags where you can specify more
1172 than one flag from the set: they are not mutually exclusive.  These flags
1173 specify boolean properties that modify the option.<p>
1174
1175 <ul>
1176
1177 <a name="cl::CommaSeparated">The <b><tt>cl::CommaSeparated</tt></b> modifier
1178 indicates that any commas specified for an option's value should be used to
1179 split the value up into multiple values for the option.  For example, these two
1180 options are equivalent when <tt>cl::CommaSeparated</tt> is specified:
1181 "<tt>-foo=a -foo=b -foo=c</tt>" and "<tt>-foo=a,b,c</tt>".  This option only
1182 makes sense to be used in a case where the option is allowed to accept one or
1183 more values (i.e. it is a <a href="#cl::list">cl::list</a> option).<p>
1184 </ul>
1185
1186 So far, the only miscellaneous option modifier is the
1187 <tt>cl::CommaSeparated</tt> modifier.<p>
1188
1189
1190 <!-- ======================================================================= -->
1191 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
1192 <a name="toplevel">Top-Level Classes and Functions
1193 </b></font></td></tr></table><ul>
1194
1195 Despite all of the builtin flexibility, the CommandLine option library really
1196 only consists of one function (<a
1197 href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>)
1198 and three main classes: <a href="#cl::opt"><tt>cl::opt</tt></a>, <a
1199 href="#cl::list"><tt>cl::list</tt></a>, and <a
1200 href="#cl::alias"><tt>cl::alias</tt></a>.  This section describes these three
1201 classes in detail.<p>
1202
1203 <!-- _______________________________________________________________________ -->
1204 </ul><a name="cl::ParseCommandLineOptions"><h4><hr size=0>The
1205 <tt>cl::ParseCommandLineOptions</tt> function</h4><ul>
1206
1207 The <tt>cl::ParseCommandLineOptions</tt> function is designed to be called
1208 directly from <tt>main</tt>, and is used to fill in the values of all of the
1209 command line option variables once <tt>argc</tt> and <tt>argv</tt> are
1210 available.<p>
1211
1212 The <tt>cl::ParseCommandLineOptions</tt> function requires two parameters
1213 (<tt>argc</tt> and <tt>argv</tt>), but may also take an optional third parameter
1214 which holds <a href="#description">additional extra text</a> to emit when the
1215 <tt>--help</tt> option is invoked.<p>
1216
1217
1218 <!-- _______________________________________________________________________ -->
1219 </ul><a name="cl::ParseEnvironmentOptions"><h4><hr size=0>The
1220 <tt>cl::ParseEnvironmentOptions</tt> function</h4><ul>
1221
1222 The <tt>cl::ParseEnvironmentOptions</tt>
1223 function has mostly the same effects as
1224 <a href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>,
1225 except that it is designed to take values for options from an
1226 environment variable, for those cases in which reading the
1227 command line is not convenient or not desired. It fills in
1228 the values of all the command line option variables just like
1229 <a href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>
1230 does.<p>
1231
1232 It takes three parameters: first, the name of the program (since <tt>argv</tt>
1233 may not be available, it can't just look in <tt>argv[0]</tt>), second,
1234 the name of the environment variable to examine, and third, the optional
1235 <a href="#description">additional extra text</a> to emit when the
1236 <tt>--help</tt> option is invoked.<p>
1237
1238 <tt>cl::ParseEnvironmentOptions</tt> will break the environment
1239 variable's value up into words and then process them using
1240 <a href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>.
1241 <b>Note:</b> Currently <tt>cl::ParseEnvironmentOptions</tt> does not support
1242 quoting, so an environment variable containing <tt>-option "foo bar"</tt> will
1243 be parsed as three words, <tt>-option</tt>, <tt>"foo</tt>, and <tt>bar"</tt>,
1244 which is different from what you would get from the shell with the same
1245 input.<p>
1246
1247 <!-- _______________________________________________________________________ -->
1248 </ul><a name="cl::opt"><h4><hr size=0>The <tt>cl::opt</tt> class</h4><ul>
1249
1250 The <tt>cl::opt</tt> class is the class used to represent scalar command line
1251 options, and is the one used most of the time.  It is a templated class which
1252 can take up to three arguments (all except for the first have default values
1253 though):<p>
1254
1255 <pre>
1256 <b>namespace</b> cl {
1257   <b>template</b> &lt;<b>class</b> DataType, <b>bool</b> ExternalStorage = <b>false</b>,
1258             <b>class</b> ParserClass = parser&lt;DataType&gt; &gt;
1259   <b>class</b> opt;
1260 }
1261 </pre><p>
1262
1263 The first template argument specifies what underlying data type the command line
1264 argument is, and is used to select a default parser implementation.  The second
1265 template argument is used to specify whether the option should contain the
1266 storage for the option (the default) or whether external storage should be used
1267 to contain the value parsed for the option (see <a href="#storage">Internal vs
1268 External Storage</a> for more information).<p>
1269
1270 The third template argument specifies which parser to use.  The default value
1271 selects an instantiation of the <tt>parser</tt> class based on the underlying
1272 data type of the option.  In general, this default works well for most
1273 applications, so this option is only used when using a <a
1274 href="#customparser">custom parser</a>.<p>
1275
1276
1277 <!-- _______________________________________________________________________ -->
1278 </ul><a name="cl::list"><h4><hr size=0>The <tt>cl::list</tt> class</h4><ul>
1279
1280 The <tt>cl::list</tt> class is the class used to represent a list of command
1281 line options.  It too is a templated class which can take up to three
1282 arguments:<p>
1283
1284 <pre>
1285 <b>namespace</b> cl {
1286   <b>template</b> &lt;<b>class</b> DataType, <b>class</b> Storage = <b>bool</b>,
1287             <b>class</b> ParserClass = parser&lt;DataType&gt; &gt;
1288   <b>class</b> list;
1289 }
1290 </pre><p>
1291
1292 This class works the exact same as the <a href="#cl::opt"><tt>cl::opt</tt></a>
1293 class, except that the second argument is the <b>type</b> of the external
1294 storage, not a boolean value.  For this class, the marker type '<tt>bool</tt>'
1295 is used to indicate that internal storage should be used.<p>
1296
1297
1298 <!-- _______________________________________________________________________ -->
1299 </ul><a name="cl::alias"><h4><hr size=0>The <tt>cl::alias</tt> class</h4><ul>
1300
1301 The <tt>cl::alias</tt> class is a nontemplated class that is used to form
1302 aliases for other arguments.<p>
1303
1304 <pre>
1305 <b>namespace</b> cl {
1306   <b>class</b> alias;
1307 }
1308 </pre></p>
1309
1310 The <a href="#cl::aliasopt"><tt>cl::aliasopt</tt></a> attribute should be used
1311 to specify which option this is an alias for.  Alias arguments default to being
1312 <a href="#cl::Hidden">Hidden</a>, and use the aliased options parser to do the
1313 conversion from string to data.<p>
1314
1315
1316 <!-- ======================================================================= -->
1317 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
1318 <a name="builtinparsers">Builtin parsers
1319 </b></font></td></tr></table><ul>
1320
1321 Parsers control how the string value taken from the command line is translated
1322 into a typed value, suitable for use in a C++ program.  By default, the
1323 CommandLine library uses an instance of <tt>parser&lt;type&gt;</tt> if the
1324 command line option specifies that it uses values of type '<tt>type</tt>'.
1325 Because of this, custom option processing is specified with specializations of
1326 the '<tt>parser</tt>' class.<p>
1327
1328 The CommandLine library provides the following builtin parser specializations,
1329 which are sufficient for most applications. It can, however, also be extended to
1330 work with new data types and new ways of interpreting the same data.  See the <a
1331 href="#customparser">Writing a Custom Parser</a> for more details on this type
1332 of library extension.<p>
1333
1334 <li><a name="genericparser">The <b>generic <tt>parser&lt;t&gt;</tt> parser</b>
1335 can be used to map strings values to any data type, through the use of the <a
1336 href="#cl::values">cl::values</a> property, which specifies the mapping
1337 information.  The most common use of this parser is for parsing enum values,
1338 which allows you to use the CommandLine library for all of the error checking to
1339 make sure that only valid enum values are specified (as opposed to accepting
1340 arbitrary strings).  Despite this, however, the generic parser class can be used
1341 for any data type.<p>
1342
1343 <li><a name="boolparser">The <b><tt>parser&lt;bool&gt;</tt> specialization</b>
1344 is used to convert boolean strings to a boolean value.  Currently accepted
1345 strings are "<tt>true</tt>", "<tt>TRUE</tt>", "<tt>True</tt>", "<tt>1</tt>",
1346 "<tt>false</tt>", "<tt>FALSE</tt>", "<tt>False</tt>", and "<tt>0</tt>".<p>
1347
1348 <li><a name="stringparser">The <b><tt>parser&lt;string&gt;</tt> specialization</b> simply stores the parsed string into the string value specified.  No conversion or modification of the data is performed.<p>
1349
1350 <li><a name="intparser">The <b><tt>parser&lt;int&gt;</tt> specialization</b>
1351 uses the C <tt>strtol</tt> function to parse the string input.  As such, it will
1352 accept a decimal number (with an optional '+' or '-' prefix) which must start
1353 with a non-zero digit.  It accepts octal numbers, which are identified with a
1354 '<tt>0</tt>' prefix digit, and hexadecimal numbers with a prefix of
1355 '<tt>0x</tt>' or '<tt>0X</tt>'.<p>
1356
1357 <li><a name="doubleparser">The <b><tt>parser&lt;double&gt;</tt></b> and
1358 <b><tt>parser&lt;float&gt;</tt> specializations</b> use the standard C
1359 <tt>strtod</tt> function to convert floating point strings into floating point
1360 values.  As such, a broad range of string formats is supported, including
1361 exponential notation (ex: <tt>1.7e15</tt>) and properly supports locales.
1362 <p>
1363
1364
1365
1366 <!-- *********************************************************************** -->
1367 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0><tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
1368 <a name="extensionguide">Extension Guide
1369 </b></font></td></tr></table><ul>
1370 <!-- *********************************************************************** -->
1371
1372 Although the CommandLine library has a lot of functionality built into it
1373 already (as discussed previously), one of its true strengths lie in its
1374 extensibility.  This section discusses how the CommandLine library works under
1375 the covers and illustrates how to do some simple, common, extensions.<p>
1376
1377
1378 <!-- ======================================================================= -->
1379 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1380 <tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF"
1381 face="Georgia,Palatino"><b> <a name="customparser">Writing a custom parser
1382 </b></font></td></tr></table><ul>
1383
1384 One of the simplest and most common extensions is the use of a custom parser.
1385 As <a href="#builtinparsers">discussed previously</a>, parsers are the portion
1386 of the CommandLine library that turns string input from the user into a
1387 particular parsed data type, validating the input in the process.<p>
1388
1389 There are two ways to use a new parser:<p>
1390
1391 <ol>
1392 <li>Specialize the <a href="#genericparser"><tt>cl::parser</tt></a> template for
1393     your custom data type.<p>
1394
1395     This approach has the advantage that users of your custom data type will
1396     automatically use your custom parser whenever they define an option with a
1397     value type of your data type.  The disadvantage of this approach is that it
1398     doesn't work if your fundemental data type is something that is already
1399     supported.<p>
1400
1401 <li>Write an independent class, using it explicitly from options that need
1402     it.<p>
1403
1404     This approach works well in situations where you would line to parse an
1405     option using special syntax for a not-very-special data-type.  The drawback
1406     of this approach is that users of your parser have to be aware that they are
1407     using your parser, instead of the builtin ones.<p>
1408
1409 </ol><p>
1410
1411 To guide the discussion, we will discuss a custom parser that accepts file
1412 sizes, specified with an optional unit after the numeric size.  For example, we
1413 would like to parse "102kb", "41M", "1G" into the appropriate integer value.  In
1414 this case, the underlying data type we want to parse into is
1415 '<tt>unsigned</tt>'.  We choose approach #2 above because we don't want to make
1416 this the default for all <tt>unsigned</tt> options.<p>
1417
1418 To start out, we declare our new <tt>FileSizeParser</tt> class:<p>
1419
1420 <pre>
1421 <b>struct</b> FileSizeParser : <b>public</b> cl::basic_parser&lt;<b>unsigned</b>&gt; {
1422   <i>// parse - Return true on error.</i>
1423   <b>bool</b> parse(cl::Option &amp;O, <b>const char</b> *ArgName, <b>const</b> std::string &amp;ArgValue,
1424              <b>unsigned</b> &amp;Val);
1425 };
1426 </pre><p>
1427
1428 Our new class inherits from the <tt>cl::basic_parser</tt> template class to fill
1429 in the default, boiler plate, code for us.  We give it the data type that we
1430 parse into (the last argument to the <tt>parse</tt> method so that clients of
1431 our custom parser know what object type to pass in to the parse method (here we
1432 declare that we parse into '<tt>unsigned</tt>' variables.<p>
1433
1434 For most purposes, the only method that must be implemented in a custom parser
1435 is the <tt>parse</tt> method.  The <tt>parse</tt> method is called whenever the
1436 option is invoked, passing in the option itself, the option name, the string to
1437 parse, and a reference to a return value.  If the string to parse is not well formed, the parser should output an error message and return true.  Otherwise it should return false and set '<tt>Val</tt>' to the parsed value.  In our example, we implement <tt>parse</tt> as:<p>
1438
1439 <pre>
1440 <b>bool</b> FileSizeParser::parse(cl::Option &amp;O, <b>const char</b> *ArgName,
1441                            <b>const</b> std::string &amp;Arg, <b>unsigned</b> &amp;Val) {
1442   <b>const char</b> *ArgStart = Arg.c_str();
1443   <b>char</b> *End;
1444  
1445   <i>// Parse integer part, leaving 'End' pointing to the first non-integer char</i>
1446   Val = (unsigned)strtol(ArgStart, &amp;End, 0);
1447
1448   <b>while</b> (1) {
1449     <b>switch</b> (*End++) {
1450     <b>case</b> 0: <b>return</b> false;   <i>// No error</i>
1451     <b>case</b> 'i':               <i>// Ignore the 'i' in KiB if people use that</i>
1452     <b>case</b> 'b': <b>case</b> 'B':     <i>// Ignore B suffix</i>
1453       <b>break</b>;
1454
1455     <b>case</b> 'g': <b>case</b> 'G': Val *= 1024*1024*1024; <b>break</b>;
1456     <b>case</b> 'm': <b>case</b> 'M': Val *= 1024*1024;      <b>break</b>;
1457     <b>case</b> 'k': <b>case</b> 'K': Val *= 1024;           <b>break</b>;
1458
1459     default:
1460       <i>// Print an error message if unrecognized character!</i>
1461       <b>return</b> O.error(": '" + Arg + "' value invalid for file size argument!");
1462     }
1463   }
1464 }
1465 </pre><p>
1466
1467 This function implements a very simple parser for the kinds of strings we are
1468 interested in.  Although it has some holes (it allows "<tt>123KKK</tt>" for
1469 example), it is good enough for this example.  Note that we use the option
1470 itself to print out the error message (the <tt>error</tt> method always returns
1471 true) in order to get a nice error message (shown below).  Now that we have our
1472 parser class, we can use it like this:<p>
1473
1474 <pre>
1475 <b>static</b> <a href="#cl::opt">cl::opt</a>&lt;<b>unsigned</b>, <b>false</b>, FileSizeParser&gt;
1476 MFS(<i>"max-file-size"</i>, <a href="#cl::desc">cl::desc</a>(<i>"Maximum file size to accept"</i>),
1477     <a href="#cl::value_desc">cl::value_desc</a>("<i>size</i>"));
1478 </pre><p>
1479
1480 Which adds this to the output of our program:<p>
1481
1482 <pre>
1483 OPTIONS:
1484   -help                 - display available options (--help-hidden for more)
1485   ...
1486   <b>-max-file-size=&lt;size&gt; - Maximum file size to accept</b>
1487 </pre><p>
1488
1489 And we can test that our parse works correctly now (the test program just prints
1490 out the max-file-size argument value):<p>
1491
1492 <pre>
1493 $ ./test
1494 MFS: 0
1495 $ ./test -max-file-size=123MB
1496 MFS: 128974848
1497 $ ./test -max-file-size=3G
1498 MFS: 3221225472
1499 $ ./test -max-file-size=dog
1500 -max-file-size option: 'dog' value invalid for file size argument!
1501 </pre><p>
1502
1503 It looks like it works.  The error message that we get is nice and helpful, and
1504 we seem to accept reasonable file sizes.  This wraps up the "custom parser"
1505 tutorial.<p>
1506
1507
1508 <!-- ======================================================================= -->
1509 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1510 <tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF"
1511 face="Georgia,Palatino"><b> <a name="explotingexternal">Exploiting external
1512 storage </b></font></td></tr></table><ul>
1513
1514
1515
1516 <!-- ======================================================================= -->
1517 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1518 <tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF"
1519 face="Georgia,Palatino"><b> <a name="dynamicopts">Dynamically adding command
1520 line options </b></font></td></tr></table><ul>
1521
1522
1523
1524
1525
1526 <!-- *********************************************************************** -->
1527 </ul>
1528 <!-- *********************************************************************** -->
1529
1530 <hr>
1531 <font size=-1>
1532 <address><a href="mailto:sabre@nondot.org">Chris Lattner</a></address>
1533 <!-- Created: Tue Jan 23 15:19:28 CST 2001 -->
1534 <!-- hhmts start -->
1535 Last modified: Fri Aug  1 16:30:11 CDT 2003
1536 <!-- hhmts end -->
1537 </font>
1538 </body></html>