blob: ad82c849479fec57c82aec0b37f224d5391f9271 [file] [log] [blame]
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
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>
22#include <map>
23#include <set>
Chris Lattner697954c2002-01-20 22:54:45 +000024#include <iostream>
Brian Gaeke2d6a2362003-10-10 17:01:36 +000025#include <cstdlib>
26#include <cerrno>
Chris Lattner51140042004-07-03 01:21:05 +000027#include <cstring>
Chris Lattner2cdd21c2003-12-14 21:35:53 +000028using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000029
Chris Lattnerdbab15a2001-07-23 17:17:47 +000030using namespace cl;
31
Reid Spencere1cc1502004-09-01 04:41:28 +000032// Globals for name and overview of program
33static const char *ProgramName = "<unknown>";
34static const char *ProgramOverview = 0;
35
Chris Lattner331de232002-07-22 02:07:59 +000036//===----------------------------------------------------------------------===//
37// Basic, shared command line option processing machinery...
38//
39
Chris Lattnerdbab15a2001-07-23 17:17:47 +000040// Return the global command line option vector. Making it a function scoped
Chris Lattnerf78032f2001-11-26 18:58:34 +000041// static ensures that it will be initialized correctly before its first use.
Chris Lattnerdbab15a2001-07-23 17:17:47 +000042//
Chris Lattnerca6433f2003-05-22 20:06:43 +000043static std::map<std::string, Option*> *CommandLineOptions = 0;
44static std::map<std::string, Option*> &getOpts() {
45 if (CommandLineOptions == 0)
46 CommandLineOptions = new std::map<std::string,Option*>();
Chris Lattnere8e258b2002-07-29 20:58:42 +000047 return *CommandLineOptions;
48}
49
Chris Lattnerca6433f2003-05-22 20:06:43 +000050static Option *getOption(const std::string &Str) {
Chris Lattnere8e258b2002-07-29 20:58:42 +000051 if (CommandLineOptions == 0) return 0;
Chris Lattnerca6433f2003-05-22 20:06:43 +000052 std::map<std::string,Option*>::iterator I = CommandLineOptions->find(Str);
Chris Lattnere8e258b2002-07-29 20:58:42 +000053 return I != CommandLineOptions->end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000054}
55
Chris Lattnerca6433f2003-05-22 20:06:43 +000056static std::vector<Option*> &getPositionalOpts() {
Alkis Evlogimenos5f65add2004-03-04 17:50:44 +000057 static std::vector<Option*> *Positional = 0;
58 if (!Positional) Positional = new std::vector<Option*>();
59 return *Positional;
Chris Lattner331de232002-07-22 02:07:59 +000060}
61
Chris Lattnere8e258b2002-07-29 20:58:42 +000062static void AddArgument(const char *ArgName, Option *Opt) {
63 if (getOption(ArgName)) {
Reid Spencere1cc1502004-09-01 04:41:28 +000064 std::cerr << ProgramName << ": CommandLine Error: Argument '"
65 << ArgName << "' defined more than once!\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +000066 } else {
Chris Lattnerf78032f2001-11-26 18:58:34 +000067 // Add argument to the argument map!
Chris Lattnere8e258b2002-07-29 20:58:42 +000068 getOpts()[ArgName] = Opt;
69 }
70}
71
72// RemoveArgument - It's possible that the argument is no longer in the map if
73// options have already been processed and the map has been deleted!
74//
75static void RemoveArgument(const char *ArgName, Option *Opt) {
76 if (CommandLineOptions == 0) return;
Chris Lattnerf98cfc72004-07-18 21:56:20 +000077#ifndef NDEBUG
78 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
79 // If we pass ArgName directly into getOption here.
80 std::string Tmp = ArgName;
81 assert(getOption(Tmp) == Opt && "Arg not in map!");
82#endif
Chris Lattnere8e258b2002-07-29 20:58:42 +000083 CommandLineOptions->erase(ArgName);
84 if (CommandLineOptions->empty()) {
85 delete CommandLineOptions;
86 CommandLineOptions = 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000087 }
88}
89
Chris Lattnercaccd762001-10-27 05:54:17 +000090static inline bool ProvideOption(Option *Handler, const char *ArgName,
91 const char *Value, int argc, char **argv,
92 int &i) {
93 // Enforce value requirements
94 switch (Handler->getValueExpectedFlag()) {
95 case ValueRequired:
96 if (Value == 0 || *Value == 0) { // No value specified?
97 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
98 Value = argv[++i];
99 } else {
100 return Handler->error(" requires a value!");
101 }
102 }
103 break;
104 case ValueDisallowed:
105 if (*Value != 0)
106 return Handler->error(" does not allow a value! '" +
Chris Lattnerca6433f2003-05-22 20:06:43 +0000107 std::string(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +0000108 break;
Reid Spencere1cc1502004-09-01 04:41:28 +0000109 case ValueOptional:
110 break;
111 default:
112 std::cerr << ProgramName
113 << ": Bad ValueMask flag! CommandLine usage error:"
114 << Handler->getValueExpectedFlag() << "\n";
115 abort();
116 break;
Chris Lattnercaccd762001-10-27 05:54:17 +0000117 }
118
119 // Run the handler now!
Reid Spencer1e13fd22004-08-13 19:47:30 +0000120 return Handler->addOccurrence(i, ArgName, Value);
Chris Lattnercaccd762001-10-27 05:54:17 +0000121}
122
Reid Spencer1e13fd22004-08-13 19:47:30 +0000123static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
124 int i) {
125 int Dummy = i;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000126 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000127}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000128
Chris Lattner331de232002-07-22 02:07:59 +0000129
130// Option predicates...
131static inline bool isGrouping(const Option *O) {
132 return O->getFormattingFlag() == cl::Grouping;
133}
134static inline bool isPrefixedOrGrouping(const Option *O) {
135 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
136}
137
138// getOptionPred - Check to see if there are any options that satisfy the
139// specified predicate with names that are the prefixes in Name. This is
140// checked by progressively stripping characters off of the name, checking to
141// see if there options that satisfy the predicate. If we find one, return it,
142// otherwise return null.
143//
144static Option *getOptionPred(std::string Name, unsigned &Length,
145 bool (*Pred)(const Option*)) {
146
Chris Lattnere8e258b2002-07-29 20:58:42 +0000147 Option *Op = getOption(Name);
148 if (Op && Pred(Op)) {
Chris Lattner331de232002-07-22 02:07:59 +0000149 Length = Name.length();
Chris Lattnere8e258b2002-07-29 20:58:42 +0000150 return Op;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000151 }
152
Chris Lattner331de232002-07-22 02:07:59 +0000153 if (Name.size() == 1) return 0;
154 do {
155 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
Chris Lattnere8e258b2002-07-29 20:58:42 +0000156 Op = getOption(Name);
Chris Lattner331de232002-07-22 02:07:59 +0000157
158 // Loop while we haven't found an option and Name still has at least two
159 // characters in it (so that the next iteration will not be the empty
160 // string...
Chris Lattnere8e258b2002-07-29 20:58:42 +0000161 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
Chris Lattner331de232002-07-22 02:07:59 +0000162
Chris Lattnere8e258b2002-07-29 20:58:42 +0000163 if (Op && Pred(Op)) {
Chris Lattner331de232002-07-22 02:07:59 +0000164 Length = Name.length();
Chris Lattnere8e258b2002-07-29 20:58:42 +0000165 return Op; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000166 }
167 return 0; // No option found!
168}
169
170static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000171 return O->getNumOccurrencesFlag() == cl::Required ||
172 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000173}
174
175static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000176 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
177 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000178}
Chris Lattnercaccd762001-10-27 05:54:17 +0000179
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000180/// ParseCStringVector - Break INPUT up wherever one or more
181/// whitespace characters are found, and store the resulting tokens in
182/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
183/// using strdup (), so it is the caller's responsibility to free ()
184/// them later.
Brian Gaeke06b06c52003-08-14 22:00:59 +0000185///
186static void ParseCStringVector (std::vector<char *> &output,
Reid Spencer69105f32004-08-04 00:36:06 +0000187 const char *input) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000188 // Characters which will be treated as token separators:
189 static const char *delims = " \v\f\t\r\n";
190
191 std::string work (input);
192 // Skip past any delims at head of input string.
193 size_t pos = work.find_first_not_of (delims);
194 // If the string consists entirely of delims, then exit early.
195 if (pos == std::string::npos) return;
196 // Otherwise, jump forward to beginning of first word.
197 work = work.substr (pos);
198 // Find position of first delimiter.
199 pos = work.find_first_of (delims);
200
201 while (!work.empty() && pos != std::string::npos) {
202 // Everything from 0 to POS is the next word to copy.
203 output.push_back (strdup (work.substr (0,pos).c_str ()));
204 // Is there another word in the string?
205 size_t nextpos = work.find_first_not_of (delims, pos + 1);
206 if (nextpos != std::string::npos) {
207 // Yes? Then remove delims from beginning ...
208 work = work.substr (work.find_first_not_of (delims, pos + 1));
209 // and find the end of the word.
210 pos = work.find_first_of (delims);
211 } else {
212 // No? (Remainder of string is delims.) End the loop.
213 work = "";
214 pos = std::string::npos;
215 }
216 }
217
218 // If `input' ended with non-delim char, then we'll get here with
219 // the last word of `input' in `work'; copy it now.
220 if (!work.empty ()) {
221 output.push_back (strdup (work.c_str ()));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000222 }
223}
224
225/// ParseEnvironmentOptions - An alternative entry point to the
226/// CommandLine library, which allows you to read the program's name
227/// from the caller (as PROGNAME) and its command-line arguments from
228/// an environment variable (whose name is given in ENVVAR).
229///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000230void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
231 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000232 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000233 assert(progName && "Program name not specified");
234 assert(envVar && "Environment variable name missing");
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000235
236 // Get the environment variable they want us to parse options out of.
237 const char *envValue = getenv (envVar);
238 if (!envValue)
239 return;
240
Brian Gaeke06b06c52003-08-14 22:00:59 +0000241 // Get program's "name", which we wouldn't know without the caller
242 // telling us.
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000243 std::vector<char *> newArgv;
244 newArgv.push_back (strdup (progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000245
246 // Parse the value of the environment variable into a "command line"
247 // and hand it off to ParseCommandLineOptions().
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000248 ParseCStringVector (newArgv, envValue);
249 int newArgc = newArgv.size ();
250 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
251
252 // Free all the strdup()ed strings.
253 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
254 i != e; ++i) {
255 free (*i);
256 }
Brian Gaeke06b06c52003-08-14 22:00:59 +0000257}
258
Chris Lattnerbf455c22004-05-06 22:04:31 +0000259/// LookupOption - Lookup the option specified by the specified option on the
260/// command line. If there is a value specified (after an equal sign) return
261/// that as well.
262static Option *LookupOption(const char *&Arg, const char *&Value) {
263 while (*Arg == '-') ++Arg; // Eat leading dashes
264
265 const char *ArgEnd = Arg;
266 while (*ArgEnd && *ArgEnd != '=')
267 ++ArgEnd; // Scan till end of argument name...
268
269 Value = ArgEnd;
270 if (*Value) // If we have an equals sign...
271 ++Value; // Advance to value...
272
273 if (*Arg == 0) return 0;
274
275 // Look up the option.
276 std::map<std::string, Option*> &Opts = getOpts();
277 std::map<std::string, Option*>::iterator I =
278 Opts.find(std::string(Arg, ArgEnd));
279 return (I != Opts.end()) ? I->second : 0;
280}
281
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000282void cl::ParseCommandLineOptions(int &argc, char **argv,
Chris Lattner0c0edf82002-07-25 06:17:51 +0000283 const char *Overview) {
Chris Lattner331de232002-07-22 02:07:59 +0000284 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
285 "No options specified, or ParseCommandLineOptions called more"
286 " than once!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000287 ProgramName = argv[0]; // Save this away safe and snug
288 ProgramOverview = Overview;
289 bool ErrorParsing = false;
290
Chris Lattnerca6433f2003-05-22 20:06:43 +0000291 std::map<std::string, Option*> &Opts = getOpts();
292 std::vector<Option*> &PositionalOpts = getPositionalOpts();
Chris Lattner331de232002-07-22 02:07:59 +0000293
294 // Check out the positional arguments to collect information about them.
295 unsigned NumPositionalRequired = 0;
296 Option *ConsumeAfterOpt = 0;
297 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000298 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000299 assert(PositionalOpts.size() > 1 &&
300 "Cannot specify cl::ConsumeAfter without a positional argument!");
301 ConsumeAfterOpt = PositionalOpts[0];
302 }
303
304 // Calculate how many positional values are _required_.
305 bool UnboundedFound = false;
306 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
307 i != e; ++i) {
308 Option *Opt = PositionalOpts[i];
309 if (RequiresValue(Opt))
310 ++NumPositionalRequired;
311 else if (ConsumeAfterOpt) {
312 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000313 // unless there is only one positional argument...
314 if (PositionalOpts.size() > 2)
315 ErrorParsing |=
316 Opt->error(" error - this positional option will never be matched, "
317 "because it does not Require a value, and a "
318 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000319 } else if (UnboundedFound && !Opt->ArgStr[0]) {
320 // This option does not "require" a value... Make sure this option is
321 // not specified after an option that eats all extra arguments, or this
322 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000323 //
324 ErrorParsing |= Opt->error(" error - option can never match, because "
325 "another positional argument will match an "
326 "unbounded number of values, and this option"
327 " does not require a value!");
328 }
329 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
330 }
331 }
332
Reid Spencer1e13fd22004-08-13 19:47:30 +0000333 // PositionalVals - A vector of "positional" arguments we accumulate into
334 // the process at the end...
Chris Lattner331de232002-07-22 02:07:59 +0000335 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000336 std::vector<std::pair<std::string,unsigned> > PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000337
Chris Lattner9cf3d472003-07-30 17:34:02 +0000338 // If the program has named positional arguments, and the name has been run
339 // across, keep track of which positional argument was named. Otherwise put
340 // the positional args into the PositionalVals list...
341 Option *ActivePositionalArg = 0;
342
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000343 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000344 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000345 for (int i = 1; i < argc; ++i) {
346 Option *Handler = 0;
347 const char *Value = "";
348 const char *ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000349
350 // Check to see if this is a positional argument. This argument is
351 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000352 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000353 //
354 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
355 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000356 if (ActivePositionalArg) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000357 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000358 continue; // We are done!
359 } else if (!PositionalOpts.empty()) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000360 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000361
362 // All of the positional arguments have been fulfulled, give the rest to
363 // the consume after option... if it's specified...
364 //
Chris Lattnerd16714b2002-07-31 16:29:43 +0000365 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000366 ConsumeAfterOpt != 0) {
367 for (++i; i < argc; ++i)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000368 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000369 break; // Handle outside of the argument processing loop...
370 }
371
372 // Delay processing positional arguments until the end...
373 continue;
374 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000375 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
376 !DashDashFound) {
377 DashDashFound = true; // This is the mythical "--"?
378 continue; // Don't try to process it as an argument itself.
379 } else if (ActivePositionalArg &&
380 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
381 // If there is a positional argument eating options, check to see if this
382 // option is another positional argument. If so, treat it as an argument,
383 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000384 ArgName = argv[i]+1;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000385 Handler = LookupOption(ArgName, Value);
386 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000387 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000388 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000389 }
390
Chris Lattnerbf455c22004-05-06 22:04:31 +0000391 } else { // We start with a '-', must be an argument...
392 ArgName = argv[i]+1;
393 Handler = LookupOption(ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000394
Chris Lattnerbf455c22004-05-06 22:04:31 +0000395 // Check to see if this "option" is really a prefixed or grouped argument.
396 if (Handler == 0 && *Value == 0) {
397 std::string RealName(ArgName);
398 if (RealName.size() > 1) {
Chris Lattner331de232002-07-22 02:07:59 +0000399 unsigned Length = 0;
400 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000401
Chris Lattner331de232002-07-22 02:07:59 +0000402 // If the option is a prefixed option, then the value is simply the
403 // rest of the name... so fall through to later processing, by
404 // setting up the argument name flags and value fields.
405 //
406 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000407 Value = ArgName+Length;
408 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
409 Opts.find(std::string(ArgName, Value))->second == PGOpt);
410 Handler = PGOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000411 } else if (PGOpt) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000412 // This must be a grouped option... handle them now.
Chris Lattner331de232002-07-22 02:07:59 +0000413 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Chris Lattnerbf455c22004-05-06 22:04:31 +0000414
Chris Lattner331de232002-07-22 02:07:59 +0000415 do {
416 // Move current arg name out of RealName into RealArgName...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000417 std::string RealArgName(RealName.begin(),
418 RealName.begin() + Length);
419 RealName.erase(RealName.begin(), RealName.begin() + Length);
420
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000421 // Because ValueRequired is an invalid flag for grouped arguments,
422 // we don't need to pass argc/argv in...
423 //
Chris Lattner331de232002-07-22 02:07:59 +0000424 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
425 "Option can not be cl::Grouping AND cl::ValueRequired!");
426 int Dummy;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000427 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
428 "", 0, 0, Dummy);
429
Chris Lattner331de232002-07-22 02:07:59 +0000430 // Get the next grouping option...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000431 PGOpt = getOptionPred(RealName, Length, isGrouping);
432 } while (PGOpt && Length != RealName.size());
433
434 Handler = PGOpt; // Ate all of the options.
Chris Lattner331de232002-07-22 02:07:59 +0000435 }
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000436 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000437 }
438 }
439
440 if (Handler == 0) {
Reid Spencere1cc1502004-09-01 04:41:28 +0000441 std::cerr << ProgramName << ": Unknown command line argument '" << argv[i]
442 << "'. Try: '" << argv[0] << " --help'\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000443 ErrorParsing = true;
444 continue;
445 }
446
Chris Lattner72fb8e52003-05-22 20:26:17 +0000447 // Check to see if this option accepts a comma separated list of values. If
448 // it does, we have to split up the value into multiple values...
449 if (Handler->getMiscFlags() & CommaSeparated) {
450 std::string Val(Value);
451 std::string::size_type Pos = Val.find(',');
452
453 while (Pos != std::string::npos) {
454 // Process the portion before the comma...
455 ErrorParsing |= ProvideOption(Handler, ArgName,
456 std::string(Val.begin(),
457 Val.begin()+Pos).c_str(),
458 argc, argv, i);
459 // Erase the portion before the comma, AND the comma...
460 Val.erase(Val.begin(), Val.begin()+Pos+1);
461 Value += Pos+1; // Increment the original value pointer as well...
462
463 // Check for another comma...
464 Pos = Val.find(',');
465 }
466 }
Chris Lattner9cf3d472003-07-30 17:34:02 +0000467
468 // If this is a named positional argument, just remember that it is the
469 // active one...
470 if (Handler->getFormattingFlag() == cl::Positional)
471 ActivePositionalArg = Handler;
472 else
473 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000474 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000475
Chris Lattner331de232002-07-22 02:07:59 +0000476 // Check and handle positional arguments now...
477 if (NumPositionalRequired > PositionalVals.size()) {
Reid Spencere1cc1502004-09-01 04:41:28 +0000478 std::cerr << ProgramName
479 << ": Not enough positional command line arguments specified!\n"
Chris Lattnerca6433f2003-05-22 20:06:43 +0000480 << "Must specify at least " << NumPositionalRequired
481 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattner331de232002-07-22 02:07:59 +0000482 ErrorParsing = true;
483
484
485 } else if (ConsumeAfterOpt == 0) {
486 // Positional args have already been handled if ConsumeAfter is specified...
487 unsigned ValNo = 0, NumVals = PositionalVals.size();
488 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
489 if (RequiresValue(PositionalOpts[i])) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000490 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
491 PositionalVals[ValNo].second);
492 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000493 --NumPositionalRequired; // We fulfilled our duty...
494 }
495
496 // If we _can_ give this option more arguments, do so now, as long as we
497 // do not give it values that others need. 'Done' controls whether the
498 // option even _WANTS_ any more.
499 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000500 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000501 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000502 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000503 case cl::Optional:
504 Done = true; // Optional arguments want _at most_ one value
505 // FALL THROUGH
506 case cl::ZeroOrMore: // Zero or more will take all they can get...
507 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer1e13fd22004-08-13 19:47:30 +0000508 ProvidePositionalOption(PositionalOpts[i],
509 PositionalVals[ValNo].first,
510 PositionalVals[ValNo].second);
511 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000512 break;
513 default:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000514 assert(0 && "Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000515 "positional argument processing!");
516 }
517 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000518 }
Chris Lattner331de232002-07-22 02:07:59 +0000519 } else {
520 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
521 unsigned ValNo = 0;
522 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000523 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000524 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000525 PositionalVals[ValNo].first,
526 PositionalVals[ValNo].second);
527 ValNo++;
528 }
Chris Lattnerfaba8092002-07-24 20:15:13 +0000529
530 // Handle the case where there is just one positional option, and it's
531 // optional. In this case, we want to give JUST THE FIRST option to the
532 // positional option and keep the rest for the consume after. The above
533 // loop would have assigned no values to positional options in this case.
534 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000535 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000536 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000537 PositionalVals[ValNo].first,
538 PositionalVals[ValNo].second);
539 ValNo++;
540 }
Chris Lattner331de232002-07-22 02:07:59 +0000541
542 // Handle over all of the rest of the arguments to the
543 // cl::ConsumeAfter command line option...
544 for (; ValNo != PositionalVals.size(); ++ValNo)
545 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000546 PositionalVals[ValNo].first,
547 PositionalVals[ValNo].second);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000548 }
549
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000550 // Loop over args and make sure all required args are specified!
Chris Lattnerca6433f2003-05-22 20:06:43 +0000551 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000552 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000553 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000554 case Required:
555 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000556 if (I->second->getNumOccurrences() == 0) {
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000557 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000558 ErrorParsing = true;
559 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000560 // Fall through
561 default:
562 break;
563 }
564 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000565
Chris Lattner331de232002-07-22 02:07:59 +0000566 // Free all of the memory allocated to the map. Command line options may only
567 // be processed once!
Chris Lattnere8e258b2002-07-29 20:58:42 +0000568 delete CommandLineOptions;
569 CommandLineOptions = 0;
Chris Lattner331de232002-07-22 02:07:59 +0000570 PositionalOpts.clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000571
572 // If we had an error processing our arguments, don't let the program execute
573 if (ErrorParsing) exit(1);
574}
575
576//===----------------------------------------------------------------------===//
577// Option Base class implementation
578//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000579
Chris Lattnerca6433f2003-05-22 20:06:43 +0000580bool Option::error(std::string Message, const char *ArgName) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000581 if (ArgName == 0) ArgName = ArgStr;
Chris Lattner331de232002-07-22 02:07:59 +0000582 if (ArgName[0] == 0)
Chris Lattnerca6433f2003-05-22 20:06:43 +0000583 std::cerr << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000584 else
Reid Spencere1cc1502004-09-01 04:41:28 +0000585 std::cerr << ProgramName << ": for the -" << ArgName;
586 std::cerr << " option: " << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000587 return true;
588}
589
Reid Spencer1e13fd22004-08-13 19:47:30 +0000590bool Option::addOccurrence(unsigned pos, const char *ArgName, const std::string &Value) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000591 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000592
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000593 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000594 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000595 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000596 return error(": may only occur zero or one times!", ArgName);
597 break;
598 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000599 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000600 return error(": must occur exactly one time!", ArgName);
601 // Fall through
602 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000603 case ZeroOrMore:
604 case ConsumeAfter: break;
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000605 default: return error(": bad num occurrences flag value!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000606 }
607
Reid Spencer1e13fd22004-08-13 19:47:30 +0000608 return handleOccurrence(pos, ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000609}
610
Chris Lattner331de232002-07-22 02:07:59 +0000611// addArgument - Tell the system that this Option subclass will handle all
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000612// occurrences of -ArgStr on the command line.
Chris Lattner331de232002-07-22 02:07:59 +0000613//
614void Option::addArgument(const char *ArgStr) {
615 if (ArgStr[0])
616 AddArgument(ArgStr, this);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000617
618 if (getFormattingFlag() == Positional)
Chris Lattner331de232002-07-22 02:07:59 +0000619 getPositionalOpts().push_back(this);
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000620 else if (getNumOccurrencesFlag() == ConsumeAfter) {
Chris Lattner9cf3d472003-07-30 17:34:02 +0000621 if (!getPositionalOpts().empty() &&
622 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
623 error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattner331de232002-07-22 02:07:59 +0000624 getPositionalOpts().insert(getPositionalOpts().begin(), this);
625 }
626}
627
Chris Lattneraa852bb2002-07-23 17:15:12 +0000628void Option::removeArgument(const char *ArgStr) {
Chris Lattner9cf3d472003-07-30 17:34:02 +0000629 if (ArgStr[0])
Chris Lattnere8e258b2002-07-29 20:58:42 +0000630 RemoveArgument(ArgStr, this);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000631
632 if (getFormattingFlag() == Positional) {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000633 std::vector<Option*>::iterator I =
Chris Lattneraa852bb2002-07-23 17:15:12 +0000634 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
635 assert(I != getPositionalOpts().end() && "Arg not registered!");
636 getPositionalOpts().erase(I);
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000637 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
Chris Lattneraa852bb2002-07-23 17:15:12 +0000638 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
639 "Arg not registered correctly!");
640 getPositionalOpts().erase(getPositionalOpts().begin());
641 }
642}
643
Chris Lattner331de232002-07-22 02:07:59 +0000644
645// getValueStr - Get the value description string, using "DefaultMsg" if nothing
646// has been specified yet.
647//
648static const char *getValueStr(const Option &O, const char *DefaultMsg) {
649 if (O.ValueStr[0] == 0) return DefaultMsg;
650 return O.ValueStr;
651}
652
653//===----------------------------------------------------------------------===//
654// cl::alias class implementation
655//
656
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000657// Return the width of the option tag for printing...
Chris Lattner331de232002-07-22 02:07:59 +0000658unsigned alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000659 return std::strlen(ArgStr)+6;
660}
661
Chris Lattner331de232002-07-22 02:07:59 +0000662// Print out the option for the alias...
663void alias::printOptionInfo(unsigned GlobalWidth) const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000664 unsigned L = std::strlen(ArgStr);
Chris Lattnerca6433f2003-05-22 20:06:43 +0000665 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
666 << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000667}
668
669
Chris Lattner331de232002-07-22 02:07:59 +0000670
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000671//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000672// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000673//
674
Chris Lattner9b14eb52002-08-07 18:36:37 +0000675// basic_parser implementation
676//
677
678// Return the width of the option tag for printing...
679unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
680 unsigned Len = std::strlen(O.ArgStr);
681 if (const char *ValName = getValueName())
682 Len += std::strlen(getValueStr(O, ValName))+3;
683
684 return Len + 6;
685}
686
687// printOptionInfo - Print out information about this option. The
688// to-be-maintained width is specified.
689//
690void basic_parser_impl::printOptionInfo(const Option &O,
691 unsigned GlobalWidth) const {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000692 std::cerr << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000693
694 if (const char *ValName = getValueName())
Chris Lattnerca6433f2003-05-22 20:06:43 +0000695 std::cerr << "=<" << getValueStr(O, ValName) << ">";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000696
Chris Lattnerca6433f2003-05-22 20:06:43 +0000697 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
698 << O.HelpStr << "\n";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000699}
700
701
702
703
Chris Lattner331de232002-07-22 02:07:59 +0000704// parser<bool> implementation
705//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000706bool parser<bool>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000707 const std::string &Arg, bool &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000708 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
709 Arg == "1") {
710 Value = true;
711 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
712 Value = false;
713 } else {
Chris Lattner331de232002-07-22 02:07:59 +0000714 return O.error(": '" + Arg +
715 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000716 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000717 return false;
718}
719
Chris Lattner331de232002-07-22 02:07:59 +0000720// parser<int> implementation
721//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000722bool parser<int>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000723 const std::string &Arg, int &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000724 char *End;
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000725 Value = (int)strtol(Arg.c_str(), &End, 0);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000726 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000727 return O.error(": '" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000728 return false;
729}
730
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000731// parser<unsigned> implementation
732//
733bool parser<unsigned>::parse(Option &O, const char *ArgName,
734 const std::string &Arg, unsigned &Value) {
735 char *End;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000736 errno = 0;
737 unsigned long V = strtoul(Arg.c_str(), &End, 0);
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000738 Value = (unsigned)V;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000739 if (((V == ULONG_MAX) && (errno == ERANGE))
740 || (*End != 0)
741 || (Value != V))
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000742 return O.error(": '" + Arg + "' value invalid for uint argument!");
743 return false;
744}
745
Chris Lattner9b14eb52002-08-07 18:36:37 +0000746// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +0000747//
Chris Lattnerca6433f2003-05-22 20:06:43 +0000748static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
Chris Lattner331de232002-07-22 02:07:59 +0000749 const char *ArgStart = Arg.c_str();
750 char *End;
751 Value = strtod(ArgStart, &End);
752 if (*End != 0)
753 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +0000754 return false;
755}
756
Chris Lattner9b14eb52002-08-07 18:36:37 +0000757bool parser<double>::parse(Option &O, const char *AN,
758 const std::string &Arg, double &Val) {
759 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +0000760}
761
Chris Lattner9b14eb52002-08-07 18:36:37 +0000762bool parser<float>::parse(Option &O, const char *AN,
763 const std::string &Arg, float &Val) {
764 double dVal;
765 if (parseDouble(O, Arg, dVal))
766 return true;
767 Val = (float)dVal;
768 return false;
Chris Lattner331de232002-07-22 02:07:59 +0000769}
770
771
Chris Lattner331de232002-07-22 02:07:59 +0000772
773// generic_parser_base implementation
774//
775
Chris Lattneraa852bb2002-07-23 17:15:12 +0000776// findOption - Return the option number corresponding to the specified
777// argument string. If the option is not found, getNumOptions() is returned.
778//
779unsigned generic_parser_base::findOption(const char *Name) {
780 unsigned i = 0, e = getNumOptions();
Chris Lattnerca6433f2003-05-22 20:06:43 +0000781 std::string N(Name);
Chris Lattneraa852bb2002-07-23 17:15:12 +0000782
783 while (i != e)
784 if (getOption(i) == N)
785 return i;
786 else
787 ++i;
788 return e;
789}
790
791
Chris Lattner331de232002-07-22 02:07:59 +0000792// Return the width of the option tag for printing...
793unsigned generic_parser_base::getOptionWidth(const Option &O) const {
794 if (O.hasArgStr()) {
795 unsigned Size = std::strlen(O.ArgStr)+6;
796 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
797 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
798 return Size;
799 } else {
800 unsigned BaseSize = 0;
801 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
802 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
803 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000804 }
805}
806
Chris Lattner331de232002-07-22 02:07:59 +0000807// printOptionInfo - Print out information about this option. The
808// to-be-maintained width is specified.
809//
810void generic_parser_base::printOptionInfo(const Option &O,
811 unsigned GlobalWidth) const {
812 if (O.hasArgStr()) {
813 unsigned L = std::strlen(O.ArgStr);
Chris Lattnerca6433f2003-05-22 20:06:43 +0000814 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
815 << " - " << O.HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000816
Chris Lattner331de232002-07-22 02:07:59 +0000817 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
818 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnerca6433f2003-05-22 20:06:43 +0000819 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
820 << " - " << getDescription(i) << "\n";
Chris Lattner9c9be482002-01-31 00:42:56 +0000821 }
Chris Lattner331de232002-07-22 02:07:59 +0000822 } else {
823 if (O.HelpStr[0])
Chris Lattnerca6433f2003-05-22 20:06:43 +0000824 std::cerr << " " << O.HelpStr << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000825 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
826 unsigned L = std::strlen(getOption(i));
Chris Lattnerca6433f2003-05-22 20:06:43 +0000827 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
828 << " - " << getDescription(i) << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000829 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000830 }
831}
832
833
834//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000835// --help and --help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000836//
Reid Spencerad0846b2004-11-14 22:04:00 +0000837
838// If this variable is set, it is a pointer to a function that the user wants
839// us to call after we print out the help info. Basically a hook to allow
840// additional help to be printed.
841void (*cl::MoreHelp)() = 0;
842
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000843namespace {
844
Chris Lattner331de232002-07-22 02:07:59 +0000845class HelpPrinter {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000846 unsigned MaxArgLen;
847 const Option *EmptyArg;
848 const bool ShowHidden;
849
Chris Lattner331de232002-07-22 02:07:59 +0000850 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
Chris Lattnerca6433f2003-05-22 20:06:43 +0000851 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000852 return OptPair.second->getOptionHiddenFlag() >= Hidden;
853 }
Chris Lattnerca6433f2003-05-22 20:06:43 +0000854 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000855 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
856 }
857
858public:
859 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
860 EmptyArg = 0;
861 }
862
863 void operator=(bool Value) {
864 if (Value == false) return;
865
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000866 // Copy Options into a vector so we can sort them as we like...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000867 std::vector<std::pair<std::string, Option*> > Options;
Chris Lattner697954c2002-01-20 22:54:45 +0000868 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000869
870 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Chris Lattner331de232002-07-22 02:07:59 +0000871 Options.erase(std::remove_if(Options.begin(), Options.end(),
872 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000873 Options.end());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000874
875 // Eliminate duplicate entries in table (from enum flags options, f.e.)
Chris Lattner331de232002-07-22 02:07:59 +0000876 { // Give OptionSet a scope
877 std::set<Option*> OptionSet;
878 for (unsigned i = 0; i != Options.size(); ++i)
879 if (OptionSet.count(Options[i].second) == 0)
880 OptionSet.insert(Options[i].second); // Add new entry to set
881 else
882 Options.erase(Options.begin()+i--); // Erase duplicate
883 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000884
885 if (ProgramOverview)
Chris Lattnerca6433f2003-05-22 20:06:43 +0000886 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000887
Chris Lattnerca6433f2003-05-22 20:06:43 +0000888 std::cerr << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +0000889
890 // Print out the positional options...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000891 std::vector<Option*> &PosOpts = getPositionalOpts();
Chris Lattner331de232002-07-22 02:07:59 +0000892 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000893 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
Chris Lattner331de232002-07-22 02:07:59 +0000894 CAOpt = PosOpts[0];
895
Chris Lattner9cf3d472003-07-30 17:34:02 +0000896 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
897 if (PosOpts[i]->ArgStr[0])
898 std::cerr << " --" << PosOpts[i]->ArgStr;
Chris Lattnerca6433f2003-05-22 20:06:43 +0000899 std::cerr << " " << PosOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000900 }
Chris Lattner331de232002-07-22 02:07:59 +0000901
902 // Print the consume after option info if it exists...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000903 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +0000904
Chris Lattnerca6433f2003-05-22 20:06:43 +0000905 std::cerr << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000906
907 // Compute the maximum argument length...
908 MaxArgLen = 0;
Chris Lattner331de232002-07-22 02:07:59 +0000909 for (unsigned i = 0, e = Options.size(); i != e; ++i)
910 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000911
Chris Lattnerca6433f2003-05-22 20:06:43 +0000912 std::cerr << "OPTIONS:\n";
Chris Lattner331de232002-07-22 02:07:59 +0000913 for (unsigned i = 0, e = Options.size(); i != e; ++i)
914 Options[i].second->printOptionInfo(MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000915
Reid Spencerad0846b2004-11-14 22:04:00 +0000916 // Call the user's hook so help output can be extended.
917 if (MoreHelp != 0)
918 (*MoreHelp)();
919
Chris Lattner331de232002-07-22 02:07:59 +0000920 // Halt the program if help information is printed
921 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000922 }
923};
924
Reid Spencer69105f32004-08-04 00:36:06 +0000925class VersionPrinter {
926public:
927 void operator=(bool OptionWasSpecified) {
928 if (OptionWasSpecified) {
929 std::cerr << "Low Level Virtual Machine (" << PACKAGE_NAME << ") "
Misha Brukmanfb4863a2004-11-07 00:58:38 +0000930 << PACKAGE_VERSION << " (see http://llvm.cs.uiuc.edu/)\n";
Reid Spencer69105f32004-08-04 00:36:06 +0000931 exit(1);
932 }
933 }
934};
Chris Lattner331de232002-07-22 02:07:59 +0000935
936
937// Define the two HelpPrinter instances that are used to print out help, or
938// help-hidden...
939//
940HelpPrinter NormalPrinter(false);
941HelpPrinter HiddenPrinter(true);
942
943cl::opt<HelpPrinter, true, parser<bool> >
944HOp("help", cl::desc("display available options (--help-hidden for more)"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000945 cl::location(NormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +0000946
947cl::opt<HelpPrinter, true, parser<bool> >
948HHOp("help-hidden", cl::desc("display all available options"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000949 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000950
Reid Spencer69105f32004-08-04 00:36:06 +0000951// Define the --version option that prints out the LLVM version for the tool
952VersionPrinter VersionPrinterInstance;
953cl::opt<VersionPrinter, true, parser<bool> >
954VersOp("version", cl::desc("display the version"),
955 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
956
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000957} // End anonymous namespace