blob: bc357b13fed779308b8c89e8e5109eb96a12d115 [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>
Chris Lattner32a32842003-05-22 20:36:06 +000039 <li><a href="#misc">Miscellaneous option modifiers</a>
Chris Lattnere76d4ab2002-08-06 19:36:06 +000040 </ul>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +000041 <li><a href="#toplevel">Top-Level Classes and Functions</a>
Chris Lattnere76d4ab2002-08-06 19:36:06 +000042 <ul>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +000043 <li><a href="#cl::ParseCommandLineOptions">The
44 <tt>cl::ParseCommandLineOptions</tt> function</a>
Chris Lattnere76d4ab2002-08-06 19:36:06 +000045 <li><a href="#cl::opt">The <tt>cl::opt</tt> class</a>
46 <li><a href="#cl::list">The <tt>cl::list</tt> class</a>
47 <li><a href="#cl::alias">The <tt>cl::alias</tt> class</a>
48 </ul>
49 <li><a href="#builtinparsers">Builtin parsers</a>
50 <ul>
51 <li><a href="#genericparser">The Generic <tt>parser&lt;t&gt;</tt>
52 parser</a>
53 <li><a href="#boolparser">The <tt>parser&lt;bool&gt;</tt>
54 specialization</a>
55 <li><a href="#stringparser">The <tt>parser&lt;string&gt;</tt>
56 specialization</a>
57 <li><a href="#intparser">The <tt>parser&lt;int&gt;</tt>
58 specialization</a>
59 <li><a href="#doubleparser">The <tt>parser&lt;double&gt;</tt> and
60 <tt>parser&lt;float&gt;</tt> specializations</a>
Chris Lattnerae853632002-07-25 19:27:01 +000061 </ul>
62 </ol>
Chris Lattner209c7f42001-07-23 23:03:12 +000063 <li><a href="#extensionguide">Extension Guide</a>
Chris Lattnerae853632002-07-25 19:27:01 +000064 <ol>
Chris Lattnere76d4ab2002-08-06 19:36:06 +000065 <li><a href="#customparser">Writing a custom parser</a>
66 <li><a href="#explotingexternal">Exploiting external storage</a>
67 <li><a href="#dynamicopts">Dynamically adding command line options</a>
Chris Lattnerae853632002-07-25 19:27:01 +000068 </ol>
Chris Lattnere76d4ab2002-08-06 19:36:06 +000069
70 <p><b>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></b><p>
Chris Lattner209c7f42001-07-23 23:03:12 +000071</ol><p>
72
73
74<!-- *********************************************************************** -->
Chris Lattnerc1ae40c2002-08-07 18:27:04 +000075<table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
Chris Lattner209c7f42001-07-23 23:03:12 +000076<tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
77<a name="introduction">Introduction
78</b></font></td></tr></table><ul>
79<!-- *********************************************************************** -->
80
Chris Lattnerae853632002-07-25 19:27:01 +000081This document describes the CommandLine argument processing library. It will
Chris Lattnere76d4ab2002-08-06 19:36:06 +000082show you how to use it, and what it can do. The CommandLine library uses a
83declarative approach to specifying the command line options that your program
84takes. By default, these options declarations implicitly hold the value parsed
85for the option declared (of course this <a href="#storage">can be
86changed</a>).<p>
Chris Lattner209c7f42001-07-23 23:03:12 +000087
Chris Lattnerae853632002-07-25 19:27:01 +000088Although there are a <b>lot</b> of command line argument parsing libraries out
89there in many different languages, none of them fit well with what I needed. By
90looking at the features and problems of other libraries, I designed the
91CommandLine library to have the following features:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +000092
93<ol>
Chris Lattnerae853632002-07-25 19:27:01 +000094<li>Speed: The CommandLine library is very quick and uses little resources. The
95parsing time of the library is directly proportional to the number of arguments
96parsed, not the the number of options recognized. Additionally, command line
97argument values are captured transparently into user defined variables, which
98can be accessed like any other variable (and with the same performance).<p>
Chris Lattner209c7f42001-07-23 23:03:12 +000099
Chris Lattnerae853632002-07-25 19:27:01 +0000100<li>Type Safe: As a user of CommandLine, you don't have to worry about
101remembering the type of arguments that you want (is it an int? a string? a
102bool? an enum?) and keep casting it around. Not only does this help prevent
103error prone constructs, it also leads to dramatically cleaner source code.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000104
Chris Lattnerae853632002-07-25 19:27:01 +0000105<li>No subclasses required: To use CommandLine, you instantiate variables that
106correspond to the arguments that you would like to capture, you don't subclass a
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000107parser. This means that you don't have to write <b>any</b> boilerplate code.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000108
Chris Lattnerae853632002-07-25 19:27:01 +0000109<li>Globally accessible: Libraries can specify command line arguments that are
110automatically enabled in any tool that links to the library. This is possible
111because the application doesn't have to keep a "list" of arguments to pass to
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000112the parser. This also makes supporting <a href="#dynamicopts">dynamically
113loaded options</a> trivial.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000114
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000115<li>Cleaner: CommandLine supports enum and other types directly, meaning that
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000116there is less error and more security built into the library. You don't have to
117worry about whether your integral command line argument accidentally got
118assigned a value that is not valid for your enum type.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000119
Chris Lattnerae853632002-07-25 19:27:01 +0000120<li>Powerful: The CommandLine library supports many different types of
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000121arguments, from simple <a href="#boolparser">boolean flags</a> to <a
122href="#cl::opt">scalars arguments</a> (<a href="#stringparser">strings</a>, <a
123href="#intparser">integers</a>, <a href="#genericparser">enums</a>, <a
124href="#doubleparser">doubles</a>), to <a href="#cl::list">lists of
125arguments</a>. This is possible because CommandLine is...<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000126
Chris Lattnerae853632002-07-25 19:27:01 +0000127<li>Extensible: It is very simple to add a new argument type to CommandLine.
128Simply specify the parser that you want to use with the command line option when
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000129you declare it. <a href="#customparser">Custom parsers</a> are no problem.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000130
Chris Lattnerae853632002-07-25 19:27:01 +0000131<li>Labor Saving: The CommandLine library cuts down on the amount of grunt work
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000132that you, the user, have to do. For example, it automatically provides a
133<tt>--help</tt> option that shows the available command line options for your
134tool. Additionally, it does most of the basic correctness checking for you.<p>
135
136<li>Capable: The CommandLine library can handle lots of different forms of
137options often found in real programs. For example, <a
138href="#positional">positional</a> arguments, <tt>ls</tt> style <a
139href="#cl::Grouping">grouping</a> options (to allow processing '<tt>ls
140-lad</tt>' naturally), <tt>ld</tt> style <a href="#cl::Prefix">prefix</a>
141options (to parse '<tt>-lmalloc -L/usr/lib</tt>'), and <a
142href="#cl::ConsumeAfter">interpreter style options</a>.<p>
143
Chris Lattner209c7f42001-07-23 23:03:12 +0000144</ol>
145
Chris Lattnerae853632002-07-25 19:27:01 +0000146This document will hopefully let you jump in and start using CommandLine in your
147utility quickly and painlessly. Additionally it should be a simple reference
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000148manual to figure out how stuff works. If it is failing in some area (or you
149want an extension to the library), nag the author, <a
150href="mailto:sabre@nondot.org">Chris Lattner</a>.<p>
151
Chris Lattner209c7f42001-07-23 23:03:12 +0000152
153
154<!-- *********************************************************************** -->
155</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>
156<a name="quickstart">Quick Start Guide
157</b></font></td></tr></table><ul>
158<!-- *********************************************************************** -->
159
Chris Lattnerae853632002-07-25 19:27:01 +0000160This section of the manual runs through a simple CommandLine'ification of a
161basic compiler tool. This is intended to show you how to jump into using the
162CommandLine library in your own program, and show you some of the cool things it
163can do.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000164
Chris Lattnerae853632002-07-25 19:27:01 +0000165To start out, you need to include the CommandLine header file into your
166program:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000167
168<pre>
Chris Lattnerae853632002-07-25 19:27:01 +0000169 #include "Support/CommandLine.h"
Chris Lattner209c7f42001-07-23 23:03:12 +0000170</pre><p>
171
172Additionally, you need to add this as the first line of your main program:<p>
173
174<pre>
175int main(int argc, char **argv) {
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000176 <a href="#cl::ParseCommandLineOptions">cl::ParseCommandLineOptions</a>(argc, argv);
Chris Lattner209c7f42001-07-23 23:03:12 +0000177 ...
178}
179</pre><p>
180
Chris Lattnerae853632002-07-25 19:27:01 +0000181... which actually parses the arguments and fills in the variable
182declarations.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000183
Chris Lattnerae853632002-07-25 19:27:01 +0000184Now that you are ready to support command line arguments, we need to tell the
185system which ones we want, and what type of argument they are. The CommandLine
186library uses a declarative syntax to model cammand line arguments with the
187variable declarations that capture the parsed values. This means that for every
188command line option that you would like to support, there should be a variable
189declaration to capture the result. For example, in a compiler, we would like to
190support the unix standard '<tt>-o &lt;filename&gt;</tt>' option to specify where
191to put the output. With the CommandLine library, this is represented like
192this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000193
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000194<pre><a name="value_desc_example">
195<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 +0000196</pre><p>
197
Chris Lattnerae853632002-07-25 19:27:01 +0000198This declares a variable "<tt>OutputFilename</tt>" that is used to capture the
199result of the "<tt>o</tt>" argument (first parameter). We specify that this is
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000200a simple scalar option by using the "<tt><a href="#cl::opt">cl::opt</a></tt>"
201template (as opposed to the <a href="#list">"<tt>cl::list</tt>
202template</a>), and tell the CommandLine library that the data type that we are
203parsing is a string.<p>
Chris Lattnerae853632002-07-25 19:27:01 +0000204
205The second and third parameters (which are optional) are used to specify what to
206output for the "<tt>--help</tt>" option. In this case, we get a line that looks
207like this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000208
209<pre>
Chris Lattnerae853632002-07-25 19:27:01 +0000210USAGE: compiler [options]
Chris Lattner209c7f42001-07-23 23:03:12 +0000211
Chris Lattnerae853632002-07-25 19:27:01 +0000212OPTIONS:
213 -help - display available options (--help-hidden for more)
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000214 <b>-o &lt;filename&gt; - Specify output filename</b>
Chris Lattnerae853632002-07-25 19:27:01 +0000215</pre>
216
217Because we specified that the command line option should parse using the
218<tt>string</tt> data type, the variable declared is automatically usable as a
219real string in all contexts that a normal C++ string object may be used. For
220example:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000221
222<pre>
223 ...
224 ofstream Output(OutputFilename.c_str());
225 if (Out.good()) ...
226 ...
227</pre><p>
228
Chris Lattnerae853632002-07-25 19:27:01 +0000229There are many different options that you can use to customize the command line
230option handling library, but the above example shows the general interface to
231these options. The options can be specified in any order, and are specified
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000232with helper functions like <a href="#cl::desc"><tt>cl::desc(...)</tt></a>, so
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000233there are no positional dependencies to remember. The available options are
234discussed in detail in the <a href="#referenceguide">Reference Guide</a>.<p>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000235
Chris Lattner209c7f42001-07-23 23:03:12 +0000236
Chris Lattnerae853632002-07-25 19:27:01 +0000237Continuing the example, we would like to have our compiler take an input
238filename as well as an output filename, but we do not want the input filename to
239be specified with a hyphen (ie, not <tt>-filename.c</tt>). To support this
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000240style of argument, the CommandLine library allows for <a
241href="#positional">positional</a> arguments to be specified for the program.
242These positional arguments are filled with command line parameters that are not
243in option form. We use this feature like this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000244
245<pre>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000246<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 +0000247</pre>
248
Chris Lattnerae853632002-07-25 19:27:01 +0000249This declaration indicates that the first positional argument should be treated
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000250as the input filename. Here we use the <tt><a
251href="#cl::init">cl::init</a></tt> option to specify an initial value for the
252command line option, which is used if the option is not specified (if you do not
253specify a <tt><a href="#cl::init">cl::init</a></tt> modifier for an option, then
254the default constructor for the data type is used to initialize the value).
Chris Lattnerae853632002-07-25 19:27:01 +0000255Command line options default to being optional, so if we would like to require
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000256that the user always specify an input filename, we would add the <tt><a
257href="#cl::Required">cl::Required</a></tt> flag, and we could eliminate the
258<tt><a href="#cl::init">cl::init</a></tt> modifier, like this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000259
260<pre>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000261<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 +0000262</pre>
263
Chris Lattnerae853632002-07-25 19:27:01 +0000264Again, the CommandLine library does not require the options to be specified in
265any particular order, so the above declaration is equivalent to:<p>
266
267<pre>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000268<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 +0000269</pre>
270
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000271By simply adding the <tt><a href="#cl::Required">cl::Required</a></tt> flag, the
272CommandLine library will automatically issue an error if the argument is not
273specified, which shifts all of the command line option verification code out of
274your application into the library. This is just one example of how using flags
275can alter the default behaviour of the library, on a per-option basis. By
276adding one of the declarations above, the <tt>--help</tt> option synopsis is now
277extended to:<p>
Chris Lattnerae853632002-07-25 19:27:01 +0000278
279<pre>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000280USAGE: compiler [options] <b>&lt;input file&gt;</b>
Chris Lattnerae853632002-07-25 19:27:01 +0000281
282OPTIONS:
283 -help - display available options (--help-hidden for more)
284 -o &lt;filename&gt; - Specify output filename
285</pre>
286
287... indicating that an input filename is expected.<p>
288
Chris Lattner209c7f42001-07-23 23:03:12 +0000289
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000290
Chris Lattner209c7f42001-07-23 23:03:12 +0000291<!-- ======================================================================= -->
292</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 +0000293<a name="bool">Boolean Arguments
Chris Lattner209c7f42001-07-23 23:03:12 +0000294</b></font></td></tr></table><ul>
295
Chris Lattnerae853632002-07-25 19:27:01 +0000296In addition to input and output filenames, we would like the compiler example to
297support three boolean flags: "<tt>-f</tt>" to force overwriting of the output
298file, "<tt>--quiet</tt>" to enable quiet mode, and "<tt>-q</tt>" for backwards
299compatibility with some of our users. We can support these by declaring options
300of boolean type like this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000301
302<pre>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000303<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>"));
304<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>"));
305<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 +0000306</pre><p>
307
Chris Lattnerae853632002-07-25 19:27:01 +0000308This does what you would expect: it declares three boolean variables
309("<tt>Force</tt>", "<tt>Quiet</tt>", and "<tt>Quiet2</tt>") to recognize these
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000310options. Note that the "<tt>-q</tt>" option is specified with the "<a
311href="#cl::Hidden"><tt>cl::Hidden</tt></a>" flag. This modifier prevents it
312from being shown by the standard "<tt>--help</tt>" output (note that it is still
313shown in the "<tt>--help-hidden</tt>" output).<p>
Chris Lattnerae853632002-07-25 19:27:01 +0000314
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000315The CommandLine library uses a <a href="#builtinparsers">different parser</a>
316for different data types. For example, in the string case, the argument passed
317to the option is copied literally into the content of the string variable... we
318obviously cannot do that in the boolean case, however, so we must use a smarter
319parser. In the case of the boolean parser, it allows no options (in which case
320it assigns the value of true to the variable), or it allows the values
321"<tt>true</tt>" or "<tt>false</tt>" to be specified, allowing any of the
322following inputs:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000323
324<pre>
Chris Lattnerae853632002-07-25 19:27:01 +0000325 compiler -f # No value, 'Force' == true
326 compiler -f=true # Value specified, 'Force' == true
327 compiler -f=TRUE # Value specified, 'Force' == true
328 compiler -f=FALSE # Value specified, 'Force' == false
329</pre>
330
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000331... you get the idea. The <a href="#boolparser">bool parser</a> just turns the
332string values into boolean values, and rejects things like '<tt>compiler
333-f=foo</tt>'. Similarly, the <a href="#doubleparser">float</a>, <a
334href="#doubleparser">double</a>, and <a href="#intparser">int</a> parsers work
335like you would expect, using the '<tt>strtol</tt>' and '<tt>strtod</tt>' C
336library calls to parse the string value into the specified data type.<p>
Chris Lattnerae853632002-07-25 19:27:01 +0000337
338With the declarations above, "<tt>compiler --help</tt>" emits this:<p>
339
340<pre>
341USAGE: compiler [options] &lt;input file&gt;
Chris Lattner209c7f42001-07-23 23:03:12 +0000342
343OPTIONS:
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000344 <b>-f - Overwrite output files</b>
Chris Lattner209c7f42001-07-23 23:03:12 +0000345 -o - Override output filename
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000346 <b>-quiet - Don't print informational messages</b>
Chris Lattner209c7f42001-07-23 23:03:12 +0000347 -help - display available options (--help-hidden for more)
348</pre><p>
349
Chris Lattnerae853632002-07-25 19:27:01 +0000350and "<tt>opt --help-hidden</tt>" prints this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000351
352<pre>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000353USAGE: compiler [options] &lt;input file&gt;
Chris Lattner209c7f42001-07-23 23:03:12 +0000354
355OPTIONS:
356 -f - Overwrite output files
357 -o - Override output filename
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000358 <b>-q - Don't print informational messages</b>
Chris Lattner209c7f42001-07-23 23:03:12 +0000359 -quiet - Don't print informational messages
360 -help - display available options (--help-hidden for more)
361</pre><p>
362
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000363This brief example has shown you how to use the '<tt><a
364href="#cl::opt">cl::opt</a></tt>' class to parse simple scalar command line
365arguments. In addition to simple scalar arguments, the CommandLine library also
366provides primitives to support CommandLine option <a href="#alias">aliases</a>,
367and <a href="#list">lists</a> of options.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000368
369
370<!-- ======================================================================= -->
371</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 +0000372<a name="alias">Argument Aliases
Chris Lattner209c7f42001-07-23 23:03:12 +0000373</b></font></td></tr></table><ul>
374
Chris Lattnerae853632002-07-25 19:27:01 +0000375So far, the example works well, except for the fact that we need to check the
376quiet condition like this now:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000377
378<pre>
379...
380 if (!Quiet &amp;&amp; !Quiet2) printInformationalMessage(...);
381...
382</pre><p>
383
Chris Lattnerae853632002-07-25 19:27:01 +0000384... which is a real pain! Instead of defining two values for the same
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000385condition, 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 +0000386option an <b>alias</b> for the "<tt>-quiet</tt>" option, instead of providing
387a value itself:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000388
389<pre>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000390<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>"));
391<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>"));
392<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 +0000393</pre><p>
394
Chris Lattnerae853632002-07-25 19:27:01 +0000395The third line (which is the only one we modified from above) defines a
396"<tt>-q</tt> alias that updates the "<tt>Quiet</tt>" variable (as specified by
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000397the <tt><a href="#cl::aliasopt">cl::aliasopt</a></tt> modifier) whenever it is
398specified. Because aliases do not hold state, the only thing the program has to
399query is the <tt>Quiet</tt> variable now. Another nice feature of aliases is
400that they automatically hide themselves from the <tt>-help</tt> output
401(although, again, they are still visible in the <tt>--help-hidden
402output</tt>).<p>
Chris Lattnerae853632002-07-25 19:27:01 +0000403
404Now the application code can simply use:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000405
406<pre>
407...
408 if (!Quiet) printInformationalMessage(...);
409...
410</pre><p>
411
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000412... 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 +0000413alternative name for any variable type, and has many uses.<p>
414
Chris Lattner209c7f42001-07-23 23:03:12 +0000415
416
417<!-- ======================================================================= -->
418</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 +0000419<a name="onealternative">Selecting an alternative from a set of possibilities
Chris Lattner209c7f42001-07-23 23:03:12 +0000420</b></font></td></tr></table><ul>
421
Chris Lattnerae853632002-07-25 19:27:01 +0000422So far, we have seen how the CommandLine library handles builtin types like
423<tt>std::string</tt>, <tt>bool</tt> and <tt>int</tt>, but how does it handle
424things it doesn't know about, like enums or '<tt>int*</tt>'s?<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000425
Chris Lattnerae853632002-07-25 19:27:01 +0000426The answer is that it uses a table driven generic parser (unless you specify
427your own parser, as described in the <a href="#extensionguide">Extension
428Guide</a>). This parser maps literal strings to whatever type is required, are
429requires you to tell it what this mapping should be.<p>
430
431Lets say that we would like to add four optimizations levels to our optimizer,
432using the standard flags "<tt>-g</tt>", "<tt>-O0</tt>", "<tt>-O1</tt>", and
433"<tt>-O2</tt>". We could easily implement this with boolean options like above,
434but there are several problems with this strategy:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000435
436<ol>
Chris Lattnerae853632002-07-25 19:27:01 +0000437<li>A user could specify more than one of the options at a time, for example,
438"<tt>opt -O3 -O2</tt>". The CommandLine library would not be able to catch this
439erroneous input for us.
440
Chris Lattner209c7f42001-07-23 23:03:12 +0000441<li>We would have to test 4 different variables to see which ones are set.
Chris Lattnerae853632002-07-25 19:27:01 +0000442
443<li>This doesn't map to the numeric levels that we want... so we cannot easily
444see if some level &gt;= "<tt>-O1</tt>" is enabled.
445
Chris Lattner209c7f42001-07-23 23:03:12 +0000446</ol><p>
447
Chris Lattnerae853632002-07-25 19:27:01 +0000448To cope with these problems, we can use an enum value, and have the CommandLine
449library fill it in with the appropriate level directly, which is used like
450this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000451
452<pre>
453enum OptLevel {
454 g, O1, O2, O3
455};
456
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000457<a href="#cl::opt">cl::opt</a>&lt;OptLevel&gt; OptimizationLevel(<a href="#cl::desc">cl::desc</a>("<i>Choose optimization level:</i>"),
458 <a href="#cl::values">cl::values</a>(
Chris Lattnerae853632002-07-25 19:27:01 +0000459 clEnumVal(g , "<i>No optimizations, enable debugging</i>"),
460 clEnumVal(O1, "<i>Enable trivial optimizations</i>"),
461 clEnumVal(O2, "<i>Enable default optimizations</i>"),
462 clEnumVal(O3, "<i>Enable expensive optimizations</i>"),
463 0));
Chris Lattner209c7f42001-07-23 23:03:12 +0000464
465...
Chris Lattnerae853632002-07-25 19:27:01 +0000466 if (OptimizationLevel &gt;= O2) doPartialRedundancyElimination(...);
Chris Lattner209c7f42001-07-23 23:03:12 +0000467...
468</pre><p>
469
Chris Lattnerae853632002-07-25 19:27:01 +0000470This declaration defines a variable "<tt>OptimizationLevel</tt>" of the
471"<tt>OptLevel</tt>" enum type. This variable can be assigned any of the values
472that are listed in the declaration (Note that the declaration list must be
473terminated with the "<tt>0</tt>" argument!). The CommandLine library enforces
474that the user can only specify one of the options, and it ensure that only valid
475enum values can be specified. The "<tt>clEnumVal</tt>" macros ensure that the
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000476command line arguments matched the enum values. With this option added, our
477help output now is:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000478
Chris Lattnerae853632002-07-25 19:27:01 +0000479<pre>
480USAGE: compiler [options] &lt;input file&gt;
Chris Lattner209c7f42001-07-23 23:03:12 +0000481
Chris Lattnerae853632002-07-25 19:27:01 +0000482OPTIONS:
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000483 <b>Choose optimization level:
Chris Lattnerae853632002-07-25 19:27:01 +0000484 -g - No optimizations, enable debugging
485 -O1 - Enable trivial optimizations
486 -O2 - Enable default optimizations
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000487 -O3 - Enable expensive optimizations</b>
Chris Lattnerae853632002-07-25 19:27:01 +0000488 -f - Overwrite output files
489 -help - display available options (--help-hidden for more)
490 -o &lt;filename&gt; - Specify output filename
491 -quiet - Don't print informational messages
492</pre>
Chris Lattner209c7f42001-07-23 23:03:12 +0000493
Chris Lattnerae853632002-07-25 19:27:01 +0000494In this case, it is sort of awkward that flag names correspond directly to enum
495names, because we probably don't want a enum definition named "<tt>g</tt>" in
496our program. Because of this, we can alternatively write this example like
497this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000498
499<pre>
500enum OptLevel {
501 Debug, O1, O2, O3
502};
503
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000504<a href="#cl::opt">cl::opt</a>&lt;OptLevel&gt; OptimizationLevel(<a href="#cl::desc">cl::desc</a>("<i>Choose optimization level:</i>"),
505 <a href="#cl::values">cl::values</a>(
Chris Lattnerae853632002-07-25 19:27:01 +0000506 clEnumValN(Debug, "g", "<i>No optimizations, enable debugging</i>"),
507 clEnumVal(O1 , "<i>Enable trivial optimizations</i>"),
508 clEnumVal(O2 , "<i>Enable default optimizations</i>"),
509 clEnumVal(O3 , "<i>Enable expensive optimizations</i>"),
510 0));
Chris Lattner209c7f42001-07-23 23:03:12 +0000511
512...
513 if (OptimizationLevel == Debug) outputDebugInfo(...);
514...
515</pre><p>
516
Chris Lattnerae853632002-07-25 19:27:01 +0000517By using the "<tt>clEnumValN</tt>" macro instead of "<tt>clEnumVal</tt>", we can
518directly specify the name that the flag should get. In general a direct mapping
519is nice, but sometimes you can't or don't want to preserve the mapping, which is
520when you would use it.<p>
521
522
Chris Lattner209c7f42001-07-23 23:03:12 +0000523
524<!-- ======================================================================= -->
525</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>
526<a name="namedalternatives">Named Alternatives
527</b></font></td></tr></table><ul>
528
Chris Lattnerae853632002-07-25 19:27:01 +0000529Another useful argument form is a named alternative style. We shall use this
530style in our compiler to specify different debug levels that can be used.
531Instead of each debug level being its own switch, we want to support the
532following options, of which only one can be specified at a time:
533"<tt>--debug-level=none</tt>", "<tt>--debug-level=quick</tt>",
534"<tt>--debug-level=detailed</tt>". To do this, we use the exact same format as
535our optimization level flags, but we also specify an option name. For this
536case, the code looks like this:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000537
538<pre>
539enum DebugLev {
540 nodebuginfo, quick, detailed
541};
542
543// Enable Debug Options to be specified on the command line
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000544<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>"),
545 <a href="#cl::values">cl::values</a>(
Chris Lattnerae853632002-07-25 19:27:01 +0000546 clEnumValN(nodebuginfo, "none", "<i>disable debug information</i>"),
547 clEnumVal(quick, "<i>enable quick debug information</i>"),
548 clEnumVal(detailed, "<i>enable detailed debug information</i>"),
549 0));
Chris Lattner209c7f42001-07-23 23:03:12 +0000550</pre>
551
Chris Lattnerae853632002-07-25 19:27:01 +0000552This definition defines an enumerated command line variable of type "<tt>enum
553DebugLev</tt>", which works exactly the same way as before. The difference here
554is just the interface exposed to the user of your program and the help output by
555the "<tt>--help</tt>" option:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000556
557<pre>
Chris Lattnerae853632002-07-25 19:27:01 +0000558USAGE: compiler [options] &lt;input file&gt;
559
Chris Lattner209c7f42001-07-23 23:03:12 +0000560OPTIONS:
Chris Lattnerae853632002-07-25 19:27:01 +0000561 Choose optimization level:
562 -g - No optimizations, enable debugging
563 -O1 - Enable trivial optimizations
564 -O2 - Enable default optimizations
565 -O3 - Enable expensive optimizations
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000566 <b>-debug_level - Set the debugging level:
Chris Lattnerae853632002-07-25 19:27:01 +0000567 =none - disable debug information
568 =quick - enable quick debug information
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000569 =detailed - enable detailed debug information</b>
Chris Lattnerae853632002-07-25 19:27:01 +0000570 -f - Overwrite output files
571 -help - display available options (--help-hidden for more)
572 -o &lt;filename&gt; - Specify output filename
573 -quiet - Don't print informational messages
Chris Lattner209c7f42001-07-23 23:03:12 +0000574</pre><p>
575
Chris Lattnerae853632002-07-25 19:27:01 +0000576Again, the only structural difference between the debug level declaration and
577the optimiation level declaration is that the debug level declaration includes
578an option name (<tt>"debug_level"</tt>), which automatically changes how the
579library processes the argument. The CommandLine library supports both forms so
580that you can choose the form most appropriate for your application.<p>
581
Chris Lattner209c7f42001-07-23 23:03:12 +0000582
583
584<!-- ======================================================================= -->
585</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 +0000586<a name="list">Parsing a list of options
Chris Lattner209c7f42001-07-23 23:03:12 +0000587</b></font></td></tr></table><ul>
588
Chris Lattnerae853632002-07-25 19:27:01 +0000589Now that we have the standard run of the mill argument types out of the way,
590lets get a little wild and crazy. Lets say that we want our optimizer to accept
591a <b>list</b> of optimizations to perform, allowing duplicates. For example, we
592might want to run: "<tt>compiler -dce -constprop -inline -dce -strip</tt>". In
593this case, the order of the arguments and the number of appearances is very
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000594important. This is what the "<tt><a href="#cl::list">cl::list</a></tt>"
595template is for. First, start by defining an enum of the optimizations that you
596would like to perform:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000597
598<pre>
599enum Opts {
Chris Lattnerae853632002-07-25 19:27:01 +0000600 // 'inline' is a C++ keyword, so name it 'inlining'
Chris Lattner209c7f42001-07-23 23:03:12 +0000601 dce, constprop, inlining, strip
Chris Lattnerae853632002-07-25 19:27:01 +0000602};
Chris Lattner209c7f42001-07-23 23:03:12 +0000603</pre><p>
604
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000605Then define your "<tt><a href="#cl::list">cl::list</a></tt>" variable:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000606
607<pre>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000608<a href="#cl::list">cl::list</a>&lt;Opts&gt; OptimizationList(<a href="#cl::desc">cl::desc</a>("<i>Available Optimizations:</i>"),
609 <a href="#cl::values">cl::values</a>(
Chris Lattnerae853632002-07-25 19:27:01 +0000610 clEnumVal(dce , "<i>Dead Code Elimination</i>"),
Misha Brukman82c89b92003-05-20 21:01:22 +0000611 clEnumVal(constprop , "<i>Constant Propagation</i>"),
Chris Lattnerae853632002-07-25 19:27:01 +0000612 clEnumValN(inlining, "<i>inline</i>", "<i>Procedure Integration</i>"),
613 clEnumVal(strip , "<i>Strip Symbols</i>"),
614 0));
Chris Lattner209c7f42001-07-23 23:03:12 +0000615</pre><p>
616
Chris Lattnerae853632002-07-25 19:27:01 +0000617This defines a variable that is conceptually of the type
618"<tt>std::vector&lt;enum Opts&gt;</tt>". Thus, you can access it with standard
619vector methods:<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000620
621<pre>
Chris Lattnerae853632002-07-25 19:27:01 +0000622 for (unsigned i = 0; i != OptimizationList.size(); ++i)
Chris Lattner209c7f42001-07-23 23:03:12 +0000623 switch (OptimizationList[i])
624 ...
625</pre>
626
Chris Lattnerae853632002-07-25 19:27:01 +0000627... to iterate through the list of options specified.<p>
Chris Lattner209c7f42001-07-23 23:03:12 +0000628
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000629Note 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 +0000630with any data types or other arguments that you can use with the
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000631"<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 +0000632capture all of the positional arguments together if there may be more than one
633specified. In the case of a linker, for example, the linker takes several
634'<tt>.o</tt>' files, and needs to capture them into a list. This is naturally
635specified as:<p>
Chris Lattner3e5fe172002-04-13 18:35:59 +0000636
637<pre>
638...
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000639<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 +0000640...
641</pre><p>
642
Chris Lattnerae853632002-07-25 19:27:01 +0000643This variable works just like a "<tt>vector&lt;string&gt;</tt>" object. As
644such, accessing the list is simple, just like above. In this example, we used
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000645the <tt><a href="#cl::OneOrMore">cl::OneOrMore</a></tt> modifier to inform the
646CommandLine library that it is an error if the user does not specify any
647<tt>.o</tt> files on our command line. Again, this just reduces the amount of
648checking we have to do.<p>
Chris Lattner3e5fe172002-04-13 18:35:59 +0000649
Chris Lattner3e5fe172002-04-13 18:35:59 +0000650
651
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000652<!-- ======================================================================= -->
653</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>
654<a name="description">Adding freeform text to help output
655</b></font></td></tr></table><ul>
656
657As our program grows and becomes more mature, we may decide to put summary
658information about what it does into the help output. The help output is styled
659to look similar to a Unix <tt>man</tt> page, providing concise information about
660a program. Unix <tt>man</tt> pages, however often have a description about what
661the program does. To add this to your CommandLine program, simply pass a third
662argument to the <a
663href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>
664call in main. This additional argument is then printed as the overview
665information for your program, allowing you to include any additional information
666that you want. For example:<p>
667
668<pre>
669int main(int argc, char **argv) {
670 <a href="#cl::ParseCommandLineOptions">cl::ParseCommandLineOptions</a>(argc, argv, " CommandLine compiler example\n\n"
671 " This program blah blah blah...\n");
672 ...
673}
674</pre><p>
675
676Would yield the help output:
677
678<pre>
679<b>OVERVIEW: CommandLine compiler example
680
681 This program blah blah blah...</b>
682
683USAGE: compiler [options] &lt;input file&gt;
684
685OPTIONS:
686 ...
687 -help - display available options (--help-hidden for more)
688 -o &lt;filename&gt; - Specify output filename
689</pre><p>
690
691
692
693
Chris Lattner209c7f42001-07-23 23:03:12 +0000694<!-- *********************************************************************** -->
695</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>
696<a name="referenceguide">Reference Guide
697</b></font></td></tr></table><ul>
698<!-- *********************************************************************** -->
699
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000700Now that you know the basics of how to use the CommandLine library, this section
701will give you the detailed information you need to tune how command line options
702work, as well as information on more "advanced" command line option processing
703capabilities.<p>
704
705
706<!-- ======================================================================= -->
707</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>
708<a name="positional">Positional Arguments
709</b></font></td></tr></table><ul>
710
711Positional arguments are those arguments that are not named, and are not
712specified with a hyphen. Positional arguments should be used when an option is
713specified by its position alone. For example, the standard Unix <tt>grep</tt>
714tool takes a regular expression argument, and an optional filename to search
715through (which defaults to standard input if a filename is not specified).
716Using the CommandLine library, this would be specified as:<p>
717
718<pre>
719<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>);
720<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>"));
721</pre>
722
723Given these two option declarations, the <tt>--help</tt> output for our grep
724replacement would look like this:<p>
725
726<pre>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000727USAGE: spiffygrep [options] <b>&lt;regular expression&gt; &lt;input file&gt;</b>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000728
729OPTIONS:
730 -help - display available options (--help-hidden for more)
731</pre>
732
733... and the resultant program could be used just like the standard <tt>grep</tt>
734tool.<p>
735
736Positional arguments are sorted by their order of construction. This means that
737command line options will be ordered according to how they are listed in a .cpp
738file, but will not have an ordering defined if they positional arguments are
739defined in multiple .cpp files. The fix for this problem is simply to define
740all of your positional arguments in one .cpp file.<p>
741
742
743
744<!-- _______________________________________________________________________ -->
745</ul><a name="--"><h4><hr size=0>Specifying positional options with hyphens</h4><ul>
746
747Sometimes you may want to specify a value to your positional argument that
748starts with a hyphen (for example, searching for '<tt>-foo</tt>' in a file). At
749first, you will have trouble doing this, because it will try to find an argument
750named '<tt>-foo</tt>', and will fail (and single quotes will not save you).
751Note that the system <tt>grep</tt> has the same problem:<p>
752
753<pre>
754 $ spiffygrep '-foo' test.txt
755 Unknown command line argument '-foo'. Try: spiffygrep --help'
756
757 $ grep '-foo' test.txt
758 grep: illegal option -- f
759 grep: illegal option -- o
760 grep: illegal option -- o
761 Usage: grep -hblcnsviw pattern file . . .
762</pre><p>
763
764The solution for this problem is the same for both your tool and the system
765version: use the '<tt>--</tt>' marker. When the user specifies '<tt>--</tt>' on
766the command line, it is telling the program that all options after the
767'<tt>--</tt>' should be treated as positional arguments, not options. Thus, we
768can use it like this:<p>
769
770<pre>
771 $ spiffygrep -- -foo test.txt
772 ...output...
773</pre><p>
774
775
776
777<!-- _______________________________________________________________________ -->
778</ul><a name="cl::ConsumeAfter"><h4><hr size=0>The <tt>cl::ConsumeAfter</tt> modifier</h4><ul>
779
780The <tt>cl::ConsumeAfter</tt> <a href="#formatting">formatting option</a> is
781used to construct programs that use "interpreter style" option processing. With
782this style of option processing, all arguments specified after the last
783positional argument are treated as special interpreter arguments that are not
784interpreted by the command line argument.<p>
785
786As a concrete example, lets say we are developing a replacement for the standard
787Unix Bourne shell (<tt>/bin/sh</tt>). To run <tt>/bin/sh</tt>, first you
788specify options to the shell itself (like <tt>-x</tt> which turns on trace
789output), then you specify the name of the script to run, then you specify
790arguments to the script. These arguments to the script are parsed by the bourne
791shell command line option processor, but are not interpreted as options to the
792shell itself. Using the CommandLine library, we would specify this as:<p>
793
794<pre>
795<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>("-"));
796<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>"));
797<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>"));
798</pre><p>
799
800which automatically provides the help output:<p>
801
802<pre>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000803USAGE: spiffysh [options] <b>&lt;input script&gt; &lt;program arguments&gt;...</b>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000804
805OPTIONS:
806 -help - display available options (--help-hidden for more)
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000807 <b>-x - Enable trace output</b>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000808</pre><p>
809
810At runtime, if we run our new shell replacement as '<tt>spiffysh -x test.sh -a
811-x -y bar</tt>', the <tt>Trace</tt> variable will be set to true, the
812<tt>Script</tt> variable will be set to "<tt>test.sh</tt>", and the
813<tt>Argv</tt> list will contain <tt>["-a", "-x", "-y", "bar"]</tt>, because
814they were specified after the last positional argument (which is the script
815name).<p>
816
817There are several limitations to when <tt>cl::ConsumeAfter</tt> options can be
818specified. For example, only one <tt>cl::ConsumeAfter</tt> can be specified per
819program, there must be at least one <a href="#positional">positional
820argument</a> specified, and the <tt>cl::ConsumeAfter</tt> option should be a <a
821href="#cl::list">cl::list</a> option.<p>
822
823
824
825<!-- ======================================================================= -->
826</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>
827<a name="storage">Internal vs External Storage
828</b></font></td></tr></table><ul>
829
830By default, all command line options automatically hold the value that they
831parse from the command line. This is very convenient in the common case,
832especially when combined with the ability to define command line options in the
833files that use them. This is called the internal storage model.<p>
834
835Sometimes, however, it is nice to separate the command line option processing
836code from the storage of the value parsed. For example, lets say that we have a
837'<tt>-debug</tt>' option that we would like to use to enable debug information
838across the entire body of our program. In this case, the boolean value
839controlling the debug code should be globally accessable (in a header file, for
840example) yet the command line option processing code should not be exposed to
841all of these clients (requiring lots of .cpp files to #include
842<tt>CommandLine.h</tt>).<p>
843
844To do this, set up your .h file with your option, like this for example:<p>
845
846<pre>
847<i>// DebugFlag.h - Get access to the '-debug' command line option
848//
849
850// DebugFlag - This boolean is set to true if the '-debug' command line option
851// is specified. This should probably not be referenced directly, instead, use
852// the DEBUG macro below.
853//</i>
854extern bool DebugFlag;
855
856<i>// DEBUG macro - This macro should be used by code to emit debug information.
857// In the '-debug' option is specified on the command line, and if this is a
858// debug build, then the code specified as the option to the macro will be
859// executed. Otherwise it will not be. Example:
860//
861// DEBUG(cerr << "Bitset contains: " << Bitset << "\n");
862//</i>
863<font color=red>#ifdef NDEBUG
864#define DEBUG(X)
865#else
866#define DEBUG(X)</font> \
867 do { if (DebugFlag) { X; } } while (0)
868<font color=red>#endif</font>
869</pre>
870
871This allows clients to blissfully use the <tt>DEBUG()</tt> macro, or the
872<tt>DebugFlag</tt> explicitly if they want to. Now we just need to be able to
873set the <tt>DebugFlag</tt> boolean when the option is set. To do this, we pass
874an additial argument to our command line argument processor, and we specify
875where to fill in with the <a href="#cl::location">cl::location</a> attribute:<p>
876
877<pre>
878bool DebugFlag; <i>// the actual value</i>
879static <a href="#cl::opt">cl::opt</a><bool, true> <i>// The parser</i>
880Debug("<i>debug</i>", <a href="#cl::desc">cl::desc</a>("<i>Enable debug output</i>")</a>, <a href="#cl::Hidden">cl::Hidden</a>,
881 <a href="#cl::location">cl::location</a>(DebugFlag));
882</pre>
883
884In the above example, we specify "<tt>true</tt>" as the second argument to the
885<a href="#cl::opt">cl::opt</a> template, indicating that the template should not
886maintain a copy of the value itself. In addition to this, we specify the <a
887href="#cl::location">cl::location</a> attribute, so that <tt>DebugFlag</tt> is
888automatically set.<p>
889
890
891
892<!-- ======================================================================= -->
893</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>
894<a name="attributes">Option Attributes
895</b></font></td></tr></table><ul>
896
897This section describes the basic attributes that you can specify on options.<p>
898
899<ul>
900
901<li>The option name attribute (which is required for all options, except <a
902href="#positional">positional options</a>) specifies what the option name is.
903This option is specified in simple double quotes:<p>
904
Chris Lattnerc1ae40c2002-08-07 18:27:04 +0000905<pre>
906<a href="#cl::opt">cl::opt</a>&lt;<b>bool</b>&gt; Quiet("<i>quiet</i>");
907</pre><p>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000908
909<li><a name="cl::desc">The <b><tt>cl::desc</tt></b> attribute specifies a
910description for the option to be shown in the <tt>--help</tt> output for the
911program.<p>
912
913<li><a name="cl::value_desc">The <b><tt>cl::value_desc</tt></b> attribute
914specifies a string that can be used to fine tune the <tt>--help</tt> output for
915a command line option. Look <a href="#value_desc_example">here</a> for an
916example.<p>
917
918<li><a name="cl::init">The <b><tt>cl::init</tt></b> attribute specifies an
919inital value for a <a href="#cl::opt">scalar</a> option. If this attribute is
920not specified then the command line option value defaults to the value created
921by the default constructor for the type.<p>
922
923<li><a name="cl::location">The <b><tt>cl::location</tt></b> attribute where to
924store the value for a parsed command line option if using external storage. See
925the section on <a href="#storage">Internal vs External Storage</a> for more
926information.<p>
927
928<li><a name="cl::aliasopt">The <b><tt>cl::aliasopt</tt></b> attribute specifies
929which option a <a href="#cl::alias">cl::alias</a> option is an alias for.<p>
930
931<li><a name="cl::values">The <b><tt>cl::values</tt></b> attribute specifies the
932string-to-value mapping to be used by the generic parser. It takes a <b>null
933terminated</b> list of (option, value, description) triplets that specify the
934option name, the value mapped to, and the description shown in the
935<tt>--help</tt> for the tool. Because the generic parser is used most frequently with enum values, two macros are often useful:<p>
936<ol>
937<li><a name="clEnumVal">The <b><tt>clEnumVal</tt></b> macro is used as a nice
938simple way to specify a triplet for an enum. This macro automatically makes the
939option name be the same as the enum name. The first option to the macro is the
940enum, the second is the description for the command line option.<p> <li><a
941name="clEnumValN">The <b><tt>clEnumValN</tt></b> macro is used to specify macro
942options where the option name doesn't equal the enum name. For this macro, the
943first argument is the enum value, the second is the flag name, and the second is
944the description.<p>
945</ol>
946
947You will get a compile time error if you try to use cl::values with a parser
948that does not support it.<p>
949
950</ul>
951
952
953
954<!-- ======================================================================= -->
955</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>
956<a name="modifiers">Option Modifiers
957</b></font></td></tr></table><ul>
958
959Option modifiers are the flags and expressions that you pass into the
960constructors for <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
961href="#cl::list">cl::list</a></tt>. These modifiers give you the ability to
962tweak how options are parsed and how <tt>--help</tt> output is generated to fit
963your application well.<p>
964
Chris Lattner32a32842003-05-22 20:36:06 +0000965These options fall into five main catagories:<p>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000966
967<ol>
968<li><a href="#hiding">Hiding an option from <tt>--help</tt> output</a>
969<li><a href="#numoccurances">Controlling the number of occurances
970 required and allowed</a>
971<li><a href="#valrequired">Controlling whether or not a value must be
972 specified</a>
973<li><a href="#formatting">Controlling other formatting options</a>
Chris Lattner32a32842003-05-22 20:36:06 +0000974<li><a href="#misc">Miscellaneous option modifiers</a>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000975</ol><p>
976
977It is not possible to specify two options from the same catagory (you'll get a
Chris Lattner32a32842003-05-22 20:36:06 +0000978runtime error) to a single option, except for options in the miscellaneous
979catagory. The CommandLine library specifies defaults for all of these settings
980that are the most useful in practice and the most common, which mean that you
981usually shouldn't have to worry about these.<p>
Chris Lattnere76d4ab2002-08-06 19:36:06 +0000982
983
984<!-- _______________________________________________________________________ -->
985</ul><a name="hiding"><h4><hr size=0>Hiding an option from <tt>--help</tt> output</h4><ul>
986
987The <tt>cl::NotHidden</tt>, <tt>cl::Hidden</tt>, and <tt>cl::ReallyHidden</tt>
988modifiers are used to control whether or not an option appears in the
989<tt>--help</tt> and <tt>--help-hidden</tt> output for the compiled program:<p>
990
991<ul>
992
993<a name="cl::NotHidden">The <b><tt>cl::NotHidden</tt></b> modifier (which is the
994default for <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
995href="#cl::list">cl::list</a></tt> options), indicates the option is to appear
996in both help listings.<p>
997
998<a name="cl::Hidden">The <b><tt>cl::Hidden</tt></b> modifier (which is the
999default for <tt><a href="#cl::alias">cl::alias</a></tt> options), indicates that
1000the option should not appear in the <tt>--help</tt> output, but should appear in
1001the <tt>--help-hidden</tt> output.<p>
1002
1003<a name="cl::ReallyHidden">The <b><tt>cl::ReallyHidden</tt></b> modifier,
1004indicates that the option should not appear in any help output.<p>
1005</ul>
1006
1007<!-- _______________________________________________________________________ -->
1008</ul><a name="numoccurances"><h4><hr size=0>Controlling the number of occurances required and allowed</h4><ul>
1009
1010This group of options is used to control how many time an option is allowed (or
1011required) to be specified on the command line of your program. Specifying a
1012value for this setting allows the CommandLine library to do error checking for
1013you.<p>
1014
1015The allowed values for this option group are:<p>
1016
1017<ul>
1018<a name="cl::Optional">The <b><tt>cl::Optional</tt></b> modifier (which is the
1019default for the <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
1020href="#cl::alias">cl::alias</a></tt> classes) indicates that your program will
1021allow either zero or one occurance of the option to be specified.<p>
1022
1023<a name="cl::ZeroOrMore">The <b><tt>cl::ZeroOrMore</tt></b> modifier (which is
1024the default for the <tt><a href="#cl::list">cl::list</a></tt> class) indicates
1025that your program will allow the option to be specified zero or more times.<p>
1026
1027<a name="cl::Required">The <b><tt>cl::Required</tt></b> modifier indicates that
1028the specified option must be specified exactly one time.<p>
1029
1030<a name="cl::OneOrMore">The <b><tt>cl::OneOrMore</tt></b> modifier indicates
1031that the option must be specified at least one time.<p>
1032
1033The <b><tt>cl::ConsumeAfter</tt></b> modifier is described in the <a
1034href="#positional">Positional arguments section</a><p>
1035
1036</ul>
1037
1038If an option is not specified, then the value of the option is equal to the
1039value specified by the <tt><a href="#cl::init">cl::init</a></tt> attribute. If
1040the <tt><a href="#cl::init">cl::init</a></tt> attribute is not specified, the
1041option value is initialized with the default constructor for the data type.<p>
1042
1043If an option is specified multiple times for an option of the <tt><a
1044href="#cl::opt">cl::opt</a></tt> class, only the last value will be retained.<p>
1045
1046
1047<!-- _______________________________________________________________________ -->
1048</ul><a name="valrequired"><h4><hr size=0>Controlling whether or not a value must be specified</h4><ul>
1049
1050This group of options is used to control whether or not the option allows a
1051value to be present. In the case of the CommandLine library, a value is either
1052specified with an equal sign (e.g. '<tt>-index-depth=17</tt>') or as a trailing
1053string (e.g. '<tt>-o a.out</tt>').<p>
1054
1055The allowed values for this option group are:<p>
1056
1057<ul>
1058<a name="cl::ValueOptional">The <b><tt>cl::ValueOptional</tt></b> modifier
1059(which is the default for <tt>bool</tt> typed options) specifies that it is
1060acceptable to have a value, or not. A boolean argument can be enabled just by
1061appearing on the command line, or it can have an explicit '<tt>-foo=true</tt>'.
1062If an option is specified with this mode, it is illegal for the value to be
1063provided without the equal sign. Therefore '<tt>-foo true</tt>' is illegal. To
1064get this behavior, you must use the <a
1065href="#cl::ValueRequired">cl::ValueRequired</a> modifier.<p>
1066
1067<a name="cl::ValueRequired">The <b><tt>cl::ValueRequired</tt></b> modifier
1068(which is the default for all other types except for <a
1069href="#onealternative">unnamed alternatives using the generic parser</a>)
1070specifies that a value must be provided. This mode informs the command line
1071library that if an option is not provides with an equal sign, that the next
1072argument provided must be the value. This allows things like '<tt>-o
1073a.out</tt>' to work.<p>
1074
1075<a name="cl::ValueDisallowed">The <b><tt>cl::ValueDisallowed</tt></b> modifier
1076(which is the default for <a href="#onealternative">unnamed alternatives using
1077the 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>
1078
1079</ul>
1080
1081In general, the default values for this option group work just like you would
1082want them to. As mentioned above, you can specify the <a
1083href="#cl::ValueDisallowed">cl::ValueDisallowed</a> modifier to a boolean
1084argument to restrict your command line parser. These options are mostly useful
1085when <a href="#extensionguide">extending the library</a>.<p>
1086
1087
1088
1089<!-- _______________________________________________________________________ -->
1090</ul><a name="formatting"><h4><hr size=0>Controlling other formatting options</h4><ul>
1091
1092The formatting option group is used to specify that the command line option has
1093special abilities and is otherwise different from other command line arguments.
1094As usual, you can only specify at most one of these arguments.<p>
1095
1096<ul>
1097<a name="cl::NormalFormatting">The <b><tt>cl::NormalFormatting</tt></b> modifier
1098(which is the default all options) specifies that this option is "normal".<p>
1099
1100<a name="cl::Positional">The <b><tt>cl::Positional</tt></b> modifier specifies
1101that this is a positional argument, that does not have a command line option
1102associated with it. See the <a href="#positional">Positional Arguments</a>
1103section for more information.<p>
1104
1105The <b><a href="#cl::ConsumeAfter"><tt>cl::ConsumeAfter</tt></a></b> modifier
1106specifies that this option is used to capture "interpreter style" arguments. See <a href="#cl::ConsumeAfter">this section for more information</a>.<p>
1107
1108
1109<a name="cl::Prefix">The <b><tt>cl::Prefix</tt></b> modifier specifies that this
1110option prefixes its value. With 'Prefix' options, there is no equal sign that
1111seperates the value from the option name specified. This is useful for
1112processing odd arguments like '<tt>-lmalloc -L/usr/lib'</tt> in a linker tool.
1113Here, the '<tt>l</tt>' and '<tt>L</tt>' options are normal string (list)
1114options, that have the <a href="#cl::Prefix">cl::Prefix</a> modifier added to
1115allow the CommandLine library to recognize them. Note that <a
1116href="#cl::Prefix">cl::Prefix</a> options must not have the <a
1117href="#cl::ValueDisallowed">cl::ValueDisallowed</a> modifier specified.<p>
1118
1119<a name="cl::Grouping">The <b><tt>cl::Grouping</tt></b> modifier is used to
1120implement unix style tools (like <tt>ls</tt>) that have lots of single letter
1121arguments, but only require a single dash. For example, the '<tt>ls -labF</tt>'
1122command actually enables four different options, all of which are single
1123letters. Note that <a href="#cl::Grouping">cl::Grouping</a> options cannot have
1124values.<p>
1125
1126</ul>
1127
1128The CommandLine library does not restrict how you use the <a
1129href="#cl::Prefix">cl::Prefix</a> or <a href="#cl::Grouping">cl::Grouping</a>
1130modifiers, but it is possible to specify ambiguous argument settings. Thus, it
1131is possible to have multiple letter options that are prefix or grouping options,
1132and they will still work as designed.<p>
1133
1134To do this, the CommandLine library uses a greedy algorithm to parse the input
1135option into (potentially multiple) prefix and grouping options. The strategy
1136basically looks like this:<p>
1137
1138<tt>parse(string OrigInput) {</tt>
1139<ol>
1140<li><tt>string input = OrigInput;</tt>
1141<li><tt>if (isOption(input)) return getOption(input).parse();</tt>&nbsp;&nbsp;&nbsp;&nbsp;<i>// Normal option</i>
1142<li><tt>while (!isOption(input) &amp;&amp; !input.empty()) input.pop_back();</tt>&nbsp;&nbsp;&nbsp;&nbsp;<i>// Remove the last letter</i>
1143<li><tt>if (input.empty()) return error();</tt>&nbsp;&nbsp;&nbsp;&nbsp;<i>// No matching option</i>
1144<li><tt>if (getOption(input).isPrefix())<br>
1145&nbsp;&nbsp;return getOption(input).parse(input);</tt>
1146<li><tt>while (!input.empty()) {&nbsp;&nbsp;&nbsp;&nbsp;<i>// Must be grouping options</i><br>
1147&nbsp;&nbsp;getOption(input).parse();<br>
1148&nbsp;&nbsp;OrigInput.erase(OrigInput.begin(), OrigInput.begin()+input.length());<br>
1149&nbsp;&nbsp;input = OrigInput;<br>
1150&nbsp;&nbsp;while (!isOption(input) &amp;&amp; !input.empty()) input.pop_back();<br>
1151}</tt>
1152<li><tt>if (!OrigInput.empty()) error();</tt>
1153</tt>
1154
1155</ol>
1156<tt>}</tt><p>
1157
1158
Chris Lattner32a32842003-05-22 20:36:06 +00001159
1160<!-- _______________________________________________________________________ -->
1161</ul><a name="misc"><h4><hr size=0>Miscellaneous option modifiers</h4><ul>
1162
1163The miscellaneous option modifiers are the only flags where you can specify more
1164than one flag from the set: they are not mutually exclusive. These flags
1165specify boolean properties that modify the option.<p>
1166
1167<ul>
1168
1169<a name="cl::CommaSeparated">The <b><tt>cl::CommaSeparated</tt></b> modifier
1170indicates that any commas specified for an option's value should be used to
1171split the value up into multiple values for the option. For example, these two
1172options are equivalent when <tt>cl::CommaSeparated</tt> is specified:
1173"<tt>-foo=a -foo=b -foo=c</tt>" and "<tt>-foo=a,b,c</tt>". This option only
1174makes sense to be used in a case where the option is allowed to accept one or
1175more values (i.e. it is a <a href="#cl::list">cl::list</a> option).<p>
1176</ul>
1177
1178So far, the only miscellaneous option modifier is the
1179<tt>cl::CommaSeparated</tt> modifier.<p>
1180
1181
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001182<!-- ======================================================================= -->
1183</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 +00001184<a name="toplevel">Top-Level Classes and Functions
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001185</b></font></td></tr></table><ul>
1186
1187Despite all of the builtin flexibility, the CommandLine option library really
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001188only consists of one function (<a
1189href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>)
1190and three main classes: <a href="#cl::opt"><tt>cl::opt</tt></a>, <a
1191href="#cl::list"><tt>cl::list</tt></a>, and <a
1192href="#cl::alias"><tt>cl::alias</tt></a>. This section describes these three
1193classes in detail.<p>
1194
1195<!-- _______________________________________________________________________ -->
1196</ul><a name="cl::ParseCommandLineOptions"><h4><hr size=0>The
1197<tt>cl::ParseCommandLineOptions</tt> function</h4><ul>
1198
1199The <tt>cl::ParseCommandLineOptions</tt> function is designed to be called
1200directly from <tt>main</tt>, and is used to fill in the values of all of the
1201command line option variables once <tt>argc</tt> and <tt>argv</tt> are
1202available.<p>
1203
1204The <tt>cl::ParseCommandLineOptions</tt> function requires two parameters
1205(<tt>argc</tt> and <tt>argv</tt>), but may also take an optional third parameter
1206which holds <a href="#description">additional extra text</a> to emit when the
1207<tt>--help</tt> option is invoked.<p>
1208
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001209
1210<!-- _______________________________________________________________________ -->
1211</ul><a name="cl::opt"><h4><hr size=0>The <tt>cl::opt</tt> class</h4><ul>
1212
1213The <tt>cl::opt</tt> class is the class used to represent scalar command line
1214options, and is the one used most of the time. It is a templated class which
1215can take up to three arguments (all except for the first have default values
1216though):<p>
1217
1218<pre>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001219<b>namespace</b> cl {
1220 <b>template</b> &lt;<b>class</b> DataType, <b>bool</b> ExternalStorage = <b>false</b>,
1221 <b>class</b> ParserClass = parser&lt;DataType&gt; &gt;
1222 <b>class</b> opt;
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001223}
1224</pre><p>
1225
1226The first template argument specifies what underlying data type the command line
1227argument is, and is used to select a default parser implementation. The second
1228template argument is used to specify whether the option should contain the
1229storage for the option (the default) or whether external storage should be used
1230to contain the value parsed for the option (see <a href="#storage">Internal vs
1231External Storage</a> for more information).<p>
1232
1233The third template argument specifies which parser to use. The default value
1234selects an instantiation of the <tt>parser</tt> class based on the underlying
1235data type of the option. In general, this default works well for most
1236applications, so this option is only used when using a <a
1237href="#customparser">custom parser</a>.<p>
1238
1239
1240<!-- _______________________________________________________________________ -->
1241</ul><a name="cl::list"><h4><hr size=0>The <tt>cl::list</tt> class</h4><ul>
1242
1243The <tt>cl::list</tt> class is the class used to represent a list of command
1244line options. It too is a templated class which can take up to three
1245arguments:<p>
1246
1247<pre>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001248<b>namespace</b> cl {
1249 <b>template</b> &lt;<b>class</b> DataType, <b>class</b> Storage = <b>bool</b>,
1250 <b>class</b> ParserClass = parser&lt;DataType&gt; &gt;
1251 <b>class</b> list;
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001252}
1253</pre><p>
1254
1255This class works the exact same as the <a href="#cl::opt"><tt>cl::opt</tt></a>
1256class, except that the second argument is the <b>type</b> of the external
1257storage, not a boolean value. For this class, the marker type '<tt>bool</tt>'
1258is used to indicate that internal storage should be used.<p>
1259
1260
1261<!-- _______________________________________________________________________ -->
1262</ul><a name="cl::alias"><h4><hr size=0>The <tt>cl::alias</tt> class</h4><ul>
1263
1264The <tt>cl::alias</tt> class is a nontemplated class that is used to form
1265aliases for other arguments.<p>
1266
1267<pre>
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001268<b>namespace</b> cl {
1269 <b>class</b> alias;
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001270}
1271</pre></p>
1272
1273The <a href="#cl::aliasopt"><tt>cl::aliasopt</tt></a> attribute should be used
1274to specify which option this is an alias for. Alias arguments default to being
1275<a href="#cl::Hidden">Hidden</a>, and use the aliased options parser to do the
1276conversion from string to data.<p>
1277
1278
1279<!-- ======================================================================= -->
1280</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>
1281<a name="builtinparsers">Builtin parsers
1282</b></font></td></tr></table><ul>
1283
1284Parsers control how the string value taken from the command line is translated
1285into a typed value, suitable for use in a C++ program. By default, the
1286CommandLine library uses an instance of <tt>parser&lt;type&gt;</tt> if the
1287command line option specifies that it uses values of type '<tt>type</tt>'.
1288Because of this, custom option processing is specified with specializations of
1289the '<tt>parser</tt>' class.<p>
1290
1291The CommandLine library provides the following builtin parser specializations,
1292which are sufficient for most applications. It can, however, also be extended to
1293work with new data types and new ways of interpreting the same data. See the <a
1294href="#customparser">Writing a Custom Parser</a> for more details on this type
1295of library extension.<p>
1296
1297<li><a name="genericparser">The <b>generic <tt>parser&lt;t&gt;</tt> parser</b>
1298can be used to map strings values to any data type, through the use of the <a
1299href="#cl::values">cl::values</a> property, which specifies the mapping
1300information. The most common use of this parser is for parsing enum values,
1301which allows you to use the CommandLine library for all of the error checking to
1302make sure that only valid enum values are specified (as opposed to accepting
1303arbitrary strings). Despite this, however, the generic parser class can be used
1304for any data type.<p>
1305
1306<li><a name="boolparser">The <b><tt>parser&lt;bool&gt;</tt> specialization</b>
1307is used to convert boolean strings to a boolean value. Currently accepted
1308strings are "<tt>true</tt>", "<tt>TRUE</tt>", "<tt>True</tt>", "<tt>1</tt>",
1309"<tt>false</tt>", "<tt>FALSE</tt>", "<tt>False</tt>", and "<tt>0</tt>".<p>
1310
1311<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>
1312
1313<li><a name="intparser">The <b><tt>parser&lt;int&gt;</tt> specialization</b>
1314uses the C <tt>strtol</tt> function to parse the string input. As such, it will
1315accept a decimal number (with an optional '+' or '-' prefix) which must start
1316with a non-zero digit. It accepts octal numbers, which are identified with a
1317'<tt>0</tt>' prefix digit, and hexadecimal numbers with a prefix of
1318'<tt>0x</tt>' or '<tt>0X</tt>'.<p>
1319
1320<li><a name="doubleparser">The <b><tt>parser&lt;double&gt;</tt></b> and
1321<b><tt>parser&lt;float&gt;</tt> specializations</b> use the standard C
1322<tt>strtod</tt> function to convert floating point strings into floating point
1323values. As such, a broad range of string formats is supported, including
1324exponential notation (ex: <tt>1.7e15</tt>) and properly supports locales.
1325<p>
1326
Chris Lattner209c7f42001-07-23 23:03:12 +00001327
1328
1329<!-- *********************************************************************** -->
1330</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>
1331<a name="extensionguide">Extension Guide
1332</b></font></td></tr></table><ul>
1333<!-- *********************************************************************** -->
1334
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001335Although the CommandLine library has a lot of functionality built into it
1336already (as discussed previously), one of its true strengths lie in its
1337extensibility. This section discusses how the CommandLine library works under
1338the covers and illustrates how to do some simple, common, extensions.<p>
1339
Chris Lattner209c7f42001-07-23 23:03:12 +00001340
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001341<!-- ======================================================================= -->
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001342</ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1343<tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF"
1344face="Georgia,Palatino"><b> <a name="customparser">Writing a custom parser
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001345</b></font></td></tr></table><ul>
1346
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001347One of the simplest and most common extensions is the use of a custom parser.
1348As <a href="#builtinparsers">discussed previously</a>, parsers are the portion
1349of the CommandLine library that turns string input from the user into a
1350particular parsed data type, validating the input in the process.<p>
1351
1352There are two ways to use a new parser:<p>
1353
1354<ol>
1355<li>Specialize the <a href="#genericparser"><tt>cl::parser</tt></a> template for
1356 your custom data type.<p>
1357
1358 This approach has the advantage that users of your custom data type will
1359 automatically use your custom parser whenever they define an option with a
1360 value type of your data type. The disadvantage of this approach is that it
1361 doesn't work if your fundemental data type is something that is already
1362 supported.<p>
1363
1364<li>Write an independant class, using it explicitly from options that need
1365 it.<p>
1366
1367 This approach works well in situations where you would line to parse an
1368 option using special syntax for a not-very-special data-type. The drawback
1369 of this approach is that users of your parser have to be aware that they are
1370 using your parser, instead of the builtin ones.<p>
1371
1372</ol><p>
1373
1374To guide the discussion, we will discuss a custom parser that accepts file
1375sizes, specified with an optional unit after the numeric size. For example, we
1376would like to parse "102kb", "41M", "1G" into the appropriate integer value. In
1377this case, the underlying data type we want to parse into is
1378'<tt>unsigned</tt>'. We choose approach #2 above because we don't want to make
1379this the default for all <tt>unsigned</tt> options.<p>
1380
1381To start out, we declare our new <tt>FileSizeParser</tt> class:<p>
1382
1383<pre>
1384<b>struct</b> FileSizeParser : <b>public</b> cl::basic_parser&lt;<b>unsigned</b>&gt; {
1385 <i>// parse - Return true on error.</i>
1386 <b>bool</b> parse(cl::Option &amp;O, <b>const char</b> *ArgName, <b>const</b> std::string &amp;ArgValue,
1387 <b>unsigned</b> &amp;Val);
1388};
1389</pre><p>
1390
1391Our new class inherits from the <tt>cl::basic_parser</tt> template class to fill
1392in the default, boiler plate, code for us. We give it the data type that we
1393parse into (the last argument to the <tt>parse</tt> method so that clients of
1394our custom parser know what object type to pass in to the parse method (here we
1395declare that we parse into '<tt>unsigned</tt>' variables.<p>
1396
1397For most purposes, the only method that must be implemented in a custom parser
1398is the <tt>parse</tt> method. The <tt>parse</tt> method is called whenever the
1399option is invoked, passing in the option itself, the option name, the string to
1400parse, 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>
1401
1402<pre>
1403<b>bool</b> FileSizeParser::parse(cl::Option &amp;O, <b>const char</b> *ArgName,
1404 <b>const</b> std::string &amp;Arg, <b>unsigned</b> &amp;Val) {
1405 <b>const char</b> *ArgStart = Arg.c_str();
1406 <b>char</b> *End;
1407
1408 <i>// Parse integer part, leaving 'End' pointing to the first non-integer char</i>
1409 Val = (unsigned)strtol(ArgStart, &amp;End, 0);
1410
1411 <b>while</b> (1) {
1412 <b>switch</b> (*End++) {
1413 <b>case</b> 0: <b>return</b> false; <i>// No error</i>
1414 <b>case</b> 'i': <i>// Ignore the 'i' in KiB if people use that</i>
1415 <b>case</b> 'b': <b>case</b> 'B': <i>// Ignore B suffix</i>
1416 <b>break</b>;
1417
1418 <b>case</b> 'g': <b>case</b> 'G': Val *= 1024*1024*1024; <b>break</b>;
1419 <b>case</b> 'm': <b>case</b> 'M': Val *= 1024*1024; <b>break</b>;
1420 <b>case</b> 'k': <b>case</b> 'K': Val *= 1024; <b>break</b>;
1421
1422 default:
1423 <i>// Print an error message if unrecognized character!</i>
1424 <b>return</b> O.error(": '" + Arg + "' value invalid for file size argument!");
1425 }
1426 }
1427}
1428</pre><p>
1429
1430This function implements a very simple parser for the kinds of strings we are
1431interested in. Although it has some holes (it allows "<tt>123KKK</tt>" for
1432example), it is good enough for this example. Note that we use the option
1433itself to print out the error message (the <tt>error</tt> method always returns
1434true) in order to get a nice error message (shown below). Now that we have our
1435parser class, we can use it like this:<p>
1436
1437<pre>
1438<b>static</b> <a href="#cl::opt">cl::opt</a>&lt;<b>unsigned</b>, <b>false</b>, FileSizeParser&gt;
1439MFS(<i>"max-file-size"</i>, <a href="#cl::desc">cl::desc</a>(<i>"Maximum file size to accept"</i>),
1440 <a href="#cl::value_desc">cl::value_desc</a>("<i>size</i>"));
1441</pre><p>
1442
1443Which adds this to the output of our program:<p>
1444
1445<pre>
1446OPTIONS:
1447 -help - display available options (--help-hidden for more)
1448 ...
1449 <b>-max-file-size=&lt;size&gt; - Maximum file size to accept</b>
1450</pre><p>
1451
1452And we can test that our parse works correctly now (the test program just prints
1453out the max-file-size argument value):<p>
1454
1455<pre>
1456$ ./test
1457MFS: 0
1458$ ./test -max-file-size=123MB
1459MFS: 128974848
1460$ ./test -max-file-size=3G
1461MFS: 3221225472
1462$ ./test -max-file-size=dog
1463-max-file-size option: 'dog' value invalid for file size argument!
1464</pre><p>
1465
1466It looks like it works. The error message that we get is nice and helpful, and
1467we seem to accept reasonable file sizes. This wraps up the "custom parser"
1468tutorial.<p>
1469
1470
1471<!-- ======================================================================= -->
1472</ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1473<tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF"
1474face="Georgia,Palatino"><b> <a name="explotingexternal">Exploiting external
1475storage </b></font></td></tr></table><ul>
1476
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001477
1478
1479<!-- ======================================================================= -->
Chris Lattnerc1ae40c2002-08-07 18:27:04 +00001480</ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1481<tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF"
1482face="Georgia,Palatino"><b> <a name="dynamicopts">Dynamically adding command
1483line options </b></font></td></tr></table><ul>
Chris Lattnere76d4ab2002-08-06 19:36:06 +00001484
1485
Chris Lattner209c7f42001-07-23 23:03:12 +00001486
1487
1488
1489<!-- *********************************************************************** -->
1490</ul>
1491<!-- *********************************************************************** -->
1492
1493<hr>
1494<font size=-1>
1495<address><a href="mailto:sabre@nondot.org">Chris Lattner</a></address>
1496<!-- Created: Tue Jan 23 15:19:28 CST 2001 -->
1497<!-- hhmts start -->
Chris Lattner32a32842003-05-22 20:36:06 +00001498Last modified: Thu May 22 15:35:19 CDT 2003
Chris Lattner209c7f42001-07-23 23:03:12 +00001499<!-- hhmts end -->
1500</font>
1501</body></html>