blob: 131b95a75cfe49540b1e85b4e07988bb20fe2bfd [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 Spencer69105f32004-08-04 00:36:06 +000019#include "Config/config.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000020#include "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
Chris Lattner331de232002-07-22 02:07:59 +000032//===----------------------------------------------------------------------===//
33// Basic, shared command line option processing machinery...
34//
35
Chris Lattnerdbab15a2001-07-23 17:17:47 +000036// Return the global command line option vector. Making it a function scoped
Chris Lattnerf78032f2001-11-26 18:58:34 +000037// static ensures that it will be initialized correctly before its first use.
Chris Lattnerdbab15a2001-07-23 17:17:47 +000038//
Chris Lattnerca6433f2003-05-22 20:06:43 +000039static std::map<std::string, Option*> *CommandLineOptions = 0;
40static std::map<std::string, Option*> &getOpts() {
41 if (CommandLineOptions == 0)
42 CommandLineOptions = new std::map<std::string,Option*>();
Chris Lattnere8e258b2002-07-29 20:58:42 +000043 return *CommandLineOptions;
44}
45
Chris Lattnerca6433f2003-05-22 20:06:43 +000046static Option *getOption(const std::string &Str) {
Chris Lattnere8e258b2002-07-29 20:58:42 +000047 if (CommandLineOptions == 0) return 0;
Chris Lattnerca6433f2003-05-22 20:06:43 +000048 std::map<std::string,Option*>::iterator I = CommandLineOptions->find(Str);
Chris Lattnere8e258b2002-07-29 20:58:42 +000049 return I != CommandLineOptions->end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000050}
51
Chris Lattnerca6433f2003-05-22 20:06:43 +000052static std::vector<Option*> &getPositionalOpts() {
Alkis Evlogimenos5f65add2004-03-04 17:50:44 +000053 static std::vector<Option*> *Positional = 0;
54 if (!Positional) Positional = new std::vector<Option*>();
55 return *Positional;
Chris Lattner331de232002-07-22 02:07:59 +000056}
57
Chris Lattnere8e258b2002-07-29 20:58:42 +000058static void AddArgument(const char *ArgName, Option *Opt) {
59 if (getOption(ArgName)) {
Chris Lattnerca6433f2003-05-22 20:06:43 +000060 std::cerr << "CommandLine Error: Argument '" << ArgName
61 << "' defined more than once!\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +000062 } else {
Chris Lattnerf78032f2001-11-26 18:58:34 +000063 // Add argument to the argument map!
Chris Lattnere8e258b2002-07-29 20:58:42 +000064 getOpts()[ArgName] = Opt;
65 }
66}
67
68// RemoveArgument - It's possible that the argument is no longer in the map if
69// options have already been processed and the map has been deleted!
70//
71static void RemoveArgument(const char *ArgName, Option *Opt) {
72 if (CommandLineOptions == 0) return;
Chris Lattnerf98cfc72004-07-18 21:56:20 +000073#ifndef NDEBUG
74 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
75 // If we pass ArgName directly into getOption here.
76 std::string Tmp = ArgName;
77 assert(getOption(Tmp) == Opt && "Arg not in map!");
78#endif
Chris Lattnere8e258b2002-07-29 20:58:42 +000079 CommandLineOptions->erase(ArgName);
80 if (CommandLineOptions->empty()) {
81 delete CommandLineOptions;
82 CommandLineOptions = 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000083 }
84}
85
86static const char *ProgramName = 0;
87static const char *ProgramOverview = 0;
88
Chris Lattnercaccd762001-10-27 05:54:17 +000089static inline bool ProvideOption(Option *Handler, const char *ArgName,
90 const char *Value, int argc, char **argv,
91 int &i) {
92 // Enforce value requirements
93 switch (Handler->getValueExpectedFlag()) {
94 case ValueRequired:
95 if (Value == 0 || *Value == 0) { // No value specified?
96 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
97 Value = argv[++i];
98 } else {
99 return Handler->error(" requires a value!");
100 }
101 }
102 break;
103 case ValueDisallowed:
104 if (*Value != 0)
105 return Handler->error(" does not allow a value! '" +
Chris Lattnerca6433f2003-05-22 20:06:43 +0000106 std::string(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +0000107 break;
108 case ValueOptional: break;
Chris Lattnerca6433f2003-05-22 20:06:43 +0000109 default: std::cerr << "Bad ValueMask flag! CommandLine usage error:"
110 << Handler->getValueExpectedFlag() << "\n"; abort();
Chris Lattnercaccd762001-10-27 05:54:17 +0000111 }
112
113 // Run the handler now!
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000114 return Handler->addOccurrence(ArgName, Value);
Chris Lattnercaccd762001-10-27 05:54:17 +0000115}
116
Chris Lattner9cf3d472003-07-30 17:34:02 +0000117static bool ProvidePositionalOption(Option *Handler, const std::string &Arg) {
Chris Lattner331de232002-07-22 02:07:59 +0000118 int Dummy;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000119 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000120}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000121
Chris Lattner331de232002-07-22 02:07:59 +0000122
123// Option predicates...
124static inline bool isGrouping(const Option *O) {
125 return O->getFormattingFlag() == cl::Grouping;
126}
127static inline bool isPrefixedOrGrouping(const Option *O) {
128 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
129}
130
131// getOptionPred - Check to see if there are any options that satisfy the
132// specified predicate with names that are the prefixes in Name. This is
133// checked by progressively stripping characters off of the name, checking to
134// see if there options that satisfy the predicate. If we find one, return it,
135// otherwise return null.
136//
137static Option *getOptionPred(std::string Name, unsigned &Length,
138 bool (*Pred)(const Option*)) {
139
Chris Lattnere8e258b2002-07-29 20:58:42 +0000140 Option *Op = getOption(Name);
141 if (Op && Pred(Op)) {
Chris Lattner331de232002-07-22 02:07:59 +0000142 Length = Name.length();
Chris Lattnere8e258b2002-07-29 20:58:42 +0000143 return Op;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000144 }
145
Chris Lattner331de232002-07-22 02:07:59 +0000146 if (Name.size() == 1) return 0;
147 do {
148 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
Chris Lattnere8e258b2002-07-29 20:58:42 +0000149 Op = getOption(Name);
Chris Lattner331de232002-07-22 02:07:59 +0000150
151 // Loop while we haven't found an option and Name still has at least two
152 // characters in it (so that the next iteration will not be the empty
153 // string...
Chris Lattnere8e258b2002-07-29 20:58:42 +0000154 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
Chris Lattner331de232002-07-22 02:07:59 +0000155
Chris Lattnere8e258b2002-07-29 20:58:42 +0000156 if (Op && Pred(Op)) {
Chris Lattner331de232002-07-22 02:07:59 +0000157 Length = Name.length();
Chris Lattnere8e258b2002-07-29 20:58:42 +0000158 return Op; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000159 }
160 return 0; // No option found!
161}
162
163static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000164 return O->getNumOccurrencesFlag() == cl::Required ||
165 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000166}
167
168static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000169 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
170 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000171}
Chris Lattnercaccd762001-10-27 05:54:17 +0000172
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000173/// ParseCStringVector - Break INPUT up wherever one or more
174/// whitespace characters are found, and store the resulting tokens in
175/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
176/// using strdup (), so it is the caller's responsibility to free ()
177/// them later.
Brian Gaeke06b06c52003-08-14 22:00:59 +0000178///
179static void ParseCStringVector (std::vector<char *> &output,
Reid Spencer69105f32004-08-04 00:36:06 +0000180 const char *input) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000181 // Characters which will be treated as token separators:
182 static const char *delims = " \v\f\t\r\n";
183
184 std::string work (input);
185 // Skip past any delims at head of input string.
186 size_t pos = work.find_first_not_of (delims);
187 // If the string consists entirely of delims, then exit early.
188 if (pos == std::string::npos) return;
189 // Otherwise, jump forward to beginning of first word.
190 work = work.substr (pos);
191 // Find position of first delimiter.
192 pos = work.find_first_of (delims);
193
194 while (!work.empty() && pos != std::string::npos) {
195 // Everything from 0 to POS is the next word to copy.
196 output.push_back (strdup (work.substr (0,pos).c_str ()));
197 // Is there another word in the string?
198 size_t nextpos = work.find_first_not_of (delims, pos + 1);
199 if (nextpos != std::string::npos) {
200 // Yes? Then remove delims from beginning ...
201 work = work.substr (work.find_first_not_of (delims, pos + 1));
202 // and find the end of the word.
203 pos = work.find_first_of (delims);
204 } else {
205 // No? (Remainder of string is delims.) End the loop.
206 work = "";
207 pos = std::string::npos;
208 }
209 }
210
211 // If `input' ended with non-delim char, then we'll get here with
212 // the last word of `input' in `work'; copy it now.
213 if (!work.empty ()) {
214 output.push_back (strdup (work.c_str ()));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000215 }
216}
217
218/// ParseEnvironmentOptions - An alternative entry point to the
219/// CommandLine library, which allows you to read the program's name
220/// from the caller (as PROGNAME) and its command-line arguments from
221/// an environment variable (whose name is given in ENVVAR).
222///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000223void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
224 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000225 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000226 assert(progName && "Program name not specified");
227 assert(envVar && "Environment variable name missing");
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000228
229 // Get the environment variable they want us to parse options out of.
230 const char *envValue = getenv (envVar);
231 if (!envValue)
232 return;
233
Brian Gaeke06b06c52003-08-14 22:00:59 +0000234 // Get program's "name", which we wouldn't know without the caller
235 // telling us.
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000236 std::vector<char *> newArgv;
237 newArgv.push_back (strdup (progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000238
239 // Parse the value of the environment variable into a "command line"
240 // and hand it off to ParseCommandLineOptions().
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000241 ParseCStringVector (newArgv, envValue);
242 int newArgc = newArgv.size ();
243 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
244
245 // Free all the strdup()ed strings.
246 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
247 i != e; ++i) {
248 free (*i);
249 }
Brian Gaeke06b06c52003-08-14 22:00:59 +0000250}
251
Chris Lattnerbf455c22004-05-06 22:04:31 +0000252/// LookupOption - Lookup the option specified by the specified option on the
253/// command line. If there is a value specified (after an equal sign) return
254/// that as well.
255static Option *LookupOption(const char *&Arg, const char *&Value) {
256 while (*Arg == '-') ++Arg; // Eat leading dashes
257
258 const char *ArgEnd = Arg;
259 while (*ArgEnd && *ArgEnd != '=')
260 ++ArgEnd; // Scan till end of argument name...
261
262 Value = ArgEnd;
263 if (*Value) // If we have an equals sign...
264 ++Value; // Advance to value...
265
266 if (*Arg == 0) return 0;
267
268 // Look up the option.
269 std::map<std::string, Option*> &Opts = getOpts();
270 std::map<std::string, Option*>::iterator I =
271 Opts.find(std::string(Arg, ArgEnd));
272 return (I != Opts.end()) ? I->second : 0;
273}
274
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000275void cl::ParseCommandLineOptions(int &argc, char **argv,
Chris Lattner0c0edf82002-07-25 06:17:51 +0000276 const char *Overview) {
Chris Lattner331de232002-07-22 02:07:59 +0000277 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
278 "No options specified, or ParseCommandLineOptions called more"
279 " than once!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000280 ProgramName = argv[0]; // Save this away safe and snug
281 ProgramOverview = Overview;
282 bool ErrorParsing = false;
283
Chris Lattnerca6433f2003-05-22 20:06:43 +0000284 std::map<std::string, Option*> &Opts = getOpts();
285 std::vector<Option*> &PositionalOpts = getPositionalOpts();
Chris Lattner331de232002-07-22 02:07:59 +0000286
287 // Check out the positional arguments to collect information about them.
288 unsigned NumPositionalRequired = 0;
289 Option *ConsumeAfterOpt = 0;
290 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000291 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000292 assert(PositionalOpts.size() > 1 &&
293 "Cannot specify cl::ConsumeAfter without a positional argument!");
294 ConsumeAfterOpt = PositionalOpts[0];
295 }
296
297 // Calculate how many positional values are _required_.
298 bool UnboundedFound = false;
299 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
300 i != e; ++i) {
301 Option *Opt = PositionalOpts[i];
302 if (RequiresValue(Opt))
303 ++NumPositionalRequired;
304 else if (ConsumeAfterOpt) {
305 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000306 // unless there is only one positional argument...
307 if (PositionalOpts.size() > 2)
308 ErrorParsing |=
309 Opt->error(" error - this positional option will never be matched, "
310 "because it does not Require a value, and a "
311 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000312 } else if (UnboundedFound && !Opt->ArgStr[0]) {
313 // This option does not "require" a value... Make sure this option is
314 // not specified after an option that eats all extra arguments, or this
315 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000316 //
317 ErrorParsing |= Opt->error(" error - option can never match, because "
318 "another positional argument will match an "
319 "unbounded number of values, and this option"
320 " does not require a value!");
321 }
322 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
323 }
324 }
325
326 // PositionalVals - A vector of "positional" arguments we accumulate into to
327 // processes at the end...
328 //
Chris Lattnerca6433f2003-05-22 20:06:43 +0000329 std::vector<std::string> PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000330
Chris Lattner9cf3d472003-07-30 17:34:02 +0000331 // If the program has named positional arguments, and the name has been run
332 // across, keep track of which positional argument was named. Otherwise put
333 // the positional args into the PositionalVals list...
334 Option *ActivePositionalArg = 0;
335
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000336 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000337 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000338 for (int i = 1; i < argc; ++i) {
339 Option *Handler = 0;
340 const char *Value = "";
341 const char *ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000342
343 // Check to see if this is a positional argument. This argument is
344 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000345 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000346 //
347 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
348 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000349 if (ActivePositionalArg) {
350 ProvidePositionalOption(ActivePositionalArg, argv[i]);
351 continue; // We are done!
352 } else if (!PositionalOpts.empty()) {
Chris Lattner331de232002-07-22 02:07:59 +0000353 PositionalVals.push_back(argv[i]);
354
355 // All of the positional arguments have been fulfulled, give the rest to
356 // the consume after option... if it's specified...
357 //
Chris Lattnerd16714b2002-07-31 16:29:43 +0000358 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000359 ConsumeAfterOpt != 0) {
360 for (++i; i < argc; ++i)
361 PositionalVals.push_back(argv[i]);
362 break; // Handle outside of the argument processing loop...
363 }
364
365 // Delay processing positional arguments until the end...
366 continue;
367 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000368 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
369 !DashDashFound) {
370 DashDashFound = true; // This is the mythical "--"?
371 continue; // Don't try to process it as an argument itself.
372 } else if (ActivePositionalArg &&
373 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
374 // If there is a positional argument eating options, check to see if this
375 // option is another positional argument. If so, treat it as an argument,
376 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000377 ArgName = argv[i]+1;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000378 Handler = LookupOption(ArgName, Value);
379 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
380 ProvidePositionalOption(ActivePositionalArg, argv[i]);
381 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000382 }
383
Chris Lattnerbf455c22004-05-06 22:04:31 +0000384 } else { // We start with a '-', must be an argument...
385 ArgName = argv[i]+1;
386 Handler = LookupOption(ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000387
Chris Lattnerbf455c22004-05-06 22:04:31 +0000388 // Check to see if this "option" is really a prefixed or grouped argument.
389 if (Handler == 0 && *Value == 0) {
390 std::string RealName(ArgName);
391 if (RealName.size() > 1) {
Chris Lattner331de232002-07-22 02:07:59 +0000392 unsigned Length = 0;
393 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000394
Chris Lattner331de232002-07-22 02:07:59 +0000395 // If the option is a prefixed option, then the value is simply the
396 // rest of the name... so fall through to later processing, by
397 // setting up the argument name flags and value fields.
398 //
399 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000400 Value = ArgName+Length;
401 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
402 Opts.find(std::string(ArgName, Value))->second == PGOpt);
403 Handler = PGOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000404 } else if (PGOpt) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000405 // This must be a grouped option... handle them now.
Chris Lattner331de232002-07-22 02:07:59 +0000406 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Chris Lattnerbf455c22004-05-06 22:04:31 +0000407
Chris Lattner331de232002-07-22 02:07:59 +0000408 do {
409 // Move current arg name out of RealName into RealArgName...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000410 std::string RealArgName(RealName.begin(),
411 RealName.begin() + Length);
412 RealName.erase(RealName.begin(), RealName.begin() + Length);
413
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000414 // Because ValueRequired is an invalid flag for grouped arguments,
415 // we don't need to pass argc/argv in...
416 //
Chris Lattner331de232002-07-22 02:07:59 +0000417 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
418 "Option can not be cl::Grouping AND cl::ValueRequired!");
419 int Dummy;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000420 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
421 "", 0, 0, Dummy);
422
Chris Lattner331de232002-07-22 02:07:59 +0000423 // Get the next grouping option...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000424 PGOpt = getOptionPred(RealName, Length, isGrouping);
425 } while (PGOpt && Length != RealName.size());
426
427 Handler = PGOpt; // Ate all of the options.
Chris Lattner331de232002-07-22 02:07:59 +0000428 }
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000429 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000430 }
431 }
432
433 if (Handler == 0) {
Brian Gaekec86e84b2003-09-16 18:00:35 +0000434 std::cerr << "Unknown command line argument '" << argv[i] << "'. Try: '"
Chris Lattnerca6433f2003-05-22 20:06:43 +0000435 << argv[0] << " --help'\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000436 ErrorParsing = true;
437 continue;
438 }
439
Chris Lattner72fb8e52003-05-22 20:26:17 +0000440 // Check to see if this option accepts a comma separated list of values. If
441 // it does, we have to split up the value into multiple values...
442 if (Handler->getMiscFlags() & CommaSeparated) {
443 std::string Val(Value);
444 std::string::size_type Pos = Val.find(',');
445
446 while (Pos != std::string::npos) {
447 // Process the portion before the comma...
448 ErrorParsing |= ProvideOption(Handler, ArgName,
449 std::string(Val.begin(),
450 Val.begin()+Pos).c_str(),
451 argc, argv, i);
452 // Erase the portion before the comma, AND the comma...
453 Val.erase(Val.begin(), Val.begin()+Pos+1);
454 Value += Pos+1; // Increment the original value pointer as well...
455
456 // Check for another comma...
457 Pos = Val.find(',');
458 }
459 }
Chris Lattner9cf3d472003-07-30 17:34:02 +0000460
461 // If this is a named positional argument, just remember that it is the
462 // active one...
463 if (Handler->getFormattingFlag() == cl::Positional)
464 ActivePositionalArg = Handler;
465 else
466 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000467 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000468
Chris Lattner331de232002-07-22 02:07:59 +0000469 // Check and handle positional arguments now...
470 if (NumPositionalRequired > PositionalVals.size()) {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000471 std::cerr << "Not enough positional command line arguments specified!\n"
472 << "Must specify at least " << NumPositionalRequired
473 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattner331de232002-07-22 02:07:59 +0000474 ErrorParsing = true;
475
476
477 } else if (ConsumeAfterOpt == 0) {
478 // Positional args have already been handled if ConsumeAfter is specified...
479 unsigned ValNo = 0, NumVals = PositionalVals.size();
480 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
481 if (RequiresValue(PositionalOpts[i])) {
482 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
483 --NumPositionalRequired; // We fulfilled our duty...
484 }
485
486 // If we _can_ give this option more arguments, do so now, as long as we
487 // do not give it values that others need. 'Done' controls whether the
488 // option even _WANTS_ any more.
489 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000490 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000491 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000492 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000493 case cl::Optional:
494 Done = true; // Optional arguments want _at most_ one value
495 // FALL THROUGH
496 case cl::ZeroOrMore: // Zero or more will take all they can get...
497 case cl::OneOrMore: // One or more will take all they can get...
498 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
499 break;
500 default:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000501 assert(0 && "Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000502 "positional argument processing!");
503 }
504 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000505 }
Chris Lattner331de232002-07-22 02:07:59 +0000506 } else {
507 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
508 unsigned ValNo = 0;
509 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
510 if (RequiresValue(PositionalOpts[j]))
Chris Lattnerfaba8092002-07-24 20:15:13 +0000511 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
512 PositionalVals[ValNo++]);
513
514 // Handle the case where there is just one positional option, and it's
515 // optional. In this case, we want to give JUST THE FIRST option to the
516 // positional option and keep the rest for the consume after. The above
517 // loop would have assigned no values to positional options in this case.
518 //
Chris Lattnerb490c202002-08-02 21:51:29 +0000519 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty())
Chris Lattnerfaba8092002-07-24 20:15:13 +0000520 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
521 PositionalVals[ValNo++]);
Chris Lattner331de232002-07-22 02:07:59 +0000522
523 // Handle over all of the rest of the arguments to the
524 // cl::ConsumeAfter command line option...
525 for (; ValNo != PositionalVals.size(); ++ValNo)
526 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
527 PositionalVals[ValNo]);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000528 }
529
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000530 // Loop over args and make sure all required args are specified!
Chris Lattnerca6433f2003-05-22 20:06:43 +0000531 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000532 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000533 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000534 case Required:
535 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000536 if (I->second->getNumOccurrences() == 0) {
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000537 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000538 ErrorParsing = true;
539 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000540 // Fall through
541 default:
542 break;
543 }
544 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000545
Chris Lattner331de232002-07-22 02:07:59 +0000546 // Free all of the memory allocated to the map. Command line options may only
547 // be processed once!
Chris Lattnere8e258b2002-07-29 20:58:42 +0000548 delete CommandLineOptions;
549 CommandLineOptions = 0;
Chris Lattner331de232002-07-22 02:07:59 +0000550 PositionalOpts.clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000551
552 // If we had an error processing our arguments, don't let the program execute
553 if (ErrorParsing) exit(1);
554}
555
556//===----------------------------------------------------------------------===//
557// Option Base class implementation
558//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000559
Chris Lattnerca6433f2003-05-22 20:06:43 +0000560bool Option::error(std::string Message, const char *ArgName) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000561 if (ArgName == 0) ArgName = ArgStr;
Chris Lattner331de232002-07-22 02:07:59 +0000562 if (ArgName[0] == 0)
Chris Lattnerca6433f2003-05-22 20:06:43 +0000563 std::cerr << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000564 else
Chris Lattnerca6433f2003-05-22 20:06:43 +0000565 std::cerr << "-" << ArgName;
566 std::cerr << " option" << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000567 return true;
568}
569
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000570bool Option::addOccurrence(const char *ArgName, const std::string &Value) {
571 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000572
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000573 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000574 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000575 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000576 return error(": may only occur zero or one times!", ArgName);
577 break;
578 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000579 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000580 return error(": must occur exactly one time!", ArgName);
581 // Fall through
582 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000583 case ZeroOrMore:
584 case ConsumeAfter: break;
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000585 default: return error(": bad num occurrences flag value!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000586 }
587
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000588 return handleOccurrence(ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000589}
590
Chris Lattner331de232002-07-22 02:07:59 +0000591// addArgument - Tell the system that this Option subclass will handle all
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000592// occurrences of -ArgStr on the command line.
Chris Lattner331de232002-07-22 02:07:59 +0000593//
594void Option::addArgument(const char *ArgStr) {
595 if (ArgStr[0])
596 AddArgument(ArgStr, this);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000597
598 if (getFormattingFlag() == Positional)
Chris Lattner331de232002-07-22 02:07:59 +0000599 getPositionalOpts().push_back(this);
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000600 else if (getNumOccurrencesFlag() == ConsumeAfter) {
Chris Lattner9cf3d472003-07-30 17:34:02 +0000601 if (!getPositionalOpts().empty() &&
602 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
603 error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattner331de232002-07-22 02:07:59 +0000604 getPositionalOpts().insert(getPositionalOpts().begin(), this);
605 }
606}
607
Chris Lattneraa852bb2002-07-23 17:15:12 +0000608void Option::removeArgument(const char *ArgStr) {
Chris Lattner9cf3d472003-07-30 17:34:02 +0000609 if (ArgStr[0])
Chris Lattnere8e258b2002-07-29 20:58:42 +0000610 RemoveArgument(ArgStr, this);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000611
612 if (getFormattingFlag() == Positional) {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000613 std::vector<Option*>::iterator I =
Chris Lattneraa852bb2002-07-23 17:15:12 +0000614 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
615 assert(I != getPositionalOpts().end() && "Arg not registered!");
616 getPositionalOpts().erase(I);
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000617 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
Chris Lattneraa852bb2002-07-23 17:15:12 +0000618 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
619 "Arg not registered correctly!");
620 getPositionalOpts().erase(getPositionalOpts().begin());
621 }
622}
623
Chris Lattner331de232002-07-22 02:07:59 +0000624
625// getValueStr - Get the value description string, using "DefaultMsg" if nothing
626// has been specified yet.
627//
628static const char *getValueStr(const Option &O, const char *DefaultMsg) {
629 if (O.ValueStr[0] == 0) return DefaultMsg;
630 return O.ValueStr;
631}
632
633//===----------------------------------------------------------------------===//
634// cl::alias class implementation
635//
636
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000637// Return the width of the option tag for printing...
Chris Lattner331de232002-07-22 02:07:59 +0000638unsigned alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000639 return std::strlen(ArgStr)+6;
640}
641
Chris Lattner331de232002-07-22 02:07:59 +0000642// Print out the option for the alias...
643void alias::printOptionInfo(unsigned GlobalWidth) const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000644 unsigned L = std::strlen(ArgStr);
Chris Lattnerca6433f2003-05-22 20:06:43 +0000645 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
646 << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000647}
648
649
Chris Lattner331de232002-07-22 02:07:59 +0000650
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000651//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000652// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000653//
654
Chris Lattner9b14eb52002-08-07 18:36:37 +0000655// basic_parser implementation
656//
657
658// Return the width of the option tag for printing...
659unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
660 unsigned Len = std::strlen(O.ArgStr);
661 if (const char *ValName = getValueName())
662 Len += std::strlen(getValueStr(O, ValName))+3;
663
664 return Len + 6;
665}
666
667// printOptionInfo - Print out information about this option. The
668// to-be-maintained width is specified.
669//
670void basic_parser_impl::printOptionInfo(const Option &O,
671 unsigned GlobalWidth) const {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000672 std::cerr << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000673
674 if (const char *ValName = getValueName())
Chris Lattnerca6433f2003-05-22 20:06:43 +0000675 std::cerr << "=<" << getValueStr(O, ValName) << ">";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000676
Chris Lattnerca6433f2003-05-22 20:06:43 +0000677 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
678 << O.HelpStr << "\n";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000679}
680
681
682
683
Chris Lattner331de232002-07-22 02:07:59 +0000684// parser<bool> implementation
685//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000686bool parser<bool>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000687 const std::string &Arg, bool &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000688 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
689 Arg == "1") {
690 Value = true;
691 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
692 Value = false;
693 } else {
Chris Lattner331de232002-07-22 02:07:59 +0000694 return O.error(": '" + Arg +
695 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000696 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000697 return false;
698}
699
Chris Lattner331de232002-07-22 02:07:59 +0000700// parser<int> implementation
701//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000702bool parser<int>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000703 const std::string &Arg, int &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000704 char *End;
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000705 Value = (int)strtol(Arg.c_str(), &End, 0);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000706 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000707 return O.error(": '" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000708 return false;
709}
710
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000711// parser<unsigned> implementation
712//
713bool parser<unsigned>::parse(Option &O, const char *ArgName,
714 const std::string &Arg, unsigned &Value) {
715 char *End;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000716 errno = 0;
717 unsigned long V = strtoul(Arg.c_str(), &End, 0);
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000718 Value = (unsigned)V;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000719 if (((V == ULONG_MAX) && (errno == ERANGE))
720 || (*End != 0)
721 || (Value != V))
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000722 return O.error(": '" + Arg + "' value invalid for uint argument!");
723 return false;
724}
725
Chris Lattner9b14eb52002-08-07 18:36:37 +0000726// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +0000727//
Chris Lattnerca6433f2003-05-22 20:06:43 +0000728static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
Chris Lattner331de232002-07-22 02:07:59 +0000729 const char *ArgStart = Arg.c_str();
730 char *End;
731 Value = strtod(ArgStart, &End);
732 if (*End != 0)
733 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +0000734 return false;
735}
736
Chris Lattner9b14eb52002-08-07 18:36:37 +0000737bool parser<double>::parse(Option &O, const char *AN,
738 const std::string &Arg, double &Val) {
739 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +0000740}
741
Chris Lattner9b14eb52002-08-07 18:36:37 +0000742bool parser<float>::parse(Option &O, const char *AN,
743 const std::string &Arg, float &Val) {
744 double dVal;
745 if (parseDouble(O, Arg, dVal))
746 return true;
747 Val = (float)dVal;
748 return false;
Chris Lattner331de232002-07-22 02:07:59 +0000749}
750
751
Chris Lattner331de232002-07-22 02:07:59 +0000752
753// generic_parser_base implementation
754//
755
Chris Lattneraa852bb2002-07-23 17:15:12 +0000756// findOption - Return the option number corresponding to the specified
757// argument string. If the option is not found, getNumOptions() is returned.
758//
759unsigned generic_parser_base::findOption(const char *Name) {
760 unsigned i = 0, e = getNumOptions();
Chris Lattnerca6433f2003-05-22 20:06:43 +0000761 std::string N(Name);
Chris Lattneraa852bb2002-07-23 17:15:12 +0000762
763 while (i != e)
764 if (getOption(i) == N)
765 return i;
766 else
767 ++i;
768 return e;
769}
770
771
Chris Lattner331de232002-07-22 02:07:59 +0000772// Return the width of the option tag for printing...
773unsigned generic_parser_base::getOptionWidth(const Option &O) const {
774 if (O.hasArgStr()) {
775 unsigned Size = std::strlen(O.ArgStr)+6;
776 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
777 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
778 return Size;
779 } else {
780 unsigned BaseSize = 0;
781 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
782 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
783 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000784 }
785}
786
Chris Lattner331de232002-07-22 02:07:59 +0000787// printOptionInfo - Print out information about this option. The
788// to-be-maintained width is specified.
789//
790void generic_parser_base::printOptionInfo(const Option &O,
791 unsigned GlobalWidth) const {
792 if (O.hasArgStr()) {
793 unsigned L = std::strlen(O.ArgStr);
Chris Lattnerca6433f2003-05-22 20:06:43 +0000794 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
795 << " - " << O.HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000796
Chris Lattner331de232002-07-22 02:07:59 +0000797 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
798 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnerca6433f2003-05-22 20:06:43 +0000799 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
800 << " - " << getDescription(i) << "\n";
Chris Lattner9c9be482002-01-31 00:42:56 +0000801 }
Chris Lattner331de232002-07-22 02:07:59 +0000802 } else {
803 if (O.HelpStr[0])
Chris Lattnerca6433f2003-05-22 20:06:43 +0000804 std::cerr << " " << O.HelpStr << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000805 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
806 unsigned L = std::strlen(getOption(i));
Chris Lattnerca6433f2003-05-22 20:06:43 +0000807 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
808 << " - " << getDescription(i) << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000809 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000810 }
811}
812
813
814//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000815// --help and --help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000816//
817namespace {
818
Chris Lattner331de232002-07-22 02:07:59 +0000819class HelpPrinter {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000820 unsigned MaxArgLen;
821 const Option *EmptyArg;
822 const bool ShowHidden;
823
Chris Lattner331de232002-07-22 02:07:59 +0000824 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
Chris Lattnerca6433f2003-05-22 20:06:43 +0000825 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000826 return OptPair.second->getOptionHiddenFlag() >= Hidden;
827 }
Chris Lattnerca6433f2003-05-22 20:06:43 +0000828 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000829 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
830 }
831
832public:
833 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
834 EmptyArg = 0;
835 }
836
837 void operator=(bool Value) {
838 if (Value == false) return;
839
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000840 // Copy Options into a vector so we can sort them as we like...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000841 std::vector<std::pair<std::string, Option*> > Options;
Chris Lattner697954c2002-01-20 22:54:45 +0000842 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000843
844 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Chris Lattner331de232002-07-22 02:07:59 +0000845 Options.erase(std::remove_if(Options.begin(), Options.end(),
846 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000847 Options.end());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000848
849 // Eliminate duplicate entries in table (from enum flags options, f.e.)
Chris Lattner331de232002-07-22 02:07:59 +0000850 { // Give OptionSet a scope
851 std::set<Option*> OptionSet;
852 for (unsigned i = 0; i != Options.size(); ++i)
853 if (OptionSet.count(Options[i].second) == 0)
854 OptionSet.insert(Options[i].second); // Add new entry to set
855 else
856 Options.erase(Options.begin()+i--); // Erase duplicate
857 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000858
859 if (ProgramOverview)
Chris Lattnerca6433f2003-05-22 20:06:43 +0000860 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000861
Chris Lattnerca6433f2003-05-22 20:06:43 +0000862 std::cerr << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +0000863
864 // Print out the positional options...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000865 std::vector<Option*> &PosOpts = getPositionalOpts();
Chris Lattner331de232002-07-22 02:07:59 +0000866 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000867 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
Chris Lattner331de232002-07-22 02:07:59 +0000868 CAOpt = PosOpts[0];
869
Chris Lattner9cf3d472003-07-30 17:34:02 +0000870 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
871 if (PosOpts[i]->ArgStr[0])
872 std::cerr << " --" << PosOpts[i]->ArgStr;
Chris Lattnerca6433f2003-05-22 20:06:43 +0000873 std::cerr << " " << PosOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000874 }
Chris Lattner331de232002-07-22 02:07:59 +0000875
876 // Print the consume after option info if it exists...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000877 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +0000878
Chris Lattnerca6433f2003-05-22 20:06:43 +0000879 std::cerr << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000880
881 // Compute the maximum argument length...
882 MaxArgLen = 0;
Chris Lattner331de232002-07-22 02:07:59 +0000883 for (unsigned i = 0, e = Options.size(); i != e; ++i)
884 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000885
Chris Lattnerca6433f2003-05-22 20:06:43 +0000886 std::cerr << "OPTIONS:\n";
Chris Lattner331de232002-07-22 02:07:59 +0000887 for (unsigned i = 0, e = Options.size(); i != e; ++i)
888 Options[i].second->printOptionInfo(MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000889
Chris Lattner331de232002-07-22 02:07:59 +0000890 // Halt the program if help information is printed
891 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000892 }
893};
894
Reid Spencer69105f32004-08-04 00:36:06 +0000895class VersionPrinter {
896public:
897 void operator=(bool OptionWasSpecified) {
898 if (OptionWasSpecified) {
899 std::cerr << "Low Level Virtual Machine (" << PACKAGE_NAME << ") "
900 << PACKAGE_VERSION << " (see http://llvm.org/)\n";
901 exit(1);
902 }
903 }
904};
Chris Lattner331de232002-07-22 02:07:59 +0000905
906
907// Define the two HelpPrinter instances that are used to print out help, or
908// help-hidden...
909//
910HelpPrinter NormalPrinter(false);
911HelpPrinter HiddenPrinter(true);
912
913cl::opt<HelpPrinter, true, parser<bool> >
914HOp("help", cl::desc("display available options (--help-hidden for more)"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000915 cl::location(NormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +0000916
917cl::opt<HelpPrinter, true, parser<bool> >
918HHOp("help-hidden", cl::desc("display all available options"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000919 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000920
Reid Spencer69105f32004-08-04 00:36:06 +0000921// Define the --version option that prints out the LLVM version for the tool
922VersionPrinter VersionPrinterInstance;
923cl::opt<VersionPrinter, true, parser<bool> >
924VersOp("version", cl::desc("display the version"),
925 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
926
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000927} // End anonymous namespace