blob: e556d76f96580c7e872cd84ae622e69e4404d84d [file] [log] [blame]
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerdbab15a2001-07-23 17:17:47 +00009//
10// This class implements a command line argument processor that is useful when
11// creating a tool. It provides a simple, minimalistic interface that is easily
12// extensible and supports nonlocal (library) command line options.
13//
Chris Lattner03fe1bd2001-07-23 23:04:07 +000014// Note that rather than trying to figure out what this code does, you could try
15// reading the library documentation located in docs/CommandLine.html
16//
Chris Lattnerdbab15a2001-07-23 17:17:47 +000017//===----------------------------------------------------------------------===//
18
Reid Spencer551ccae2004-09-01 22:55:40 +000019#include "llvm/Config/config.h"
20#include "llvm/Support/CommandLine.h"
Chris Lattner90aa8392006-10-04 21:52:35 +000021#include "llvm/Support/ManagedStatic.h"
Bill Wendlingfe6b1462006-11-26 10:52:51 +000022#include "llvm/Support/Streams.h"
Reid Spencer6f4c6072006-08-23 07:10:06 +000023#include "llvm/System/Path.h"
Chris Lattnerdbab15a2001-07-23 17:17:47 +000024#include <algorithm>
Duraid Madina786e3e22005-12-26 04:56:16 +000025#include <functional>
Chris Lattnerdbab15a2001-07-23 17:17:47 +000026#include <map>
Bill Wendling1a097e32006-12-07 23:41:45 +000027#include <ostream>
Chris Lattnerdbab15a2001-07-23 17:17:47 +000028#include <set>
Brian Gaeke2d6a2362003-10-10 17:01:36 +000029#include <cstdlib>
30#include <cerrno>
Chris Lattner51140042004-07-03 01:21:05 +000031#include <cstring>
Chris Lattner2cdd21c2003-12-14 21:35:53 +000032using namespace llvm;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000033using namespace cl;
34
Chris Lattner7422a762006-08-27 12:45:47 +000035//===----------------------------------------------------------------------===//
36// Template instantiations and anchors.
37//
38TEMPLATE_INSTANTIATION(class basic_parser<bool>);
39TEMPLATE_INSTANTIATION(class basic_parser<int>);
40TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
41TEMPLATE_INSTANTIATION(class basic_parser<double>);
42TEMPLATE_INSTANTIATION(class basic_parser<float>);
43TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
44
45TEMPLATE_INSTANTIATION(class opt<unsigned>);
46TEMPLATE_INSTANTIATION(class opt<int>);
47TEMPLATE_INSTANTIATION(class opt<std::string>);
48TEMPLATE_INSTANTIATION(class opt<bool>);
49
50void Option::anchor() {}
51void basic_parser_impl::anchor() {}
52void parser<bool>::anchor() {}
53void parser<int>::anchor() {}
54void parser<unsigned>::anchor() {}
55void parser<double>::anchor() {}
56void parser<float>::anchor() {}
57void parser<std::string>::anchor() {}
58
59//===----------------------------------------------------------------------===//
60
Chris Lattnerefa3da52006-10-13 00:06:24 +000061// Globals for name and overview of program. Program name is not a string to
62// avoid static ctor/dtor issues.
63static char ProgramName[80] = "<premain>";
Reid Spencere1cc1502004-09-01 04:41:28 +000064static const char *ProgramOverview = 0;
65
Chris Lattnerc540ebb2004-11-19 17:08:15 +000066// This collects additional help to be printed.
Chris Lattner90aa8392006-10-04 21:52:35 +000067static ManagedStatic<std::vector<const char*> > MoreHelp;
Chris Lattnerc540ebb2004-11-19 17:08:15 +000068
Chris Lattner90aa8392006-10-04 21:52:35 +000069extrahelp::extrahelp(const char *Help)
Chris Lattnerc540ebb2004-11-19 17:08:15 +000070 : morehelp(Help) {
Chris Lattner90aa8392006-10-04 21:52:35 +000071 MoreHelp->push_back(Help);
Chris Lattnerc540ebb2004-11-19 17:08:15 +000072}
73
Chris Lattner331de232002-07-22 02:07:59 +000074//===----------------------------------------------------------------------===//
Chris Lattner7422a762006-08-27 12:45:47 +000075// Basic, shared command line option processing machinery.
Chris Lattner331de232002-07-22 02:07:59 +000076//
77
Chris Lattner90aa8392006-10-04 21:52:35 +000078static ManagedStatic<std::map<std::string, Option*> > Options;
79static ManagedStatic<std::vector<Option*> > PositionalOptions;
Chris Lattnere8e258b2002-07-29 20:58:42 +000080
Chris Lattnerca6433f2003-05-22 20:06:43 +000081static Option *getOption(const std::string &Str) {
Chris Lattner90aa8392006-10-04 21:52:35 +000082 std::map<std::string,Option*>::iterator I = Options->find(Str);
83 return I != Options->end() ? I->second : 0;
Chris Lattner331de232002-07-22 02:07:59 +000084}
85
Chris Lattnere8e258b2002-07-29 20:58:42 +000086static void AddArgument(const char *ArgName, Option *Opt) {
87 if (getOption(ArgName)) {
Bill Wendlinge8156192006-12-07 01:30:32 +000088 cerr << ProgramName << ": CommandLine Error: Argument '"
89 << ArgName << "' defined more than once!\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +000090 } else {
Chris Lattnerf78032f2001-11-26 18:58:34 +000091 // Add argument to the argument map!
Chris Lattner90aa8392006-10-04 21:52:35 +000092 (*Options)[ArgName] = Opt;
Chris Lattnere8e258b2002-07-29 20:58:42 +000093 }
94}
95
96// RemoveArgument - It's possible that the argument is no longer in the map if
97// options have already been processed and the map has been deleted!
Misha Brukmanf976c852005-04-21 22:55:34 +000098//
Chris Lattnere8e258b2002-07-29 20:58:42 +000099static void RemoveArgument(const char *ArgName, Option *Opt) {
Chris Lattner90aa8392006-10-04 21:52:35 +0000100 if (Options->empty()) return;
Tanya Lattnerc4ae8e92004-11-20 23:35:20 +0000101
Chris Lattnerf98cfc72004-07-18 21:56:20 +0000102#ifndef NDEBUG
103 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
104 // If we pass ArgName directly into getOption here.
105 std::string Tmp = ArgName;
106 assert(getOption(Tmp) == Opt && "Arg not in map!");
107#endif
Chris Lattner90aa8392006-10-04 21:52:35 +0000108 Options->erase(ArgName);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000109}
110
Chris Lattnercaccd762001-10-27 05:54:17 +0000111static inline bool ProvideOption(Option *Handler, const char *ArgName,
112 const char *Value, int argc, char **argv,
113 int &i) {
114 // Enforce value requirements
115 switch (Handler->getValueExpectedFlag()) {
116 case ValueRequired:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000117 if (Value == 0) { // No value specified?
Chris Lattnercaccd762001-10-27 05:54:17 +0000118 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
119 Value = argv[++i];
120 } else {
121 return Handler->error(" requires a value!");
122 }
123 }
124 break;
125 case ValueDisallowed:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000126 if (Value)
Misha Brukmanf976c852005-04-21 22:55:34 +0000127 return Handler->error(" does not allow a value! '" +
Chris Lattnerca6433f2003-05-22 20:06:43 +0000128 std::string(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +0000129 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000130 case ValueOptional:
Reid Spencere1cc1502004-09-01 04:41:28 +0000131 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000132 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000133 cerr << ProgramName
134 << ": Bad ValueMask flag! CommandLine usage error:"
135 << Handler->getValueExpectedFlag() << "\n";
Reid Spencere1cc1502004-09-01 04:41:28 +0000136 abort();
137 break;
Chris Lattnercaccd762001-10-27 05:54:17 +0000138 }
139
140 // Run the handler now!
Chris Lattner6d5857e2005-05-10 23:20:17 +0000141 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
Chris Lattnercaccd762001-10-27 05:54:17 +0000142}
143
Misha Brukmanf976c852005-04-21 22:55:34 +0000144static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000145 int i) {
146 int Dummy = i;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000147 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000148}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000149
Chris Lattner331de232002-07-22 02:07:59 +0000150
151// Option predicates...
152static inline bool isGrouping(const Option *O) {
153 return O->getFormattingFlag() == cl::Grouping;
154}
155static inline bool isPrefixedOrGrouping(const Option *O) {
156 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
157}
158
159// getOptionPred - Check to see if there are any options that satisfy the
160// specified predicate with names that are the prefixes in Name. This is
161// checked by progressively stripping characters off of the name, checking to
162// see if there options that satisfy the predicate. If we find one, return it,
163// otherwise return null.
164//
165static Option *getOptionPred(std::string Name, unsigned &Length,
166 bool (*Pred)(const Option*)) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000167
Chris Lattnere8e258b2002-07-29 20:58:42 +0000168 Option *Op = getOption(Name);
169 if (Op && Pred(Op)) {
Chris Lattner331de232002-07-22 02:07:59 +0000170 Length = Name.length();
Chris Lattnere8e258b2002-07-29 20:58:42 +0000171 return Op;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000172 }
173
Chris Lattner331de232002-07-22 02:07:59 +0000174 if (Name.size() == 1) return 0;
175 do {
176 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
Chris Lattnere8e258b2002-07-29 20:58:42 +0000177 Op = getOption(Name);
Chris Lattner331de232002-07-22 02:07:59 +0000178
179 // Loop while we haven't found an option and Name still has at least two
180 // characters in it (so that the next iteration will not be the empty
181 // string...
Chris Lattnere8e258b2002-07-29 20:58:42 +0000182 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
Chris Lattner331de232002-07-22 02:07:59 +0000183
Chris Lattnere8e258b2002-07-29 20:58:42 +0000184 if (Op && Pred(Op)) {
Chris Lattner331de232002-07-22 02:07:59 +0000185 Length = Name.length();
Chris Lattnere8e258b2002-07-29 20:58:42 +0000186 return Op; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000187 }
188 return 0; // No option found!
189}
190
191static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000192 return O->getNumOccurrencesFlag() == cl::Required ||
193 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000194}
195
196static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000197 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
198 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000199}
Chris Lattnercaccd762001-10-27 05:54:17 +0000200
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000201/// ParseCStringVector - Break INPUT up wherever one or more
202/// whitespace characters are found, and store the resulting tokens in
203/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
204/// using strdup (), so it is the caller's responsibility to free ()
205/// them later.
Brian Gaeke06b06c52003-08-14 22:00:59 +0000206///
Chris Lattner23288582006-08-27 22:10:29 +0000207static void ParseCStringVector(std::vector<char *> &output,
208 const char *input) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000209 // Characters which will be treated as token separators:
210 static const char *delims = " \v\f\t\r\n";
211
212 std::string work (input);
213 // Skip past any delims at head of input string.
214 size_t pos = work.find_first_not_of (delims);
215 // If the string consists entirely of delims, then exit early.
216 if (pos == std::string::npos) return;
217 // Otherwise, jump forward to beginning of first word.
218 work = work.substr (pos);
219 // Find position of first delimiter.
220 pos = work.find_first_of (delims);
221
222 while (!work.empty() && pos != std::string::npos) {
223 // Everything from 0 to POS is the next word to copy.
224 output.push_back (strdup (work.substr (0,pos).c_str ()));
225 // Is there another word in the string?
226 size_t nextpos = work.find_first_not_of (delims, pos + 1);
227 if (nextpos != std::string::npos) {
228 // Yes? Then remove delims from beginning ...
229 work = work.substr (work.find_first_not_of (delims, pos + 1));
230 // and find the end of the word.
231 pos = work.find_first_of (delims);
232 } else {
233 // No? (Remainder of string is delims.) End the loop.
234 work = "";
235 pos = std::string::npos;
236 }
237 }
238
239 // If `input' ended with non-delim char, then we'll get here with
240 // the last word of `input' in `work'; copy it now.
241 if (!work.empty ()) {
242 output.push_back (strdup (work.c_str ()));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000243 }
244}
245
246/// ParseEnvironmentOptions - An alternative entry point to the
247/// CommandLine library, which allows you to read the program's name
248/// from the caller (as PROGNAME) and its command-line arguments from
249/// an environment variable (whose name is given in ENVVAR).
250///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000251void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
252 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000253 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000254 assert(progName && "Program name not specified");
255 assert(envVar && "Environment variable name missing");
Misha Brukmanf976c852005-04-21 22:55:34 +0000256
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000257 // Get the environment variable they want us to parse options out of.
Chris Lattner23288582006-08-27 22:10:29 +0000258 const char *envValue = getenv(envVar);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000259 if (!envValue)
260 return;
261
Brian Gaeke06b06c52003-08-14 22:00:59 +0000262 // Get program's "name", which we wouldn't know without the caller
263 // telling us.
Chris Lattner23288582006-08-27 22:10:29 +0000264 std::vector<char*> newArgv;
265 newArgv.push_back(strdup(progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000266
267 // Parse the value of the environment variable into a "command line"
268 // and hand it off to ParseCommandLineOptions().
Chris Lattner23288582006-08-27 22:10:29 +0000269 ParseCStringVector(newArgv, envValue);
270 int newArgc = newArgv.size();
271 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000272
273 // Free all the strdup()ed strings.
Chris Lattner23288582006-08-27 22:10:29 +0000274 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
275 i != e; ++i)
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000276 free (*i);
Brian Gaeke06b06c52003-08-14 22:00:59 +0000277}
278
Chris Lattnerbf455c22004-05-06 22:04:31 +0000279/// LookupOption - Lookup the option specified by the specified option on the
280/// command line. If there is a value specified (after an equal sign) return
281/// that as well.
282static Option *LookupOption(const char *&Arg, const char *&Value) {
283 while (*Arg == '-') ++Arg; // Eat leading dashes
Misha Brukmanf976c852005-04-21 22:55:34 +0000284
Chris Lattnerbf455c22004-05-06 22:04:31 +0000285 const char *ArgEnd = Arg;
286 while (*ArgEnd && *ArgEnd != '=')
Chris Lattner6d5857e2005-05-10 23:20:17 +0000287 ++ArgEnd; // Scan till end of argument name.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000288
Chris Lattner6d5857e2005-05-10 23:20:17 +0000289 if (*ArgEnd == '=') // If we have an equals sign...
290 Value = ArgEnd+1; // Get the value, not the equals
291
Misha Brukmanf976c852005-04-21 22:55:34 +0000292
Chris Lattnerbf455c22004-05-06 22:04:31 +0000293 if (*Arg == 0) return 0;
294
295 // Look up the option.
Chris Lattner90aa8392006-10-04 21:52:35 +0000296 std::map<std::string, Option*> &Opts = *Options;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000297 std::map<std::string, Option*>::iterator I =
298 Opts.find(std::string(Arg, ArgEnd));
299 return (I != Opts.end()) ? I->second : 0;
300}
301
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000302void cl::ParseCommandLineOptions(int &argc, char **argv,
Chris Lattner0c0edf82002-07-25 06:17:51 +0000303 const char *Overview) {
Chris Lattner90aa8392006-10-04 21:52:35 +0000304 assert((!Options->empty() || !PositionalOptions->empty()) &&
Chris Lattner331de232002-07-22 02:07:59 +0000305 "No options specified, or ParseCommandLineOptions called more"
306 " than once!");
Reid Spencer6f4c6072006-08-23 07:10:06 +0000307 sys::Path progname(argv[0]);
Chris Lattnerefa3da52006-10-13 00:06:24 +0000308
309 // Copy the program name into ProgName, making sure not to overflow it.
310 std::string ProgName = sys::Path(argv[0]).getLast();
311 if (ProgName.size() > 79) ProgName.resize(79);
312 strcpy(ProgramName, ProgName.c_str());
313
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000314 ProgramOverview = Overview;
315 bool ErrorParsing = false;
316
Chris Lattner90aa8392006-10-04 21:52:35 +0000317 std::map<std::string, Option*> &Opts = *Options;
318 std::vector<Option*> &PositionalOpts = *PositionalOptions;
Chris Lattner331de232002-07-22 02:07:59 +0000319
320 // Check out the positional arguments to collect information about them.
321 unsigned NumPositionalRequired = 0;
Chris Lattnerde013242005-08-08 17:25:38 +0000322
323 // Determine whether or not there are an unlimited number of positionals
324 bool HasUnlimitedPositionals = false;
325
Chris Lattner331de232002-07-22 02:07:59 +0000326 Option *ConsumeAfterOpt = 0;
327 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000328 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000329 assert(PositionalOpts.size() > 1 &&
330 "Cannot specify cl::ConsumeAfter without a positional argument!");
331 ConsumeAfterOpt = PositionalOpts[0];
332 }
333
334 // Calculate how many positional values are _required_.
335 bool UnboundedFound = false;
336 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
337 i != e; ++i) {
338 Option *Opt = PositionalOpts[i];
339 if (RequiresValue(Opt))
340 ++NumPositionalRequired;
341 else if (ConsumeAfterOpt) {
342 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000343 // unless there is only one positional argument...
344 if (PositionalOpts.size() > 2)
345 ErrorParsing |=
346 Opt->error(" error - this positional option will never be matched, "
347 "because it does not Require a value, and a "
348 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000349 } else if (UnboundedFound && !Opt->ArgStr[0]) {
350 // This option does not "require" a value... Make sure this option is
351 // not specified after an option that eats all extra arguments, or this
352 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000353 //
354 ErrorParsing |= Opt->error(" error - option can never match, because "
355 "another positional argument will match an "
356 "unbounded number of values, and this option"
357 " does not require a value!");
358 }
359 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
360 }
Chris Lattner21e1a792005-08-08 21:57:27 +0000361 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000362 }
363
Reid Spencer1e13fd22004-08-13 19:47:30 +0000364 // PositionalVals - A vector of "positional" arguments we accumulate into
365 // the process at the end...
Chris Lattner331de232002-07-22 02:07:59 +0000366 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000367 std::vector<std::pair<std::string,unsigned> > PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000368
Chris Lattner9cf3d472003-07-30 17:34:02 +0000369 // If the program has named positional arguments, and the name has been run
370 // across, keep track of which positional argument was named. Otherwise put
371 // the positional args into the PositionalVals list...
372 Option *ActivePositionalArg = 0;
373
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000374 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000375 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000376 for (int i = 1; i < argc; ++i) {
377 Option *Handler = 0;
Chris Lattner6d5857e2005-05-10 23:20:17 +0000378 const char *Value = 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000379 const char *ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000380
381 // Check to see if this is a positional argument. This argument is
382 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000383 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000384 //
385 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
386 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000387 if (ActivePositionalArg) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000388 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000389 continue; // We are done!
390 } else if (!PositionalOpts.empty()) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000391 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000392
393 // All of the positional arguments have been fulfulled, give the rest to
394 // the consume after option... if it's specified...
395 //
Misha Brukmanf976c852005-04-21 22:55:34 +0000396 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000397 ConsumeAfterOpt != 0) {
398 for (++i; i < argc; ++i)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000399 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000400 break; // Handle outside of the argument processing loop...
401 }
402
403 // Delay processing positional arguments until the end...
404 continue;
405 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000406 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
407 !DashDashFound) {
408 DashDashFound = true; // This is the mythical "--"?
409 continue; // Don't try to process it as an argument itself.
410 } else if (ActivePositionalArg &&
411 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
412 // If there is a positional argument eating options, check to see if this
413 // option is another positional argument. If so, treat it as an argument,
414 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000415 ArgName = argv[i]+1;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000416 Handler = LookupOption(ArgName, Value);
417 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000418 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000419 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000420 }
421
Chris Lattnerbf455c22004-05-06 22:04:31 +0000422 } else { // We start with a '-', must be an argument...
423 ArgName = argv[i]+1;
424 Handler = LookupOption(ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000425
Chris Lattnerbf455c22004-05-06 22:04:31 +0000426 // Check to see if this "option" is really a prefixed or grouped argument.
Reid Spencer5f8448f2004-11-24 06:13:42 +0000427 if (Handler == 0) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000428 std::string RealName(ArgName);
429 if (RealName.size() > 1) {
Chris Lattner331de232002-07-22 02:07:59 +0000430 unsigned Length = 0;
431 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
Misha Brukmanf976c852005-04-21 22:55:34 +0000432
Chris Lattner331de232002-07-22 02:07:59 +0000433 // If the option is a prefixed option, then the value is simply the
434 // rest of the name... so fall through to later processing, by
435 // setting up the argument name flags and value fields.
436 //
437 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000438 Value = ArgName+Length;
439 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
440 Opts.find(std::string(ArgName, Value))->second == PGOpt);
441 Handler = PGOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000442 } else if (PGOpt) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000443 // This must be a grouped option... handle them now.
Chris Lattner331de232002-07-22 02:07:59 +0000444 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000445
Chris Lattner331de232002-07-22 02:07:59 +0000446 do {
447 // Move current arg name out of RealName into RealArgName...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000448 std::string RealArgName(RealName.begin(),
449 RealName.begin() + Length);
450 RealName.erase(RealName.begin(), RealName.begin() + Length);
Misha Brukmanf976c852005-04-21 22:55:34 +0000451
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000452 // Because ValueRequired is an invalid flag for grouped arguments,
453 // we don't need to pass argc/argv in...
454 //
Chris Lattner331de232002-07-22 02:07:59 +0000455 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
456 "Option can not be cl::Grouping AND cl::ValueRequired!");
457 int Dummy;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000458 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
Chris Lattner6d5857e2005-05-10 23:20:17 +0000459 0, 0, 0, Dummy);
Misha Brukmanf976c852005-04-21 22:55:34 +0000460
Chris Lattner331de232002-07-22 02:07:59 +0000461 // Get the next grouping option...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000462 PGOpt = getOptionPred(RealName, Length, isGrouping);
463 } while (PGOpt && Length != RealName.size());
Misha Brukmanf976c852005-04-21 22:55:34 +0000464
Chris Lattnerbf455c22004-05-06 22:04:31 +0000465 Handler = PGOpt; // Ate all of the options.
Chris Lattner331de232002-07-22 02:07:59 +0000466 }
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000467 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000468 }
469 }
470
471 if (Handler == 0) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000472 cerr << ProgramName << ": Unknown command line argument '"
473 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000474 ErrorParsing = true;
475 continue;
476 }
477
Chris Lattner72fb8e52003-05-22 20:26:17 +0000478 // Check to see if this option accepts a comma separated list of values. If
479 // it does, we have to split up the value into multiple values...
Chris Lattner6d5857e2005-05-10 23:20:17 +0000480 if (Value && Handler->getMiscFlags() & CommaSeparated) {
Chris Lattner72fb8e52003-05-22 20:26:17 +0000481 std::string Val(Value);
482 std::string::size_type Pos = Val.find(',');
483
484 while (Pos != std::string::npos) {
485 // Process the portion before the comma...
486 ErrorParsing |= ProvideOption(Handler, ArgName,
487 std::string(Val.begin(),
488 Val.begin()+Pos).c_str(),
489 argc, argv, i);
490 // Erase the portion before the comma, AND the comma...
491 Val.erase(Val.begin(), Val.begin()+Pos+1);
492 Value += Pos+1; // Increment the original value pointer as well...
493
494 // Check for another comma...
495 Pos = Val.find(',');
496 }
497 }
Chris Lattner9cf3d472003-07-30 17:34:02 +0000498
499 // If this is a named positional argument, just remember that it is the
500 // active one...
501 if (Handler->getFormattingFlag() == cl::Positional)
502 ActivePositionalArg = Handler;
Misha Brukmanf976c852005-04-21 22:55:34 +0000503 else
Chris Lattner9cf3d472003-07-30 17:34:02 +0000504 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000505 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000506
Chris Lattner331de232002-07-22 02:07:59 +0000507 // Check and handle positional arguments now...
508 if (NumPositionalRequired > PositionalVals.size()) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000509 cerr << ProgramName
510 << ": Not enough positional command line arguments specified!\n"
511 << "Must specify at least " << NumPositionalRequired
512 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattner79959d22006-01-17 00:32:28 +0000513
Chris Lattner331de232002-07-22 02:07:59 +0000514 ErrorParsing = true;
Chris Lattnerde013242005-08-08 17:25:38 +0000515 } else if (!HasUnlimitedPositionals
516 && PositionalVals.size() > PositionalOpts.size()) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000517 cerr << ProgramName
518 << ": Too many positional arguments specified!\n"
519 << "Can specify at most " << PositionalOpts.size()
520 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattnerde013242005-08-08 17:25:38 +0000521 ErrorParsing = true;
Chris Lattner331de232002-07-22 02:07:59 +0000522
523 } else if (ConsumeAfterOpt == 0) {
524 // Positional args have already been handled if ConsumeAfter is specified...
525 unsigned ValNo = 0, NumVals = PositionalVals.size();
526 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
527 if (RequiresValue(PositionalOpts[i])) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000528 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000529 PositionalVals[ValNo].second);
530 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000531 --NumPositionalRequired; // We fulfilled our duty...
532 }
533
534 // If we _can_ give this option more arguments, do so now, as long as we
535 // do not give it values that others need. 'Done' controls whether the
536 // option even _WANTS_ any more.
537 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000538 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000539 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000540 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000541 case cl::Optional:
542 Done = true; // Optional arguments want _at most_ one value
543 // FALL THROUGH
544 case cl::ZeroOrMore: // Zero or more will take all they can get...
545 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer1e13fd22004-08-13 19:47:30 +0000546 ProvidePositionalOption(PositionalOpts[i],
547 PositionalVals[ValNo].first,
548 PositionalVals[ValNo].second);
549 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000550 break;
551 default:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000552 assert(0 && "Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000553 "positional argument processing!");
554 }
555 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000556 }
Chris Lattner331de232002-07-22 02:07:59 +0000557 } else {
558 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
559 unsigned ValNo = 0;
560 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000561 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000562 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000563 PositionalVals[ValNo].first,
564 PositionalVals[ValNo].second);
565 ValNo++;
566 }
Chris Lattnerfaba8092002-07-24 20:15:13 +0000567
568 // Handle the case where there is just one positional option, and it's
569 // optional. In this case, we want to give JUST THE FIRST option to the
570 // positional option and keep the rest for the consume after. The above
571 // loop would have assigned no values to positional options in this case.
572 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000573 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000574 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000575 PositionalVals[ValNo].first,
576 PositionalVals[ValNo].second);
577 ValNo++;
578 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000579
Chris Lattner331de232002-07-22 02:07:59 +0000580 // Handle over all of the rest of the arguments to the
581 // cl::ConsumeAfter command line option...
582 for (; ValNo != PositionalVals.size(); ++ValNo)
583 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000584 PositionalVals[ValNo].first,
585 PositionalVals[ValNo].second);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000586 }
587
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000588 // Loop over args and make sure all required args are specified!
Misha Brukmanf976c852005-04-21 22:55:34 +0000589 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000590 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000591 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000592 case Required:
593 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000594 if (I->second->getNumOccurrences() == 0) {
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000595 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000596 ErrorParsing = true;
597 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000598 // Fall through
599 default:
600 break;
601 }
602 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000603
Chris Lattner331de232002-07-22 02:07:59 +0000604 // Free all of the memory allocated to the map. Command line options may only
605 // be processed once!
Chris Lattner90aa8392006-10-04 21:52:35 +0000606 Opts.clear();
Chris Lattner331de232002-07-22 02:07:59 +0000607 PositionalOpts.clear();
Chris Lattner90aa8392006-10-04 21:52:35 +0000608 MoreHelp->clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000609
610 // If we had an error processing our arguments, don't let the program execute
611 if (ErrorParsing) exit(1);
612}
613
614//===----------------------------------------------------------------------===//
615// Option Base class implementation
616//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000617
Chris Lattnerca6433f2003-05-22 20:06:43 +0000618bool Option::error(std::string Message, const char *ArgName) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000619 if (ArgName == 0) ArgName = ArgStr;
Chris Lattner331de232002-07-22 02:07:59 +0000620 if (ArgName[0] == 0)
Bill Wendlinge8156192006-12-07 01:30:32 +0000621 cerr << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000622 else
Bill Wendlinge8156192006-12-07 01:30:32 +0000623 cerr << ProgramName << ": for the -" << ArgName;
Jim Laskeyabe0e3e2006-08-02 20:15:56 +0000624
Bill Wendlinge8156192006-12-07 01:30:32 +0000625 cerr << " option: " << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000626 return true;
627}
628
Chris Lattner6d5857e2005-05-10 23:20:17 +0000629bool Option::addOccurrence(unsigned pos, const char *ArgName,
630 const std::string &Value) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000631 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000632
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000633 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000634 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000635 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000636 return error(": may only occur zero or one times!", ArgName);
637 break;
638 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000639 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000640 return error(": must occur exactly one time!", ArgName);
641 // Fall through
642 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000643 case ZeroOrMore:
644 case ConsumeAfter: break;
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000645 default: return error(": bad num occurrences flag value!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000646 }
647
Reid Spencer1e13fd22004-08-13 19:47:30 +0000648 return handleOccurrence(pos, ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000649}
650
Chris Lattner331de232002-07-22 02:07:59 +0000651// addArgument - Tell the system that this Option subclass will handle all
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000652// occurrences of -ArgStr on the command line.
Chris Lattner331de232002-07-22 02:07:59 +0000653//
654void Option::addArgument(const char *ArgStr) {
655 if (ArgStr[0])
656 AddArgument(ArgStr, this);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000657
658 if (getFormattingFlag() == Positional)
Chris Lattner90aa8392006-10-04 21:52:35 +0000659 PositionalOptions->push_back(this);
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000660 else if (getNumOccurrencesFlag() == ConsumeAfter) {
Chris Lattner90aa8392006-10-04 21:52:35 +0000661 if (!PositionalOptions->empty() &&
662 PositionalOptions->front()->getNumOccurrencesFlag() == ConsumeAfter)
Chris Lattner9cf3d472003-07-30 17:34:02 +0000663 error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattner90aa8392006-10-04 21:52:35 +0000664 PositionalOptions->insert(PositionalOptions->begin(), this);
Chris Lattner331de232002-07-22 02:07:59 +0000665 }
666}
667
Chris Lattneraa852bb2002-07-23 17:15:12 +0000668void Option::removeArgument(const char *ArgStr) {
Chris Lattner9cf3d472003-07-30 17:34:02 +0000669 if (ArgStr[0])
Chris Lattnere8e258b2002-07-29 20:58:42 +0000670 RemoveArgument(ArgStr, this);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000671
672 if (getFormattingFlag() == Positional) {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000673 std::vector<Option*>::iterator I =
Chris Lattner90aa8392006-10-04 21:52:35 +0000674 std::find(PositionalOptions->begin(), PositionalOptions->end(), this);
675 assert(I != PositionalOptions->end() && "Arg not registered!");
676 PositionalOptions->erase(I);
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000677 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
Chris Lattner90aa8392006-10-04 21:52:35 +0000678 assert(!PositionalOptions->empty() && (*PositionalOptions)[0] == this &&
Chris Lattneraa852bb2002-07-23 17:15:12 +0000679 "Arg not registered correctly!");
Chris Lattner90aa8392006-10-04 21:52:35 +0000680 PositionalOptions->erase(PositionalOptions->begin());
Chris Lattneraa852bb2002-07-23 17:15:12 +0000681 }
682}
683
Chris Lattner331de232002-07-22 02:07:59 +0000684
685// getValueStr - Get the value description string, using "DefaultMsg" if nothing
686// has been specified yet.
687//
688static const char *getValueStr(const Option &O, const char *DefaultMsg) {
689 if (O.ValueStr[0] == 0) return DefaultMsg;
690 return O.ValueStr;
691}
692
693//===----------------------------------------------------------------------===//
694// cl::alias class implementation
695//
696
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000697// Return the width of the option tag for printing...
Chris Lattner331de232002-07-22 02:07:59 +0000698unsigned alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000699 return std::strlen(ArgStr)+6;
700}
701
Chris Lattnera0de8432006-04-28 05:36:25 +0000702// Print out the option for the alias.
Chris Lattner331de232002-07-22 02:07:59 +0000703void alias::printOptionInfo(unsigned GlobalWidth) const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000704 unsigned L = std::strlen(ArgStr);
Bill Wendlinge8156192006-12-07 01:30:32 +0000705 cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
706 << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000707}
708
709
Chris Lattner331de232002-07-22 02:07:59 +0000710
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000711//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000712// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000713//
714
Chris Lattner9b14eb52002-08-07 18:36:37 +0000715// basic_parser implementation
716//
717
718// Return the width of the option tag for printing...
719unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
720 unsigned Len = std::strlen(O.ArgStr);
721 if (const char *ValName = getValueName())
722 Len += std::strlen(getValueStr(O, ValName))+3;
723
724 return Len + 6;
725}
726
Misha Brukmanf976c852005-04-21 22:55:34 +0000727// printOptionInfo - Print out information about this option. The
Chris Lattner9b14eb52002-08-07 18:36:37 +0000728// to-be-maintained width is specified.
729//
730void basic_parser_impl::printOptionInfo(const Option &O,
731 unsigned GlobalWidth) const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000732 cout << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000733
734 if (const char *ValName = getValueName())
Bill Wendlinge8156192006-12-07 01:30:32 +0000735 cout << "=<" << getValueStr(O, ValName) << ">";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000736
Bill Wendlinge8156192006-12-07 01:30:32 +0000737 cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
738 << O.HelpStr << "\n";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000739}
740
741
742
743
Chris Lattner331de232002-07-22 02:07:59 +0000744// parser<bool> implementation
745//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000746bool parser<bool>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000747 const std::string &Arg, bool &Value) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000748 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000749 Arg == "1") {
750 Value = true;
751 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
752 Value = false;
753 } else {
Chris Lattner331de232002-07-22 02:07:59 +0000754 return O.error(": '" + Arg +
755 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000756 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000757 return false;
758}
759
Chris Lattner331de232002-07-22 02:07:59 +0000760// parser<int> implementation
761//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000762bool parser<int>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000763 const std::string &Arg, int &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000764 char *End;
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000765 Value = (int)strtol(Arg.c_str(), &End, 0);
Misha Brukmanf976c852005-04-21 22:55:34 +0000766 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000767 return O.error(": '" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000768 return false;
769}
770
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000771// parser<unsigned> implementation
772//
773bool parser<unsigned>::parse(Option &O, const char *ArgName,
774 const std::string &Arg, unsigned &Value) {
775 char *End;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000776 errno = 0;
777 unsigned long V = strtoul(Arg.c_str(), &End, 0);
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000778 Value = (unsigned)V;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000779 if (((V == ULONG_MAX) && (errno == ERANGE))
780 || (*End != 0)
781 || (Value != V))
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000782 return O.error(": '" + Arg + "' value invalid for uint argument!");
783 return false;
784}
785
Chris Lattner9b14eb52002-08-07 18:36:37 +0000786// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +0000787//
Chris Lattnerca6433f2003-05-22 20:06:43 +0000788static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
Chris Lattner331de232002-07-22 02:07:59 +0000789 const char *ArgStart = Arg.c_str();
790 char *End;
791 Value = strtod(ArgStart, &End);
Misha Brukmanf976c852005-04-21 22:55:34 +0000792 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000793 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +0000794 return false;
795}
796
Chris Lattner9b14eb52002-08-07 18:36:37 +0000797bool parser<double>::parse(Option &O, const char *AN,
798 const std::string &Arg, double &Val) {
799 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +0000800}
801
Chris Lattner9b14eb52002-08-07 18:36:37 +0000802bool parser<float>::parse(Option &O, const char *AN,
803 const std::string &Arg, float &Val) {
804 double dVal;
805 if (parseDouble(O, Arg, dVal))
806 return true;
807 Val = (float)dVal;
808 return false;
Chris Lattner331de232002-07-22 02:07:59 +0000809}
810
811
Chris Lattner331de232002-07-22 02:07:59 +0000812
813// generic_parser_base implementation
814//
815
Chris Lattneraa852bb2002-07-23 17:15:12 +0000816// findOption - Return the option number corresponding to the specified
817// argument string. If the option is not found, getNumOptions() is returned.
818//
819unsigned generic_parser_base::findOption(const char *Name) {
820 unsigned i = 0, e = getNumOptions();
Chris Lattnerca6433f2003-05-22 20:06:43 +0000821 std::string N(Name);
Chris Lattneraa852bb2002-07-23 17:15:12 +0000822
823 while (i != e)
824 if (getOption(i) == N)
825 return i;
826 else
827 ++i;
828 return e;
829}
830
831
Chris Lattner331de232002-07-22 02:07:59 +0000832// Return the width of the option tag for printing...
833unsigned generic_parser_base::getOptionWidth(const Option &O) const {
834 if (O.hasArgStr()) {
835 unsigned Size = std::strlen(O.ArgStr)+6;
836 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
837 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
838 return Size;
839 } else {
840 unsigned BaseSize = 0;
841 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
842 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
843 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000844 }
845}
846
Misha Brukmanf976c852005-04-21 22:55:34 +0000847// printOptionInfo - Print out information about this option. The
Chris Lattner331de232002-07-22 02:07:59 +0000848// to-be-maintained width is specified.
849//
850void generic_parser_base::printOptionInfo(const Option &O,
851 unsigned GlobalWidth) const {
852 if (O.hasArgStr()) {
853 unsigned L = std::strlen(O.ArgStr);
Bill Wendlinge8156192006-12-07 01:30:32 +0000854 cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
855 << " - " << O.HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000856
Chris Lattner331de232002-07-22 02:07:59 +0000857 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
858 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Bill Wendlinge8156192006-12-07 01:30:32 +0000859 cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
860 << " - " << getDescription(i) << "\n";
Chris Lattner9c9be482002-01-31 00:42:56 +0000861 }
Chris Lattner331de232002-07-22 02:07:59 +0000862 } else {
863 if (O.HelpStr[0])
Bill Wendlinge8156192006-12-07 01:30:32 +0000864 cout << " " << O.HelpStr << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000865 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
866 unsigned L = std::strlen(getOption(i));
Bill Wendlinge8156192006-12-07 01:30:32 +0000867 cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
868 << " - " << getDescription(i) << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000869 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000870 }
871}
872
873
874//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000875// --help and --help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000876//
Reid Spencerad0846b2004-11-14 22:04:00 +0000877
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000878namespace {
879
Chris Lattner331de232002-07-22 02:07:59 +0000880class HelpPrinter {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000881 unsigned MaxArgLen;
882 const Option *EmptyArg;
883 const bool ShowHidden;
884
Chris Lattner331de232002-07-22 02:07:59 +0000885 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
Chris Lattnerca6433f2003-05-22 20:06:43 +0000886 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000887 return OptPair.second->getOptionHiddenFlag() >= Hidden;
888 }
Chris Lattnerca6433f2003-05-22 20:06:43 +0000889 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000890 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
891 }
892
893public:
894 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
895 EmptyArg = 0;
896 }
897
898 void operator=(bool Value) {
899 if (Value == false) return;
900
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000901 // Copy Options into a vector so we can sort them as we like...
Chris Lattner90aa8392006-10-04 21:52:35 +0000902 std::vector<std::pair<std::string, Option*> > Opts;
903 copy(Options->begin(), Options->end(), std::back_inserter(Opts));
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000904
905 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Chris Lattner90aa8392006-10-04 21:52:35 +0000906 Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
907 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
908 Opts.end());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000909
910 // Eliminate duplicate entries in table (from enum flags options, f.e.)
Chris Lattner331de232002-07-22 02:07:59 +0000911 { // Give OptionSet a scope
912 std::set<Option*> OptionSet;
Chris Lattner90aa8392006-10-04 21:52:35 +0000913 for (unsigned i = 0; i != Opts.size(); ++i)
914 if (OptionSet.count(Opts[i].second) == 0)
915 OptionSet.insert(Opts[i].second); // Add new entry to set
Chris Lattner331de232002-07-22 02:07:59 +0000916 else
Chris Lattner90aa8392006-10-04 21:52:35 +0000917 Opts.erase(Opts.begin()+i--); // Erase duplicate
Chris Lattner331de232002-07-22 02:07:59 +0000918 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000919
920 if (ProgramOverview)
Bill Wendlinge8156192006-12-07 01:30:32 +0000921 cout << "OVERVIEW:" << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000922
Bill Wendlinge8156192006-12-07 01:30:32 +0000923 cout << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +0000924
Chris Lattner90aa8392006-10-04 21:52:35 +0000925 // Print out the positional options.
926 std::vector<Option*> &PosOpts = *PositionalOptions;
Chris Lattner331de232002-07-22 02:07:59 +0000927 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000928 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
Chris Lattner331de232002-07-22 02:07:59 +0000929 CAOpt = PosOpts[0];
930
Chris Lattner9cf3d472003-07-30 17:34:02 +0000931 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
932 if (PosOpts[i]->ArgStr[0])
Bill Wendlinge8156192006-12-07 01:30:32 +0000933 cout << " --" << PosOpts[i]->ArgStr;
934 cout << " " << PosOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000935 }
Chris Lattner331de232002-07-22 02:07:59 +0000936
937 // Print the consume after option info if it exists...
Bill Wendlinge8156192006-12-07 01:30:32 +0000938 if (CAOpt) cout << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +0000939
Bill Wendlinge8156192006-12-07 01:30:32 +0000940 cout << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000941
942 // Compute the maximum argument length...
943 MaxArgLen = 0;
Chris Lattner90aa8392006-10-04 21:52:35 +0000944 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
945 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000946
Bill Wendlinge8156192006-12-07 01:30:32 +0000947 cout << "OPTIONS:\n";
Chris Lattner90aa8392006-10-04 21:52:35 +0000948 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
949 Opts[i].second->printOptionInfo(MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000950
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000951 // Print any extra help the user has declared.
Chris Lattner90aa8392006-10-04 21:52:35 +0000952 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
953 E = MoreHelp->end(); I != E; ++I)
Bill Wendlinge8156192006-12-07 01:30:32 +0000954 cout << *I;
Chris Lattner90aa8392006-10-04 21:52:35 +0000955 MoreHelp->clear();
Reid Spencerad0846b2004-11-14 22:04:00 +0000956
Reid Spencer9bbba0912004-11-16 06:11:52 +0000957 // Halt the program since help information was printed
Chris Lattner90aa8392006-10-04 21:52:35 +0000958 Options->clear(); // Don't bother making option dtors remove from map.
Chris Lattner331de232002-07-22 02:07:59 +0000959 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000960 }
961};
Chris Lattner500d8bf2006-10-12 22:09:17 +0000962} // End anonymous namespace
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000963
Chris Lattner331de232002-07-22 02:07:59 +0000964// Define the two HelpPrinter instances that are used to print out help, or
965// help-hidden...
966//
Chris Lattner500d8bf2006-10-12 22:09:17 +0000967static HelpPrinter NormalPrinter(false);
968static HelpPrinter HiddenPrinter(true);
Chris Lattner331de232002-07-22 02:07:59 +0000969
Chris Lattner500d8bf2006-10-12 22:09:17 +0000970static cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +0000971HOp("help", cl::desc("Display available options (--help-hidden for more)"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000972 cl::location(NormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +0000973
Chris Lattner500d8bf2006-10-12 22:09:17 +0000974static cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +0000975HHOp("help-hidden", cl::desc("Display all available options"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000976 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000977
Chris Lattner500d8bf2006-10-12 22:09:17 +0000978static void (*OverrideVersionPrinter)() = 0;
Reid Spencer515b5b32006-06-05 16:22:56 +0000979
Chris Lattner500d8bf2006-10-12 22:09:17 +0000980namespace {
Reid Spencer515b5b32006-06-05 16:22:56 +0000981class VersionPrinter {
982public:
Devang Patelaed293d2007-02-01 01:43:37 +0000983 void print() {
Bill Wendlinge8156192006-12-07 01:30:32 +0000984 cout << "Low Level Virtual Machine (http://llvm.org/):\n";
985 cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner3fc2f4e2006-07-06 18:33:03 +0000986#ifdef LLVM_VERSION_INFO
Bill Wendlinge8156192006-12-07 01:30:32 +0000987 cout << LLVM_VERSION_INFO;
Reid Spencer515b5b32006-06-05 16:22:56 +0000988#endif
Bill Wendlinge8156192006-12-07 01:30:32 +0000989 cout << "\n ";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +0000990#ifndef __OPTIMIZE__
Bill Wendlinge8156192006-12-07 01:30:32 +0000991 cout << "DEBUG build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +0000992#else
Bill Wendlinge8156192006-12-07 01:30:32 +0000993 cout << "Optimized build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +0000994#endif
995#ifndef NDEBUG
Bill Wendlinge8156192006-12-07 01:30:32 +0000996 cout << " with assertions";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +0000997#endif
Bill Wendlinge8156192006-12-07 01:30:32 +0000998 cout << ".\n";
Devang Patelaed293d2007-02-01 01:43:37 +0000999 }
1000 void operator=(bool OptionWasSpecified) {
1001 if (OptionWasSpecified) {
1002 if (OverrideVersionPrinter == 0) {
1003 print();
Chris Lattner90aa8392006-10-04 21:52:35 +00001004 Options->clear(); // Don't bother making option dtors remove from map.
Reid Spencer515b5b32006-06-05 16:22:56 +00001005 exit(1);
1006 } else {
1007 (*OverrideVersionPrinter)();
1008 exit(1);
1009 }
1010 }
1011 }
1012};
Chris Lattner500d8bf2006-10-12 22:09:17 +00001013} // End anonymous namespace
Reid Spencer515b5b32006-06-05 16:22:56 +00001014
1015
Reid Spencer69105f32004-08-04 00:36:06 +00001016// Define the --version option that prints out the LLVM version for the tool
Chris Lattner500d8bf2006-10-12 22:09:17 +00001017static VersionPrinter VersionPrinterInstance;
1018
1019static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001020VersOp("version", cl::desc("Display the version of this program"),
Reid Spencer69105f32004-08-04 00:36:06 +00001021 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1022
Reid Spencer9bbba0912004-11-16 06:11:52 +00001023// Utility function for printing the help message.
1024void cl::PrintHelpMessage() {
Misha Brukmanf976c852005-04-21 22:55:34 +00001025 // This looks weird, but it actually prints the help message. The
Reid Spencer5cc498f2004-11-16 06:50:36 +00001026 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1027 // its operator= is invoked. That's because the "normal" usages of the
Misha Brukmanf976c852005-04-21 22:55:34 +00001028 // help printer is to be assigned true/false depending on whether the
Reid Spencer5cc498f2004-11-16 06:50:36 +00001029 // --help option was given or not. Since we're circumventing that we have
1030 // to make it look like --help was given, so we assign true.
Reid Spencer9bbba0912004-11-16 06:11:52 +00001031 NormalPrinter = true;
1032}
Reid Spencer515b5b32006-06-05 16:22:56 +00001033
Devang Patelaed293d2007-02-01 01:43:37 +00001034/// Utility function for printing version number.
1035void cl::PrintVersionMessage() {
1036 VersionPrinterInstance.print();
1037}
1038
Reid Spencer515b5b32006-06-05 16:22:56 +00001039void cl::SetVersionPrinter(void (*func)()) {
1040 OverrideVersionPrinter = func;
1041}