blob: 069940162b4a1ee69866badf0533c2e1e395ab75 [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 Lattnerdbab15a2001-07-23 17:17:47 +000021#include <algorithm>
Duraid Madina786e3e22005-12-26 04:56:16 +000022#include <functional>
Chris Lattnerdbab15a2001-07-23 17:17:47 +000023#include <map>
24#include <set>
Chris Lattner697954c2002-01-20 22:54:45 +000025#include <iostream>
Brian Gaeke2d6a2362003-10-10 17:01:36 +000026#include <cstdlib>
27#include <cerrno>
Chris Lattner51140042004-07-03 01:21:05 +000028#include <cstring>
Chris Lattner2cdd21c2003-12-14 21:35:53 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattnerdbab15a2001-07-23 17:17:47 +000031using namespace cl;
32
Reid Spencere1cc1502004-09-01 04:41:28 +000033// Globals for name and overview of program
Reid Spencer023fcf92006-08-21 02:04:43 +000034static const char *ProgramName = "<premain>";
Reid Spencere1cc1502004-09-01 04:41:28 +000035static const char *ProgramOverview = 0;
36
Chris Lattnerc540ebb2004-11-19 17:08:15 +000037// This collects additional help to be printed.
38static std::vector<const char*> &MoreHelp() {
39 static std::vector<const char*> moreHelp;
40 return moreHelp;
41}
42
43extrahelp::extrahelp(const char* Help)
44 : morehelp(Help) {
45 MoreHelp().push_back(Help);
46}
47
Chris Lattner331de232002-07-22 02:07:59 +000048//===----------------------------------------------------------------------===//
49// Basic, shared command line option processing machinery...
50//
51
Chris Lattnerdbab15a2001-07-23 17:17:47 +000052// Return the global command line option vector. Making it a function scoped
Chris Lattnerf78032f2001-11-26 18:58:34 +000053// static ensures that it will be initialized correctly before its first use.
Chris Lattnerdbab15a2001-07-23 17:17:47 +000054//
Chris Lattnerca6433f2003-05-22 20:06:43 +000055static std::map<std::string, Option*> &getOpts() {
Chris Lattnerc540ebb2004-11-19 17:08:15 +000056 static std::map<std::string, Option*> CommandLineOptions;
57 return CommandLineOptions;
Chris Lattnere8e258b2002-07-29 20:58:42 +000058}
59
Chris Lattnerca6433f2003-05-22 20:06:43 +000060static Option *getOption(const std::string &Str) {
Chris Lattnerc540ebb2004-11-19 17:08:15 +000061 std::map<std::string,Option*>::iterator I = getOpts().find(Str);
62 return I != getOpts().end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000063}
64
Chris Lattnerca6433f2003-05-22 20:06:43 +000065static std::vector<Option*> &getPositionalOpts() {
Chris Lattnerc540ebb2004-11-19 17:08:15 +000066 static std::vector<Option*> Positional;
67 return Positional;
Chris Lattner331de232002-07-22 02:07:59 +000068}
69
Chris Lattnere8e258b2002-07-29 20:58:42 +000070static void AddArgument(const char *ArgName, Option *Opt) {
71 if (getOption(ArgName)) {
Misha Brukmanf976c852005-04-21 22:55:34 +000072 std::cerr << ProgramName << ": CommandLine Error: Argument '"
Reid Spencere1cc1502004-09-01 04:41:28 +000073 << ArgName << "' defined more than once!\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +000074 } else {
Chris Lattnerf78032f2001-11-26 18:58:34 +000075 // Add argument to the argument map!
Chris Lattnere8e258b2002-07-29 20:58:42 +000076 getOpts()[ArgName] = Opt;
77 }
78}
79
80// RemoveArgument - It's possible that the argument is no longer in the map if
81// options have already been processed and the map has been deleted!
Misha Brukmanf976c852005-04-21 22:55:34 +000082//
Chris Lattnere8e258b2002-07-29 20:58:42 +000083static void RemoveArgument(const char *ArgName, Option *Opt) {
Tanya Lattnerc4ae8e92004-11-20 23:35:20 +000084 if(getOpts().empty()) return;
85
Chris Lattnerf98cfc72004-07-18 21:56:20 +000086#ifndef NDEBUG
87 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
88 // If we pass ArgName directly into getOption here.
89 std::string Tmp = ArgName;
90 assert(getOption(Tmp) == Opt && "Arg not in map!");
91#endif
Chris Lattnerc540ebb2004-11-19 17:08:15 +000092 getOpts().erase(ArgName);
Chris Lattnerdbab15a2001-07-23 17:17:47 +000093}
94
Chris Lattnercaccd762001-10-27 05:54:17 +000095static inline bool ProvideOption(Option *Handler, const char *ArgName,
96 const char *Value, int argc, char **argv,
97 int &i) {
98 // Enforce value requirements
99 switch (Handler->getValueExpectedFlag()) {
100 case ValueRequired:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000101 if (Value == 0) { // No value specified?
Chris Lattnercaccd762001-10-27 05:54:17 +0000102 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
103 Value = argv[++i];
104 } else {
105 return Handler->error(" requires a value!");
106 }
107 }
108 break;
109 case ValueDisallowed:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000110 if (Value)
Misha Brukmanf976c852005-04-21 22:55:34 +0000111 return Handler->error(" does not allow a value! '" +
Chris Lattnerca6433f2003-05-22 20:06:43 +0000112 std::string(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +0000113 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000114 case ValueOptional:
Reid Spencere1cc1502004-09-01 04:41:28 +0000115 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000116 default:
117 std::cerr << ProgramName
118 << ": Bad ValueMask flag! CommandLine usage error:"
119 << Handler->getValueExpectedFlag() << "\n";
Reid Spencere1cc1502004-09-01 04:41:28 +0000120 abort();
121 break;
Chris Lattnercaccd762001-10-27 05:54:17 +0000122 }
123
124 // Run the handler now!
Chris Lattner6d5857e2005-05-10 23:20:17 +0000125 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
Chris Lattnercaccd762001-10-27 05:54:17 +0000126}
127
Misha Brukmanf976c852005-04-21 22:55:34 +0000128static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000129 int i) {
130 int Dummy = i;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000131 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000132}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000133
Chris Lattner331de232002-07-22 02:07:59 +0000134
135// Option predicates...
136static inline bool isGrouping(const Option *O) {
137 return O->getFormattingFlag() == cl::Grouping;
138}
139static inline bool isPrefixedOrGrouping(const Option *O) {
140 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
141}
142
143// getOptionPred - Check to see if there are any options that satisfy the
144// specified predicate with names that are the prefixes in Name. This is
145// checked by progressively stripping characters off of the name, checking to
146// see if there options that satisfy the predicate. If we find one, return it,
147// otherwise return null.
148//
149static Option *getOptionPred(std::string Name, unsigned &Length,
150 bool (*Pred)(const Option*)) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000151
Chris Lattnere8e258b2002-07-29 20:58:42 +0000152 Option *Op = getOption(Name);
153 if (Op && Pred(Op)) {
Chris Lattner331de232002-07-22 02:07:59 +0000154 Length = Name.length();
Chris Lattnere8e258b2002-07-29 20:58:42 +0000155 return Op;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000156 }
157
Chris Lattner331de232002-07-22 02:07:59 +0000158 if (Name.size() == 1) return 0;
159 do {
160 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
Chris Lattnere8e258b2002-07-29 20:58:42 +0000161 Op = getOption(Name);
Chris Lattner331de232002-07-22 02:07:59 +0000162
163 // Loop while we haven't found an option and Name still has at least two
164 // characters in it (so that the next iteration will not be the empty
165 // string...
Chris Lattnere8e258b2002-07-29 20:58:42 +0000166 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
Chris Lattner331de232002-07-22 02:07:59 +0000167
Chris Lattnere8e258b2002-07-29 20:58:42 +0000168 if (Op && Pred(Op)) {
Chris Lattner331de232002-07-22 02:07:59 +0000169 Length = Name.length();
Chris Lattnere8e258b2002-07-29 20:58:42 +0000170 return Op; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000171 }
172 return 0; // No option found!
173}
174
175static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000176 return O->getNumOccurrencesFlag() == cl::Required ||
177 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000178}
179
180static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000181 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
182 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000183}
Chris Lattnercaccd762001-10-27 05:54:17 +0000184
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000185/// ParseCStringVector - Break INPUT up wherever one or more
186/// whitespace characters are found, and store the resulting tokens in
187/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
188/// using strdup (), so it is the caller's responsibility to free ()
189/// them later.
Brian Gaeke06b06c52003-08-14 22:00:59 +0000190///
191static void ParseCStringVector (std::vector<char *> &output,
Reid Spencer69105f32004-08-04 00:36:06 +0000192 const char *input) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000193 // Characters which will be treated as token separators:
194 static const char *delims = " \v\f\t\r\n";
195
196 std::string work (input);
197 // Skip past any delims at head of input string.
198 size_t pos = work.find_first_not_of (delims);
199 // If the string consists entirely of delims, then exit early.
200 if (pos == std::string::npos) return;
201 // Otherwise, jump forward to beginning of first word.
202 work = work.substr (pos);
203 // Find position of first delimiter.
204 pos = work.find_first_of (delims);
205
206 while (!work.empty() && pos != std::string::npos) {
207 // Everything from 0 to POS is the next word to copy.
208 output.push_back (strdup (work.substr (0,pos).c_str ()));
209 // Is there another word in the string?
210 size_t nextpos = work.find_first_not_of (delims, pos + 1);
211 if (nextpos != std::string::npos) {
212 // Yes? Then remove delims from beginning ...
213 work = work.substr (work.find_first_not_of (delims, pos + 1));
214 // and find the end of the word.
215 pos = work.find_first_of (delims);
216 } else {
217 // No? (Remainder of string is delims.) End the loop.
218 work = "";
219 pos = std::string::npos;
220 }
221 }
222
223 // If `input' ended with non-delim char, then we'll get here with
224 // the last word of `input' in `work'; copy it now.
225 if (!work.empty ()) {
226 output.push_back (strdup (work.c_str ()));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000227 }
228}
229
230/// ParseEnvironmentOptions - An alternative entry point to the
231/// CommandLine library, which allows you to read the program's name
232/// from the caller (as PROGNAME) and its command-line arguments from
233/// an environment variable (whose name is given in ENVVAR).
234///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000235void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
236 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000237 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000238 assert(progName && "Program name not specified");
239 assert(envVar && "Environment variable name missing");
Misha Brukmanf976c852005-04-21 22:55:34 +0000240
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000241 // Get the environment variable they want us to parse options out of.
242 const char *envValue = getenv (envVar);
243 if (!envValue)
244 return;
245
Brian Gaeke06b06c52003-08-14 22:00:59 +0000246 // Get program's "name", which we wouldn't know without the caller
247 // telling us.
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000248 std::vector<char *> newArgv;
249 newArgv.push_back (strdup (progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000250
251 // Parse the value of the environment variable into a "command line"
252 // and hand it off to ParseCommandLineOptions().
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000253 ParseCStringVector (newArgv, envValue);
254 int newArgc = newArgv.size ();
255 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
256
257 // Free all the strdup()ed strings.
258 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
259 i != e; ++i) {
260 free (*i);
261 }
Brian Gaeke06b06c52003-08-14 22:00:59 +0000262}
263
Chris Lattnerbf455c22004-05-06 22:04:31 +0000264/// LookupOption - Lookup the option specified by the specified option on the
265/// command line. If there is a value specified (after an equal sign) return
266/// that as well.
267static Option *LookupOption(const char *&Arg, const char *&Value) {
268 while (*Arg == '-') ++Arg; // Eat leading dashes
Misha Brukmanf976c852005-04-21 22:55:34 +0000269
Chris Lattnerbf455c22004-05-06 22:04:31 +0000270 const char *ArgEnd = Arg;
271 while (*ArgEnd && *ArgEnd != '=')
Chris Lattner6d5857e2005-05-10 23:20:17 +0000272 ++ArgEnd; // Scan till end of argument name.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000273
Chris Lattner6d5857e2005-05-10 23:20:17 +0000274 if (*ArgEnd == '=') // If we have an equals sign...
275 Value = ArgEnd+1; // Get the value, not the equals
276
Misha Brukmanf976c852005-04-21 22:55:34 +0000277
Chris Lattnerbf455c22004-05-06 22:04:31 +0000278 if (*Arg == 0) return 0;
279
280 // Look up the option.
281 std::map<std::string, Option*> &Opts = getOpts();
282 std::map<std::string, Option*>::iterator I =
283 Opts.find(std::string(Arg, ArgEnd));
284 return (I != Opts.end()) ? I->second : 0;
285}
286
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000287void cl::ParseCommandLineOptions(int &argc, char **argv,
Chris Lattner0c0edf82002-07-25 06:17:51 +0000288 const char *Overview) {
Chris Lattner331de232002-07-22 02:07:59 +0000289 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
290 "No options specified, or ParseCommandLineOptions called more"
291 " than once!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000292 ProgramName = argv[0]; // Save this away safe and snug
293 ProgramOverview = Overview;
294 bool ErrorParsing = false;
295
Chris Lattnerca6433f2003-05-22 20:06:43 +0000296 std::map<std::string, Option*> &Opts = getOpts();
297 std::vector<Option*> &PositionalOpts = getPositionalOpts();
Chris Lattner331de232002-07-22 02:07:59 +0000298
299 // Check out the positional arguments to collect information about them.
300 unsigned NumPositionalRequired = 0;
Chris Lattnerde013242005-08-08 17:25:38 +0000301
302 // Determine whether or not there are an unlimited number of positionals
303 bool HasUnlimitedPositionals = false;
304
Chris Lattner331de232002-07-22 02:07:59 +0000305 Option *ConsumeAfterOpt = 0;
306 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000307 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000308 assert(PositionalOpts.size() > 1 &&
309 "Cannot specify cl::ConsumeAfter without a positional argument!");
310 ConsumeAfterOpt = PositionalOpts[0];
311 }
312
313 // Calculate how many positional values are _required_.
314 bool UnboundedFound = false;
315 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
316 i != e; ++i) {
317 Option *Opt = PositionalOpts[i];
318 if (RequiresValue(Opt))
319 ++NumPositionalRequired;
320 else if (ConsumeAfterOpt) {
321 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000322 // unless there is only one positional argument...
323 if (PositionalOpts.size() > 2)
324 ErrorParsing |=
325 Opt->error(" error - this positional option will never be matched, "
326 "because it does not Require a value, and a "
327 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000328 } else if (UnboundedFound && !Opt->ArgStr[0]) {
329 // This option does not "require" a value... Make sure this option is
330 // not specified after an option that eats all extra arguments, or this
331 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000332 //
333 ErrorParsing |= Opt->error(" error - option can never match, because "
334 "another positional argument will match an "
335 "unbounded number of values, and this option"
336 " does not require a value!");
337 }
338 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
339 }
Chris Lattner21e1a792005-08-08 21:57:27 +0000340 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000341 }
342
Reid Spencer1e13fd22004-08-13 19:47:30 +0000343 // PositionalVals - A vector of "positional" arguments we accumulate into
344 // the process at the end...
Chris Lattner331de232002-07-22 02:07:59 +0000345 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000346 std::vector<std::pair<std::string,unsigned> > PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000347
Chris Lattner9cf3d472003-07-30 17:34:02 +0000348 // If the program has named positional arguments, and the name has been run
349 // across, keep track of which positional argument was named. Otherwise put
350 // the positional args into the PositionalVals list...
351 Option *ActivePositionalArg = 0;
352
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000353 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000354 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000355 for (int i = 1; i < argc; ++i) {
356 Option *Handler = 0;
Chris Lattner6d5857e2005-05-10 23:20:17 +0000357 const char *Value = 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000358 const char *ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000359
360 // Check to see if this is a positional argument. This argument is
361 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000362 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000363 //
364 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
365 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000366 if (ActivePositionalArg) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000367 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000368 continue; // We are done!
369 } else if (!PositionalOpts.empty()) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000370 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000371
372 // All of the positional arguments have been fulfulled, give the rest to
373 // the consume after option... if it's specified...
374 //
Misha Brukmanf976c852005-04-21 22:55:34 +0000375 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000376 ConsumeAfterOpt != 0) {
377 for (++i; i < argc; ++i)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000378 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000379 break; // Handle outside of the argument processing loop...
380 }
381
382 // Delay processing positional arguments until the end...
383 continue;
384 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000385 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
386 !DashDashFound) {
387 DashDashFound = true; // This is the mythical "--"?
388 continue; // Don't try to process it as an argument itself.
389 } else if (ActivePositionalArg &&
390 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
391 // If there is a positional argument eating options, check to see if this
392 // option is another positional argument. If so, treat it as an argument,
393 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000394 ArgName = argv[i]+1;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000395 Handler = LookupOption(ArgName, Value);
396 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000397 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000398 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000399 }
400
Chris Lattnerbf455c22004-05-06 22:04:31 +0000401 } else { // We start with a '-', must be an argument...
402 ArgName = argv[i]+1;
403 Handler = LookupOption(ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000404
Chris Lattnerbf455c22004-05-06 22:04:31 +0000405 // Check to see if this "option" is really a prefixed or grouped argument.
Reid Spencer5f8448f2004-11-24 06:13:42 +0000406 if (Handler == 0) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000407 std::string RealName(ArgName);
408 if (RealName.size() > 1) {
Chris Lattner331de232002-07-22 02:07:59 +0000409 unsigned Length = 0;
410 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
Misha Brukmanf976c852005-04-21 22:55:34 +0000411
Chris Lattner331de232002-07-22 02:07:59 +0000412 // If the option is a prefixed option, then the value is simply the
413 // rest of the name... so fall through to later processing, by
414 // setting up the argument name flags and value fields.
415 //
416 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000417 Value = ArgName+Length;
418 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
419 Opts.find(std::string(ArgName, Value))->second == PGOpt);
420 Handler = PGOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000421 } else if (PGOpt) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000422 // This must be a grouped option... handle them now.
Chris Lattner331de232002-07-22 02:07:59 +0000423 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000424
Chris Lattner331de232002-07-22 02:07:59 +0000425 do {
426 // Move current arg name out of RealName into RealArgName...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000427 std::string RealArgName(RealName.begin(),
428 RealName.begin() + Length);
429 RealName.erase(RealName.begin(), RealName.begin() + Length);
Misha Brukmanf976c852005-04-21 22:55:34 +0000430
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000431 // Because ValueRequired is an invalid flag for grouped arguments,
432 // we don't need to pass argc/argv in...
433 //
Chris Lattner331de232002-07-22 02:07:59 +0000434 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
435 "Option can not be cl::Grouping AND cl::ValueRequired!");
436 int Dummy;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000437 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
Chris Lattner6d5857e2005-05-10 23:20:17 +0000438 0, 0, 0, Dummy);
Misha Brukmanf976c852005-04-21 22:55:34 +0000439
Chris Lattner331de232002-07-22 02:07:59 +0000440 // Get the next grouping option...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000441 PGOpt = getOptionPred(RealName, Length, isGrouping);
442 } while (PGOpt && Length != RealName.size());
Misha Brukmanf976c852005-04-21 22:55:34 +0000443
Chris Lattnerbf455c22004-05-06 22:04:31 +0000444 Handler = PGOpt; // Ate all of the options.
Chris Lattner331de232002-07-22 02:07:59 +0000445 }
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000446 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000447 }
448 }
449
450 if (Handler == 0) {
Chris Lattner79959d22006-01-17 00:32:28 +0000451 if (ProgramName)
452 std::cerr << ProgramName << ": Unknown command line argument '"
453 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
454 else
455 std::cerr << "Unknown command line argument '" << argv[i] << "'.\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000456 ErrorParsing = true;
457 continue;
458 }
459
Chris Lattner72fb8e52003-05-22 20:26:17 +0000460 // Check to see if this option accepts a comma separated list of values. If
461 // it does, we have to split up the value into multiple values...
Chris Lattner6d5857e2005-05-10 23:20:17 +0000462 if (Value && Handler->getMiscFlags() & CommaSeparated) {
Chris Lattner72fb8e52003-05-22 20:26:17 +0000463 std::string Val(Value);
464 std::string::size_type Pos = Val.find(',');
465
466 while (Pos != std::string::npos) {
467 // Process the portion before the comma...
468 ErrorParsing |= ProvideOption(Handler, ArgName,
469 std::string(Val.begin(),
470 Val.begin()+Pos).c_str(),
471 argc, argv, i);
472 // Erase the portion before the comma, AND the comma...
473 Val.erase(Val.begin(), Val.begin()+Pos+1);
474 Value += Pos+1; // Increment the original value pointer as well...
475
476 // Check for another comma...
477 Pos = Val.find(',');
478 }
479 }
Chris Lattner9cf3d472003-07-30 17:34:02 +0000480
481 // If this is a named positional argument, just remember that it is the
482 // active one...
483 if (Handler->getFormattingFlag() == cl::Positional)
484 ActivePositionalArg = Handler;
Misha Brukmanf976c852005-04-21 22:55:34 +0000485 else
Chris Lattner9cf3d472003-07-30 17:34:02 +0000486 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000487 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000488
Chris Lattner331de232002-07-22 02:07:59 +0000489 // Check and handle positional arguments now...
490 if (NumPositionalRequired > PositionalVals.size()) {
Chris Lattner79959d22006-01-17 00:32:28 +0000491 if (ProgramName)
492 std::cerr << ProgramName
493 << ": Not enough positional command line arguments specified!\n"
494 << "Must specify at least " << NumPositionalRequired
495 << " positional arguments: See: " << argv[0] << " --help\n";
496 else
497 std::cerr << "Not enough positional command line arguments specified!\n"
498 << "Must specify at least " << NumPositionalRequired
499 << " positional arguments.";
500
Chris Lattner331de232002-07-22 02:07:59 +0000501 ErrorParsing = true;
Chris Lattnerde013242005-08-08 17:25:38 +0000502 } else if (!HasUnlimitedPositionals
503 && PositionalVals.size() > PositionalOpts.size()) {
Chris Lattner79959d22006-01-17 00:32:28 +0000504 if (ProgramName)
505 std::cerr << ProgramName
506 << ": Too many positional arguments specified!\n"
507 << "Can specify at most " << PositionalOpts.size()
508 << " positional arguments: See: " << argv[0] << " --help\n";
509 else
510 std::cerr << "Too many positional arguments specified!\n"
511 << "Can specify at most " << PositionalOpts.size()
512 << " positional arguments.\n";
Chris Lattnerde013242005-08-08 17:25:38 +0000513 ErrorParsing = true;
Chris Lattner331de232002-07-22 02:07:59 +0000514
515 } else if (ConsumeAfterOpt == 0) {
516 // Positional args have already been handled if ConsumeAfter is specified...
517 unsigned ValNo = 0, NumVals = PositionalVals.size();
518 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
519 if (RequiresValue(PositionalOpts[i])) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000520 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000521 PositionalVals[ValNo].second);
522 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000523 --NumPositionalRequired; // We fulfilled our duty...
524 }
525
526 // If we _can_ give this option more arguments, do so now, as long as we
527 // do not give it values that others need. 'Done' controls whether the
528 // option even _WANTS_ any more.
529 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000530 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000531 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000532 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000533 case cl::Optional:
534 Done = true; // Optional arguments want _at most_ one value
535 // FALL THROUGH
536 case cl::ZeroOrMore: // Zero or more will take all they can get...
537 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer1e13fd22004-08-13 19:47:30 +0000538 ProvidePositionalOption(PositionalOpts[i],
539 PositionalVals[ValNo].first,
540 PositionalVals[ValNo].second);
541 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000542 break;
543 default:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000544 assert(0 && "Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000545 "positional argument processing!");
546 }
547 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000548 }
Chris Lattner331de232002-07-22 02:07:59 +0000549 } else {
550 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
551 unsigned ValNo = 0;
552 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000553 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000554 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000555 PositionalVals[ValNo].first,
556 PositionalVals[ValNo].second);
557 ValNo++;
558 }
Chris Lattnerfaba8092002-07-24 20:15:13 +0000559
560 // Handle the case where there is just one positional option, and it's
561 // optional. In this case, we want to give JUST THE FIRST option to the
562 // positional option and keep the rest for the consume after. The above
563 // loop would have assigned no values to positional options in this case.
564 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000565 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000566 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000567 PositionalVals[ValNo].first,
568 PositionalVals[ValNo].second);
569 ValNo++;
570 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000571
Chris Lattner331de232002-07-22 02:07:59 +0000572 // Handle over all of the rest of the arguments to the
573 // cl::ConsumeAfter command line option...
574 for (; ValNo != PositionalVals.size(); ++ValNo)
575 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000576 PositionalVals[ValNo].first,
577 PositionalVals[ValNo].second);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000578 }
579
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000580 // Loop over args and make sure all required args are specified!
Misha Brukmanf976c852005-04-21 22:55:34 +0000581 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000582 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000583 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000584 case Required:
585 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000586 if (I->second->getNumOccurrences() == 0) {
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000587 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000588 ErrorParsing = true;
589 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000590 // Fall through
591 default:
592 break;
593 }
594 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000595
Chris Lattner331de232002-07-22 02:07:59 +0000596 // Free all of the memory allocated to the map. Command line options may only
597 // be processed once!
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000598 getOpts().clear();
Chris Lattner331de232002-07-22 02:07:59 +0000599 PositionalOpts.clear();
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000600 MoreHelp().clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000601
602 // If we had an error processing our arguments, don't let the program execute
603 if (ErrorParsing) exit(1);
604}
605
606//===----------------------------------------------------------------------===//
607// Option Base class implementation
608//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000609
Chris Lattner433fd762006-07-18 23:59:33 +0000610// Out of line virtual function to provide home for the class.
611void Option::anchor() {
612}
613
Chris Lattnerca6433f2003-05-22 20:06:43 +0000614bool Option::error(std::string Message, const char *ArgName) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000615 if (ArgName == 0) ArgName = ArgStr;
Chris Lattner331de232002-07-22 02:07:59 +0000616 if (ArgName[0] == 0)
Chris Lattnerca6433f2003-05-22 20:06:43 +0000617 std::cerr << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000618 else
Jim Laskeyabe0e3e2006-08-02 20:15:56 +0000619 std::cerr << (ProgramName ? ProgramName : "***")
620 << ": for the -" << ArgName;
621
Reid Spencere1cc1502004-09-01 04:41:28 +0000622 std::cerr << " option: " << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000623 return true;
624}
625
Chris Lattner6d5857e2005-05-10 23:20:17 +0000626bool Option::addOccurrence(unsigned pos, const char *ArgName,
627 const std::string &Value) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000628 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000629
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000630 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000631 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000632 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000633 return error(": may only occur zero or one times!", ArgName);
634 break;
635 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000636 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000637 return error(": must occur exactly one time!", ArgName);
638 // Fall through
639 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000640 case ZeroOrMore:
641 case ConsumeAfter: break;
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000642 default: return error(": bad num occurrences flag value!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000643 }
644
Reid Spencer1e13fd22004-08-13 19:47:30 +0000645 return handleOccurrence(pos, ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000646}
647
Chris Lattner331de232002-07-22 02:07:59 +0000648// addArgument - Tell the system that this Option subclass will handle all
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000649// occurrences of -ArgStr on the command line.
Chris Lattner331de232002-07-22 02:07:59 +0000650//
651void Option::addArgument(const char *ArgStr) {
652 if (ArgStr[0])
653 AddArgument(ArgStr, this);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000654
655 if (getFormattingFlag() == Positional)
Chris Lattner331de232002-07-22 02:07:59 +0000656 getPositionalOpts().push_back(this);
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000657 else if (getNumOccurrencesFlag() == ConsumeAfter) {
Chris Lattner9cf3d472003-07-30 17:34:02 +0000658 if (!getPositionalOpts().empty() &&
659 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
660 error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattner331de232002-07-22 02:07:59 +0000661 getPositionalOpts().insert(getPositionalOpts().begin(), this);
662 }
663}
664
Chris Lattneraa852bb2002-07-23 17:15:12 +0000665void Option::removeArgument(const char *ArgStr) {
Chris Lattner9cf3d472003-07-30 17:34:02 +0000666 if (ArgStr[0])
Chris Lattnere8e258b2002-07-29 20:58:42 +0000667 RemoveArgument(ArgStr, this);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000668
669 if (getFormattingFlag() == Positional) {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000670 std::vector<Option*>::iterator I =
Chris Lattneraa852bb2002-07-23 17:15:12 +0000671 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
672 assert(I != getPositionalOpts().end() && "Arg not registered!");
673 getPositionalOpts().erase(I);
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000674 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
Chris Lattneraa852bb2002-07-23 17:15:12 +0000675 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
676 "Arg not registered correctly!");
677 getPositionalOpts().erase(getPositionalOpts().begin());
678 }
679}
680
Chris Lattner331de232002-07-22 02:07:59 +0000681
682// getValueStr - Get the value description string, using "DefaultMsg" if nothing
683// has been specified yet.
684//
685static const char *getValueStr(const Option &O, const char *DefaultMsg) {
686 if (O.ValueStr[0] == 0) return DefaultMsg;
687 return O.ValueStr;
688}
689
690//===----------------------------------------------------------------------===//
691// cl::alias class implementation
692//
693
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000694// Return the width of the option tag for printing...
Chris Lattner331de232002-07-22 02:07:59 +0000695unsigned alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000696 return std::strlen(ArgStr)+6;
697}
698
Chris Lattnera0de8432006-04-28 05:36:25 +0000699// Print out the option for the alias.
Chris Lattner331de232002-07-22 02:07:59 +0000700void alias::printOptionInfo(unsigned GlobalWidth) const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000701 unsigned L = std::strlen(ArgStr);
Chris Lattnera0de8432006-04-28 05:36:25 +0000702 std::cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
Chris Lattnerca6433f2003-05-22 20:06:43 +0000703 << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000704}
705
706
Chris Lattner331de232002-07-22 02:07:59 +0000707
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000708//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000709// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000710//
711
Chris Lattner9b14eb52002-08-07 18:36:37 +0000712// basic_parser implementation
713//
714
715// Return the width of the option tag for printing...
716unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
717 unsigned Len = std::strlen(O.ArgStr);
718 if (const char *ValName = getValueName())
719 Len += std::strlen(getValueStr(O, ValName))+3;
720
721 return Len + 6;
722}
723
Misha Brukmanf976c852005-04-21 22:55:34 +0000724// printOptionInfo - Print out information about this option. The
Chris Lattner9b14eb52002-08-07 18:36:37 +0000725// to-be-maintained width is specified.
726//
727void basic_parser_impl::printOptionInfo(const Option &O,
728 unsigned GlobalWidth) const {
Chris Lattnera0de8432006-04-28 05:36:25 +0000729 std::cout << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000730
731 if (const char *ValName = getValueName())
Chris Lattnera0de8432006-04-28 05:36:25 +0000732 std::cout << "=<" << getValueStr(O, ValName) << ">";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000733
Chris Lattnera0de8432006-04-28 05:36:25 +0000734 std::cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
Chris Lattnerca6433f2003-05-22 20:06:43 +0000735 << O.HelpStr << "\n";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000736}
737
738
739
740
Chris Lattner331de232002-07-22 02:07:59 +0000741// parser<bool> implementation
742//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000743bool parser<bool>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000744 const std::string &Arg, bool &Value) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000745 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000746 Arg == "1") {
747 Value = true;
748 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
749 Value = false;
750 } else {
Chris Lattner331de232002-07-22 02:07:59 +0000751 return O.error(": '" + Arg +
752 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000753 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000754 return false;
755}
756
Chris Lattner331de232002-07-22 02:07:59 +0000757// parser<int> implementation
758//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000759bool parser<int>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000760 const std::string &Arg, int &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000761 char *End;
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000762 Value = (int)strtol(Arg.c_str(), &End, 0);
Misha Brukmanf976c852005-04-21 22:55:34 +0000763 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000764 return O.error(": '" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000765 return false;
766}
767
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000768// parser<unsigned> implementation
769//
770bool parser<unsigned>::parse(Option &O, const char *ArgName,
771 const std::string &Arg, unsigned &Value) {
772 char *End;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000773 errno = 0;
774 unsigned long V = strtoul(Arg.c_str(), &End, 0);
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000775 Value = (unsigned)V;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000776 if (((V == ULONG_MAX) && (errno == ERANGE))
777 || (*End != 0)
778 || (Value != V))
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000779 return O.error(": '" + Arg + "' value invalid for uint argument!");
780 return false;
781}
782
Chris Lattner9b14eb52002-08-07 18:36:37 +0000783// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +0000784//
Chris Lattnerca6433f2003-05-22 20:06:43 +0000785static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
Chris Lattner331de232002-07-22 02:07:59 +0000786 const char *ArgStart = Arg.c_str();
787 char *End;
788 Value = strtod(ArgStart, &End);
Misha Brukmanf976c852005-04-21 22:55:34 +0000789 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000790 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +0000791 return false;
792}
793
Chris Lattner9b14eb52002-08-07 18:36:37 +0000794bool parser<double>::parse(Option &O, const char *AN,
795 const std::string &Arg, double &Val) {
796 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +0000797}
798
Chris Lattner9b14eb52002-08-07 18:36:37 +0000799bool parser<float>::parse(Option &O, const char *AN,
800 const std::string &Arg, float &Val) {
801 double dVal;
802 if (parseDouble(O, Arg, dVal))
803 return true;
804 Val = (float)dVal;
805 return false;
Chris Lattner331de232002-07-22 02:07:59 +0000806}
807
808
Chris Lattner331de232002-07-22 02:07:59 +0000809
810// generic_parser_base implementation
811//
812
Chris Lattneraa852bb2002-07-23 17:15:12 +0000813// findOption - Return the option number corresponding to the specified
814// argument string. If the option is not found, getNumOptions() is returned.
815//
816unsigned generic_parser_base::findOption(const char *Name) {
817 unsigned i = 0, e = getNumOptions();
Chris Lattnerca6433f2003-05-22 20:06:43 +0000818 std::string N(Name);
Chris Lattneraa852bb2002-07-23 17:15:12 +0000819
820 while (i != e)
821 if (getOption(i) == N)
822 return i;
823 else
824 ++i;
825 return e;
826}
827
828
Chris Lattner331de232002-07-22 02:07:59 +0000829// Return the width of the option tag for printing...
830unsigned generic_parser_base::getOptionWidth(const Option &O) const {
831 if (O.hasArgStr()) {
832 unsigned Size = std::strlen(O.ArgStr)+6;
833 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
834 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
835 return Size;
836 } else {
837 unsigned BaseSize = 0;
838 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
839 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
840 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000841 }
842}
843
Misha Brukmanf976c852005-04-21 22:55:34 +0000844// printOptionInfo - Print out information about this option. The
Chris Lattner331de232002-07-22 02:07:59 +0000845// to-be-maintained width is specified.
846//
847void generic_parser_base::printOptionInfo(const Option &O,
848 unsigned GlobalWidth) const {
849 if (O.hasArgStr()) {
850 unsigned L = std::strlen(O.ArgStr);
Chris Lattnera0de8432006-04-28 05:36:25 +0000851 std::cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
Chris Lattnerca6433f2003-05-22 20:06:43 +0000852 << " - " << O.HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000853
Chris Lattner331de232002-07-22 02:07:59 +0000854 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
855 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnera0de8432006-04-28 05:36:25 +0000856 std::cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
Chris Lattnerca6433f2003-05-22 20:06:43 +0000857 << " - " << getDescription(i) << "\n";
Chris Lattner9c9be482002-01-31 00:42:56 +0000858 }
Chris Lattner331de232002-07-22 02:07:59 +0000859 } else {
860 if (O.HelpStr[0])
Chris Lattnera0de8432006-04-28 05:36:25 +0000861 std::cout << " " << O.HelpStr << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000862 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
863 unsigned L = std::strlen(getOption(i));
Chris Lattnera0de8432006-04-28 05:36:25 +0000864 std::cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
Chris Lattnerca6433f2003-05-22 20:06:43 +0000865 << " - " << getDescription(i) << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000866 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000867 }
868}
869
870
871//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000872// --help and --help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000873//
Reid Spencerad0846b2004-11-14 22:04:00 +0000874
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000875namespace {
876
Chris Lattner331de232002-07-22 02:07:59 +0000877class HelpPrinter {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000878 unsigned MaxArgLen;
879 const Option *EmptyArg;
880 const bool ShowHidden;
881
Chris Lattner331de232002-07-22 02:07:59 +0000882 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
Chris Lattnerca6433f2003-05-22 20:06:43 +0000883 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000884 return OptPair.second->getOptionHiddenFlag() >= Hidden;
885 }
Chris Lattnerca6433f2003-05-22 20:06:43 +0000886 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000887 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
888 }
889
890public:
891 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
892 EmptyArg = 0;
893 }
894
895 void operator=(bool Value) {
896 if (Value == false) return;
897
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000898 // Copy Options into a vector so we can sort them as we like...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000899 std::vector<std::pair<std::string, Option*> > Options;
Chris Lattner697954c2002-01-20 22:54:45 +0000900 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000901
902 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Misha Brukmanf976c852005-04-21 22:55:34 +0000903 Options.erase(std::remove_if(Options.begin(), Options.end(),
Chris Lattner331de232002-07-22 02:07:59 +0000904 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000905 Options.end());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000906
907 // Eliminate duplicate entries in table (from enum flags options, f.e.)
Chris Lattner331de232002-07-22 02:07:59 +0000908 { // Give OptionSet a scope
909 std::set<Option*> OptionSet;
910 for (unsigned i = 0; i != Options.size(); ++i)
911 if (OptionSet.count(Options[i].second) == 0)
912 OptionSet.insert(Options[i].second); // Add new entry to set
913 else
914 Options.erase(Options.begin()+i--); // Erase duplicate
915 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000916
917 if (ProgramOverview)
Chris Lattnera0de8432006-04-28 05:36:25 +0000918 std::cout << "OVERVIEW:" << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000919
Chris Lattnera0de8432006-04-28 05:36:25 +0000920 std::cout << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +0000921
922 // Print out the positional options...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000923 std::vector<Option*> &PosOpts = getPositionalOpts();
Chris Lattner331de232002-07-22 02:07:59 +0000924 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000925 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
Chris Lattner331de232002-07-22 02:07:59 +0000926 CAOpt = PosOpts[0];
927
Chris Lattner9cf3d472003-07-30 17:34:02 +0000928 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
929 if (PosOpts[i]->ArgStr[0])
Chris Lattnera0de8432006-04-28 05:36:25 +0000930 std::cout << " --" << PosOpts[i]->ArgStr;
931 std::cout << " " << PosOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000932 }
Chris Lattner331de232002-07-22 02:07:59 +0000933
934 // Print the consume after option info if it exists...
Chris Lattnera0de8432006-04-28 05:36:25 +0000935 if (CAOpt) std::cout << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +0000936
Chris Lattnera0de8432006-04-28 05:36:25 +0000937 std::cout << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000938
939 // Compute the maximum argument length...
940 MaxArgLen = 0;
Chris Lattner331de232002-07-22 02:07:59 +0000941 for (unsigned i = 0, e = Options.size(); i != e; ++i)
942 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000943
Chris Lattnera0de8432006-04-28 05:36:25 +0000944 std::cout << "OPTIONS:\n";
Chris Lattner331de232002-07-22 02:07:59 +0000945 for (unsigned i = 0, e = Options.size(); i != e; ++i)
946 Options[i].second->printOptionInfo(MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000947
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000948 // Print any extra help the user has declared.
949 for (std::vector<const char *>::iterator I = MoreHelp().begin(),
950 E = MoreHelp().end(); I != E; ++I)
Chris Lattnera0de8432006-04-28 05:36:25 +0000951 std::cout << *I;
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000952 MoreHelp().clear();
Reid Spencerad0846b2004-11-14 22:04:00 +0000953
Reid Spencer9bbba0912004-11-16 06:11:52 +0000954 // Halt the program since help information was printed
Chris Lattnera92d12c2005-02-14 19:17:29 +0000955 getOpts().clear(); // Don't bother making option dtors remove from map.
Chris Lattner331de232002-07-22 02:07:59 +0000956 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000957 }
958};
959
Chris Lattner331de232002-07-22 02:07:59 +0000960// Define the two HelpPrinter instances that are used to print out help, or
961// help-hidden...
962//
963HelpPrinter NormalPrinter(false);
964HelpPrinter HiddenPrinter(true);
965
Misha Brukmanf976c852005-04-21 22:55:34 +0000966cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +0000967HOp("help", cl::desc("Display available options (--help-hidden for more)"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000968 cl::location(NormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +0000969
970cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +0000971HHOp("help-hidden", cl::desc("Display all available options"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000972 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000973
Reid Spencer515b5b32006-06-05 16:22:56 +0000974void (*OverrideVersionPrinter)() = 0;
975
976class VersionPrinter {
977public:
978 void operator=(bool OptionWasSpecified) {
979 if (OptionWasSpecified) {
980 if (OverrideVersionPrinter == 0) {
Chris Lattner3fc2f4e2006-07-06 18:33:03 +0000981 std::cout << "Low Level Virtual Machine (http://llvm.org/):\n";
982 std::cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
983#ifdef LLVM_VERSION_INFO
984 std::cout << LLVM_VERSION_INFO;
Reid Spencer515b5b32006-06-05 16:22:56 +0000985#endif
Chris Lattner3fc2f4e2006-07-06 18:33:03 +0000986 std::cout << "\n ";
987#ifndef __OPTIMIZE__
988 std::cout << "DEBUG build";
989#else
990 std::cout << "Optimized build";
991#endif
992#ifndef NDEBUG
993 std::cout << " with assertions";
994#endif
995 std::cout << ".\n";
Reid Spencer515b5b32006-06-05 16:22:56 +0000996 getOpts().clear(); // Don't bother making option dtors remove from map.
997 exit(1);
998 } else {
999 (*OverrideVersionPrinter)();
1000 exit(1);
1001 }
1002 }
1003 }
1004};
1005
1006
Reid Spencer69105f32004-08-04 00:36:06 +00001007// Define the --version option that prints out the LLVM version for the tool
1008VersionPrinter VersionPrinterInstance;
1009cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001010VersOp("version", cl::desc("Display the version of this program"),
Reid Spencer69105f32004-08-04 00:36:06 +00001011 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1012
Reid Spencer9bbba0912004-11-16 06:11:52 +00001013
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001014} // End anonymous namespace
Reid Spencer9bbba0912004-11-16 06:11:52 +00001015
1016// Utility function for printing the help message.
1017void cl::PrintHelpMessage() {
Misha Brukmanf976c852005-04-21 22:55:34 +00001018 // This looks weird, but it actually prints the help message. The
Reid Spencer5cc498f2004-11-16 06:50:36 +00001019 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1020 // its operator= is invoked. That's because the "normal" usages of the
Misha Brukmanf976c852005-04-21 22:55:34 +00001021 // help printer is to be assigned true/false depending on whether the
Reid Spencer5cc498f2004-11-16 06:50:36 +00001022 // --help option was given or not. Since we're circumventing that we have
1023 // to make it look like --help was given, so we assign true.
Reid Spencer9bbba0912004-11-16 06:11:52 +00001024 NormalPrinter = true;
1025}
Reid Spencer515b5b32006-06-05 16:22:56 +00001026
1027void cl::SetVersionPrinter(void (*func)()) {
1028 OverrideVersionPrinter = func;
1029}