blob: 57620b50d6c6f8a3a8e81c194616a414a923e53c [file] [log] [blame]
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerdbab15a2001-07-23 17:17:47 +00009//
10// This class implements a command line argument processor that is useful when
11// creating a tool. It provides a simple, minimalistic interface that is easily
12// extensible and supports nonlocal (library) command line options.
13//
Chris Lattner03fe1bd2001-07-23 23:04:07 +000014// Note that rather than trying to figure out what this code does, you could try
15// reading the library documentation located in docs/CommandLine.html
16//
Chris Lattnerdbab15a2001-07-23 17:17:47 +000017//===----------------------------------------------------------------------===//
18
Reid Spencer551ccae2004-09-01 22:55:40 +000019#include "llvm/Config/config.h"
20#include "llvm/Support/CommandLine.h"
Reid Spencer6f4c6072006-08-23 07:10:06 +000021#include "llvm/System/Path.h"
Chris Lattnerdbab15a2001-07-23 17:17:47 +000022#include <algorithm>
Duraid Madina786e3e22005-12-26 04:56:16 +000023#include <functional>
Chris Lattnerdbab15a2001-07-23 17:17:47 +000024#include <map>
25#include <set>
Chris Lattner697954c2002-01-20 22:54:45 +000026#include <iostream>
Brian Gaeke2d6a2362003-10-10 17:01:36 +000027#include <cstdlib>
28#include <cerrno>
Chris Lattner51140042004-07-03 01:21:05 +000029#include <cstring>
Chris Lattner2cdd21c2003-12-14 21:35:53 +000030using namespace llvm;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000031using namespace cl;
32
Chris Lattner7422a762006-08-27 12:45:47 +000033//===----------------------------------------------------------------------===//
34// Template instantiations and anchors.
35//
36TEMPLATE_INSTANTIATION(class basic_parser<bool>);
37TEMPLATE_INSTANTIATION(class basic_parser<int>);
38TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
39TEMPLATE_INSTANTIATION(class basic_parser<double>);
40TEMPLATE_INSTANTIATION(class basic_parser<float>);
41TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
42
43TEMPLATE_INSTANTIATION(class opt<unsigned>);
44TEMPLATE_INSTANTIATION(class opt<int>);
45TEMPLATE_INSTANTIATION(class opt<std::string>);
46TEMPLATE_INSTANTIATION(class opt<bool>);
47
48void Option::anchor() {}
49void basic_parser_impl::anchor() {}
50void parser<bool>::anchor() {}
51void parser<int>::anchor() {}
52void parser<unsigned>::anchor() {}
53void parser<double>::anchor() {}
54void parser<float>::anchor() {}
55void parser<std::string>::anchor() {}
56
57//===----------------------------------------------------------------------===//
58
Reid Spencere1cc1502004-09-01 04:41:28 +000059// Globals for name and overview of program
Chris Lattner7422a762006-08-27 12:45:47 +000060static std::string ProgramName = "<premain>";
Reid Spencere1cc1502004-09-01 04:41:28 +000061static const char *ProgramOverview = 0;
62
Chris Lattnerc540ebb2004-11-19 17:08:15 +000063// This collects additional help to be printed.
64static std::vector<const char*> &MoreHelp() {
65 static std::vector<const char*> moreHelp;
66 return moreHelp;
67}
68
69extrahelp::extrahelp(const char* Help)
70 : morehelp(Help) {
71 MoreHelp().push_back(Help);
72}
73
Chris Lattner331de232002-07-22 02:07:59 +000074//===----------------------------------------------------------------------===//
Chris Lattner7422a762006-08-27 12:45:47 +000075// Basic, shared command line option processing machinery.
Chris Lattner331de232002-07-22 02:07:59 +000076//
77
Chris Lattnerdbab15a2001-07-23 17:17:47 +000078// Return the global command line option vector. Making it a function scoped
Chris Lattnerf78032f2001-11-26 18:58:34 +000079// static ensures that it will be initialized correctly before its first use.
Chris Lattnerdbab15a2001-07-23 17:17:47 +000080//
Chris Lattnerca6433f2003-05-22 20:06:43 +000081static std::map<std::string, Option*> &getOpts() {
Chris Lattnerc540ebb2004-11-19 17:08:15 +000082 static std::map<std::string, Option*> CommandLineOptions;
83 return CommandLineOptions;
Chris Lattnere8e258b2002-07-29 20:58:42 +000084}
85
Chris Lattnerca6433f2003-05-22 20:06:43 +000086static Option *getOption(const std::string &Str) {
Chris Lattnerc540ebb2004-11-19 17:08:15 +000087 std::map<std::string,Option*>::iterator I = getOpts().find(Str);
88 return I != getOpts().end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000089}
90
Chris Lattnerca6433f2003-05-22 20:06:43 +000091static std::vector<Option*> &getPositionalOpts() {
Chris Lattnerc540ebb2004-11-19 17:08:15 +000092 static std::vector<Option*> Positional;
93 return Positional;
Chris Lattner331de232002-07-22 02:07:59 +000094}
95
Chris Lattnere8e258b2002-07-29 20:58:42 +000096static void AddArgument(const char *ArgName, Option *Opt) {
97 if (getOption(ArgName)) {
Misha Brukmanf976c852005-04-21 22:55:34 +000098 std::cerr << ProgramName << ": CommandLine Error: Argument '"
Reid Spencere1cc1502004-09-01 04:41:28 +000099 << ArgName << "' defined more than once!\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000100 } else {
Chris Lattnerf78032f2001-11-26 18:58:34 +0000101 // Add argument to the argument map!
Chris Lattnere8e258b2002-07-29 20:58:42 +0000102 getOpts()[ArgName] = Opt;
103 }
104}
105
106// RemoveArgument - It's possible that the argument is no longer in the map if
107// options have already been processed and the map has been deleted!
Misha Brukmanf976c852005-04-21 22:55:34 +0000108//
Chris Lattnere8e258b2002-07-29 20:58:42 +0000109static void RemoveArgument(const char *ArgName, Option *Opt) {
Tanya Lattnerc4ae8e92004-11-20 23:35:20 +0000110 if(getOpts().empty()) return;
111
Chris Lattnerf98cfc72004-07-18 21:56:20 +0000112#ifndef NDEBUG
113 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
114 // If we pass ArgName directly into getOption here.
115 std::string Tmp = ArgName;
116 assert(getOption(Tmp) == Opt && "Arg not in map!");
117#endif
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000118 getOpts().erase(ArgName);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000119}
120
Chris Lattnercaccd762001-10-27 05:54:17 +0000121static inline bool ProvideOption(Option *Handler, const char *ArgName,
122 const char *Value, int argc, char **argv,
123 int &i) {
124 // Enforce value requirements
125 switch (Handler->getValueExpectedFlag()) {
126 case ValueRequired:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000127 if (Value == 0) { // No value specified?
Chris Lattnercaccd762001-10-27 05:54:17 +0000128 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
129 Value = argv[++i];
130 } else {
131 return Handler->error(" requires a value!");
132 }
133 }
134 break;
135 case ValueDisallowed:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000136 if (Value)
Misha Brukmanf976c852005-04-21 22:55:34 +0000137 return Handler->error(" does not allow a value! '" +
Chris Lattnerca6433f2003-05-22 20:06:43 +0000138 std::string(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +0000139 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000140 case ValueOptional:
Reid Spencere1cc1502004-09-01 04:41:28 +0000141 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000142 default:
143 std::cerr << ProgramName
144 << ": Bad ValueMask flag! CommandLine usage error:"
145 << Handler->getValueExpectedFlag() << "\n";
Reid Spencere1cc1502004-09-01 04:41:28 +0000146 abort();
147 break;
Chris Lattnercaccd762001-10-27 05:54:17 +0000148 }
149
150 // Run the handler now!
Chris Lattner6d5857e2005-05-10 23:20:17 +0000151 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
Chris Lattnercaccd762001-10-27 05:54:17 +0000152}
153
Misha Brukmanf976c852005-04-21 22:55:34 +0000154static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000155 int i) {
156 int Dummy = i;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000157 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000158}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000159
Chris Lattner331de232002-07-22 02:07:59 +0000160
161// Option predicates...
162static inline bool isGrouping(const Option *O) {
163 return O->getFormattingFlag() == cl::Grouping;
164}
165static inline bool isPrefixedOrGrouping(const Option *O) {
166 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
167}
168
169// getOptionPred - Check to see if there are any options that satisfy the
170// specified predicate with names that are the prefixes in Name. This is
171// checked by progressively stripping characters off of the name, checking to
172// see if there options that satisfy the predicate. If we find one, return it,
173// otherwise return null.
174//
175static Option *getOptionPred(std::string Name, unsigned &Length,
176 bool (*Pred)(const Option*)) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000177
Chris Lattnere8e258b2002-07-29 20:58:42 +0000178 Option *Op = getOption(Name);
179 if (Op && Pred(Op)) {
Chris Lattner331de232002-07-22 02:07:59 +0000180 Length = Name.length();
Chris Lattnere8e258b2002-07-29 20:58:42 +0000181 return Op;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000182 }
183
Chris Lattner331de232002-07-22 02:07:59 +0000184 if (Name.size() == 1) return 0;
185 do {
186 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
Chris Lattnere8e258b2002-07-29 20:58:42 +0000187 Op = getOption(Name);
Chris Lattner331de232002-07-22 02:07:59 +0000188
189 // Loop while we haven't found an option and Name still has at least two
190 // characters in it (so that the next iteration will not be the empty
191 // string...
Chris Lattnere8e258b2002-07-29 20:58:42 +0000192 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
Chris Lattner331de232002-07-22 02:07:59 +0000193
Chris Lattnere8e258b2002-07-29 20:58:42 +0000194 if (Op && Pred(Op)) {
Chris Lattner331de232002-07-22 02:07:59 +0000195 Length = Name.length();
Chris Lattnere8e258b2002-07-29 20:58:42 +0000196 return Op; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000197 }
198 return 0; // No option found!
199}
200
201static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000202 return O->getNumOccurrencesFlag() == cl::Required ||
203 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000204}
205
206static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000207 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
208 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000209}
Chris Lattnercaccd762001-10-27 05:54:17 +0000210
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000211/// ParseCStringVector - Break INPUT up wherever one or more
212/// whitespace characters are found, and store the resulting tokens in
213/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
214/// using strdup (), so it is the caller's responsibility to free ()
215/// them later.
Brian Gaeke06b06c52003-08-14 22:00:59 +0000216///
Chris Lattner23288582006-08-27 22:10:29 +0000217static void ParseCStringVector(std::vector<char *> &output,
218 const char *input) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000219 // Characters which will be treated as token separators:
220 static const char *delims = " \v\f\t\r\n";
221
222 std::string work (input);
223 // Skip past any delims at head of input string.
224 size_t pos = work.find_first_not_of (delims);
225 // If the string consists entirely of delims, then exit early.
226 if (pos == std::string::npos) return;
227 // Otherwise, jump forward to beginning of first word.
228 work = work.substr (pos);
229 // Find position of first delimiter.
230 pos = work.find_first_of (delims);
231
232 while (!work.empty() && pos != std::string::npos) {
233 // Everything from 0 to POS is the next word to copy.
234 output.push_back (strdup (work.substr (0,pos).c_str ()));
235 // Is there another word in the string?
236 size_t nextpos = work.find_first_not_of (delims, pos + 1);
237 if (nextpos != std::string::npos) {
238 // Yes? Then remove delims from beginning ...
239 work = work.substr (work.find_first_not_of (delims, pos + 1));
240 // and find the end of the word.
241 pos = work.find_first_of (delims);
242 } else {
243 // No? (Remainder of string is delims.) End the loop.
244 work = "";
245 pos = std::string::npos;
246 }
247 }
248
249 // If `input' ended with non-delim char, then we'll get here with
250 // the last word of `input' in `work'; copy it now.
251 if (!work.empty ()) {
252 output.push_back (strdup (work.c_str ()));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000253 }
254}
255
256/// ParseEnvironmentOptions - An alternative entry point to the
257/// CommandLine library, which allows you to read the program's name
258/// from the caller (as PROGNAME) and its command-line arguments from
259/// an environment variable (whose name is given in ENVVAR).
260///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000261void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
262 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000263 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000264 assert(progName && "Program name not specified");
265 assert(envVar && "Environment variable name missing");
Misha Brukmanf976c852005-04-21 22:55:34 +0000266
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000267 // Get the environment variable they want us to parse options out of.
Chris Lattner23288582006-08-27 22:10:29 +0000268 const char *envValue = getenv(envVar);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000269 if (!envValue)
270 return;
271
Brian Gaeke06b06c52003-08-14 22:00:59 +0000272 // Get program's "name", which we wouldn't know without the caller
273 // telling us.
Chris Lattner23288582006-08-27 22:10:29 +0000274 std::vector<char*> newArgv;
275 newArgv.push_back(strdup(progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000276
277 // Parse the value of the environment variable into a "command line"
278 // and hand it off to ParseCommandLineOptions().
Chris Lattner23288582006-08-27 22:10:29 +0000279 ParseCStringVector(newArgv, envValue);
280 int newArgc = newArgv.size();
281 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000282
283 // Free all the strdup()ed strings.
Chris Lattner23288582006-08-27 22:10:29 +0000284 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
285 i != e; ++i)
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000286 free (*i);
Brian Gaeke06b06c52003-08-14 22:00:59 +0000287}
288
Chris Lattnerbf455c22004-05-06 22:04:31 +0000289/// LookupOption - Lookup the option specified by the specified option on the
290/// command line. If there is a value specified (after an equal sign) return
291/// that as well.
292static Option *LookupOption(const char *&Arg, const char *&Value) {
293 while (*Arg == '-') ++Arg; // Eat leading dashes
Misha Brukmanf976c852005-04-21 22:55:34 +0000294
Chris Lattnerbf455c22004-05-06 22:04:31 +0000295 const char *ArgEnd = Arg;
296 while (*ArgEnd && *ArgEnd != '=')
Chris Lattner6d5857e2005-05-10 23:20:17 +0000297 ++ArgEnd; // Scan till end of argument name.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000298
Chris Lattner6d5857e2005-05-10 23:20:17 +0000299 if (*ArgEnd == '=') // If we have an equals sign...
300 Value = ArgEnd+1; // Get the value, not the equals
301
Misha Brukmanf976c852005-04-21 22:55:34 +0000302
Chris Lattnerbf455c22004-05-06 22:04:31 +0000303 if (*Arg == 0) return 0;
304
305 // Look up the option.
306 std::map<std::string, Option*> &Opts = getOpts();
307 std::map<std::string, Option*>::iterator I =
308 Opts.find(std::string(Arg, ArgEnd));
309 return (I != Opts.end()) ? I->second : 0;
310}
311
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000312void cl::ParseCommandLineOptions(int &argc, char **argv,
Chris Lattner0c0edf82002-07-25 06:17:51 +0000313 const char *Overview) {
Chris Lattner331de232002-07-22 02:07:59 +0000314 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
315 "No options specified, or ParseCommandLineOptions called more"
316 " than once!");
Reid Spencer6f4c6072006-08-23 07:10:06 +0000317 sys::Path progname(argv[0]);
318 ProgramName = sys::Path(argv[0]).getLast();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000319 ProgramOverview = Overview;
320 bool ErrorParsing = false;
321
Chris Lattnerca6433f2003-05-22 20:06:43 +0000322 std::map<std::string, Option*> &Opts = getOpts();
323 std::vector<Option*> &PositionalOpts = getPositionalOpts();
Chris Lattner331de232002-07-22 02:07:59 +0000324
325 // Check out the positional arguments to collect information about them.
326 unsigned NumPositionalRequired = 0;
Chris Lattnerde013242005-08-08 17:25:38 +0000327
328 // Determine whether or not there are an unlimited number of positionals
329 bool HasUnlimitedPositionals = false;
330
Chris Lattner331de232002-07-22 02:07:59 +0000331 Option *ConsumeAfterOpt = 0;
332 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000333 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000334 assert(PositionalOpts.size() > 1 &&
335 "Cannot specify cl::ConsumeAfter without a positional argument!");
336 ConsumeAfterOpt = PositionalOpts[0];
337 }
338
339 // Calculate how many positional values are _required_.
340 bool UnboundedFound = false;
341 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
342 i != e; ++i) {
343 Option *Opt = PositionalOpts[i];
344 if (RequiresValue(Opt))
345 ++NumPositionalRequired;
346 else if (ConsumeAfterOpt) {
347 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000348 // unless there is only one positional argument...
349 if (PositionalOpts.size() > 2)
350 ErrorParsing |=
351 Opt->error(" error - this positional option will never be matched, "
352 "because it does not Require a value, and a "
353 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000354 } else if (UnboundedFound && !Opt->ArgStr[0]) {
355 // This option does not "require" a value... Make sure this option is
356 // not specified after an option that eats all extra arguments, or this
357 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000358 //
359 ErrorParsing |= Opt->error(" error - option can never match, because "
360 "another positional argument will match an "
361 "unbounded number of values, and this option"
362 " does not require a value!");
363 }
364 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
365 }
Chris Lattner21e1a792005-08-08 21:57:27 +0000366 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000367 }
368
Reid Spencer1e13fd22004-08-13 19:47:30 +0000369 // PositionalVals - A vector of "positional" arguments we accumulate into
370 // the process at the end...
Chris Lattner331de232002-07-22 02:07:59 +0000371 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000372 std::vector<std::pair<std::string,unsigned> > PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000373
Chris Lattner9cf3d472003-07-30 17:34:02 +0000374 // If the program has named positional arguments, and the name has been run
375 // across, keep track of which positional argument was named. Otherwise put
376 // the positional args into the PositionalVals list...
377 Option *ActivePositionalArg = 0;
378
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000379 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000380 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000381 for (int i = 1; i < argc; ++i) {
382 Option *Handler = 0;
Chris Lattner6d5857e2005-05-10 23:20:17 +0000383 const char *Value = 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000384 const char *ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000385
386 // Check to see if this is a positional argument. This argument is
387 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000388 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000389 //
390 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
391 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000392 if (ActivePositionalArg) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000393 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000394 continue; // We are done!
395 } else if (!PositionalOpts.empty()) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000396 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000397
398 // All of the positional arguments have been fulfulled, give the rest to
399 // the consume after option... if it's specified...
400 //
Misha Brukmanf976c852005-04-21 22:55:34 +0000401 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000402 ConsumeAfterOpt != 0) {
403 for (++i; i < argc; ++i)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000404 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000405 break; // Handle outside of the argument processing loop...
406 }
407
408 // Delay processing positional arguments until the end...
409 continue;
410 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000411 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
412 !DashDashFound) {
413 DashDashFound = true; // This is the mythical "--"?
414 continue; // Don't try to process it as an argument itself.
415 } else if (ActivePositionalArg &&
416 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
417 // If there is a positional argument eating options, check to see if this
418 // option is another positional argument. If so, treat it as an argument,
419 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000420 ArgName = argv[i]+1;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000421 Handler = LookupOption(ArgName, Value);
422 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000423 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000424 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000425 }
426
Chris Lattnerbf455c22004-05-06 22:04:31 +0000427 } else { // We start with a '-', must be an argument...
428 ArgName = argv[i]+1;
429 Handler = LookupOption(ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000430
Chris Lattnerbf455c22004-05-06 22:04:31 +0000431 // Check to see if this "option" is really a prefixed or grouped argument.
Reid Spencer5f8448f2004-11-24 06:13:42 +0000432 if (Handler == 0) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000433 std::string RealName(ArgName);
434 if (RealName.size() > 1) {
Chris Lattner331de232002-07-22 02:07:59 +0000435 unsigned Length = 0;
436 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
Misha Brukmanf976c852005-04-21 22:55:34 +0000437
Chris Lattner331de232002-07-22 02:07:59 +0000438 // If the option is a prefixed option, then the value is simply the
439 // rest of the name... so fall through to later processing, by
440 // setting up the argument name flags and value fields.
441 //
442 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000443 Value = ArgName+Length;
444 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
445 Opts.find(std::string(ArgName, Value))->second == PGOpt);
446 Handler = PGOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000447 } else if (PGOpt) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000448 // This must be a grouped option... handle them now.
Chris Lattner331de232002-07-22 02:07:59 +0000449 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000450
Chris Lattner331de232002-07-22 02:07:59 +0000451 do {
452 // Move current arg name out of RealName into RealArgName...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000453 std::string RealArgName(RealName.begin(),
454 RealName.begin() + Length);
455 RealName.erase(RealName.begin(), RealName.begin() + Length);
Misha Brukmanf976c852005-04-21 22:55:34 +0000456
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000457 // Because ValueRequired is an invalid flag for grouped arguments,
458 // we don't need to pass argc/argv in...
459 //
Chris Lattner331de232002-07-22 02:07:59 +0000460 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
461 "Option can not be cl::Grouping AND cl::ValueRequired!");
462 int Dummy;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000463 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
Chris Lattner6d5857e2005-05-10 23:20:17 +0000464 0, 0, 0, Dummy);
Misha Brukmanf976c852005-04-21 22:55:34 +0000465
Chris Lattner331de232002-07-22 02:07:59 +0000466 // Get the next grouping option...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000467 PGOpt = getOptionPred(RealName, Length, isGrouping);
468 } while (PGOpt && Length != RealName.size());
Misha Brukmanf976c852005-04-21 22:55:34 +0000469
Chris Lattnerbf455c22004-05-06 22:04:31 +0000470 Handler = PGOpt; // Ate all of the options.
Chris Lattner331de232002-07-22 02:07:59 +0000471 }
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000472 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000473 }
474 }
475
476 if (Handler == 0) {
Reid Spencer6f4c6072006-08-23 07:10:06 +0000477 std::cerr << ProgramName << ": Unknown command line argument '"
Chris Lattner79959d22006-01-17 00:32:28 +0000478 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000479 ErrorParsing = true;
480 continue;
481 }
482
Chris Lattner72fb8e52003-05-22 20:26:17 +0000483 // Check to see if this option accepts a comma separated list of values. If
484 // it does, we have to split up the value into multiple values...
Chris Lattner6d5857e2005-05-10 23:20:17 +0000485 if (Value && Handler->getMiscFlags() & CommaSeparated) {
Chris Lattner72fb8e52003-05-22 20:26:17 +0000486 std::string Val(Value);
487 std::string::size_type Pos = Val.find(',');
488
489 while (Pos != std::string::npos) {
490 // Process the portion before the comma...
491 ErrorParsing |= ProvideOption(Handler, ArgName,
492 std::string(Val.begin(),
493 Val.begin()+Pos).c_str(),
494 argc, argv, i);
495 // Erase the portion before the comma, AND the comma...
496 Val.erase(Val.begin(), Val.begin()+Pos+1);
497 Value += Pos+1; // Increment the original value pointer as well...
498
499 // Check for another comma...
500 Pos = Val.find(',');
501 }
502 }
Chris Lattner9cf3d472003-07-30 17:34:02 +0000503
504 // If this is a named positional argument, just remember that it is the
505 // active one...
506 if (Handler->getFormattingFlag() == cl::Positional)
507 ActivePositionalArg = Handler;
Misha Brukmanf976c852005-04-21 22:55:34 +0000508 else
Chris Lattner9cf3d472003-07-30 17:34:02 +0000509 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000510 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000511
Chris Lattner331de232002-07-22 02:07:59 +0000512 // Check and handle positional arguments now...
513 if (NumPositionalRequired > PositionalVals.size()) {
Reid Spencer6f4c6072006-08-23 07:10:06 +0000514 std::cerr << ProgramName
515 << ": Not enough positional command line arguments specified!\n"
516 << "Must specify at least " << NumPositionalRequired
517 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattner79959d22006-01-17 00:32:28 +0000518
Chris Lattner331de232002-07-22 02:07:59 +0000519 ErrorParsing = true;
Chris Lattnerde013242005-08-08 17:25:38 +0000520 } else if (!HasUnlimitedPositionals
521 && PositionalVals.size() > PositionalOpts.size()) {
Reid Spencer6f4c6072006-08-23 07:10:06 +0000522 std::cerr << ProgramName
523 << ": Too many positional arguments specified!\n"
524 << "Can specify at most " << PositionalOpts.size()
525 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattnerde013242005-08-08 17:25:38 +0000526 ErrorParsing = true;
Chris Lattner331de232002-07-22 02:07:59 +0000527
528 } else if (ConsumeAfterOpt == 0) {
529 // Positional args have already been handled if ConsumeAfter is specified...
530 unsigned ValNo = 0, NumVals = PositionalVals.size();
531 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
532 if (RequiresValue(PositionalOpts[i])) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000533 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000534 PositionalVals[ValNo].second);
535 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000536 --NumPositionalRequired; // We fulfilled our duty...
537 }
538
539 // If we _can_ give this option more arguments, do so now, as long as we
540 // do not give it values that others need. 'Done' controls whether the
541 // option even _WANTS_ any more.
542 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000543 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000544 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000545 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000546 case cl::Optional:
547 Done = true; // Optional arguments want _at most_ one value
548 // FALL THROUGH
549 case cl::ZeroOrMore: // Zero or more will take all they can get...
550 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer1e13fd22004-08-13 19:47:30 +0000551 ProvidePositionalOption(PositionalOpts[i],
552 PositionalVals[ValNo].first,
553 PositionalVals[ValNo].second);
554 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000555 break;
556 default:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000557 assert(0 && "Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000558 "positional argument processing!");
559 }
560 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000561 }
Chris Lattner331de232002-07-22 02:07:59 +0000562 } else {
563 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
564 unsigned ValNo = 0;
565 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000566 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000567 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000568 PositionalVals[ValNo].first,
569 PositionalVals[ValNo].second);
570 ValNo++;
571 }
Chris Lattnerfaba8092002-07-24 20:15:13 +0000572
573 // Handle the case where there is just one positional option, and it's
574 // optional. In this case, we want to give JUST THE FIRST option to the
575 // positional option and keep the rest for the consume after. The above
576 // loop would have assigned no values to positional options in this case.
577 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000578 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000579 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000580 PositionalVals[ValNo].first,
581 PositionalVals[ValNo].second);
582 ValNo++;
583 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000584
Chris Lattner331de232002-07-22 02:07:59 +0000585 // Handle over all of the rest of the arguments to the
586 // cl::ConsumeAfter command line option...
587 for (; ValNo != PositionalVals.size(); ++ValNo)
588 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000589 PositionalVals[ValNo].first,
590 PositionalVals[ValNo].second);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000591 }
592
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000593 // Loop over args and make sure all required args are specified!
Misha Brukmanf976c852005-04-21 22:55:34 +0000594 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000595 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000596 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000597 case Required:
598 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000599 if (I->second->getNumOccurrences() == 0) {
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000600 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000601 ErrorParsing = true;
602 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000603 // Fall through
604 default:
605 break;
606 }
607 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000608
Chris Lattner331de232002-07-22 02:07:59 +0000609 // Free all of the memory allocated to the map. Command line options may only
610 // be processed once!
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000611 getOpts().clear();
Chris Lattner331de232002-07-22 02:07:59 +0000612 PositionalOpts.clear();
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000613 MoreHelp().clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000614
615 // If we had an error processing our arguments, don't let the program execute
616 if (ErrorParsing) exit(1);
617}
618
619//===----------------------------------------------------------------------===//
620// Option Base class implementation
621//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000622
Chris Lattnerca6433f2003-05-22 20:06:43 +0000623bool Option::error(std::string Message, const char *ArgName) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000624 if (ArgName == 0) ArgName = ArgStr;
Chris Lattner331de232002-07-22 02:07:59 +0000625 if (ArgName[0] == 0)
Chris Lattnerca6433f2003-05-22 20:06:43 +0000626 std::cerr << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000627 else
Reid Spencer6f4c6072006-08-23 07:10:06 +0000628 std::cerr << ProgramName << ": for the -" << ArgName;
Jim Laskeyabe0e3e2006-08-02 20:15:56 +0000629
Reid Spencere1cc1502004-09-01 04:41:28 +0000630 std::cerr << " option: " << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000631 return true;
632}
633
Chris Lattner6d5857e2005-05-10 23:20:17 +0000634bool Option::addOccurrence(unsigned pos, const char *ArgName,
635 const std::string &Value) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000636 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000637
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000638 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000639 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000640 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000641 return error(": may only occur zero or one times!", ArgName);
642 break;
643 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000644 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000645 return error(": must occur exactly one time!", ArgName);
646 // Fall through
647 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000648 case ZeroOrMore:
649 case ConsumeAfter: break;
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000650 default: return error(": bad num occurrences flag value!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000651 }
652
Reid Spencer1e13fd22004-08-13 19:47:30 +0000653 return handleOccurrence(pos, ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000654}
655
Chris Lattner331de232002-07-22 02:07:59 +0000656// addArgument - Tell the system that this Option subclass will handle all
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000657// occurrences of -ArgStr on the command line.
Chris Lattner331de232002-07-22 02:07:59 +0000658//
659void Option::addArgument(const char *ArgStr) {
660 if (ArgStr[0])
661 AddArgument(ArgStr, this);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000662
663 if (getFormattingFlag() == Positional)
Chris Lattner331de232002-07-22 02:07:59 +0000664 getPositionalOpts().push_back(this);
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000665 else if (getNumOccurrencesFlag() == ConsumeAfter) {
Chris Lattner9cf3d472003-07-30 17:34:02 +0000666 if (!getPositionalOpts().empty() &&
667 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
668 error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattner331de232002-07-22 02:07:59 +0000669 getPositionalOpts().insert(getPositionalOpts().begin(), this);
670 }
671}
672
Chris Lattneraa852bb2002-07-23 17:15:12 +0000673void Option::removeArgument(const char *ArgStr) {
Chris Lattner9cf3d472003-07-30 17:34:02 +0000674 if (ArgStr[0])
Chris Lattnere8e258b2002-07-29 20:58:42 +0000675 RemoveArgument(ArgStr, this);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000676
677 if (getFormattingFlag() == Positional) {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000678 std::vector<Option*>::iterator I =
Chris Lattneraa852bb2002-07-23 17:15:12 +0000679 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
680 assert(I != getPositionalOpts().end() && "Arg not registered!");
681 getPositionalOpts().erase(I);
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000682 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
Chris Lattneraa852bb2002-07-23 17:15:12 +0000683 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
684 "Arg not registered correctly!");
685 getPositionalOpts().erase(getPositionalOpts().begin());
686 }
687}
688
Chris Lattner331de232002-07-22 02:07:59 +0000689
690// getValueStr - Get the value description string, using "DefaultMsg" if nothing
691// has been specified yet.
692//
693static const char *getValueStr(const Option &O, const char *DefaultMsg) {
694 if (O.ValueStr[0] == 0) return DefaultMsg;
695 return O.ValueStr;
696}
697
698//===----------------------------------------------------------------------===//
699// cl::alias class implementation
700//
701
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000702// Return the width of the option tag for printing...
Chris Lattner331de232002-07-22 02:07:59 +0000703unsigned alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000704 return std::strlen(ArgStr)+6;
705}
706
Chris Lattnera0de8432006-04-28 05:36:25 +0000707// Print out the option for the alias.
Chris Lattner331de232002-07-22 02:07:59 +0000708void alias::printOptionInfo(unsigned GlobalWidth) const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000709 unsigned L = std::strlen(ArgStr);
Chris Lattnera0de8432006-04-28 05:36:25 +0000710 std::cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
Chris Lattnerca6433f2003-05-22 20:06:43 +0000711 << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000712}
713
714
Chris Lattner331de232002-07-22 02:07:59 +0000715
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000716//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000717// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000718//
719
Chris Lattner9b14eb52002-08-07 18:36:37 +0000720// basic_parser implementation
721//
722
723// Return the width of the option tag for printing...
724unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
725 unsigned Len = std::strlen(O.ArgStr);
726 if (const char *ValName = getValueName())
727 Len += std::strlen(getValueStr(O, ValName))+3;
728
729 return Len + 6;
730}
731
Misha Brukmanf976c852005-04-21 22:55:34 +0000732// printOptionInfo - Print out information about this option. The
Chris Lattner9b14eb52002-08-07 18:36:37 +0000733// to-be-maintained width is specified.
734//
735void basic_parser_impl::printOptionInfo(const Option &O,
736 unsigned GlobalWidth) const {
Chris Lattnera0de8432006-04-28 05:36:25 +0000737 std::cout << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000738
739 if (const char *ValName = getValueName())
Chris Lattnera0de8432006-04-28 05:36:25 +0000740 std::cout << "=<" << getValueStr(O, ValName) << ">";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000741
Chris Lattnera0de8432006-04-28 05:36:25 +0000742 std::cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
Chris Lattnerca6433f2003-05-22 20:06:43 +0000743 << O.HelpStr << "\n";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000744}
745
746
747
748
Chris Lattner331de232002-07-22 02:07:59 +0000749// parser<bool> implementation
750//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000751bool parser<bool>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000752 const std::string &Arg, bool &Value) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000753 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000754 Arg == "1") {
755 Value = true;
756 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
757 Value = false;
758 } else {
Chris Lattner331de232002-07-22 02:07:59 +0000759 return O.error(": '" + Arg +
760 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000761 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000762 return false;
763}
764
Chris Lattner331de232002-07-22 02:07:59 +0000765// parser<int> implementation
766//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000767bool parser<int>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000768 const std::string &Arg, int &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000769 char *End;
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000770 Value = (int)strtol(Arg.c_str(), &End, 0);
Misha Brukmanf976c852005-04-21 22:55:34 +0000771 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000772 return O.error(": '" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000773 return false;
774}
775
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000776// parser<unsigned> implementation
777//
778bool parser<unsigned>::parse(Option &O, const char *ArgName,
779 const std::string &Arg, unsigned &Value) {
780 char *End;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000781 errno = 0;
782 unsigned long V = strtoul(Arg.c_str(), &End, 0);
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000783 Value = (unsigned)V;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000784 if (((V == ULONG_MAX) && (errno == ERANGE))
785 || (*End != 0)
786 || (Value != V))
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000787 return O.error(": '" + Arg + "' value invalid for uint argument!");
788 return false;
789}
790
Chris Lattner9b14eb52002-08-07 18:36:37 +0000791// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +0000792//
Chris Lattnerca6433f2003-05-22 20:06:43 +0000793static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
Chris Lattner331de232002-07-22 02:07:59 +0000794 const char *ArgStart = Arg.c_str();
795 char *End;
796 Value = strtod(ArgStart, &End);
Misha Brukmanf976c852005-04-21 22:55:34 +0000797 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000798 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +0000799 return false;
800}
801
Chris Lattner9b14eb52002-08-07 18:36:37 +0000802bool parser<double>::parse(Option &O, const char *AN,
803 const std::string &Arg, double &Val) {
804 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +0000805}
806
Chris Lattner9b14eb52002-08-07 18:36:37 +0000807bool parser<float>::parse(Option &O, const char *AN,
808 const std::string &Arg, float &Val) {
809 double dVal;
810 if (parseDouble(O, Arg, dVal))
811 return true;
812 Val = (float)dVal;
813 return false;
Chris Lattner331de232002-07-22 02:07:59 +0000814}
815
816
Chris Lattner331de232002-07-22 02:07:59 +0000817
818// generic_parser_base implementation
819//
820
Chris Lattneraa852bb2002-07-23 17:15:12 +0000821// findOption - Return the option number corresponding to the specified
822// argument string. If the option is not found, getNumOptions() is returned.
823//
824unsigned generic_parser_base::findOption(const char *Name) {
825 unsigned i = 0, e = getNumOptions();
Chris Lattnerca6433f2003-05-22 20:06:43 +0000826 std::string N(Name);
Chris Lattneraa852bb2002-07-23 17:15:12 +0000827
828 while (i != e)
829 if (getOption(i) == N)
830 return i;
831 else
832 ++i;
833 return e;
834}
835
836
Chris Lattner331de232002-07-22 02:07:59 +0000837// Return the width of the option tag for printing...
838unsigned generic_parser_base::getOptionWidth(const Option &O) const {
839 if (O.hasArgStr()) {
840 unsigned Size = std::strlen(O.ArgStr)+6;
841 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
842 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
843 return Size;
844 } else {
845 unsigned BaseSize = 0;
846 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
847 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
848 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000849 }
850}
851
Misha Brukmanf976c852005-04-21 22:55:34 +0000852// printOptionInfo - Print out information about this option. The
Chris Lattner331de232002-07-22 02:07:59 +0000853// to-be-maintained width is specified.
854//
855void generic_parser_base::printOptionInfo(const Option &O,
856 unsigned GlobalWidth) const {
857 if (O.hasArgStr()) {
858 unsigned L = std::strlen(O.ArgStr);
Chris Lattnera0de8432006-04-28 05:36:25 +0000859 std::cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
Chris Lattnerca6433f2003-05-22 20:06:43 +0000860 << " - " << O.HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000861
Chris Lattner331de232002-07-22 02:07:59 +0000862 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
863 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnera0de8432006-04-28 05:36:25 +0000864 std::cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
Chris Lattnerca6433f2003-05-22 20:06:43 +0000865 << " - " << getDescription(i) << "\n";
Chris Lattner9c9be482002-01-31 00:42:56 +0000866 }
Chris Lattner331de232002-07-22 02:07:59 +0000867 } else {
868 if (O.HelpStr[0])
Chris Lattnera0de8432006-04-28 05:36:25 +0000869 std::cout << " " << O.HelpStr << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000870 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
871 unsigned L = std::strlen(getOption(i));
Chris Lattnera0de8432006-04-28 05:36:25 +0000872 std::cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
Chris Lattnerca6433f2003-05-22 20:06:43 +0000873 << " - " << getDescription(i) << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000874 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000875 }
876}
877
878
879//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000880// --help and --help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000881//
Reid Spencerad0846b2004-11-14 22:04:00 +0000882
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000883namespace {
884
Chris Lattner331de232002-07-22 02:07:59 +0000885class HelpPrinter {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000886 unsigned MaxArgLen;
887 const Option *EmptyArg;
888 const bool ShowHidden;
889
Chris Lattner331de232002-07-22 02:07:59 +0000890 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
Chris Lattnerca6433f2003-05-22 20:06:43 +0000891 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000892 return OptPair.second->getOptionHiddenFlag() >= Hidden;
893 }
Chris Lattnerca6433f2003-05-22 20:06:43 +0000894 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000895 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
896 }
897
898public:
899 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
900 EmptyArg = 0;
901 }
902
903 void operator=(bool Value) {
904 if (Value == false) return;
905
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000906 // Copy Options into a vector so we can sort them as we like...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000907 std::vector<std::pair<std::string, Option*> > Options;
Chris Lattner697954c2002-01-20 22:54:45 +0000908 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000909
910 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Misha Brukmanf976c852005-04-21 22:55:34 +0000911 Options.erase(std::remove_if(Options.begin(), Options.end(),
Chris Lattner331de232002-07-22 02:07:59 +0000912 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000913 Options.end());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000914
915 // Eliminate duplicate entries in table (from enum flags options, f.e.)
Chris Lattner331de232002-07-22 02:07:59 +0000916 { // Give OptionSet a scope
917 std::set<Option*> OptionSet;
918 for (unsigned i = 0; i != Options.size(); ++i)
919 if (OptionSet.count(Options[i].second) == 0)
920 OptionSet.insert(Options[i].second); // Add new entry to set
921 else
922 Options.erase(Options.begin()+i--); // Erase duplicate
923 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000924
925 if (ProgramOverview)
Chris Lattnera0de8432006-04-28 05:36:25 +0000926 std::cout << "OVERVIEW:" << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000927
Chris Lattnera0de8432006-04-28 05:36:25 +0000928 std::cout << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +0000929
930 // Print out the positional options...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000931 std::vector<Option*> &PosOpts = getPositionalOpts();
Chris Lattner331de232002-07-22 02:07:59 +0000932 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000933 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
Chris Lattner331de232002-07-22 02:07:59 +0000934 CAOpt = PosOpts[0];
935
Chris Lattner9cf3d472003-07-30 17:34:02 +0000936 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
937 if (PosOpts[i]->ArgStr[0])
Chris Lattnera0de8432006-04-28 05:36:25 +0000938 std::cout << " --" << PosOpts[i]->ArgStr;
939 std::cout << " " << PosOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000940 }
Chris Lattner331de232002-07-22 02:07:59 +0000941
942 // Print the consume after option info if it exists...
Chris Lattnera0de8432006-04-28 05:36:25 +0000943 if (CAOpt) std::cout << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +0000944
Chris Lattnera0de8432006-04-28 05:36:25 +0000945 std::cout << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000946
947 // Compute the maximum argument length...
948 MaxArgLen = 0;
Chris Lattner331de232002-07-22 02:07:59 +0000949 for (unsigned i = 0, e = Options.size(); i != e; ++i)
950 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000951
Chris Lattnera0de8432006-04-28 05:36:25 +0000952 std::cout << "OPTIONS:\n";
Chris Lattner331de232002-07-22 02:07:59 +0000953 for (unsigned i = 0, e = Options.size(); i != e; ++i)
954 Options[i].second->printOptionInfo(MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000955
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000956 // Print any extra help the user has declared.
957 for (std::vector<const char *>::iterator I = MoreHelp().begin(),
958 E = MoreHelp().end(); I != E; ++I)
Chris Lattnera0de8432006-04-28 05:36:25 +0000959 std::cout << *I;
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000960 MoreHelp().clear();
Reid Spencerad0846b2004-11-14 22:04:00 +0000961
Reid Spencer9bbba0912004-11-16 06:11:52 +0000962 // Halt the program since help information was printed
Chris Lattnera92d12c2005-02-14 19:17:29 +0000963 getOpts().clear(); // Don't bother making option dtors remove from map.
Chris Lattner331de232002-07-22 02:07:59 +0000964 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000965 }
966};
967
Chris Lattner331de232002-07-22 02:07:59 +0000968// Define the two HelpPrinter instances that are used to print out help, or
969// help-hidden...
970//
971HelpPrinter NormalPrinter(false);
972HelpPrinter HiddenPrinter(true);
973
Misha Brukmanf976c852005-04-21 22:55:34 +0000974cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +0000975HOp("help", cl::desc("Display available options (--help-hidden for more)"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000976 cl::location(NormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +0000977
978cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +0000979HHOp("help-hidden", cl::desc("Display all available options"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000980 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000981
Reid Spencer515b5b32006-06-05 16:22:56 +0000982void (*OverrideVersionPrinter)() = 0;
983
984class VersionPrinter {
985public:
986 void operator=(bool OptionWasSpecified) {
987 if (OptionWasSpecified) {
988 if (OverrideVersionPrinter == 0) {
Chris Lattner3fc2f4e2006-07-06 18:33:03 +0000989 std::cout << "Low Level Virtual Machine (http://llvm.org/):\n";
990 std::cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
991#ifdef LLVM_VERSION_INFO
992 std::cout << LLVM_VERSION_INFO;
Reid Spencer515b5b32006-06-05 16:22:56 +0000993#endif
Chris Lattner3fc2f4e2006-07-06 18:33:03 +0000994 std::cout << "\n ";
995#ifndef __OPTIMIZE__
996 std::cout << "DEBUG build";
997#else
998 std::cout << "Optimized build";
999#endif
1000#ifndef NDEBUG
1001 std::cout << " with assertions";
1002#endif
1003 std::cout << ".\n";
Reid Spencer515b5b32006-06-05 16:22:56 +00001004 getOpts().clear(); // Don't bother making option dtors remove from map.
1005 exit(1);
1006 } else {
1007 (*OverrideVersionPrinter)();
1008 exit(1);
1009 }
1010 }
1011 }
1012};
1013
1014
Reid Spencer69105f32004-08-04 00:36:06 +00001015// Define the --version option that prints out the LLVM version for the tool
1016VersionPrinter VersionPrinterInstance;
1017cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001018VersOp("version", cl::desc("Display the version of this program"),
Reid Spencer69105f32004-08-04 00:36:06 +00001019 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1020
Reid Spencer9bbba0912004-11-16 06:11:52 +00001021
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001022} // End anonymous namespace
Reid Spencer9bbba0912004-11-16 06:11:52 +00001023
1024// Utility function for printing the help message.
1025void cl::PrintHelpMessage() {
Misha Brukmanf976c852005-04-21 22:55:34 +00001026 // This looks weird, but it actually prints the help message. The
Reid Spencer5cc498f2004-11-16 06:50:36 +00001027 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1028 // its operator= is invoked. That's because the "normal" usages of the
Misha Brukmanf976c852005-04-21 22:55:34 +00001029 // help printer is to be assigned true/false depending on whether the
Reid Spencer5cc498f2004-11-16 06:50:36 +00001030 // --help option was given or not. Since we're circumventing that we have
1031 // to make it look like --help was given, so we assign true.
Reid Spencer9bbba0912004-11-16 06:11:52 +00001032 NormalPrinter = true;
1033}
Reid Spencer515b5b32006-06-05 16:22:56 +00001034
1035void cl::SetVersionPrinter(void (*func)()) {
1036 OverrideVersionPrinter = func;
1037}