blob: fc66091a2b34d8f8a0b0ea27e3b86ef6759c6734 [file] [log] [blame]
Chris Lattner209c7f42001-07-23 23:03:12 +00001<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
Chris Lattnerae853632002-07-25 19:27:01 +00002<html><head><title>CommandLine 2.0 Library Manual</title></head>
Chris Lattner209c7f42001-07-23 23:03:12 +00003<body bgcolor=white>
4
5<table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
Chris Lattnere76d4ab2002-08-06 19:36:06 +00006<tr><td>&nbsp; <font size=+3 color="#EEEEFF" face="Georgia,Palatino,Times,Roman"><b>CommandLine 2.0 Library Manual</b></font></td>
Chris Lattner209c7f42001-07-23 23:03:12 +00007</tr></table>
8
9<ol>
10 <li><a href="#introduction">Introduction</a>
11 <li><a href="#quickstart">Quick Start Guide</a>
12 <ol>
Chris Lattnerae853632002-07-25 19:27:01 +000013 <li><a href="#bool">Boolean Arguments</a>
14 <li><a href="#alias">Argument Aliases</a>
Chris Lattnere76d4ab2002-08-06 19:36:06 +000015 <li><a href="#onealternative">Selecting an alternative from a
16 set of possibilities</a>
Chris Lattner209c7f42001-07-23 23:03:12 +000017 <li><a href="#namedalternatives">Named alternatives</a>
Chris Lattnerae853632002-07-25 19:27:01 +000018 <li><a href="#list">Parsing a list of options</a>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +000019 <li><a href="#description">Adding freeform text to help output</a>
Chris Lattner209c7f42001-07-23 23:03:12 +000020 </ol>
21 <li><a href="#referenceguide">Reference Guide</a>
Chris Lattnerae853632002-07-25 19:27:01 +000022 <ol>
Chris Lattnere76d4ab2002-08-06 19:36:06 +000023 <li><a href="#positional">Positional Arguments</a>
Chris Lattnerae853632002-07-25 19:27:01 +000024 <ul>
Chris Lattnere76d4ab2002-08-06 19:36:06 +000025 <li><a href="#--">Specifying positional options with hyphens</a>
26 <li><a href="#cl::ConsumeAfter">The <tt>cl::ConsumeAfter</tt>
27 modifier</a>
Chris Lattnerae853632002-07-25 19:27:01 +000028 </ul>
Chris Lattnere76d4ab2002-08-06 19:36:06 +000029 <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>
Chris Lattnerae853632002-07-25 19:27:01 +000032 <ul>
Chris Lattnere76d4ab2002-08-06 19:36:06 +000033 <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 </ul>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +000040 <li><a href="#toplevel">Top-Level Classes and Functions</a>
Chris Lattnere76d4ab2002-08-06 19:36:06 +000041 <ul>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +000042 <li><a href="#cl::ParseCommandLineOptions">The
43 <tt>cl::ParseCommandLineOptions</tt> function</a>
Chris Lattnere76d4ab2002-08-06 19:36:06 +000044 <li><a href="#cl::opt">The <tt>cl::opt</tt> class</a>
45 <li><a href="#cl::list">The <tt>cl::list</tt> class</a>
46 <li><a href="#cl::alias">The <tt>cl::alias</tt> class</a>
47 </ul>
48 <li><a href="#builtinparsers">Builtin parsers</a>
49 <ul>
50 <li><a href="#genericparser">The Generic <tt>parser&lt;t&gt;</tt>
51 parser</a>
52 <li><a href="#boolparser">The <tt>parser&lt;bool&gt;</tt>
53 specialization</a>
54 <li><a href="#stringparser">The <tt>parser&lt;string&gt;</tt>
55 specialization</a>
56 <li><a href="#intparser">The <tt>parser&lt;int&gt;</tt>
57 specialization</a>
58 <li><a href="#doubleparser">The <tt>parser&lt;double&gt;</tt> and
59 <tt>parser&lt;float&gt;</tt> specializations</a>
Chris Lattnerae853632002-07-25 19:27:01 +000060 </ul>
61 </ol>
Chris Lattner209c7f42001-07-23 23:03:12 +000062 <li><a href="#extensionguide">Extension Guide</a>
Chris Lattnerae853632002-07-25 19:27:01 +000063 <ol>
Chris Lattnere76d4ab2002-08-06 19:36:06 +000064 <li><a href="#customparser">Writing a custom parser</a>
65 <li><a href="#explotingexternal">Exploiting external storage</a>
66 <li><a href="#dynamicopts">Dynamically adding command line options</a>
Chris Lattnerae853632002-07-25 19:27:01 +000067 </ol>
Chris Lattnere76d4ab2002-08-06 19:36:06 +000068
69 <p><b>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></b><p>
Chris Lattner209c7f42001-07-23 23:03:12 +000070</ol><p>
71
72
73<!-- *********************************************************************** -->
Chris Lattnerc1ae40c2002-08-07 18:27:04 +000074<table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
Chris Lattner209c7f42001-07-23 23:03:12 +000075<tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
76<a name="introduction">Introduction
77</b></font></td></tr></table><ul>
78<!-- *********************************************************************** -->
79
Chris Lattnerae853632002-07-25 19:27:01 +000080This document describes the CommandLine argument processing library. It will
Chris Lattnere76d4ab2002-08-06 19:36:06 +000081show you how to use it, and what it can do. The CommandLine library uses a
82declarative approach to specifying the command line options that your program
83takes. By default, these options declarations implicitly hold the value parsed
84for the option declared (of course this <a href="#storage">can be
85changed</a>).<p>
Chris Lattner209c7f42001-07-23 23:03:12 +000086
Chris Lattnerae853632002-07-25 19:27:01 +000087Although there are a <b>lot</b> of command line argument parsing libraries out
88there in many different languages, none of them fit well with what I needed. By
89looking at the features and problems of other libraries, I designed the
90CommandLine library to have the following features:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +000091
92<ol>
Chris Lattnerae853632002-07-25 19:27:01 +000093<li>Speed: The CommandLine library is very quick and uses little resources. The
94parsing time of the library is directly proportional to the number of arguments
95parsed, not the the number of options recognized. Additionally, command line
96argument values are captured transparently into user defined variables, which
97can be accessed like any other variable (and with the same performance).<p>
Chris Lattner209c7f42001-07-23 23:03:12 +000098
Chris Lattnerae853632002-07-25 19:27:01 +000099<li>Type Safe: As a user of CommandLine, you don't have to worry about
100remembering the type of arguments that you want (is it an int? a string? a
101bool? an enum?) and keep casting it around. Not only does this help prevent
102error prone constructs, it also leads to dramatically cleaner source code.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000103
Chris Lattnerae853632002-07-25 19:27:01 +0000104<li>No subclasses required: To use CommandLine, you instantiate variables that
105correspond to the arguments that you would like to capture, you don't subclass a
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000106parser. This means that you don't have to write <b>any</b> boilerplate code.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000107
Chris Lattnerae853632002-07-25 19:27:01 +0000108<li>Globally accessible: Libraries can specify command line arguments that are
109automatically enabled in any tool that links to the library. This is possible
110because the application doesn't have to keep a "list" of arguments to pass to
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000111the parser. This also makes supporting <a href="#dynamicopts">dynamically
112loaded options</a> trivial.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000113
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000114<li>Cleaner: CommandLine supports enum and other types directly, meaning that
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000115there is less error and more security built into the library. You don't have to
116worry about whether your integral command line argument accidentally got
117assigned a value that is not valid for your enum type.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000118
Chris Lattnerae853632002-07-25 19:27:01 +0000119<li>Powerful: The CommandLine library supports many different types of
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000120arguments, from simple <a href="#boolparser">boolean flags</a> to <a
121href="#cl::opt">scalars arguments</a> (<a href="#stringparser">strings</a>, <a
122href="#intparser">integers</a>, <a href="#genericparser">enums</a>, <a
123href="#doubleparser">doubles</a>), to <a href="#cl::list">lists of
124arguments</a>. This is possible because CommandLine is...<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000125
Chris Lattnerae853632002-07-25 19:27:01 +0000126<li>Extensible: It is very simple to add a new argument type to CommandLine.
127Simply specify the parser that you want to use with the command line option when
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000128you declare it. <a href="#customparser">Custom parsers</a> are no problem.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000129
Chris Lattnerae853632002-07-25 19:27:01 +0000130<li>Labor Saving: The CommandLine library cuts down on the amount of grunt work
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000131that you, the user, have to do. For example, it automatically provides a
132<tt>--help</tt> option that shows the available command line options for your
133tool. Additionally, it does most of the basic correctness checking for you.<p>
134
135<li>Capable: The CommandLine library can handle lots of different forms of
136options often found in real programs. For example, <a
137href="#positional">positional</a> arguments, <tt>ls</tt> style <a
138href="#cl::Grouping">grouping</a> options (to allow processing '<tt>ls
139-lad</tt>' naturally), <tt>ld</tt> style <a href="#cl::Prefix">prefix</a>
140options (to parse '<tt>-lmalloc -L/usr/lib</tt>'), and <a
141href="#cl::ConsumeAfter">interpreter style options</a>.<p>
142
Chris Lattner209c7f42001-07-23 23:03:12 +0000143</ol>
144
Chris Lattnerae853632002-07-25 19:27:01 +0000145This document will hopefully let you jump in and start using CommandLine in your
146utility quickly and painlessly. Additionally it should be a simple reference
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000147manual to figure out how stuff works. If it is failing in some area (or you
148want an extension to the library), nag the author, <a
149href="mailto:sabre@nondot.org">Chris Lattner</a>.<p>
150
Chris Lattner209c7f42001-07-23 23:03:12 +0000151
152
153<!-- *********************************************************************** -->
154</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>
155<a name="quickstart">Quick Start Guide
156</b></font></td></tr></table><ul>
157<!-- *********************************************************************** -->
158
Chris Lattnerae853632002-07-25 19:27:01 +0000159This section of the manual runs through a simple CommandLine'ification of a
160basic compiler tool. This is intended to show you how to jump into using the
161CommandLine library in your own program, and show you some of the cool things it
162can do.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000163
Chris Lattnerae853632002-07-25 19:27:01 +0000164To start out, you need to include the CommandLine header file into your
165program:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000166
167<pre>
Chris Lattnerae853632002-07-25 19:27:01 +0000168 #include "Support/CommandLine.h"
Chris Lattner209c7f42001-07-23 23:03:12 +0000169</pre><p>
170
171Additionally, you need to add this as the first line of your main program:<p>
172
173<pre>
174int main(int argc, char **argv) {
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000175 <a href="#cl::ParseCommandLineOptions">cl::ParseCommandLineOptions</a>(argc, argv);
Chris Lattner209c7f42001-07-23 23:03:12 +0000176 ...
177}
178</pre><p>
179
Chris Lattnerae853632002-07-25 19:27:01 +0000180... which actually parses the arguments and fills in the variable
181declarations.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000182
Chris Lattnerae853632002-07-25 19:27:01 +0000183Now that you are ready to support command line arguments, we need to tell the
184system which ones we want, and what type of argument they are. The CommandLine
185library uses a declarative syntax to model cammand line arguments with the
186variable declarations that capture the parsed values. This means that for every
187command line option that you would like to support, there should be a variable
188declaration to capture the result. For example, in a compiler, we would like to
189support the unix standard '<tt>-o &lt;filename&gt;</tt>' option to specify where
190to put the output. With the CommandLine library, this is represented like
191this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000192
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000193<pre><a name="value_desc_example">
194<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>"));
Chris Lattner209c7f42001-07-23 23:03:12 +0000195</pre><p>
196
Chris Lattnerae853632002-07-25 19:27:01 +0000197This declares a variable "<tt>OutputFilename</tt>" that is used to capture the
198result of the "<tt>o</tt>" argument (first parameter). We specify that this is
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000199a simple scalar option by using the "<tt><a href="#cl::opt">cl::opt</a></tt>"
200template (as opposed to the <a href="#list">"<tt>cl::list</tt>
201template</a>), and tell the CommandLine library that the data type that we are
202parsing is a string.<p>
Chris Lattnerae853632002-07-25 19:27:01 +0000203
204The second and third parameters (which are optional) are used to specify what to
205output for the "<tt>--help</tt>" option. In this case, we get a line that looks
206like this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000207
208<pre>
Chris Lattnerae853632002-07-25 19:27:01 +0000209USAGE: compiler [options]
Chris Lattner209c7f42001-07-23 23:03:12 +0000210
Chris Lattnerae853632002-07-25 19:27:01 +0000211OPTIONS:
212 -help - display available options (--help-hidden for more)
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000213 <b>-o &lt;filename&gt; - Specify output filename</b>
Chris Lattnerae853632002-07-25 19:27:01 +0000214</pre>
215
216Because we specified that the command line option should parse using the
217<tt>string</tt> data type, the variable declared is automatically usable as a
218real string in all contexts that a normal C++ string object may be used. For
219example:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000220
221<pre>
222 ...
223 ofstream Output(OutputFilename.c_str());
224 if (Out.good()) ...
225 ...
226</pre><p>
227
Chris Lattnerae853632002-07-25 19:27:01 +0000228There are many different options that you can use to customize the command line
229option handling library, but the above example shows the general interface to
230these options. The options can be specified in any order, and are specified
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000231with helper functions like <a href="#cl::desc"><tt>cl::desc(...)</tt></a>, so
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000232there are no positional dependencies to remember. The available options are
233discussed in detail in the <a href="#referenceguide">Reference Guide</a>.<p>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000234
Chris Lattner209c7f42001-07-23 23:03:12 +0000235
Chris Lattnerae853632002-07-25 19:27:01 +0000236Continuing the example, we would like to have our compiler take an input
237filename as well as an output filename, but we do not want the input filename to
238be specified with a hyphen (ie, not <tt>-filename.c</tt>). To support this
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000239style of argument, the CommandLine library allows for <a
240href="#positional">positional</a> arguments to be specified for the program.
241These positional arguments are filled with command line parameters that are not
242in option form. We use this feature like this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000243
244<pre>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000245<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>"));
Chris Lattner209c7f42001-07-23 23:03:12 +0000246</pre>
247
Chris Lattnerae853632002-07-25 19:27:01 +0000248This declaration indicates that the first positional argument should be treated
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000249as the input filename. Here we use the <tt><a
250href="#cl::init">cl::init</a></tt> option to specify an initial value for the
251command line option, which is used if the option is not specified (if you do not
252specify a <tt><a href="#cl::init">cl::init</a></tt> modifier for an option, then
253the default constructor for the data type is used to initialize the value).
Chris Lattnerae853632002-07-25 19:27:01 +0000254Command line options default to being optional, so if we would like to require
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000255that the user always specify an input filename, we would add the <tt><a
256href="#cl::Required">cl::Required</a></tt> flag, and we could eliminate the
257<tt><a href="#cl::init">cl::init</a></tt> modifier, like this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000258
259<pre>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000260<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>);
Chris Lattner209c7f42001-07-23 23:03:12 +0000261</pre>
262
Chris Lattnerae853632002-07-25 19:27:01 +0000263Again, the CommandLine library does not require the options to be specified in
264any particular order, so the above declaration is equivalent to:<p>
265
266<pre>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000267<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>"));
Chris Lattnerae853632002-07-25 19:27:01 +0000268</pre>
269
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000270By simply adding the <tt><a href="#cl::Required">cl::Required</a></tt> flag, the
271CommandLine library will automatically issue an error if the argument is not
272specified, which shifts all of the command line option verification code out of
273your application into the library. This is just one example of how using flags
274can alter the default behaviour of the library, on a per-option basis. By
275adding one of the declarations above, the <tt>--help</tt> option synopsis is now
276extended to:<p>
Chris Lattnerae853632002-07-25 19:27:01 +0000277
278<pre>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000279USAGE: compiler [options] <b>&lt;input file&gt;</b>
Chris Lattnerae853632002-07-25 19:27:01 +0000280
281OPTIONS:
282 -help - display available options (--help-hidden for more)
283 -o &lt;filename&gt; - Specify output filename
284</pre>
285
286... indicating that an input filename is expected.<p>
287
Chris Lattner209c7f42001-07-23 23:03:12 +0000288
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000289
Chris Lattner209c7f42001-07-23 23:03:12 +0000290<!-- ======================================================================= -->
291</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>
Chris Lattnerae853632002-07-25 19:27:01 +0000292<a name="bool">Boolean Arguments
Chris Lattner209c7f42001-07-23 23:03:12 +0000293</b></font></td></tr></table><ul>
294
Chris Lattnerae853632002-07-25 19:27:01 +0000295In addition to input and output filenames, we would like the compiler example to
296support three boolean flags: "<tt>-f</tt>" to force overwriting of the output
297file, "<tt>--quiet</tt>" to enable quiet mode, and "<tt>-q</tt>" for backwards
298compatibility with some of our users. We can support these by declaring options
299of boolean type like this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000300
301<pre>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000302<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>"));
303<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>"));
304<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>);
Chris Lattner209c7f42001-07-23 23:03:12 +0000305</pre><p>
306
Chris Lattnerae853632002-07-25 19:27:01 +0000307This does what you would expect: it declares three boolean variables
308("<tt>Force</tt>", "<tt>Quiet</tt>", and "<tt>Quiet2</tt>") to recognize these
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000309options. Note that the "<tt>-q</tt>" option is specified with the "<a
310href="#cl::Hidden"><tt>cl::Hidden</tt></a>" flag. This modifier prevents it
311from being shown by the standard "<tt>--help</tt>" output (note that it is still
312shown in the "<tt>--help-hidden</tt>" output).<p>
Chris Lattnerae853632002-07-25 19:27:01 +0000313
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000314The CommandLine library uses a <a href="#builtinparsers">different parser</a>
315for different data types. For example, in the string case, the argument passed
316to the option is copied literally into the content of the string variable... we
317obviously cannot do that in the boolean case, however, so we must use a smarter
318parser. In the case of the boolean parser, it allows no options (in which case
319it assigns the value of true to the variable), or it allows the values
320"<tt>true</tt>" or "<tt>false</tt>" to be specified, allowing any of the
321following inputs:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000322
323<pre>
Chris Lattnerae853632002-07-25 19:27:01 +0000324 compiler -f # No value, 'Force' == true
325 compiler -f=true # Value specified, 'Force' == true
326 compiler -f=TRUE # Value specified, 'Force' == true
327 compiler -f=FALSE # Value specified, 'Force' == false
328</pre>
329
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000330... you get the idea. The <a href="#boolparser">bool parser</a> just turns the
331string values into boolean values, and rejects things like '<tt>compiler
332-f=foo</tt>'. Similarly, the <a href="#doubleparser">float</a>, <a
333href="#doubleparser">double</a>, and <a href="#intparser">int</a> parsers work
334like you would expect, using the '<tt>strtol</tt>' and '<tt>strtod</tt>' C
335library calls to parse the string value into the specified data type.<p>
Chris Lattnerae853632002-07-25 19:27:01 +0000336
337With the declarations above, "<tt>compiler --help</tt>" emits this:<p>
338
339<pre>
340USAGE: compiler [options] &lt;input file&gt;
Chris Lattner209c7f42001-07-23 23:03:12 +0000341
342OPTIONS:
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000343 <b>-f - Overwrite output files</b>
Chris Lattner209c7f42001-07-23 23:03:12 +0000344 -o - Override output filename
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000345 <b>-quiet - Don't print informational messages</b>
Chris Lattner209c7f42001-07-23 23:03:12 +0000346 -help - display available options (--help-hidden for more)
347</pre><p>
348
Chris Lattnerae853632002-07-25 19:27:01 +0000349and "<tt>opt --help-hidden</tt>" prints this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000350
351<pre>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000352USAGE: compiler [options] &lt;input file&gt;
Chris Lattner209c7f42001-07-23 23:03:12 +0000353
354OPTIONS:
355 -f - Overwrite output files
356 -o - Override output filename
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000357 <b>-q - Don't print informational messages</b>
Chris Lattner209c7f42001-07-23 23:03:12 +0000358 -quiet - Don't print informational messages
359 -help - display available options (--help-hidden for more)
360</pre><p>
361
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000362This brief example has shown you how to use the '<tt><a
363href="#cl::opt">cl::opt</a></tt>' class to parse simple scalar command line
364arguments. In addition to simple scalar arguments, the CommandLine library also
365provides primitives to support CommandLine option <a href="#alias">aliases</a>,
366and <a href="#list">lists</a> of options.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000367
368
369<!-- ======================================================================= -->
370</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>
Chris Lattnerae853632002-07-25 19:27:01 +0000371<a name="alias">Argument Aliases
Chris Lattner209c7f42001-07-23 23:03:12 +0000372</b></font></td></tr></table><ul>
373
Chris Lattnerae853632002-07-25 19:27:01 +0000374So far, the example works well, except for the fact that we need to check the
375quiet condition like this now:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000376
377<pre>
378...
379 if (!Quiet &amp;&amp; !Quiet2) printInformationalMessage(...);
380...
381</pre><p>
382
Chris Lattnerae853632002-07-25 19:27:01 +0000383... which is a real pain! Instead of defining two values for the same
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000384condition, we can use the "<tt><a href="#cl::alias">cl::alias</a></tt>" class to make the "<tt>-q</tt>"
Chris Lattnerae853632002-07-25 19:27:01 +0000385option an <b>alias</b> for the "<tt>-quiet</tt>" option, instead of providing
386a value itself:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000387
388<pre>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000389<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>"));
390<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>"));
391<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));
Chris Lattner209c7f42001-07-23 23:03:12 +0000392</pre><p>
393
Chris Lattnerae853632002-07-25 19:27:01 +0000394The third line (which is the only one we modified from above) defines a
395"<tt>-q</tt> alias that updates the "<tt>Quiet</tt>" variable (as specified by
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000396the <tt><a href="#cl::aliasopt">cl::aliasopt</a></tt> modifier) whenever it is
397specified. Because aliases do not hold state, the only thing the program has to
398query is the <tt>Quiet</tt> variable now. Another nice feature of aliases is
399that they automatically hide themselves from the <tt>-help</tt> output
400(although, again, they are still visible in the <tt>--help-hidden
401output</tt>).<p>
Chris Lattnerae853632002-07-25 19:27:01 +0000402
403Now the application code can simply use:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000404
405<pre>
406...
407 if (!Quiet) printInformationalMessage(...);
408...
409</pre><p>
410
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000411... which is much nicer! The "<tt><a href="#cl::alias">cl::alias</a></tt>" can be used to specify an
Chris Lattnerae853632002-07-25 19:27:01 +0000412alternative name for any variable type, and has many uses.<p>
413
Chris Lattner209c7f42001-07-23 23:03:12 +0000414
415
416<!-- ======================================================================= -->
417</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>
Chris Lattnerae853632002-07-25 19:27:01 +0000418<a name="onealternative">Selecting an alternative from a set of possibilities
Chris Lattner209c7f42001-07-23 23:03:12 +0000419</b></font></td></tr></table><ul>
420
Chris Lattnerae853632002-07-25 19:27:01 +0000421So far, we have seen how the CommandLine library handles builtin types like
422<tt>std::string</tt>, <tt>bool</tt> and <tt>int</tt>, but how does it handle
423things it doesn't know about, like enums or '<tt>int*</tt>'s?<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000424
Chris Lattnerae853632002-07-25 19:27:01 +0000425The answer is that it uses a table driven generic parser (unless you specify
426your own parser, as described in the <a href="#extensionguide">Extension
427Guide</a>). This parser maps literal strings to whatever type is required, are
428requires you to tell it what this mapping should be.<p>
429
430Lets say that we would like to add four optimizations levels to our optimizer,
431using the standard flags "<tt>-g</tt>", "<tt>-O0</tt>", "<tt>-O1</tt>", and
432"<tt>-O2</tt>". We could easily implement this with boolean options like above,
433but there are several problems with this strategy:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000434
435<ol>
Chris Lattnerae853632002-07-25 19:27:01 +0000436<li>A user could specify more than one of the options at a time, for example,
437"<tt>opt -O3 -O2</tt>". The CommandLine library would not be able to catch this
438erroneous input for us.
439
Chris Lattner209c7f42001-07-23 23:03:12 +0000440<li>We would have to test 4 different variables to see which ones are set.
Chris Lattnerae853632002-07-25 19:27:01 +0000441
442<li>This doesn't map to the numeric levels that we want... so we cannot easily
443see if some level &gt;= "<tt>-O1</tt>" is enabled.
444
Chris Lattner209c7f42001-07-23 23:03:12 +0000445</ol><p>
446
Chris Lattnerae853632002-07-25 19:27:01 +0000447To cope with these problems, we can use an enum value, and have the CommandLine
448library fill it in with the appropriate level directly, which is used like
449this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000450
451<pre>
452enum OptLevel {
453 g, O1, O2, O3
454};
455
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000456<a href="#cl::opt">cl::opt</a>&lt;OptLevel&gt; OptimizationLevel(<a href="#cl::desc">cl::desc</a>("<i>Choose optimization level:</i>"),
457 <a href="#cl::values">cl::values</a>(
Chris Lattnerae853632002-07-25 19:27:01 +0000458 clEnumVal(g , "<i>No optimizations, enable debugging</i>"),
459 clEnumVal(O1, "<i>Enable trivial optimizations</i>"),
460 clEnumVal(O2, "<i>Enable default optimizations</i>"),
461 clEnumVal(O3, "<i>Enable expensive optimizations</i>"),
462 0));
Chris Lattner209c7f42001-07-23 23:03:12 +0000463
464...
Chris Lattnerae853632002-07-25 19:27:01 +0000465 if (OptimizationLevel &gt;= O2) doPartialRedundancyElimination(...);
Chris Lattner209c7f42001-07-23 23:03:12 +0000466...
467</pre><p>
468
Chris Lattnerae853632002-07-25 19:27:01 +0000469This declaration defines a variable "<tt>OptimizationLevel</tt>" of the
470"<tt>OptLevel</tt>" enum type. This variable can be assigned any of the values
471that are listed in the declaration (Note that the declaration list must be
472terminated with the "<tt>0</tt>" argument!). The CommandLine library enforces
473that the user can only specify one of the options, and it ensure that only valid
474enum values can be specified. The "<tt>clEnumVal</tt>" macros ensure that the
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000475command line arguments matched the enum values. With this option added, our
476help output now is:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000477
Chris Lattnerae853632002-07-25 19:27:01 +0000478<pre>
479USAGE: compiler [options] &lt;input file&gt;
Chris Lattner209c7f42001-07-23 23:03:12 +0000480
Chris Lattnerae853632002-07-25 19:27:01 +0000481OPTIONS:
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000482 <b>Choose optimization level:
Chris Lattnerae853632002-07-25 19:27:01 +0000483 -g - No optimizations, enable debugging
484 -O1 - Enable trivial optimizations
485 -O2 - Enable default optimizations
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000486 -O3 - Enable expensive optimizations</b>
Chris Lattnerae853632002-07-25 19:27:01 +0000487 -f - Overwrite output files
488 -help - display available options (--help-hidden for more)
489 -o &lt;filename&gt; - Specify output filename
490 -quiet - Don't print informational messages
491</pre>
Chris Lattner209c7f42001-07-23 23:03:12 +0000492
Chris Lattnerae853632002-07-25 19:27:01 +0000493In this case, it is sort of awkward that flag names correspond directly to enum
494names, because we probably don't want a enum definition named "<tt>g</tt>" in
495our program. Because of this, we can alternatively write this example like
496this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000497
498<pre>
499enum OptLevel {
500 Debug, O1, O2, O3
501};
502
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000503<a href="#cl::opt">cl::opt</a>&lt;OptLevel&gt; OptimizationLevel(<a href="#cl::desc">cl::desc</a>("<i>Choose optimization level:</i>"),
504 <a href="#cl::values">cl::values</a>(
Chris Lattnerae853632002-07-25 19:27:01 +0000505 clEnumValN(Debug, "g", "<i>No optimizations, enable debugging</i>"),
506 clEnumVal(O1 , "<i>Enable trivial optimizations</i>"),
507 clEnumVal(O2 , "<i>Enable default optimizations</i>"),
508 clEnumVal(O3 , "<i>Enable expensive optimizations</i>"),
509 0));
Chris Lattner209c7f42001-07-23 23:03:12 +0000510
511...
512 if (OptimizationLevel == Debug) outputDebugInfo(...);
513...
514</pre><p>
515
Chris Lattnerae853632002-07-25 19:27:01 +0000516By using the "<tt>clEnumValN</tt>" macro instead of "<tt>clEnumVal</tt>", we can
517directly specify the name that the flag should get. In general a direct mapping
518is nice, but sometimes you can't or don't want to preserve the mapping, which is
519when you would use it.<p>
520
521
Chris Lattner209c7f42001-07-23 23:03:12 +0000522
523<!-- ======================================================================= -->
524</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>
525<a name="namedalternatives">Named Alternatives
526</b></font></td></tr></table><ul>
527
Chris Lattnerae853632002-07-25 19:27:01 +0000528Another useful argument form is a named alternative style. We shall use this
529style in our compiler to specify different debug levels that can be used.
530Instead of each debug level being its own switch, we want to support the
531following options, of which only one can be specified at a time:
532"<tt>--debug-level=none</tt>", "<tt>--debug-level=quick</tt>",
533"<tt>--debug-level=detailed</tt>". To do this, we use the exact same format as
534our optimization level flags, but we also specify an option name. For this
535case, the code looks like this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000536
537<pre>
538enum DebugLev {
539 nodebuginfo, quick, detailed
540};
541
542// Enable Debug Options to be specified on the command line
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000543<a href="#cl::opt">cl::opt</a><DebugLev> DebugLevel("<i>debug_level</i>", <a href="#cl::desc">cl::desc</a>("<i>Set the debugging level:</i>"),
544 <a href="#cl::values">cl::values</a>(
Chris Lattnerae853632002-07-25 19:27:01 +0000545 clEnumValN(nodebuginfo, "none", "<i>disable debug information</i>"),
546 clEnumVal(quick, "<i>enable quick debug information</i>"),
547 clEnumVal(detailed, "<i>enable detailed debug information</i>"),
548 0));
Chris Lattner209c7f42001-07-23 23:03:12 +0000549</pre>
550
Chris Lattnerae853632002-07-25 19:27:01 +0000551This definition defines an enumerated command line variable of type "<tt>enum
552DebugLev</tt>", which works exactly the same way as before. The difference here
553is just the interface exposed to the user of your program and the help output by
554the "<tt>--help</tt>" option:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000555
556<pre>
Chris Lattnerae853632002-07-25 19:27:01 +0000557USAGE: compiler [options] &lt;input file&gt;
558
Chris Lattner209c7f42001-07-23 23:03:12 +0000559OPTIONS:
Chris Lattnerae853632002-07-25 19:27:01 +0000560 Choose optimization level:
561 -g - No optimizations, enable debugging
562 -O1 - Enable trivial optimizations
563 -O2 - Enable default optimizations
564 -O3 - Enable expensive optimizations
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000565 <b>-debug_level - Set the debugging level:
Chris Lattnerae853632002-07-25 19:27:01 +0000566 =none - disable debug information
567 =quick - enable quick debug information
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000568 =detailed - enable detailed debug information</b>
Chris Lattnerae853632002-07-25 19:27:01 +0000569 -f - Overwrite output files
570 -help - display available options (--help-hidden for more)
571 -o &lt;filename&gt; - Specify output filename
572 -quiet - Don't print informational messages
Chris Lattner209c7f42001-07-23 23:03:12 +0000573</pre><p>
574
Chris Lattnerae853632002-07-25 19:27:01 +0000575Again, the only structural difference between the debug level declaration and
576the optimiation level declaration is that the debug level declaration includes
577an option name (<tt>"debug_level"</tt>), which automatically changes how the
578library processes the argument. The CommandLine library supports both forms so
579that you can choose the form most appropriate for your application.<p>
580
Chris Lattner209c7f42001-07-23 23:03:12 +0000581
582
583<!-- ======================================================================= -->
584</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>
Chris Lattnerae853632002-07-25 19:27:01 +0000585<a name="list">Parsing a list of options
Chris Lattner209c7f42001-07-23 23:03:12 +0000586</b></font></td></tr></table><ul>
587
Chris Lattnerae853632002-07-25 19:27:01 +0000588Now that we have the standard run of the mill argument types out of the way,
589lets get a little wild and crazy. Lets say that we want our optimizer to accept
590a <b>list</b> of optimizations to perform, allowing duplicates. For example, we
591might want to run: "<tt>compiler -dce -constprop -inline -dce -strip</tt>". In
592this case, the order of the arguments and the number of appearances is very
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000593important. This is what the "<tt><a href="#cl::list">cl::list</a></tt>"
594template is for. First, start by defining an enum of the optimizations that you
595would like to perform:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000596
597<pre>
598enum Opts {
Chris Lattnerae853632002-07-25 19:27:01 +0000599 // 'inline' is a C++ keyword, so name it 'inlining'
Chris Lattner209c7f42001-07-23 23:03:12 +0000600 dce, constprop, inlining, strip
Chris Lattnerae853632002-07-25 19:27:01 +0000601};
Chris Lattner209c7f42001-07-23 23:03:12 +0000602</pre><p>
603
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000604Then define your "<tt><a href="#cl::list">cl::list</a></tt>" variable:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000605
606<pre>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000607<a href="#cl::list">cl::list</a>&lt;Opts&gt; OptimizationList(<a href="#cl::desc">cl::desc</a>("<i>Available Optimizations:</i>"),
608 <a href="#cl::values">cl::values</a>(
Chris Lattnerae853632002-07-25 19:27:01 +0000609 clEnumVal(dce , "<i>Dead Code Elimination</i>"),
Misha Brukman82c89b92003-05-20 21:01:22 +0000610 clEnumVal(constprop , "<i>Constant Propagation</i>"),
Chris Lattnerae853632002-07-25 19:27:01 +0000611 clEnumValN(inlining, "<i>inline</i>", "<i>Procedure Integration</i>"),
612 clEnumVal(strip , "<i>Strip Symbols</i>"),
613 0));
Chris Lattner209c7f42001-07-23 23:03:12 +0000614</pre><p>
615
Chris Lattnerae853632002-07-25 19:27:01 +0000616This defines a variable that is conceptually of the type
617"<tt>std::vector&lt;enum Opts&gt;</tt>". Thus, you can access it with standard
618vector methods:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000619
620<pre>
Chris Lattnerae853632002-07-25 19:27:01 +0000621 for (unsigned i = 0; i != OptimizationList.size(); ++i)
Chris Lattner209c7f42001-07-23 23:03:12 +0000622 switch (OptimizationList[i])
623 ...
624</pre>
625
Chris Lattnerae853632002-07-25 19:27:01 +0000626... to iterate through the list of options specified.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000627
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000628Note that the "<tt><a href="#cl::list">cl::list</a></tt>" template is completely general and may be used
Chris Lattnerae853632002-07-25 19:27:01 +0000629with any data types or other arguments that you can use with the
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000630"<tt><a href="#cl::opt">cl::opt</a></tt>" template. One especially useful way to use a list is to
Chris Lattnerae853632002-07-25 19:27:01 +0000631capture all of the positional arguments together if there may be more than one
632specified. In the case of a linker, for example, the linker takes several
633'<tt>.o</tt>' files, and needs to capture them into a list. This is naturally
634specified as:<p>
Chris Lattner3e5fe172002-04-13 18:35:59 +0000635
636<pre>
637...
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000638<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>);
Chris Lattner3e5fe172002-04-13 18:35:59 +0000639...
640</pre><p>
641
Chris Lattnerae853632002-07-25 19:27:01 +0000642This variable works just like a "<tt>vector&lt;string&gt;</tt>" object. As
643such, accessing the list is simple, just like above. In this example, we used
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000644the <tt><a href="#cl::OneOrMore">cl::OneOrMore</a></tt> modifier to inform the
645CommandLine library that it is an error if the user does not specify any
646<tt>.o</tt> files on our command line. Again, this just reduces the amount of
647checking we have to do.<p>
Chris Lattner3e5fe172002-04-13 18:35:59 +0000648
Chris Lattner3e5fe172002-04-13 18:35:59 +0000649
650
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000651<!-- ======================================================================= -->
652</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>
653<a name="description">Adding freeform text to help output
654</b></font></td></tr></table><ul>
655
656As our program grows and becomes more mature, we may decide to put summary
657information about what it does into the help output. The help output is styled
658to look similar to a Unix <tt>man</tt> page, providing concise information about
659a program. Unix <tt>man</tt> pages, however often have a description about what
660the program does. To add this to your CommandLine program, simply pass a third
661argument to the <a
662href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>
663call in main. This additional argument is then printed as the overview
664information for your program, allowing you to include any additional information
665that you want. For example:<p>
666
667<pre>
668int main(int argc, char **argv) {
669 <a href="#cl::ParseCommandLineOptions">cl::ParseCommandLineOptions</a>(argc, argv, " CommandLine compiler example\n\n"
670 " This program blah blah blah...\n");
671 ...
672}
673</pre><p>
674
675Would yield the help output:
676
677<pre>
678<b>OVERVIEW: CommandLine compiler example
679
680 This program blah blah blah...</b>
681
682USAGE: compiler [options] &lt;input file&gt;
683
684OPTIONS:
685 ...
686 -help - display available options (--help-hidden for more)
687 -o &lt;filename&gt; - Specify output filename
688</pre><p>
689
690
691
692
Chris Lattner209c7f42001-07-23 23:03:12 +0000693<!-- *********************************************************************** -->
694</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>
695<a name="referenceguide">Reference Guide
696</b></font></td></tr></table><ul>
697<!-- *********************************************************************** -->
698
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000699Now that you know the basics of how to use the CommandLine library, this section
700will give you the detailed information you need to tune how command line options
701work, as well as information on more "advanced" command line option processing
702capabilities.<p>
703
704
705<!-- ======================================================================= -->
706</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>
707<a name="positional">Positional Arguments
708</b></font></td></tr></table><ul>
709
710Positional arguments are those arguments that are not named, and are not
711specified with a hyphen. Positional arguments should be used when an option is
712specified by its position alone. For example, the standard Unix <tt>grep</tt>
713tool takes a regular expression argument, and an optional filename to search
714through (which defaults to standard input if a filename is not specified).
715Using the CommandLine library, this would be specified as:<p>
716
717<pre>
718<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>);
719<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>"));
720</pre>
721
722Given these two option declarations, the <tt>--help</tt> output for our grep
723replacement would look like this:<p>
724
725<pre>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000726USAGE: spiffygrep [options] <b>&lt;regular expression&gt; &lt;input file&gt;</b>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000727
728OPTIONS:
729 -help - display available options (--help-hidden for more)
730</pre>
731
732... and the resultant program could be used just like the standard <tt>grep</tt>
733tool.<p>
734
735Positional arguments are sorted by their order of construction. This means that
736command line options will be ordered according to how they are listed in a .cpp
737file, but will not have an ordering defined if they positional arguments are
738defined in multiple .cpp files. The fix for this problem is simply to define
739all of your positional arguments in one .cpp file.<p>
740
741
742
743<!-- _______________________________________________________________________ -->
744</ul><a name="--"><h4><hr size=0>Specifying positional options with hyphens</h4><ul>
745
746Sometimes you may want to specify a value to your positional argument that
747starts with a hyphen (for example, searching for '<tt>-foo</tt>' in a file). At
748first, you will have trouble doing this, because it will try to find an argument
749named '<tt>-foo</tt>', and will fail (and single quotes will not save you).
750Note that the system <tt>grep</tt> has the same problem:<p>
751
752<pre>
753 $ spiffygrep '-foo' test.txt
754 Unknown command line argument '-foo'. Try: spiffygrep --help'
755
756 $ grep '-foo' test.txt
757 grep: illegal option -- f
758 grep: illegal option -- o
759 grep: illegal option -- o
760 Usage: grep -hblcnsviw pattern file . . .
761</pre><p>
762
763The solution for this problem is the same for both your tool and the system
764version: use the '<tt>--</tt>' marker. When the user specifies '<tt>--</tt>' on
765the command line, it is telling the program that all options after the
766'<tt>--</tt>' should be treated as positional arguments, not options. Thus, we
767can use it like this:<p>
768
769<pre>
770 $ spiffygrep -- -foo test.txt
771 ...output...
772</pre><p>
773
774
775
776<!-- _______________________________________________________________________ -->
777</ul><a name="cl::ConsumeAfter"><h4><hr size=0>The <tt>cl::ConsumeAfter</tt> modifier</h4><ul>
778
779The <tt>cl::ConsumeAfter</tt> <a href="#formatting">formatting option</a> is
780used to construct programs that use "interpreter style" option processing. With
781this style of option processing, all arguments specified after the last
782positional argument are treated as special interpreter arguments that are not
783interpreted by the command line argument.<p>
784
785As a concrete example, lets say we are developing a replacement for the standard
786Unix Bourne shell (<tt>/bin/sh</tt>). To run <tt>/bin/sh</tt>, first you
787specify options to the shell itself (like <tt>-x</tt> which turns on trace
788output), then you specify the name of the script to run, then you specify
789arguments to the script. These arguments to the script are parsed by the bourne
790shell command line option processor, but are not interpreted as options to the
791shell itself. Using the CommandLine library, we would specify this as:<p>
792
793<pre>
794<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>("-"));
795<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>"));
796<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>"));
797</pre><p>
798
799which automatically provides the help output:<p>
800
801<pre>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000802USAGE: spiffysh [options] <b>&lt;input script&gt; &lt;program arguments&gt;...</b>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000803
804OPTIONS:
805 -help - display available options (--help-hidden for more)
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000806 <b>-x - Enable trace output</b>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000807</pre><p>
808
809At runtime, if we run our new shell replacement as '<tt>spiffysh -x test.sh -a
810-x -y bar</tt>', the <tt>Trace</tt> variable will be set to true, the
811<tt>Script</tt> variable will be set to "<tt>test.sh</tt>", and the
812<tt>Argv</tt> list will contain <tt>["-a", "-x", "-y", "bar"]</tt>, because
813they were specified after the last positional argument (which is the script
814name).<p>
815
816There are several limitations to when <tt>cl::ConsumeAfter</tt> options can be
817specified. For example, only one <tt>cl::ConsumeAfter</tt> can be specified per
818program, there must be at least one <a href="#positional">positional
819argument</a> specified, and the <tt>cl::ConsumeAfter</tt> option should be a <a
820href="#cl::list">cl::list</a> option.<p>
821
822
823
824<!-- ======================================================================= -->
825</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>
826<a name="storage">Internal vs External Storage
827</b></font></td></tr></table><ul>
828
829By default, all command line options automatically hold the value that they
830parse from the command line. This is very convenient in the common case,
831especially when combined with the ability to define command line options in the
832files that use them. This is called the internal storage model.<p>
833
834Sometimes, however, it is nice to separate the command line option processing
835code from the storage of the value parsed. For example, lets say that we have a
836'<tt>-debug</tt>' option that we would like to use to enable debug information
837across the entire body of our program. In this case, the boolean value
838controlling the debug code should be globally accessable (in a header file, for
839example) yet the command line option processing code should not be exposed to
840all of these clients (requiring lots of .cpp files to #include
841<tt>CommandLine.h</tt>).<p>
842
843To do this, set up your .h file with your option, like this for example:<p>
844
845<pre>
846<i>// DebugFlag.h - Get access to the '-debug' command line option
847//
848
849// DebugFlag - This boolean is set to true if the '-debug' command line option
850// is specified. This should probably not be referenced directly, instead, use
851// the DEBUG macro below.
852//</i>
853extern bool DebugFlag;
854
855<i>// DEBUG macro - This macro should be used by code to emit debug information.
856// In the '-debug' option is specified on the command line, and if this is a
857// debug build, then the code specified as the option to the macro will be
858// executed. Otherwise it will not be. Example:
859//
860// DEBUG(cerr << "Bitset contains: " << Bitset << "\n");
861//</i>
862<font color=red>#ifdef NDEBUG
863#define DEBUG(X)
864#else
865#define DEBUG(X)</font> \
866 do { if (DebugFlag) { X; } } while (0)
867<font color=red>#endif</font>
868</pre>
869
870This allows clients to blissfully use the <tt>DEBUG()</tt> macro, or the
871<tt>DebugFlag</tt> explicitly if they want to. Now we just need to be able to
872set the <tt>DebugFlag</tt> boolean when the option is set. To do this, we pass
873an additial argument to our command line argument processor, and we specify
874where to fill in with the <a href="#cl::location">cl::location</a> attribute:<p>
875
876<pre>
877bool DebugFlag; <i>// the actual value</i>
878static <a href="#cl::opt">cl::opt</a><bool, true> <i>// The parser</i>
879Debug("<i>debug</i>", <a href="#cl::desc">cl::desc</a>("<i>Enable debug output</i>")</a>, <a href="#cl::Hidden">cl::Hidden</a>,
880 <a href="#cl::location">cl::location</a>(DebugFlag));
881</pre>
882
883In the above example, we specify "<tt>true</tt>" as the second argument to the
884<a href="#cl::opt">cl::opt</a> template, indicating that the template should not
885maintain a copy of the value itself. In addition to this, we specify the <a
886href="#cl::location">cl::location</a> attribute, so that <tt>DebugFlag</tt> is
887automatically set.<p>
888
889
890
891<!-- ======================================================================= -->
892</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>
893<a name="attributes">Option Attributes
894</b></font></td></tr></table><ul>
895
896This section describes the basic attributes that you can specify on options.<p>
897
898<ul>
899
900<li>The option name attribute (which is required for all options, except <a
901href="#positional">positional options</a>) specifies what the option name is.
902This option is specified in simple double quotes:<p>
903
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000904<pre>
905<a href="#cl::opt">cl::opt</a>&lt;<b>bool</b>&gt; Quiet("<i>quiet</i>");
906</pre><p>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000907
908<li><a name="cl::desc">The <b><tt>cl::desc</tt></b> attribute specifies a
909description for the option to be shown in the <tt>--help</tt> output for the
910program.<p>
911
912<li><a name="cl::value_desc">The <b><tt>cl::value_desc</tt></b> attribute
913specifies a string that can be used to fine tune the <tt>--help</tt> output for
914a command line option. Look <a href="#value_desc_example">here</a> for an
915example.<p>
916
917<li><a name="cl::init">The <b><tt>cl::init</tt></b> attribute specifies an
918inital value for a <a href="#cl::opt">scalar</a> option. If this attribute is
919not specified then the command line option value defaults to the value created
920by the default constructor for the type.<p>
921
922<li><a name="cl::location">The <b><tt>cl::location</tt></b> attribute where to
923store the value for a parsed command line option if using external storage. See
924the section on <a href="#storage">Internal vs External Storage</a> for more
925information.<p>
926
927<li><a name="cl::aliasopt">The <b><tt>cl::aliasopt</tt></b> attribute specifies
928which option a <a href="#cl::alias">cl::alias</a> option is an alias for.<p>
929
930<li><a name="cl::values">The <b><tt>cl::values</tt></b> attribute specifies the
931string-to-value mapping to be used by the generic parser. It takes a <b>null
932terminated</b> list of (option, value, description) triplets that specify the
933option name, the value mapped to, and the description shown in the
934<tt>--help</tt> for the tool. Because the generic parser is used most frequently with enum values, two macros are often useful:<p>
935<ol>
936<li><a name="clEnumVal">The <b><tt>clEnumVal</tt></b> macro is used as a nice
937simple way to specify a triplet for an enum. This macro automatically makes the
938option name be the same as the enum name. The first option to the macro is the
939enum, the second is the description for the command line option.<p> <li><a
940name="clEnumValN">The <b><tt>clEnumValN</tt></b> macro is used to specify macro
941options where the option name doesn't equal the enum name. For this macro, the
942first argument is the enum value, the second is the flag name, and the second is
943the description.<p>
944</ol>
945
946You will get a compile time error if you try to use cl::values with a parser
947that does not support it.<p>
948
949</ul>
950
951
952
953<!-- ======================================================================= -->
954</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>
955<a name="modifiers">Option Modifiers
956</b></font></td></tr></table><ul>
957
958Option modifiers are the flags and expressions that you pass into the
959constructors for <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
960href="#cl::list">cl::list</a></tt>. These modifiers give you the ability to
961tweak how options are parsed and how <tt>--help</tt> output is generated to fit
962your application well.<p>
963
964These options naturally fall into four main catagories:<p>
965
966<ol>
967<li><a href="#hiding">Hiding an option from <tt>--help</tt> output</a>
968<li><a href="#numoccurances">Controlling the number of occurances
969 required and allowed</a>
970<li><a href="#valrequired">Controlling whether or not a value must be
971 specified</a>
972<li><a href="#formatting">Controlling other formatting options</a>
973</ol><p>
974
975It is not possible to specify two options from the same catagory (you'll get a
976runtime error) to a single option. The CommandLine library specifies defaults
977for all of these settings that are the most useful in practice and the most
978common, which mean that you usually shouldn't have to worry about these.<p>
979
980
981<!-- _______________________________________________________________________ -->
982</ul><a name="hiding"><h4><hr size=0>Hiding an option from <tt>--help</tt> output</h4><ul>
983
984The <tt>cl::NotHidden</tt>, <tt>cl::Hidden</tt>, and <tt>cl::ReallyHidden</tt>
985modifiers are used to control whether or not an option appears in the
986<tt>--help</tt> and <tt>--help-hidden</tt> output for the compiled program:<p>
987
988<ul>
989
990<a name="cl::NotHidden">The <b><tt>cl::NotHidden</tt></b> modifier (which is the
991default for <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
992href="#cl::list">cl::list</a></tt> options), indicates the option is to appear
993in both help listings.<p>
994
995<a name="cl::Hidden">The <b><tt>cl::Hidden</tt></b> modifier (which is the
996default for <tt><a href="#cl::alias">cl::alias</a></tt> options), indicates that
997the option should not appear in the <tt>--help</tt> output, but should appear in
998the <tt>--help-hidden</tt> output.<p>
999
1000<a name="cl::ReallyHidden">The <b><tt>cl::ReallyHidden</tt></b> modifier,
1001indicates that the option should not appear in any help output.<p>
1002</ul>
1003
1004<!-- _______________________________________________________________________ -->
1005</ul><a name="numoccurances"><h4><hr size=0>Controlling the number of occurances required and allowed</h4><ul>
1006
1007This group of options is used to control how many time an option is allowed (or
1008required) to be specified on the command line of your program. Specifying a
1009value for this setting allows the CommandLine library to do error checking for
1010you.<p>
1011
1012The allowed values for this option group are:<p>
1013
1014<ul>
1015<a name="cl::Optional">The <b><tt>cl::Optional</tt></b> modifier (which is the
1016default for the <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
1017href="#cl::alias">cl::alias</a></tt> classes) indicates that your program will
1018allow either zero or one occurance of the option to be specified.<p>
1019
1020<a name="cl::ZeroOrMore">The <b><tt>cl::ZeroOrMore</tt></b> modifier (which is
1021the default for the <tt><a href="#cl::list">cl::list</a></tt> class) indicates
1022that your program will allow the option to be specified zero or more times.<p>
1023
1024<a name="cl::Required">The <b><tt>cl::Required</tt></b> modifier indicates that
1025the specified option must be specified exactly one time.<p>
1026
1027<a name="cl::OneOrMore">The <b><tt>cl::OneOrMore</tt></b> modifier indicates
1028that the option must be specified at least one time.<p>
1029
1030The <b><tt>cl::ConsumeAfter</tt></b> modifier is described in the <a
1031href="#positional">Positional arguments section</a><p>
1032
1033</ul>
1034
1035If an option is not specified, then the value of the option is equal to the
1036value specified by the <tt><a href="#cl::init">cl::init</a></tt> attribute. If
1037the <tt><a href="#cl::init">cl::init</a></tt> attribute is not specified, the
1038option value is initialized with the default constructor for the data type.<p>
1039
1040If an option is specified multiple times for an option of the <tt><a
1041href="#cl::opt">cl::opt</a></tt> class, only the last value will be retained.<p>
1042
1043
1044<!-- _______________________________________________________________________ -->
1045</ul><a name="valrequired"><h4><hr size=0>Controlling whether or not a value must be specified</h4><ul>
1046
1047This group of options is used to control whether or not the option allows a
1048value to be present. In the case of the CommandLine library, a value is either
1049specified with an equal sign (e.g. '<tt>-index-depth=17</tt>') or as a trailing
1050string (e.g. '<tt>-o a.out</tt>').<p>
1051
1052The allowed values for this option group are:<p>
1053
1054<ul>
1055<a name="cl::ValueOptional">The <b><tt>cl::ValueOptional</tt></b> modifier
1056(which is the default for <tt>bool</tt> typed options) specifies that it is
1057acceptable to have a value, or not. A boolean argument can be enabled just by
1058appearing on the command line, or it can have an explicit '<tt>-foo=true</tt>'.
1059If an option is specified with this mode, it is illegal for the value to be
1060provided without the equal sign. Therefore '<tt>-foo true</tt>' is illegal. To
1061get this behavior, you must use the <a
1062href="#cl::ValueRequired">cl::ValueRequired</a> modifier.<p>
1063
1064<a name="cl::ValueRequired">The <b><tt>cl::ValueRequired</tt></b> modifier
1065(which is the default for all other types except for <a
1066href="#onealternative">unnamed alternatives using the generic parser</a>)
1067specifies that a value must be provided. This mode informs the command line
1068library that if an option is not provides with an equal sign, that the next
1069argument provided must be the value. This allows things like '<tt>-o
1070a.out</tt>' to work.<p>
1071
1072<a name="cl::ValueDisallowed">The <b><tt>cl::ValueDisallowed</tt></b> modifier
1073(which is the default for <a href="#onealternative">unnamed alternatives using
1074the 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>
1075
1076</ul>
1077
1078In general, the default values for this option group work just like you would
1079want them to. As mentioned above, you can specify the <a
1080href="#cl::ValueDisallowed">cl::ValueDisallowed</a> modifier to a boolean
1081argument to restrict your command line parser. These options are mostly useful
1082when <a href="#extensionguide">extending the library</a>.<p>
1083
1084
1085
1086<!-- _______________________________________________________________________ -->
1087</ul><a name="formatting"><h4><hr size=0>Controlling other formatting options</h4><ul>
1088
1089The formatting option group is used to specify that the command line option has
1090special abilities and is otherwise different from other command line arguments.
1091As usual, you can only specify at most one of these arguments.<p>
1092
1093<ul>
1094<a name="cl::NormalFormatting">The <b><tt>cl::NormalFormatting</tt></b> modifier
1095(which is the default all options) specifies that this option is "normal".<p>
1096
1097<a name="cl::Positional">The <b><tt>cl::Positional</tt></b> modifier specifies
1098that this is a positional argument, that does not have a command line option
1099associated with it. See the <a href="#positional">Positional Arguments</a>
1100section for more information.<p>
1101
1102The <b><a href="#cl::ConsumeAfter"><tt>cl::ConsumeAfter</tt></a></b> modifier
1103specifies that this option is used to capture "interpreter style" arguments. See <a href="#cl::ConsumeAfter">this section for more information</a>.<p>
1104
1105
1106<a name="cl::Prefix">The <b><tt>cl::Prefix</tt></b> modifier specifies that this
1107option prefixes its value. With 'Prefix' options, there is no equal sign that
1108seperates the value from the option name specified. This is useful for
1109processing odd arguments like '<tt>-lmalloc -L/usr/lib'</tt> in a linker tool.
1110Here, the '<tt>l</tt>' and '<tt>L</tt>' options are normal string (list)
1111options, that have the <a href="#cl::Prefix">cl::Prefix</a> modifier added to
1112allow the CommandLine library to recognize them. Note that <a
1113href="#cl::Prefix">cl::Prefix</a> options must not have the <a
1114href="#cl::ValueDisallowed">cl::ValueDisallowed</a> modifier specified.<p>
1115
1116<a name="cl::Grouping">The <b><tt>cl::Grouping</tt></b> modifier is used to
1117implement unix style tools (like <tt>ls</tt>) that have lots of single letter
1118arguments, but only require a single dash. For example, the '<tt>ls -labF</tt>'
1119command actually enables four different options, all of which are single
1120letters. Note that <a href="#cl::Grouping">cl::Grouping</a> options cannot have
1121values.<p>
1122
1123</ul>
1124
1125The CommandLine library does not restrict how you use the <a
1126href="#cl::Prefix">cl::Prefix</a> or <a href="#cl::Grouping">cl::Grouping</a>
1127modifiers, but it is possible to specify ambiguous argument settings. Thus, it
1128is possible to have multiple letter options that are prefix or grouping options,
1129and they will still work as designed.<p>
1130
1131To do this, the CommandLine library uses a greedy algorithm to parse the input
1132option into (potentially multiple) prefix and grouping options. The strategy
1133basically looks like this:<p>
1134
1135<tt>parse(string OrigInput) {</tt>
1136<ol>
1137<li><tt>string input = OrigInput;</tt>
1138<li><tt>if (isOption(input)) return getOption(input).parse();</tt>&nbsp;&nbsp;&nbsp;&nbsp;<i>// Normal option</i>
1139<li><tt>while (!isOption(input) &amp;&amp; !input.empty()) input.pop_back();</tt>&nbsp;&nbsp;&nbsp;&nbsp;<i>// Remove the last letter</i>
1140<li><tt>if (input.empty()) return error();</tt>&nbsp;&nbsp;&nbsp;&nbsp;<i>// No matching option</i>
1141<li><tt>if (getOption(input).isPrefix())<br>
1142&nbsp;&nbsp;return getOption(input).parse(input);</tt>
1143<li><tt>while (!input.empty()) {&nbsp;&nbsp;&nbsp;&nbsp;<i>// Must be grouping options</i><br>
1144&nbsp;&nbsp;getOption(input).parse();<br>
1145&nbsp;&nbsp;OrigInput.erase(OrigInput.begin(), OrigInput.begin()+input.length());<br>
1146&nbsp;&nbsp;input = OrigInput;<br>
1147&nbsp;&nbsp;while (!isOption(input) &amp;&amp; !input.empty()) input.pop_back();<br>
1148}</tt>
1149<li><tt>if (!OrigInput.empty()) error();</tt>
1150</tt>
1151
1152</ol>
1153<tt>}</tt><p>
1154
1155
1156<!-- ======================================================================= -->
1157</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>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001158<a name="toplevel">Top-Level Classes and Functions
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001159</b></font></td></tr></table><ul>
1160
1161Despite all of the builtin flexibility, the CommandLine option library really
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001162only consists of one function (<a
1163href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>)
1164and three main classes: <a href="#cl::opt"><tt>cl::opt</tt></a>, <a
1165href="#cl::list"><tt>cl::list</tt></a>, and <a
1166href="#cl::alias"><tt>cl::alias</tt></a>. This section describes these three
1167classes in detail.<p>
1168
1169<!-- _______________________________________________________________________ -->
1170</ul><a name="cl::ParseCommandLineOptions"><h4><hr size=0>The
1171<tt>cl::ParseCommandLineOptions</tt> function</h4><ul>
1172
1173The <tt>cl::ParseCommandLineOptions</tt> function is designed to be called
1174directly from <tt>main</tt>, and is used to fill in the values of all of the
1175command line option variables once <tt>argc</tt> and <tt>argv</tt> are
1176available.<p>
1177
1178The <tt>cl::ParseCommandLineOptions</tt> function requires two parameters
1179(<tt>argc</tt> and <tt>argv</tt>), but may also take an optional third parameter
1180which holds <a href="#description">additional extra text</a> to emit when the
1181<tt>--help</tt> option is invoked.<p>
1182
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001183
1184<!-- _______________________________________________________________________ -->
1185</ul><a name="cl::opt"><h4><hr size=0>The <tt>cl::opt</tt> class</h4><ul>
1186
1187The <tt>cl::opt</tt> class is the class used to represent scalar command line
1188options, and is the one used most of the time. It is a templated class which
1189can take up to three arguments (all except for the first have default values
1190though):<p>
1191
1192<pre>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001193<b>namespace</b> cl {
1194 <b>template</b> &lt;<b>class</b> DataType, <b>bool</b> ExternalStorage = <b>false</b>,
1195 <b>class</b> ParserClass = parser&lt;DataType&gt; &gt;
1196 <b>class</b> opt;
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001197}
1198</pre><p>
1199
1200The first template argument specifies what underlying data type the command line
1201argument is, and is used to select a default parser implementation. The second
1202template argument is used to specify whether the option should contain the
1203storage for the option (the default) or whether external storage should be used
1204to contain the value parsed for the option (see <a href="#storage">Internal vs
1205External Storage</a> for more information).<p>
1206
1207The third template argument specifies which parser to use. The default value
1208selects an instantiation of the <tt>parser</tt> class based on the underlying
1209data type of the option. In general, this default works well for most
1210applications, so this option is only used when using a <a
1211href="#customparser">custom parser</a>.<p>
1212
1213
1214<!-- _______________________________________________________________________ -->
1215</ul><a name="cl::list"><h4><hr size=0>The <tt>cl::list</tt> class</h4><ul>
1216
1217The <tt>cl::list</tt> class is the class used to represent a list of command
1218line options. It too is a templated class which can take up to three
1219arguments:<p>
1220
1221<pre>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001222<b>namespace</b> cl {
1223 <b>template</b> &lt;<b>class</b> DataType, <b>class</b> Storage = <b>bool</b>,
1224 <b>class</b> ParserClass = parser&lt;DataType&gt; &gt;
1225 <b>class</b> list;
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001226}
1227</pre><p>
1228
1229This class works the exact same as the <a href="#cl::opt"><tt>cl::opt</tt></a>
1230class, except that the second argument is the <b>type</b> of the external
1231storage, not a boolean value. For this class, the marker type '<tt>bool</tt>'
1232is used to indicate that internal storage should be used.<p>
1233
1234
1235<!-- _______________________________________________________________________ -->
1236</ul><a name="cl::alias"><h4><hr size=0>The <tt>cl::alias</tt> class</h4><ul>
1237
1238The <tt>cl::alias</tt> class is a nontemplated class that is used to form
1239aliases for other arguments.<p>
1240
1241<pre>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001242<b>namespace</b> cl {
1243 <b>class</b> alias;
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001244}
1245</pre></p>
1246
1247The <a href="#cl::aliasopt"><tt>cl::aliasopt</tt></a> attribute should be used
1248to specify which option this is an alias for. Alias arguments default to being
1249<a href="#cl::Hidden">Hidden</a>, and use the aliased options parser to do the
1250conversion from string to data.<p>
1251
1252
1253<!-- ======================================================================= -->
1254</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>
1255<a name="builtinparsers">Builtin parsers
1256</b></font></td></tr></table><ul>
1257
1258Parsers control how the string value taken from the command line is translated
1259into a typed value, suitable for use in a C++ program. By default, the
1260CommandLine library uses an instance of <tt>parser&lt;type&gt;</tt> if the
1261command line option specifies that it uses values of type '<tt>type</tt>'.
1262Because of this, custom option processing is specified with specializations of
1263the '<tt>parser</tt>' class.<p>
1264
1265The CommandLine library provides the following builtin parser specializations,
1266which are sufficient for most applications. It can, however, also be extended to
1267work with new data types and new ways of interpreting the same data. See the <a
1268href="#customparser">Writing a Custom Parser</a> for more details on this type
1269of library extension.<p>
1270
1271<li><a name="genericparser">The <b>generic <tt>parser&lt;t&gt;</tt> parser</b>
1272can be used to map strings values to any data type, through the use of the <a
1273href="#cl::values">cl::values</a> property, which specifies the mapping
1274information. The most common use of this parser is for parsing enum values,
1275which allows you to use the CommandLine library for all of the error checking to
1276make sure that only valid enum values are specified (as opposed to accepting
1277arbitrary strings). Despite this, however, the generic parser class can be used
1278for any data type.<p>
1279
1280<li><a name="boolparser">The <b><tt>parser&lt;bool&gt;</tt> specialization</b>
1281is used to convert boolean strings to a boolean value. Currently accepted
1282strings are "<tt>true</tt>", "<tt>TRUE</tt>", "<tt>True</tt>", "<tt>1</tt>",
1283"<tt>false</tt>", "<tt>FALSE</tt>", "<tt>False</tt>", and "<tt>0</tt>".<p>
1284
1285<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>
1286
1287<li><a name="intparser">The <b><tt>parser&lt;int&gt;</tt> specialization</b>
1288uses the C <tt>strtol</tt> function to parse the string input. As such, it will
1289accept a decimal number (with an optional '+' or '-' prefix) which must start
1290with a non-zero digit. It accepts octal numbers, which are identified with a
1291'<tt>0</tt>' prefix digit, and hexadecimal numbers with a prefix of
1292'<tt>0x</tt>' or '<tt>0X</tt>'.<p>
1293
1294<li><a name="doubleparser">The <b><tt>parser&lt;double&gt;</tt></b> and
1295<b><tt>parser&lt;float&gt;</tt> specializations</b> use the standard C
1296<tt>strtod</tt> function to convert floating point strings into floating point
1297values. As such, a broad range of string formats is supported, including
1298exponential notation (ex: <tt>1.7e15</tt>) and properly supports locales.
1299<p>
1300
Chris Lattner209c7f42001-07-23 23:03:12 +00001301
1302
1303<!-- *********************************************************************** -->
1304</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>
1305<a name="extensionguide">Extension Guide
1306</b></font></td></tr></table><ul>
1307<!-- *********************************************************************** -->
1308
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001309Although the CommandLine library has a lot of functionality built into it
1310already (as discussed previously), one of its true strengths lie in its
1311extensibility. This section discusses how the CommandLine library works under
1312the covers and illustrates how to do some simple, common, extensions.<p>
1313
Chris Lattner209c7f42001-07-23 23:03:12 +00001314
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001315<!-- ======================================================================= -->
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001316</ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1317<tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF"
1318face="Georgia,Palatino"><b> <a name="customparser">Writing a custom parser
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001319</b></font></td></tr></table><ul>
1320
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001321One of the simplest and most common extensions is the use of a custom parser.
1322As <a href="#builtinparsers">discussed previously</a>, parsers are the portion
1323of the CommandLine library that turns string input from the user into a
1324particular parsed data type, validating the input in the process.<p>
1325
1326There are two ways to use a new parser:<p>
1327
1328<ol>
1329<li>Specialize the <a href="#genericparser"><tt>cl::parser</tt></a> template for
1330 your custom data type.<p>
1331
1332 This approach has the advantage that users of your custom data type will
1333 automatically use your custom parser whenever they define an option with a
1334 value type of your data type. The disadvantage of this approach is that it
1335 doesn't work if your fundemental data type is something that is already
1336 supported.<p>
1337
1338<li>Write an independant class, using it explicitly from options that need
1339 it.<p>
1340
1341 This approach works well in situations where you would line to parse an
1342 option using special syntax for a not-very-special data-type. The drawback
1343 of this approach is that users of your parser have to be aware that they are
1344 using your parser, instead of the builtin ones.<p>
1345
1346</ol><p>
1347
1348To guide the discussion, we will discuss a custom parser that accepts file
1349sizes, specified with an optional unit after the numeric size. For example, we
1350would like to parse "102kb", "41M", "1G" into the appropriate integer value. In
1351this case, the underlying data type we want to parse into is
1352'<tt>unsigned</tt>'. We choose approach #2 above because we don't want to make
1353this the default for all <tt>unsigned</tt> options.<p>
1354
1355To start out, we declare our new <tt>FileSizeParser</tt> class:<p>
1356
1357<pre>
1358<b>struct</b> FileSizeParser : <b>public</b> cl::basic_parser&lt;<b>unsigned</b>&gt; {
1359 <i>// parse - Return true on error.</i>
1360 <b>bool</b> parse(cl::Option &amp;O, <b>const char</b> *ArgName, <b>const</b> std::string &amp;ArgValue,
1361 <b>unsigned</b> &amp;Val);
1362};
1363</pre><p>
1364
1365Our new class inherits from the <tt>cl::basic_parser</tt> template class to fill
1366in the default, boiler plate, code for us. We give it the data type that we
1367parse into (the last argument to the <tt>parse</tt> method so that clients of
1368our custom parser know what object type to pass in to the parse method (here we
1369declare that we parse into '<tt>unsigned</tt>' variables.<p>
1370
1371For most purposes, the only method that must be implemented in a custom parser
1372is the <tt>parse</tt> method. The <tt>parse</tt> method is called whenever the
1373option is invoked, passing in the option itself, the option name, the string to
1374parse, 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>
1375
1376<pre>
1377<b>bool</b> FileSizeParser::parse(cl::Option &amp;O, <b>const char</b> *ArgName,
1378 <b>const</b> std::string &amp;Arg, <b>unsigned</b> &amp;Val) {
1379 <b>const char</b> *ArgStart = Arg.c_str();
1380 <b>char</b> *End;
1381
1382 <i>// Parse integer part, leaving 'End' pointing to the first non-integer char</i>
1383 Val = (unsigned)strtol(ArgStart, &amp;End, 0);
1384
1385 <b>while</b> (1) {
1386 <b>switch</b> (*End++) {
1387 <b>case</b> 0: <b>return</b> false; <i>// No error</i>
1388 <b>case</b> 'i': <i>// Ignore the 'i' in KiB if people use that</i>
1389 <b>case</b> 'b': <b>case</b> 'B': <i>// Ignore B suffix</i>
1390 <b>break</b>;
1391
1392 <b>case</b> 'g': <b>case</b> 'G': Val *= 1024*1024*1024; <b>break</b>;
1393 <b>case</b> 'm': <b>case</b> 'M': Val *= 1024*1024; <b>break</b>;
1394 <b>case</b> 'k': <b>case</b> 'K': Val *= 1024; <b>break</b>;
1395
1396 default:
1397 <i>// Print an error message if unrecognized character!</i>
1398 <b>return</b> O.error(": '" + Arg + "' value invalid for file size argument!");
1399 }
1400 }
1401}
1402</pre><p>
1403
1404This function implements a very simple parser for the kinds of strings we are
1405interested in. Although it has some holes (it allows "<tt>123KKK</tt>" for
1406example), it is good enough for this example. Note that we use the option
1407itself to print out the error message (the <tt>error</tt> method always returns
1408true) in order to get a nice error message (shown below). Now that we have our
1409parser class, we can use it like this:<p>
1410
1411<pre>
1412<b>static</b> <a href="#cl::opt">cl::opt</a>&lt;<b>unsigned</b>, <b>false</b>, FileSizeParser&gt;
1413MFS(<i>"max-file-size"</i>, <a href="#cl::desc">cl::desc</a>(<i>"Maximum file size to accept"</i>),
1414 <a href="#cl::value_desc">cl::value_desc</a>("<i>size</i>"));
1415</pre><p>
1416
1417Which adds this to the output of our program:<p>
1418
1419<pre>
1420OPTIONS:
1421 -help - display available options (--help-hidden for more)
1422 ...
1423 <b>-max-file-size=&lt;size&gt; - Maximum file size to accept</b>
1424</pre><p>
1425
1426And we can test that our parse works correctly now (the test program just prints
1427out the max-file-size argument value):<p>
1428
1429<pre>
1430$ ./test
1431MFS: 0
1432$ ./test -max-file-size=123MB
1433MFS: 128974848
1434$ ./test -max-file-size=3G
1435MFS: 3221225472
1436$ ./test -max-file-size=dog
1437-max-file-size option: 'dog' value invalid for file size argument!
1438</pre><p>
1439
1440It looks like it works. The error message that we get is nice and helpful, and
1441we seem to accept reasonable file sizes. This wraps up the "custom parser"
1442tutorial.<p>
1443
1444
1445<!-- ======================================================================= -->
1446</ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1447<tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF"
1448face="Georgia,Palatino"><b> <a name="explotingexternal">Exploiting external
1449storage </b></font></td></tr></table><ul>
1450
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001451
1452
1453<!-- ======================================================================= -->
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001454</ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1455<tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF"
1456face="Georgia,Palatino"><b> <a name="dynamicopts">Dynamically adding command
1457line options </b></font></td></tr></table><ul>
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001458
1459
Chris Lattner209c7f42001-07-23 23:03:12 +00001460
1461
1462
1463<!-- *********************************************************************** -->
1464</ul>
1465<!-- *********************************************************************** -->
1466
1467<hr>
1468<font size=-1>
1469<address><a href="mailto:sabre@nondot.org">Chris Lattner</a></address>
1470<!-- Created: Tue Jan 23 15:19:28 CST 2001 -->
1471<!-- hhmts start -->
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001472Last modified: Wed Aug 7 13:22:40 CDT 2002
Chris Lattner209c7f42001-07-23 23:03:12 +00001473<!-- hhmts end -->
1474</font>
1475</body></html>