blob: 5abeb8d2ef19fdc2797da2baee991b44a929fba7 [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 Lattnerc540ebb2004-11-19 17:08:15 +000036// This collects additional help to be printed.
37static std::vector<const char*> &MoreHelp() {
38 static std::vector<const char*> moreHelp;
39 return moreHelp;
40}
41
42extrahelp::extrahelp(const char* Help)
43 : morehelp(Help) {
44 MoreHelp().push_back(Help);
45}
46
Chris Lattner331de232002-07-22 02:07:59 +000047//===----------------------------------------------------------------------===//
48// Basic, shared command line option processing machinery...
49//
50
Chris Lattnerdbab15a2001-07-23 17:17:47 +000051// Return the global command line option vector. Making it a function scoped
Chris Lattnerf78032f2001-11-26 18:58:34 +000052// static ensures that it will be initialized correctly before its first use.
Chris Lattnerdbab15a2001-07-23 17:17:47 +000053//
Chris Lattnerca6433f2003-05-22 20:06:43 +000054static std::map<std::string, Option*> &getOpts() {
Chris Lattnerc540ebb2004-11-19 17:08:15 +000055 static std::map<std::string, Option*> CommandLineOptions;
56 return CommandLineOptions;
Chris Lattnere8e258b2002-07-29 20:58:42 +000057}
58
Chris Lattnerca6433f2003-05-22 20:06:43 +000059static Option *getOption(const std::string &Str) {
Chris Lattnerc540ebb2004-11-19 17:08:15 +000060 std::map<std::string,Option*>::iterator I = getOpts().find(Str);
61 return I != getOpts().end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000062}
63
Chris Lattnerca6433f2003-05-22 20:06:43 +000064static std::vector<Option*> &getPositionalOpts() {
Chris Lattnerc540ebb2004-11-19 17:08:15 +000065 static std::vector<Option*> Positional;
66 return Positional;
Chris Lattner331de232002-07-22 02:07:59 +000067}
68
Chris Lattnere8e258b2002-07-29 20:58:42 +000069static void AddArgument(const char *ArgName, Option *Opt) {
70 if (getOption(ArgName)) {
Reid Spencere1cc1502004-09-01 04:41:28 +000071 std::cerr << ProgramName << ": CommandLine Error: Argument '"
72 << ArgName << "' defined more than once!\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +000073 } else {
Chris Lattnerf78032f2001-11-26 18:58:34 +000074 // Add argument to the argument map!
Chris Lattnere8e258b2002-07-29 20:58:42 +000075 getOpts()[ArgName] = Opt;
76 }
77}
78
79// RemoveArgument - It's possible that the argument is no longer in the map if
80// options have already been processed and the map has been deleted!
81//
82static void RemoveArgument(const char *ArgName, Option *Opt) {
Chris Lattnerf98cfc72004-07-18 21:56:20 +000083#ifndef NDEBUG
84 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
85 // If we pass ArgName directly into getOption here.
86 std::string Tmp = ArgName;
87 assert(getOption(Tmp) == Opt && "Arg not in map!");
88#endif
Chris Lattnerc540ebb2004-11-19 17:08:15 +000089 getOpts().erase(ArgName);
Chris Lattnerdbab15a2001-07-23 17:17:47 +000090}
91
Chris Lattnercaccd762001-10-27 05:54:17 +000092static inline bool ProvideOption(Option *Handler, const char *ArgName,
93 const char *Value, int argc, char **argv,
94 int &i) {
95 // Enforce value requirements
96 switch (Handler->getValueExpectedFlag()) {
97 case ValueRequired:
98 if (Value == 0 || *Value == 0) { // No value specified?
99 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
100 Value = argv[++i];
101 } else {
102 return Handler->error(" requires a value!");
103 }
104 }
105 break;
106 case ValueDisallowed:
107 if (*Value != 0)
108 return Handler->error(" does not allow a value! '" +
Chris Lattnerca6433f2003-05-22 20:06:43 +0000109 std::string(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +0000110 break;
Reid Spencere1cc1502004-09-01 04:41:28 +0000111 case ValueOptional:
112 break;
113 default:
114 std::cerr << ProgramName
115 << ": Bad ValueMask flag! CommandLine usage error:"
116 << Handler->getValueExpectedFlag() << "\n";
117 abort();
118 break;
Chris Lattnercaccd762001-10-27 05:54:17 +0000119 }
120
121 // Run the handler now!
Reid Spencer1e13fd22004-08-13 19:47:30 +0000122 return Handler->addOccurrence(i, ArgName, Value);
Chris Lattnercaccd762001-10-27 05:54:17 +0000123}
124
Reid Spencer1e13fd22004-08-13 19:47:30 +0000125static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
126 int i) {
127 int Dummy = i;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000128 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000129}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000130
Chris Lattner331de232002-07-22 02:07:59 +0000131
132// Option predicates...
133static inline bool isGrouping(const Option *O) {
134 return O->getFormattingFlag() == cl::Grouping;
135}
136static inline bool isPrefixedOrGrouping(const Option *O) {
137 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
138}
139
140// getOptionPred - Check to see if there are any options that satisfy the
141// specified predicate with names that are the prefixes in Name. This is
142// checked by progressively stripping characters off of the name, checking to
143// see if there options that satisfy the predicate. If we find one, return it,
144// otherwise return null.
145//
146static Option *getOptionPred(std::string Name, unsigned &Length,
147 bool (*Pred)(const Option*)) {
148
Chris Lattnere8e258b2002-07-29 20:58:42 +0000149 Option *Op = getOption(Name);
150 if (Op && Pred(Op)) {
Chris Lattner331de232002-07-22 02:07:59 +0000151 Length = Name.length();
Chris Lattnere8e258b2002-07-29 20:58:42 +0000152 return Op;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000153 }
154
Chris Lattner331de232002-07-22 02:07:59 +0000155 if (Name.size() == 1) return 0;
156 do {
157 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
Chris Lattnere8e258b2002-07-29 20:58:42 +0000158 Op = getOption(Name);
Chris Lattner331de232002-07-22 02:07:59 +0000159
160 // Loop while we haven't found an option and Name still has at least two
161 // characters in it (so that the next iteration will not be the empty
162 // string...
Chris Lattnere8e258b2002-07-29 20:58:42 +0000163 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
Chris Lattner331de232002-07-22 02:07:59 +0000164
Chris Lattnere8e258b2002-07-29 20:58:42 +0000165 if (Op && Pred(Op)) {
Chris Lattner331de232002-07-22 02:07:59 +0000166 Length = Name.length();
Chris Lattnere8e258b2002-07-29 20:58:42 +0000167 return Op; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000168 }
169 return 0; // No option found!
170}
171
172static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000173 return O->getNumOccurrencesFlag() == cl::Required ||
174 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000175}
176
177static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000178 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
179 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000180}
Chris Lattnercaccd762001-10-27 05:54:17 +0000181
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000182/// ParseCStringVector - Break INPUT up wherever one or more
183/// whitespace characters are found, and store the resulting tokens in
184/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
185/// using strdup (), so it is the caller's responsibility to free ()
186/// them later.
Brian Gaeke06b06c52003-08-14 22:00:59 +0000187///
188static void ParseCStringVector (std::vector<char *> &output,
Reid Spencer69105f32004-08-04 00:36:06 +0000189 const char *input) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000190 // Characters which will be treated as token separators:
191 static const char *delims = " \v\f\t\r\n";
192
193 std::string work (input);
194 // Skip past any delims at head of input string.
195 size_t pos = work.find_first_not_of (delims);
196 // If the string consists entirely of delims, then exit early.
197 if (pos == std::string::npos) return;
198 // Otherwise, jump forward to beginning of first word.
199 work = work.substr (pos);
200 // Find position of first delimiter.
201 pos = work.find_first_of (delims);
202
203 while (!work.empty() && pos != std::string::npos) {
204 // Everything from 0 to POS is the next word to copy.
205 output.push_back (strdup (work.substr (0,pos).c_str ()));
206 // Is there another word in the string?
207 size_t nextpos = work.find_first_not_of (delims, pos + 1);
208 if (nextpos != std::string::npos) {
209 // Yes? Then remove delims from beginning ...
210 work = work.substr (work.find_first_not_of (delims, pos + 1));
211 // and find the end of the word.
212 pos = work.find_first_of (delims);
213 } else {
214 // No? (Remainder of string is delims.) End the loop.
215 work = "";
216 pos = std::string::npos;
217 }
218 }
219
220 // If `input' ended with non-delim char, then we'll get here with
221 // the last word of `input' in `work'; copy it now.
222 if (!work.empty ()) {
223 output.push_back (strdup (work.c_str ()));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000224 }
225}
226
227/// ParseEnvironmentOptions - An alternative entry point to the
228/// CommandLine library, which allows you to read the program's name
229/// from the caller (as PROGNAME) and its command-line arguments from
230/// an environment variable (whose name is given in ENVVAR).
231///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000232void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
233 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000234 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000235 assert(progName && "Program name not specified");
236 assert(envVar && "Environment variable name missing");
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000237
238 // Get the environment variable they want us to parse options out of.
239 const char *envValue = getenv (envVar);
240 if (!envValue)
241 return;
242
Brian Gaeke06b06c52003-08-14 22:00:59 +0000243 // Get program's "name", which we wouldn't know without the caller
244 // telling us.
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000245 std::vector<char *> newArgv;
246 newArgv.push_back (strdup (progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000247
248 // Parse the value of the environment variable into a "command line"
249 // and hand it off to ParseCommandLineOptions().
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000250 ParseCStringVector (newArgv, envValue);
251 int newArgc = newArgv.size ();
252 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
253
254 // Free all the strdup()ed strings.
255 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
256 i != e; ++i) {
257 free (*i);
258 }
Brian Gaeke06b06c52003-08-14 22:00:59 +0000259}
260
Chris Lattnerbf455c22004-05-06 22:04:31 +0000261/// LookupOption - Lookup the option specified by the specified option on the
262/// command line. If there is a value specified (after an equal sign) return
263/// that as well.
264static Option *LookupOption(const char *&Arg, const char *&Value) {
265 while (*Arg == '-') ++Arg; // Eat leading dashes
266
267 const char *ArgEnd = Arg;
268 while (*ArgEnd && *ArgEnd != '=')
269 ++ArgEnd; // Scan till end of argument name...
270
271 Value = ArgEnd;
272 if (*Value) // If we have an equals sign...
273 ++Value; // Advance to value...
274
275 if (*Arg == 0) return 0;
276
277 // Look up the option.
278 std::map<std::string, Option*> &Opts = getOpts();
279 std::map<std::string, Option*>::iterator I =
280 Opts.find(std::string(Arg, ArgEnd));
281 return (I != Opts.end()) ? I->second : 0;
282}
283
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000284void cl::ParseCommandLineOptions(int &argc, char **argv,
Chris Lattner0c0edf82002-07-25 06:17:51 +0000285 const char *Overview) {
Chris Lattner331de232002-07-22 02:07:59 +0000286 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
287 "No options specified, or ParseCommandLineOptions called more"
288 " than once!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000289 ProgramName = argv[0]; // Save this away safe and snug
290 ProgramOverview = Overview;
291 bool ErrorParsing = false;
292
Chris Lattnerca6433f2003-05-22 20:06:43 +0000293 std::map<std::string, Option*> &Opts = getOpts();
294 std::vector<Option*> &PositionalOpts = getPositionalOpts();
Chris Lattner331de232002-07-22 02:07:59 +0000295
296 // Check out the positional arguments to collect information about them.
297 unsigned NumPositionalRequired = 0;
298 Option *ConsumeAfterOpt = 0;
299 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000300 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000301 assert(PositionalOpts.size() > 1 &&
302 "Cannot specify cl::ConsumeAfter without a positional argument!");
303 ConsumeAfterOpt = PositionalOpts[0];
304 }
305
306 // Calculate how many positional values are _required_.
307 bool UnboundedFound = false;
308 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
309 i != e; ++i) {
310 Option *Opt = PositionalOpts[i];
311 if (RequiresValue(Opt))
312 ++NumPositionalRequired;
313 else if (ConsumeAfterOpt) {
314 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000315 // unless there is only one positional argument...
316 if (PositionalOpts.size() > 2)
317 ErrorParsing |=
318 Opt->error(" error - this positional option will never be matched, "
319 "because it does not Require a value, and a "
320 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000321 } else if (UnboundedFound && !Opt->ArgStr[0]) {
322 // This option does not "require" a value... Make sure this option is
323 // not specified after an option that eats all extra arguments, or this
324 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000325 //
326 ErrorParsing |= Opt->error(" error - option can never match, because "
327 "another positional argument will match an "
328 "unbounded number of values, and this option"
329 " does not require a value!");
330 }
331 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
332 }
333 }
334
Reid Spencer1e13fd22004-08-13 19:47:30 +0000335 // PositionalVals - A vector of "positional" arguments we accumulate into
336 // the process at the end...
Chris Lattner331de232002-07-22 02:07:59 +0000337 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000338 std::vector<std::pair<std::string,unsigned> > PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000339
Chris Lattner9cf3d472003-07-30 17:34:02 +0000340 // If the program has named positional arguments, and the name has been run
341 // across, keep track of which positional argument was named. Otherwise put
342 // the positional args into the PositionalVals list...
343 Option *ActivePositionalArg = 0;
344
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000345 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000346 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000347 for (int i = 1; i < argc; ++i) {
348 Option *Handler = 0;
349 const char *Value = "";
350 const char *ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000351
352 // Check to see if this is a positional argument. This argument is
353 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000354 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000355 //
356 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
357 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000358 if (ActivePositionalArg) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000359 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000360 continue; // We are done!
361 } else if (!PositionalOpts.empty()) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000362 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000363
364 // All of the positional arguments have been fulfulled, give the rest to
365 // the consume after option... if it's specified...
366 //
Chris Lattnerd16714b2002-07-31 16:29:43 +0000367 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000368 ConsumeAfterOpt != 0) {
369 for (++i; i < argc; ++i)
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 break; // Handle outside of the argument processing loop...
372 }
373
374 // Delay processing positional arguments until the end...
375 continue;
376 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000377 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
378 !DashDashFound) {
379 DashDashFound = true; // This is the mythical "--"?
380 continue; // Don't try to process it as an argument itself.
381 } else if (ActivePositionalArg &&
382 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
383 // If there is a positional argument eating options, check to see if this
384 // option is another positional argument. If so, treat it as an argument,
385 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000386 ArgName = argv[i]+1;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000387 Handler = LookupOption(ArgName, Value);
388 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000389 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000390 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000391 }
392
Chris Lattnerbf455c22004-05-06 22:04:31 +0000393 } else { // We start with a '-', must be an argument...
394 ArgName = argv[i]+1;
395 Handler = LookupOption(ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000396
Chris Lattnerbf455c22004-05-06 22:04:31 +0000397 // Check to see if this "option" is really a prefixed or grouped argument.
398 if (Handler == 0 && *Value == 0) {
399 std::string RealName(ArgName);
400 if (RealName.size() > 1) {
Chris Lattner331de232002-07-22 02:07:59 +0000401 unsigned Length = 0;
402 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000403
Chris Lattner331de232002-07-22 02:07:59 +0000404 // If the option is a prefixed option, then the value is simply the
405 // rest of the name... so fall through to later processing, by
406 // setting up the argument name flags and value fields.
407 //
408 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000409 Value = ArgName+Length;
410 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
411 Opts.find(std::string(ArgName, Value))->second == PGOpt);
412 Handler = PGOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000413 } else if (PGOpt) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000414 // This must be a grouped option... handle them now.
Chris Lattner331de232002-07-22 02:07:59 +0000415 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Chris Lattnerbf455c22004-05-06 22:04:31 +0000416
Chris Lattner331de232002-07-22 02:07:59 +0000417 do {
418 // Move current arg name out of RealName into RealArgName...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000419 std::string RealArgName(RealName.begin(),
420 RealName.begin() + Length);
421 RealName.erase(RealName.begin(), RealName.begin() + Length);
422
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000423 // Because ValueRequired is an invalid flag for grouped arguments,
424 // we don't need to pass argc/argv in...
425 //
Chris Lattner331de232002-07-22 02:07:59 +0000426 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
427 "Option can not be cl::Grouping AND cl::ValueRequired!");
428 int Dummy;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000429 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
430 "", 0, 0, Dummy);
431
Chris Lattner331de232002-07-22 02:07:59 +0000432 // Get the next grouping option...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000433 PGOpt = getOptionPred(RealName, Length, isGrouping);
434 } while (PGOpt && Length != RealName.size());
435
436 Handler = PGOpt; // Ate all of the options.
Chris Lattner331de232002-07-22 02:07:59 +0000437 }
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000438 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000439 }
440 }
441
442 if (Handler == 0) {
Reid Spencere1cc1502004-09-01 04:41:28 +0000443 std::cerr << ProgramName << ": Unknown command line argument '" << argv[i]
444 << "'. Try: '" << argv[0] << " --help'\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000445 ErrorParsing = true;
446 continue;
447 }
448
Chris Lattner72fb8e52003-05-22 20:26:17 +0000449 // Check to see if this option accepts a comma separated list of values. If
450 // it does, we have to split up the value into multiple values...
451 if (Handler->getMiscFlags() & CommaSeparated) {
452 std::string Val(Value);
453 std::string::size_type Pos = Val.find(',');
454
455 while (Pos != std::string::npos) {
456 // Process the portion before the comma...
457 ErrorParsing |= ProvideOption(Handler, ArgName,
458 std::string(Val.begin(),
459 Val.begin()+Pos).c_str(),
460 argc, argv, i);
461 // Erase the portion before the comma, AND the comma...
462 Val.erase(Val.begin(), Val.begin()+Pos+1);
463 Value += Pos+1; // Increment the original value pointer as well...
464
465 // Check for another comma...
466 Pos = Val.find(',');
467 }
468 }
Chris Lattner9cf3d472003-07-30 17:34:02 +0000469
470 // If this is a named positional argument, just remember that it is the
471 // active one...
472 if (Handler->getFormattingFlag() == cl::Positional)
473 ActivePositionalArg = Handler;
474 else
475 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000476 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000477
Chris Lattner331de232002-07-22 02:07:59 +0000478 // Check and handle positional arguments now...
479 if (NumPositionalRequired > PositionalVals.size()) {
Reid Spencere1cc1502004-09-01 04:41:28 +0000480 std::cerr << ProgramName
481 << ": Not enough positional command line arguments specified!\n"
Chris Lattnerca6433f2003-05-22 20:06:43 +0000482 << "Must specify at least " << NumPositionalRequired
483 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattner331de232002-07-22 02:07:59 +0000484 ErrorParsing = true;
485
486
487 } else if (ConsumeAfterOpt == 0) {
488 // Positional args have already been handled if ConsumeAfter is specified...
489 unsigned ValNo = 0, NumVals = PositionalVals.size();
490 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
491 if (RequiresValue(PositionalOpts[i])) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000492 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
493 PositionalVals[ValNo].second);
494 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000495 --NumPositionalRequired; // We fulfilled our duty...
496 }
497
498 // If we _can_ give this option more arguments, do so now, as long as we
499 // do not give it values that others need. 'Done' controls whether the
500 // option even _WANTS_ any more.
501 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000502 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000503 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000504 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000505 case cl::Optional:
506 Done = true; // Optional arguments want _at most_ one value
507 // FALL THROUGH
508 case cl::ZeroOrMore: // Zero or more will take all they can get...
509 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer1e13fd22004-08-13 19:47:30 +0000510 ProvidePositionalOption(PositionalOpts[i],
511 PositionalVals[ValNo].first,
512 PositionalVals[ValNo].second);
513 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000514 break;
515 default:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000516 assert(0 && "Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000517 "positional argument processing!");
518 }
519 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000520 }
Chris Lattner331de232002-07-22 02:07:59 +0000521 } else {
522 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
523 unsigned ValNo = 0;
524 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000525 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000526 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000527 PositionalVals[ValNo].first,
528 PositionalVals[ValNo].second);
529 ValNo++;
530 }
Chris Lattnerfaba8092002-07-24 20:15:13 +0000531
532 // Handle the case where there is just one positional option, and it's
533 // optional. In this case, we want to give JUST THE FIRST option to the
534 // positional option and keep the rest for the consume after. The above
535 // loop would have assigned no values to positional options in this case.
536 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000537 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000538 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000539 PositionalVals[ValNo].first,
540 PositionalVals[ValNo].second);
541 ValNo++;
542 }
Chris Lattner331de232002-07-22 02:07:59 +0000543
544 // Handle over all of the rest of the arguments to the
545 // cl::ConsumeAfter command line option...
546 for (; ValNo != PositionalVals.size(); ++ValNo)
547 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000548 PositionalVals[ValNo].first,
549 PositionalVals[ValNo].second);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000550 }
551
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000552 // Loop over args and make sure all required args are specified!
Chris Lattnerca6433f2003-05-22 20:06:43 +0000553 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000554 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000555 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000556 case Required:
557 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000558 if (I->second->getNumOccurrences() == 0) {
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000559 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000560 ErrorParsing = true;
561 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000562 // Fall through
563 default:
564 break;
565 }
566 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000567
Chris Lattner331de232002-07-22 02:07:59 +0000568 // Free all of the memory allocated to the map. Command line options may only
569 // be processed once!
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000570 getOpts().clear();
Chris Lattner331de232002-07-22 02:07:59 +0000571 PositionalOpts.clear();
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000572 MoreHelp().clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000573
574 // If we had an error processing our arguments, don't let the program execute
575 if (ErrorParsing) exit(1);
576}
577
578//===----------------------------------------------------------------------===//
579// Option Base class implementation
580//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000581
Chris Lattnerca6433f2003-05-22 20:06:43 +0000582bool Option::error(std::string Message, const char *ArgName) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000583 if (ArgName == 0) ArgName = ArgStr;
Chris Lattner331de232002-07-22 02:07:59 +0000584 if (ArgName[0] == 0)
Chris Lattnerca6433f2003-05-22 20:06:43 +0000585 std::cerr << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000586 else
Reid Spencere1cc1502004-09-01 04:41:28 +0000587 std::cerr << ProgramName << ": for the -" << ArgName;
588 std::cerr << " option: " << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000589 return true;
590}
591
Reid Spencer1e13fd22004-08-13 19:47:30 +0000592bool Option::addOccurrence(unsigned pos, const char *ArgName, const std::string &Value) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000593 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000594
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000595 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000596 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000597 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000598 return error(": may only occur zero or one times!", ArgName);
599 break;
600 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000601 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000602 return error(": must occur exactly one time!", ArgName);
603 // Fall through
604 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000605 case ZeroOrMore:
606 case ConsumeAfter: break;
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000607 default: return error(": bad num occurrences flag value!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000608 }
609
Reid Spencer1e13fd22004-08-13 19:47:30 +0000610 return handleOccurrence(pos, ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000611}
612
Chris Lattner331de232002-07-22 02:07:59 +0000613// addArgument - Tell the system that this Option subclass will handle all
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000614// occurrences of -ArgStr on the command line.
Chris Lattner331de232002-07-22 02:07:59 +0000615//
616void Option::addArgument(const char *ArgStr) {
617 if (ArgStr[0])
618 AddArgument(ArgStr, this);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000619
620 if (getFormattingFlag() == Positional)
Chris Lattner331de232002-07-22 02:07:59 +0000621 getPositionalOpts().push_back(this);
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000622 else if (getNumOccurrencesFlag() == ConsumeAfter) {
Chris Lattner9cf3d472003-07-30 17:34:02 +0000623 if (!getPositionalOpts().empty() &&
624 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
625 error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattner331de232002-07-22 02:07:59 +0000626 getPositionalOpts().insert(getPositionalOpts().begin(), this);
627 }
628}
629
Chris Lattneraa852bb2002-07-23 17:15:12 +0000630void Option::removeArgument(const char *ArgStr) {
Chris Lattner9cf3d472003-07-30 17:34:02 +0000631 if (ArgStr[0])
Chris Lattnere8e258b2002-07-29 20:58:42 +0000632 RemoveArgument(ArgStr, this);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000633
634 if (getFormattingFlag() == Positional) {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000635 std::vector<Option*>::iterator I =
Chris Lattneraa852bb2002-07-23 17:15:12 +0000636 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
637 assert(I != getPositionalOpts().end() && "Arg not registered!");
638 getPositionalOpts().erase(I);
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000639 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
Chris Lattneraa852bb2002-07-23 17:15:12 +0000640 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
641 "Arg not registered correctly!");
642 getPositionalOpts().erase(getPositionalOpts().begin());
643 }
644}
645
Chris Lattner331de232002-07-22 02:07:59 +0000646
647// getValueStr - Get the value description string, using "DefaultMsg" if nothing
648// has been specified yet.
649//
650static const char *getValueStr(const Option &O, const char *DefaultMsg) {
651 if (O.ValueStr[0] == 0) return DefaultMsg;
652 return O.ValueStr;
653}
654
655//===----------------------------------------------------------------------===//
656// cl::alias class implementation
657//
658
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000659// Return the width of the option tag for printing...
Chris Lattner331de232002-07-22 02:07:59 +0000660unsigned alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000661 return std::strlen(ArgStr)+6;
662}
663
Chris Lattner331de232002-07-22 02:07:59 +0000664// Print out the option for the alias...
665void alias::printOptionInfo(unsigned GlobalWidth) const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000666 unsigned L = std::strlen(ArgStr);
Chris Lattnerca6433f2003-05-22 20:06:43 +0000667 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
668 << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000669}
670
671
Chris Lattner331de232002-07-22 02:07:59 +0000672
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000673//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000674// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000675//
676
Chris Lattner9b14eb52002-08-07 18:36:37 +0000677// basic_parser implementation
678//
679
680// Return the width of the option tag for printing...
681unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
682 unsigned Len = std::strlen(O.ArgStr);
683 if (const char *ValName = getValueName())
684 Len += std::strlen(getValueStr(O, ValName))+3;
685
686 return Len + 6;
687}
688
689// printOptionInfo - Print out information about this option. The
690// to-be-maintained width is specified.
691//
692void basic_parser_impl::printOptionInfo(const Option &O,
693 unsigned GlobalWidth) const {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000694 std::cerr << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000695
696 if (const char *ValName = getValueName())
Chris Lattnerca6433f2003-05-22 20:06:43 +0000697 std::cerr << "=<" << getValueStr(O, ValName) << ">";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000698
Chris Lattnerca6433f2003-05-22 20:06:43 +0000699 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
700 << O.HelpStr << "\n";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000701}
702
703
704
705
Chris Lattner331de232002-07-22 02:07:59 +0000706// parser<bool> implementation
707//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000708bool parser<bool>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000709 const std::string &Arg, bool &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000710 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
711 Arg == "1") {
712 Value = true;
713 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
714 Value = false;
715 } else {
Chris Lattner331de232002-07-22 02:07:59 +0000716 return O.error(": '" + Arg +
717 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000718 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000719 return false;
720}
721
Chris Lattner331de232002-07-22 02:07:59 +0000722// parser<int> implementation
723//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000724bool parser<int>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000725 const std::string &Arg, int &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000726 char *End;
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000727 Value = (int)strtol(Arg.c_str(), &End, 0);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000728 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000729 return O.error(": '" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000730 return false;
731}
732
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000733// parser<unsigned> implementation
734//
735bool parser<unsigned>::parse(Option &O, const char *ArgName,
736 const std::string &Arg, unsigned &Value) {
737 char *End;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000738 errno = 0;
739 unsigned long V = strtoul(Arg.c_str(), &End, 0);
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000740 Value = (unsigned)V;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000741 if (((V == ULONG_MAX) && (errno == ERANGE))
742 || (*End != 0)
743 || (Value != V))
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000744 return O.error(": '" + Arg + "' value invalid for uint argument!");
745 return false;
746}
747
Chris Lattner9b14eb52002-08-07 18:36:37 +0000748// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +0000749//
Chris Lattnerca6433f2003-05-22 20:06:43 +0000750static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
Chris Lattner331de232002-07-22 02:07:59 +0000751 const char *ArgStart = Arg.c_str();
752 char *End;
753 Value = strtod(ArgStart, &End);
754 if (*End != 0)
755 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +0000756 return false;
757}
758
Chris Lattner9b14eb52002-08-07 18:36:37 +0000759bool parser<double>::parse(Option &O, const char *AN,
760 const std::string &Arg, double &Val) {
761 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +0000762}
763
Chris Lattner9b14eb52002-08-07 18:36:37 +0000764bool parser<float>::parse(Option &O, const char *AN,
765 const std::string &Arg, float &Val) {
766 double dVal;
767 if (parseDouble(O, Arg, dVal))
768 return true;
769 Val = (float)dVal;
770 return false;
Chris Lattner331de232002-07-22 02:07:59 +0000771}
772
773
Chris Lattner331de232002-07-22 02:07:59 +0000774
775// generic_parser_base implementation
776//
777
Chris Lattneraa852bb2002-07-23 17:15:12 +0000778// findOption - Return the option number corresponding to the specified
779// argument string. If the option is not found, getNumOptions() is returned.
780//
781unsigned generic_parser_base::findOption(const char *Name) {
782 unsigned i = 0, e = getNumOptions();
Chris Lattnerca6433f2003-05-22 20:06:43 +0000783 std::string N(Name);
Chris Lattneraa852bb2002-07-23 17:15:12 +0000784
785 while (i != e)
786 if (getOption(i) == N)
787 return i;
788 else
789 ++i;
790 return e;
791}
792
793
Chris Lattner331de232002-07-22 02:07:59 +0000794// Return the width of the option tag for printing...
795unsigned generic_parser_base::getOptionWidth(const Option &O) const {
796 if (O.hasArgStr()) {
797 unsigned Size = std::strlen(O.ArgStr)+6;
798 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
799 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
800 return Size;
801 } else {
802 unsigned BaseSize = 0;
803 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
804 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
805 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000806 }
807}
808
Chris Lattner331de232002-07-22 02:07:59 +0000809// printOptionInfo - Print out information about this option. The
810// to-be-maintained width is specified.
811//
812void generic_parser_base::printOptionInfo(const Option &O,
813 unsigned GlobalWidth) const {
814 if (O.hasArgStr()) {
815 unsigned L = std::strlen(O.ArgStr);
Chris Lattnerca6433f2003-05-22 20:06:43 +0000816 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
817 << " - " << O.HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000818
Chris Lattner331de232002-07-22 02:07:59 +0000819 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
820 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnerca6433f2003-05-22 20:06:43 +0000821 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
822 << " - " << getDescription(i) << "\n";
Chris Lattner9c9be482002-01-31 00:42:56 +0000823 }
Chris Lattner331de232002-07-22 02:07:59 +0000824 } else {
825 if (O.HelpStr[0])
Chris Lattnerca6433f2003-05-22 20:06:43 +0000826 std::cerr << " " << O.HelpStr << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000827 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
828 unsigned L = std::strlen(getOption(i));
Chris Lattnerca6433f2003-05-22 20:06:43 +0000829 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
830 << " - " << getDescription(i) << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000831 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000832 }
833}
834
835
836//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000837// --help and --help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000838//
Reid Spencerad0846b2004-11-14 22:04:00 +0000839
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000840namespace {
841
Chris Lattner331de232002-07-22 02:07:59 +0000842class HelpPrinter {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000843 unsigned MaxArgLen;
844 const Option *EmptyArg;
845 const bool ShowHidden;
846
Chris Lattner331de232002-07-22 02:07:59 +0000847 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
Chris Lattnerca6433f2003-05-22 20:06:43 +0000848 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000849 return OptPair.second->getOptionHiddenFlag() >= Hidden;
850 }
Chris Lattnerca6433f2003-05-22 20:06:43 +0000851 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000852 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
853 }
854
855public:
856 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
857 EmptyArg = 0;
858 }
859
860 void operator=(bool Value) {
861 if (Value == false) return;
862
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000863 // Copy Options into a vector so we can sort them as we like...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000864 std::vector<std::pair<std::string, Option*> > Options;
Chris Lattner697954c2002-01-20 22:54:45 +0000865 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000866
867 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Chris Lattner331de232002-07-22 02:07:59 +0000868 Options.erase(std::remove_if(Options.begin(), Options.end(),
869 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000870 Options.end());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000871
872 // Eliminate duplicate entries in table (from enum flags options, f.e.)
Chris Lattner331de232002-07-22 02:07:59 +0000873 { // Give OptionSet a scope
874 std::set<Option*> OptionSet;
875 for (unsigned i = 0; i != Options.size(); ++i)
876 if (OptionSet.count(Options[i].second) == 0)
877 OptionSet.insert(Options[i].second); // Add new entry to set
878 else
879 Options.erase(Options.begin()+i--); // Erase duplicate
880 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000881
882 if (ProgramOverview)
Chris Lattnerca6433f2003-05-22 20:06:43 +0000883 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000884
Chris Lattnerca6433f2003-05-22 20:06:43 +0000885 std::cerr << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +0000886
887 // Print out the positional options...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000888 std::vector<Option*> &PosOpts = getPositionalOpts();
Chris Lattner331de232002-07-22 02:07:59 +0000889 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000890 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
Chris Lattner331de232002-07-22 02:07:59 +0000891 CAOpt = PosOpts[0];
892
Chris Lattner9cf3d472003-07-30 17:34:02 +0000893 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
894 if (PosOpts[i]->ArgStr[0])
895 std::cerr << " --" << PosOpts[i]->ArgStr;
Chris Lattnerca6433f2003-05-22 20:06:43 +0000896 std::cerr << " " << PosOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000897 }
Chris Lattner331de232002-07-22 02:07:59 +0000898
899 // Print the consume after option info if it exists...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000900 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +0000901
Chris Lattnerca6433f2003-05-22 20:06:43 +0000902 std::cerr << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000903
904 // Compute the maximum argument length...
905 MaxArgLen = 0;
Chris Lattner331de232002-07-22 02:07:59 +0000906 for (unsigned i = 0, e = Options.size(); i != e; ++i)
907 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000908
Chris Lattnerca6433f2003-05-22 20:06:43 +0000909 std::cerr << "OPTIONS:\n";
Chris Lattner331de232002-07-22 02:07:59 +0000910 for (unsigned i = 0, e = Options.size(); i != e; ++i)
911 Options[i].second->printOptionInfo(MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000912
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000913 // Print any extra help the user has declared.
914 for (std::vector<const char *>::iterator I = MoreHelp().begin(),
915 E = MoreHelp().end(); I != E; ++I)
916 std::cerr << *I;
917 MoreHelp().clear();
Reid Spencerad0846b2004-11-14 22:04:00 +0000918
Reid Spencer9bbba0912004-11-16 06:11:52 +0000919 // Halt the program since help information was printed
Chris Lattner331de232002-07-22 02:07:59 +0000920 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000921 }
922};
923
Reid Spencer69105f32004-08-04 00:36:06 +0000924class VersionPrinter {
925public:
926 void operator=(bool OptionWasSpecified) {
927 if (OptionWasSpecified) {
928 std::cerr << "Low Level Virtual Machine (" << PACKAGE_NAME << ") "
Misha Brukmanfb4863a2004-11-07 00:58:38 +0000929 << PACKAGE_VERSION << " (see http://llvm.cs.uiuc.edu/)\n";
Reid Spencer69105f32004-08-04 00:36:06 +0000930 exit(1);
931 }
932 }
933};
Chris Lattner331de232002-07-22 02:07:59 +0000934
935
936// Define the two HelpPrinter instances that are used to print out help, or
937// help-hidden...
938//
939HelpPrinter NormalPrinter(false);
940HelpPrinter HiddenPrinter(true);
941
942cl::opt<HelpPrinter, true, parser<bool> >
943HOp("help", cl::desc("display available options (--help-hidden for more)"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000944 cl::location(NormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +0000945
946cl::opt<HelpPrinter, true, parser<bool> >
947HHOp("help-hidden", cl::desc("display all available options"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000948 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000949
Reid Spencer69105f32004-08-04 00:36:06 +0000950// Define the --version option that prints out the LLVM version for the tool
951VersionPrinter VersionPrinterInstance;
952cl::opt<VersionPrinter, true, parser<bool> >
953VersOp("version", cl::desc("display the version"),
954 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
955
Reid Spencer9bbba0912004-11-16 06:11:52 +0000956
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000957} // End anonymous namespace
Reid Spencer9bbba0912004-11-16 06:11:52 +0000958
959// Utility function for printing the help message.
960void cl::PrintHelpMessage() {
Reid Spencer5cc498f2004-11-16 06:50:36 +0000961 // This looks weird, but it actually prints the help message. The
962 // NormalPrinter variable is a HelpPrinter and the help gets printed when
963 // its operator= is invoked. That's because the "normal" usages of the
964 // help printer is to be assigned true/false depending on whether the
965 // --help option was given or not. Since we're circumventing that we have
966 // to make it look like --help was given, so we assign true.
Reid Spencer9bbba0912004-11-16 06:11:52 +0000967 NormalPrinter = true;
968}