blob: 768bd6c05b6cf9aeca4e6290a5e5f2d63ea295ea [file] [log] [blame]
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerdbab15a2001-07-23 17:17:47 +00009//
10// This class implements a command line argument processor that is useful when
11// creating a tool. It provides a simple, minimalistic interface that is easily
12// extensible and supports nonlocal (library) command line options.
13//
Chris Lattner03fe1bd2001-07-23 23:04:07 +000014// Note that rather than trying to figure out what this code does, you could try
15// reading the library documentation located in docs/CommandLine.html
16//
Chris Lattnerdbab15a2001-07-23 17:17:47 +000017//===----------------------------------------------------------------------===//
18
Reid Spencer551ccae2004-09-01 22:55:40 +000019#include "llvm/Config/config.h"
20#include "llvm/Support/CommandLine.h"
Chris Lattner90aa8392006-10-04 21:52:35 +000021#include "llvm/Support/ManagedStatic.h"
Bill Wendlingfe6b1462006-11-26 10:52:51 +000022#include "llvm/Support/Streams.h"
Reid Spencer6f4c6072006-08-23 07:10:06 +000023#include "llvm/System/Path.h"
Chris Lattnerdbab15a2001-07-23 17:17:47 +000024#include <algorithm>
Duraid Madina786e3e22005-12-26 04:56:16 +000025#include <functional>
Chris Lattnerdbab15a2001-07-23 17:17:47 +000026#include <map>
Bill Wendling1a097e32006-12-07 23:41:45 +000027#include <ostream>
Chris Lattnerdbab15a2001-07-23 17:17:47 +000028#include <set>
Brian Gaeke2d6a2362003-10-10 17:01:36 +000029#include <cstdlib>
30#include <cerrno>
Chris Lattner51140042004-07-03 01:21:05 +000031#include <cstring>
Chris Lattner2cdd21c2003-12-14 21:35:53 +000032using namespace llvm;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000033using namespace cl;
34
Chris Lattner7422a762006-08-27 12:45:47 +000035//===----------------------------------------------------------------------===//
36// Template instantiations and anchors.
37//
38TEMPLATE_INSTANTIATION(class basic_parser<bool>);
39TEMPLATE_INSTANTIATION(class basic_parser<int>);
40TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
41TEMPLATE_INSTANTIATION(class basic_parser<double>);
42TEMPLATE_INSTANTIATION(class basic_parser<float>);
43TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
44
45TEMPLATE_INSTANTIATION(class opt<unsigned>);
46TEMPLATE_INSTANTIATION(class opt<int>);
47TEMPLATE_INSTANTIATION(class opt<std::string>);
48TEMPLATE_INSTANTIATION(class opt<bool>);
49
50void Option::anchor() {}
51void basic_parser_impl::anchor() {}
52void parser<bool>::anchor() {}
53void parser<int>::anchor() {}
54void parser<unsigned>::anchor() {}
55void parser<double>::anchor() {}
56void parser<float>::anchor() {}
57void parser<std::string>::anchor() {}
58
59//===----------------------------------------------------------------------===//
60
Chris Lattnerefa3da52006-10-13 00:06:24 +000061// Globals for name and overview of program. Program name is not a string to
62// avoid static ctor/dtor issues.
63static char ProgramName[80] = "<premain>";
Reid Spencere1cc1502004-09-01 04:41:28 +000064static const char *ProgramOverview = 0;
65
Chris Lattnerc540ebb2004-11-19 17:08:15 +000066// This collects additional help to be printed.
Chris Lattner90aa8392006-10-04 21:52:35 +000067static ManagedStatic<std::vector<const char*> > MoreHelp;
Chris Lattnerc540ebb2004-11-19 17:08:15 +000068
Chris Lattner90aa8392006-10-04 21:52:35 +000069extrahelp::extrahelp(const char *Help)
Chris Lattnerc540ebb2004-11-19 17:08:15 +000070 : morehelp(Help) {
Chris Lattner90aa8392006-10-04 21:52:35 +000071 MoreHelp->push_back(Help);
Chris Lattnerc540ebb2004-11-19 17:08:15 +000072}
73
Chris Lattner9878d6a2007-04-06 21:06:55 +000074/// RegisteredOptionList - This is the list of the command line options that
75/// have statically constructed themselves.
76static Option *RegisteredOptionList = 0;
77
78void Option::addArgument() {
79 assert(NextRegistered == 0 && "argument multiply registered!");
80
81 NextRegistered = RegisteredOptionList;
82 RegisteredOptionList = this;
83}
84
Chris Lattner331de232002-07-22 02:07:59 +000085//===----------------------------------------------------------------------===//
Chris Lattner7422a762006-08-27 12:45:47 +000086// Basic, shared command line option processing machinery.
Chris Lattner331de232002-07-22 02:07:59 +000087//
88
Chris Lattner9878d6a2007-04-06 21:06:55 +000089/// GetOptionInfo - Scan the list of registered options, turning them into data
90/// structures that are easier to handle.
91static void GetOptionInfo(std::vector<Option*> &PositionalOpts,
92 std::map<std::string, Option*> &OptionsMap) {
93 std::vector<const char*> OptionNames;
Chris Lattneree2b3202007-04-07 05:38:53 +000094 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
Chris Lattner9878d6a2007-04-06 21:06:55 +000095 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
96 // If this option wants to handle multiple option names, get the full set.
97 // This handles enum options like "-O1 -O2" etc.
98 O->getExtraOptionNames(OptionNames);
99 if (O->ArgStr[0])
100 OptionNames.push_back(O->ArgStr);
101
102 // Handle named options.
103 for (unsigned i = 0, e = OptionNames.size(); i != e; ++i) {
104 // Add argument to the argument map!
105 if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i],
106 O)).second) {
107 cerr << ProgramName << ": CommandLine Error: Argument '"
108 << OptionNames[0] << "' defined more than once!\n";
109 }
110 }
111
112 OptionNames.clear();
113
114 // Remember information about positional options.
115 if (O->getFormattingFlag() == cl::Positional)
116 PositionalOpts.push_back(O);
117 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattneree2b3202007-04-07 05:38:53 +0000118 if (CAOpt)
Chris Lattner9878d6a2007-04-06 21:06:55 +0000119 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattneree2b3202007-04-07 05:38:53 +0000120 CAOpt = O;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000121 }
Chris Lattnere8e258b2002-07-29 20:58:42 +0000122 }
Chris Lattneree2b3202007-04-07 05:38:53 +0000123
124 if (CAOpt)
125 PositionalOpts.push_back(CAOpt);
126
127 // Make sure that they are in order of registration not backwards.
128 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
Chris Lattnere8e258b2002-07-29 20:58:42 +0000129}
130
Chris Lattner9878d6a2007-04-06 21:06:55 +0000131
Chris Lattneraf035f32007-04-05 21:58:17 +0000132/// LookupOption - Lookup the option specified by the specified option on the
133/// command line. If there is a value specified (after an equal sign) return
134/// that as well.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000135static Option *LookupOption(const char *&Arg, const char *&Value,
136 std::map<std::string, Option*> &OptionsMap) {
Chris Lattneraf035f32007-04-05 21:58:17 +0000137 while (*Arg == '-') ++Arg; // Eat leading dashes
138
139 const char *ArgEnd = Arg;
140 while (*ArgEnd && *ArgEnd != '=')
141 ++ArgEnd; // Scan till end of argument name.
142
143 if (*ArgEnd == '=') // If we have an equals sign...
144 Value = ArgEnd+1; // Get the value, not the equals
145
146
147 if (*Arg == 0) return 0;
148
149 // Look up the option.
Chris Lattneraf035f32007-04-05 21:58:17 +0000150 std::map<std::string, Option*>::iterator I =
Chris Lattner9878d6a2007-04-06 21:06:55 +0000151 OptionsMap.find(std::string(Arg, ArgEnd));
152 return I != OptionsMap.end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000153}
154
Chris Lattnercaccd762001-10-27 05:54:17 +0000155static inline bool ProvideOption(Option *Handler, const char *ArgName,
156 const char *Value, int argc, char **argv,
157 int &i) {
158 // Enforce value requirements
159 switch (Handler->getValueExpectedFlag()) {
160 case ValueRequired:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000161 if (Value == 0) { // No value specified?
Chris Lattnercaccd762001-10-27 05:54:17 +0000162 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
163 Value = argv[++i];
164 } else {
165 return Handler->error(" requires a value!");
166 }
167 }
168 break;
169 case ValueDisallowed:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000170 if (Value)
Misha Brukmanf976c852005-04-21 22:55:34 +0000171 return Handler->error(" does not allow a value! '" +
Chris Lattnerca6433f2003-05-22 20:06:43 +0000172 std::string(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +0000173 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000174 case ValueOptional:
Reid Spencere1cc1502004-09-01 04:41:28 +0000175 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000176 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000177 cerr << ProgramName
178 << ": Bad ValueMask flag! CommandLine usage error:"
179 << Handler->getValueExpectedFlag() << "\n";
Reid Spencere1cc1502004-09-01 04:41:28 +0000180 abort();
181 break;
Chris Lattnercaccd762001-10-27 05:54:17 +0000182 }
183
184 // Run the handler now!
Chris Lattner6d5857e2005-05-10 23:20:17 +0000185 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
Chris Lattnercaccd762001-10-27 05:54:17 +0000186}
187
Misha Brukmanf976c852005-04-21 22:55:34 +0000188static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000189 int i) {
190 int Dummy = i;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000191 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000192}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000193
Chris Lattner331de232002-07-22 02:07:59 +0000194
195// Option predicates...
196static inline bool isGrouping(const Option *O) {
197 return O->getFormattingFlag() == cl::Grouping;
198}
199static inline bool isPrefixedOrGrouping(const Option *O) {
200 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
201}
202
203// getOptionPred - Check to see if there are any options that satisfy the
204// specified predicate with names that are the prefixes in Name. This is
205// checked by progressively stripping characters off of the name, checking to
206// see if there options that satisfy the predicate. If we find one, return it,
207// otherwise return null.
208//
209static Option *getOptionPred(std::string Name, unsigned &Length,
Chris Lattner9878d6a2007-04-06 21:06:55 +0000210 bool (*Pred)(const Option*),
211 std::map<std::string, Option*> &OptionsMap) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000212
Chris Lattner9878d6a2007-04-06 21:06:55 +0000213 std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name);
214 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner331de232002-07-22 02:07:59 +0000215 Length = Name.length();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000216 return OMI->second;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000217 }
218
Chris Lattner331de232002-07-22 02:07:59 +0000219 if (Name.size() == 1) return 0;
220 do {
221 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000222 OMI = OptionsMap.find(Name);
Chris Lattner331de232002-07-22 02:07:59 +0000223
224 // Loop while we haven't found an option and Name still has at least two
225 // characters in it (so that the next iteration will not be the empty
226 // string...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000227 } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1);
Chris Lattner331de232002-07-22 02:07:59 +0000228
Chris Lattner9878d6a2007-04-06 21:06:55 +0000229 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner331de232002-07-22 02:07:59 +0000230 Length = Name.length();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000231 return OMI->second; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000232 }
233 return 0; // No option found!
234}
235
236static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000237 return O->getNumOccurrencesFlag() == cl::Required ||
238 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000239}
240
241static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000242 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
243 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000244}
Chris Lattnercaccd762001-10-27 05:54:17 +0000245
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000246/// ParseCStringVector - Break INPUT up wherever one or more
247/// whitespace characters are found, and store the resulting tokens in
248/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
249/// using strdup (), so it is the caller's responsibility to free ()
250/// them later.
Brian Gaeke06b06c52003-08-14 22:00:59 +0000251///
Chris Lattner23288582006-08-27 22:10:29 +0000252static void ParseCStringVector(std::vector<char *> &output,
253 const char *input) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000254 // Characters which will be treated as token separators:
255 static const char *delims = " \v\f\t\r\n";
256
257 std::string work (input);
258 // Skip past any delims at head of input string.
259 size_t pos = work.find_first_not_of (delims);
260 // If the string consists entirely of delims, then exit early.
261 if (pos == std::string::npos) return;
262 // Otherwise, jump forward to beginning of first word.
263 work = work.substr (pos);
264 // Find position of first delimiter.
265 pos = work.find_first_of (delims);
266
267 while (!work.empty() && pos != std::string::npos) {
268 // Everything from 0 to POS is the next word to copy.
269 output.push_back (strdup (work.substr (0,pos).c_str ()));
270 // Is there another word in the string?
271 size_t nextpos = work.find_first_not_of (delims, pos + 1);
272 if (nextpos != std::string::npos) {
273 // Yes? Then remove delims from beginning ...
274 work = work.substr (work.find_first_not_of (delims, pos + 1));
275 // and find the end of the word.
276 pos = work.find_first_of (delims);
277 } else {
278 // No? (Remainder of string is delims.) End the loop.
279 work = "";
280 pos = std::string::npos;
281 }
282 }
283
284 // If `input' ended with non-delim char, then we'll get here with
285 // the last word of `input' in `work'; copy it now.
286 if (!work.empty ()) {
287 output.push_back (strdup (work.c_str ()));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000288 }
289}
290
291/// ParseEnvironmentOptions - An alternative entry point to the
292/// CommandLine library, which allows you to read the program's name
293/// from the caller (as PROGNAME) and its command-line arguments from
294/// an environment variable (whose name is given in ENVVAR).
295///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000296void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
297 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000298 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000299 assert(progName && "Program name not specified");
300 assert(envVar && "Environment variable name missing");
Misha Brukmanf976c852005-04-21 22:55:34 +0000301
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000302 // Get the environment variable they want us to parse options out of.
Chris Lattner23288582006-08-27 22:10:29 +0000303 const char *envValue = getenv(envVar);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000304 if (!envValue)
305 return;
306
Brian Gaeke06b06c52003-08-14 22:00:59 +0000307 // Get program's "name", which we wouldn't know without the caller
308 // telling us.
Chris Lattner23288582006-08-27 22:10:29 +0000309 std::vector<char*> newArgv;
310 newArgv.push_back(strdup(progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000311
312 // Parse the value of the environment variable into a "command line"
313 // and hand it off to ParseCommandLineOptions().
Chris Lattner23288582006-08-27 22:10:29 +0000314 ParseCStringVector(newArgv, envValue);
315 int newArgc = newArgv.size();
316 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000317
318 // Free all the strdup()ed strings.
Chris Lattner23288582006-08-27 22:10:29 +0000319 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
320 i != e; ++i)
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000321 free (*i);
Brian Gaeke06b06c52003-08-14 22:00:59 +0000322}
323
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000324void cl::ParseCommandLineOptions(int &argc, char **argv,
Chris Lattner0c0edf82002-07-25 06:17:51 +0000325 const char *Overview) {
Chris Lattner9878d6a2007-04-06 21:06:55 +0000326 // Process all registered options.
327 std::vector<Option*> PositionalOpts;
328 std::map<std::string, Option*> Opts;
329 GetOptionInfo(PositionalOpts, Opts);
330
331 assert((!Opts.empty() || !PositionalOpts.empty()) &&
332 "No options specified!");
Reid Spencer6f4c6072006-08-23 07:10:06 +0000333 sys::Path progname(argv[0]);
Chris Lattnerefa3da52006-10-13 00:06:24 +0000334
335 // Copy the program name into ProgName, making sure not to overflow it.
336 std::string ProgName = sys::Path(argv[0]).getLast();
337 if (ProgName.size() > 79) ProgName.resize(79);
338 strcpy(ProgramName, ProgName.c_str());
339
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000340 ProgramOverview = Overview;
341 bool ErrorParsing = false;
342
Chris Lattner331de232002-07-22 02:07:59 +0000343 // Check out the positional arguments to collect information about them.
344 unsigned NumPositionalRequired = 0;
Chris Lattnerde013242005-08-08 17:25:38 +0000345
346 // Determine whether or not there are an unlimited number of positionals
347 bool HasUnlimitedPositionals = false;
348
Chris Lattner331de232002-07-22 02:07:59 +0000349 Option *ConsumeAfterOpt = 0;
350 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000351 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000352 assert(PositionalOpts.size() > 1 &&
353 "Cannot specify cl::ConsumeAfter without a positional argument!");
354 ConsumeAfterOpt = PositionalOpts[0];
355 }
356
357 // Calculate how many positional values are _required_.
358 bool UnboundedFound = false;
359 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
360 i != e; ++i) {
361 Option *Opt = PositionalOpts[i];
362 if (RequiresValue(Opt))
363 ++NumPositionalRequired;
364 else if (ConsumeAfterOpt) {
365 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000366 // unless there is only one positional argument...
367 if (PositionalOpts.size() > 2)
368 ErrorParsing |=
369 Opt->error(" error - this positional option will never be matched, "
370 "because it does not Require a value, and a "
371 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000372 } else if (UnboundedFound && !Opt->ArgStr[0]) {
373 // This option does not "require" a value... Make sure this option is
374 // not specified after an option that eats all extra arguments, or this
375 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000376 //
377 ErrorParsing |= Opt->error(" error - option can never match, because "
378 "another positional argument will match an "
379 "unbounded number of values, and this option"
380 " does not require a value!");
381 }
382 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
383 }
Chris Lattner21e1a792005-08-08 21:57:27 +0000384 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000385 }
386
Reid Spencer1e13fd22004-08-13 19:47:30 +0000387 // PositionalVals - A vector of "positional" arguments we accumulate into
388 // the process at the end...
Chris Lattner331de232002-07-22 02:07:59 +0000389 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000390 std::vector<std::pair<std::string,unsigned> > PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000391
Chris Lattner9cf3d472003-07-30 17:34:02 +0000392 // If the program has named positional arguments, and the name has been run
393 // across, keep track of which positional argument was named. Otherwise put
394 // the positional args into the PositionalVals list...
395 Option *ActivePositionalArg = 0;
396
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000397 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000398 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000399 for (int i = 1; i < argc; ++i) {
400 Option *Handler = 0;
Chris Lattner6d5857e2005-05-10 23:20:17 +0000401 const char *Value = 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000402 const char *ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000403
404 // Check to see if this is a positional argument. This argument is
405 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000406 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000407 //
408 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
409 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000410 if (ActivePositionalArg) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000411 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000412 continue; // We are done!
413 } else if (!PositionalOpts.empty()) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000414 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000415
416 // All of the positional arguments have been fulfulled, give the rest to
417 // the consume after option... if it's specified...
418 //
Misha Brukmanf976c852005-04-21 22:55:34 +0000419 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000420 ConsumeAfterOpt != 0) {
421 for (++i; i < argc; ++i)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000422 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000423 break; // Handle outside of the argument processing loop...
424 }
425
426 // Delay processing positional arguments until the end...
427 continue;
428 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000429 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
430 !DashDashFound) {
431 DashDashFound = true; // This is the mythical "--"?
432 continue; // Don't try to process it as an argument itself.
433 } else if (ActivePositionalArg &&
434 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
435 // If there is a positional argument eating options, check to see if this
436 // option is another positional argument. If so, treat it as an argument,
437 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000438 ArgName = argv[i]+1;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000439 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000440 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000441 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000442 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000443 }
444
Chris Lattnerbf455c22004-05-06 22:04:31 +0000445 } else { // We start with a '-', must be an argument...
446 ArgName = argv[i]+1;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000447 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000448
Chris Lattnerbf455c22004-05-06 22:04:31 +0000449 // Check to see if this "option" is really a prefixed or grouped argument.
Reid Spencer5f8448f2004-11-24 06:13:42 +0000450 if (Handler == 0) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000451 std::string RealName(ArgName);
452 if (RealName.size() > 1) {
Chris Lattner331de232002-07-22 02:07:59 +0000453 unsigned Length = 0;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000454 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping,
455 Opts);
Misha Brukmanf976c852005-04-21 22:55:34 +0000456
Chris Lattner331de232002-07-22 02:07:59 +0000457 // If the option is a prefixed option, then the value is simply the
458 // rest of the name... so fall through to later processing, by
459 // setting up the argument name flags and value fields.
460 //
461 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000462 Value = ArgName+Length;
463 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
464 Opts.find(std::string(ArgName, Value))->second == PGOpt);
465 Handler = PGOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000466 } else if (PGOpt) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000467 // This must be a grouped option... handle them now.
Chris Lattner331de232002-07-22 02:07:59 +0000468 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000469
Chris Lattner331de232002-07-22 02:07:59 +0000470 do {
471 // Move current arg name out of RealName into RealArgName...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000472 std::string RealArgName(RealName.begin(),
473 RealName.begin() + Length);
474 RealName.erase(RealName.begin(), RealName.begin() + Length);
Misha Brukmanf976c852005-04-21 22:55:34 +0000475
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000476 // Because ValueRequired is an invalid flag for grouped arguments,
477 // we don't need to pass argc/argv in...
478 //
Chris Lattner331de232002-07-22 02:07:59 +0000479 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
480 "Option can not be cl::Grouping AND cl::ValueRequired!");
481 int Dummy;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000482 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
Chris Lattner6d5857e2005-05-10 23:20:17 +0000483 0, 0, 0, Dummy);
Misha Brukmanf976c852005-04-21 22:55:34 +0000484
Chris Lattner331de232002-07-22 02:07:59 +0000485 // Get the next grouping option...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000486 PGOpt = getOptionPred(RealName, Length, isGrouping, Opts);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000487 } while (PGOpt && Length != RealName.size());
Misha Brukmanf976c852005-04-21 22:55:34 +0000488
Chris Lattnerbf455c22004-05-06 22:04:31 +0000489 Handler = PGOpt; // Ate all of the options.
Chris Lattner331de232002-07-22 02:07:59 +0000490 }
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000491 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000492 }
493 }
494
495 if (Handler == 0) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000496 cerr << ProgramName << ": Unknown command line argument '"
497 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000498 ErrorParsing = true;
499 continue;
500 }
501
Chris Lattner72fb8e52003-05-22 20:26:17 +0000502 // Check to see if this option accepts a comma separated list of values. If
503 // it does, we have to split up the value into multiple values...
Chris Lattner6d5857e2005-05-10 23:20:17 +0000504 if (Value && Handler->getMiscFlags() & CommaSeparated) {
Chris Lattner72fb8e52003-05-22 20:26:17 +0000505 std::string Val(Value);
506 std::string::size_type Pos = Val.find(',');
507
508 while (Pos != std::string::npos) {
509 // Process the portion before the comma...
510 ErrorParsing |= ProvideOption(Handler, ArgName,
511 std::string(Val.begin(),
512 Val.begin()+Pos).c_str(),
513 argc, argv, i);
514 // Erase the portion before the comma, AND the comma...
515 Val.erase(Val.begin(), Val.begin()+Pos+1);
516 Value += Pos+1; // Increment the original value pointer as well...
517
518 // Check for another comma...
519 Pos = Val.find(',');
520 }
521 }
Chris Lattner9cf3d472003-07-30 17:34:02 +0000522
523 // If this is a named positional argument, just remember that it is the
524 // active one...
525 if (Handler->getFormattingFlag() == cl::Positional)
526 ActivePositionalArg = Handler;
Misha Brukmanf976c852005-04-21 22:55:34 +0000527 else
Chris Lattner9cf3d472003-07-30 17:34:02 +0000528 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000529 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000530
Chris Lattner331de232002-07-22 02:07:59 +0000531 // Check and handle positional arguments now...
532 if (NumPositionalRequired > PositionalVals.size()) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000533 cerr << ProgramName
534 << ": Not enough positional command line arguments specified!\n"
535 << "Must specify at least " << NumPositionalRequired
536 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattner79959d22006-01-17 00:32:28 +0000537
Chris Lattner331de232002-07-22 02:07:59 +0000538 ErrorParsing = true;
Chris Lattnerde013242005-08-08 17:25:38 +0000539 } else if (!HasUnlimitedPositionals
540 && PositionalVals.size() > PositionalOpts.size()) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000541 cerr << ProgramName
542 << ": Too many positional arguments specified!\n"
543 << "Can specify at most " << PositionalOpts.size()
544 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattnerde013242005-08-08 17:25:38 +0000545 ErrorParsing = true;
Chris Lattner331de232002-07-22 02:07:59 +0000546
547 } else if (ConsumeAfterOpt == 0) {
548 // Positional args have already been handled if ConsumeAfter is specified...
549 unsigned ValNo = 0, NumVals = PositionalVals.size();
550 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
551 if (RequiresValue(PositionalOpts[i])) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000552 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000553 PositionalVals[ValNo].second);
554 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000555 --NumPositionalRequired; // We fulfilled our duty...
556 }
557
558 // If we _can_ give this option more arguments, do so now, as long as we
559 // do not give it values that others need. 'Done' controls whether the
560 // option even _WANTS_ any more.
561 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000562 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000563 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000564 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000565 case cl::Optional:
566 Done = true; // Optional arguments want _at most_ one value
567 // FALL THROUGH
568 case cl::ZeroOrMore: // Zero or more will take all they can get...
569 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer1e13fd22004-08-13 19:47:30 +0000570 ProvidePositionalOption(PositionalOpts[i],
571 PositionalVals[ValNo].first,
572 PositionalVals[ValNo].second);
573 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000574 break;
575 default:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000576 assert(0 && "Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000577 "positional argument processing!");
578 }
579 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000580 }
Chris Lattner331de232002-07-22 02:07:59 +0000581 } else {
582 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
583 unsigned ValNo = 0;
584 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000585 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000586 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000587 PositionalVals[ValNo].first,
588 PositionalVals[ValNo].second);
589 ValNo++;
590 }
Chris Lattnerfaba8092002-07-24 20:15:13 +0000591
592 // Handle the case where there is just one positional option, and it's
593 // optional. In this case, we want to give JUST THE FIRST option to the
594 // positional option and keep the rest for the consume after. The above
595 // loop would have assigned no values to positional options in this case.
596 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000597 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000598 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000599 PositionalVals[ValNo].first,
600 PositionalVals[ValNo].second);
601 ValNo++;
602 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000603
Chris Lattner331de232002-07-22 02:07:59 +0000604 // Handle over all of the rest of the arguments to the
605 // cl::ConsumeAfter command line option...
606 for (; ValNo != PositionalVals.size(); ++ValNo)
607 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000608 PositionalVals[ValNo].first,
609 PositionalVals[ValNo].second);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000610 }
611
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000612 // Loop over args and make sure all required args are specified!
Misha Brukmanf976c852005-04-21 22:55:34 +0000613 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000614 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000615 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000616 case Required:
617 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000618 if (I->second->getNumOccurrences() == 0) {
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000619 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000620 ErrorParsing = true;
621 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000622 // Fall through
623 default:
624 break;
625 }
626 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000627
Chris Lattner331de232002-07-22 02:07:59 +0000628 // Free all of the memory allocated to the map. Command line options may only
629 // be processed once!
Chris Lattner90aa8392006-10-04 21:52:35 +0000630 Opts.clear();
Chris Lattner331de232002-07-22 02:07:59 +0000631 PositionalOpts.clear();
Chris Lattner90aa8392006-10-04 21:52:35 +0000632 MoreHelp->clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000633
634 // If we had an error processing our arguments, don't let the program execute
635 if (ErrorParsing) exit(1);
636}
637
638//===----------------------------------------------------------------------===//
639// Option Base class implementation
640//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000641
Chris Lattnerca6433f2003-05-22 20:06:43 +0000642bool Option::error(std::string Message, const char *ArgName) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000643 if (ArgName == 0) ArgName = ArgStr;
Chris Lattner331de232002-07-22 02:07:59 +0000644 if (ArgName[0] == 0)
Bill Wendlinge8156192006-12-07 01:30:32 +0000645 cerr << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000646 else
Bill Wendlinge8156192006-12-07 01:30:32 +0000647 cerr << ProgramName << ": for the -" << ArgName;
Jim Laskeyabe0e3e2006-08-02 20:15:56 +0000648
Bill Wendlinge8156192006-12-07 01:30:32 +0000649 cerr << " option: " << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000650 return true;
651}
652
Chris Lattner6d5857e2005-05-10 23:20:17 +0000653bool Option::addOccurrence(unsigned pos, const char *ArgName,
654 const std::string &Value) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000655 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000656
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000657 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000658 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000659 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000660 return error(": may only occur zero or one times!", ArgName);
661 break;
662 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000663 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000664 return error(": must occur exactly one time!", ArgName);
665 // Fall through
666 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000667 case ZeroOrMore:
668 case ConsumeAfter: break;
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000669 default: return error(": bad num occurrences flag value!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000670 }
671
Reid Spencer1e13fd22004-08-13 19:47:30 +0000672 return handleOccurrence(pos, ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000673}
674
Chris Lattner331de232002-07-22 02:07:59 +0000675
676// getValueStr - Get the value description string, using "DefaultMsg" if nothing
677// has been specified yet.
678//
679static const char *getValueStr(const Option &O, const char *DefaultMsg) {
680 if (O.ValueStr[0] == 0) return DefaultMsg;
681 return O.ValueStr;
682}
683
684//===----------------------------------------------------------------------===//
685// cl::alias class implementation
686//
687
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000688// Return the width of the option tag for printing...
Chris Lattner331de232002-07-22 02:07:59 +0000689unsigned alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000690 return std::strlen(ArgStr)+6;
691}
692
Chris Lattnera0de8432006-04-28 05:36:25 +0000693// Print out the option for the alias.
Chris Lattner331de232002-07-22 02:07:59 +0000694void alias::printOptionInfo(unsigned GlobalWidth) const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000695 unsigned L = std::strlen(ArgStr);
Bill Wendlinge8156192006-12-07 01:30:32 +0000696 cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
697 << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000698}
699
700
Chris Lattner331de232002-07-22 02:07:59 +0000701
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000702//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000703// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000704//
705
Chris Lattner9b14eb52002-08-07 18:36:37 +0000706// basic_parser implementation
707//
708
709// Return the width of the option tag for printing...
710unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
711 unsigned Len = std::strlen(O.ArgStr);
712 if (const char *ValName = getValueName())
713 Len += std::strlen(getValueStr(O, ValName))+3;
714
715 return Len + 6;
716}
717
Misha Brukmanf976c852005-04-21 22:55:34 +0000718// printOptionInfo - Print out information about this option. The
Chris Lattner9b14eb52002-08-07 18:36:37 +0000719// to-be-maintained width is specified.
720//
721void basic_parser_impl::printOptionInfo(const Option &O,
722 unsigned GlobalWidth) const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000723 cout << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000724
725 if (const char *ValName = getValueName())
Bill Wendlinge8156192006-12-07 01:30:32 +0000726 cout << "=<" << getValueStr(O, ValName) << ">";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000727
Bill Wendlinge8156192006-12-07 01:30:32 +0000728 cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
729 << O.HelpStr << "\n";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000730}
731
732
733
734
Chris Lattner331de232002-07-22 02:07:59 +0000735// parser<bool> implementation
736//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000737bool parser<bool>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000738 const std::string &Arg, bool &Value) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000739 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000740 Arg == "1") {
741 Value = true;
742 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
743 Value = false;
744 } else {
Chris Lattner331de232002-07-22 02:07:59 +0000745 return O.error(": '" + Arg +
746 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000747 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000748 return false;
749}
750
Chris Lattner331de232002-07-22 02:07:59 +0000751// parser<int> implementation
752//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000753bool parser<int>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000754 const std::string &Arg, int &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000755 char *End;
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000756 Value = (int)strtol(Arg.c_str(), &End, 0);
Misha Brukmanf976c852005-04-21 22:55:34 +0000757 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000758 return O.error(": '" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000759 return false;
760}
761
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000762// parser<unsigned> implementation
763//
764bool parser<unsigned>::parse(Option &O, const char *ArgName,
765 const std::string &Arg, unsigned &Value) {
766 char *End;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000767 errno = 0;
768 unsigned long V = strtoul(Arg.c_str(), &End, 0);
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000769 Value = (unsigned)V;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000770 if (((V == ULONG_MAX) && (errno == ERANGE))
771 || (*End != 0)
772 || (Value != V))
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000773 return O.error(": '" + Arg + "' value invalid for uint argument!");
774 return false;
775}
776
Chris Lattner9b14eb52002-08-07 18:36:37 +0000777// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +0000778//
Chris Lattnerca6433f2003-05-22 20:06:43 +0000779static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
Chris Lattner331de232002-07-22 02:07:59 +0000780 const char *ArgStart = Arg.c_str();
781 char *End;
782 Value = strtod(ArgStart, &End);
Misha Brukmanf976c852005-04-21 22:55:34 +0000783 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000784 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +0000785 return false;
786}
787
Chris Lattner9b14eb52002-08-07 18:36:37 +0000788bool parser<double>::parse(Option &O, const char *AN,
789 const std::string &Arg, double &Val) {
790 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +0000791}
792
Chris Lattner9b14eb52002-08-07 18:36:37 +0000793bool parser<float>::parse(Option &O, const char *AN,
794 const std::string &Arg, float &Val) {
795 double dVal;
796 if (parseDouble(O, Arg, dVal))
797 return true;
798 Val = (float)dVal;
799 return false;
Chris Lattner331de232002-07-22 02:07:59 +0000800}
801
802
Chris Lattner331de232002-07-22 02:07:59 +0000803
804// generic_parser_base implementation
805//
806
Chris Lattneraa852bb2002-07-23 17:15:12 +0000807// findOption - Return the option number corresponding to the specified
808// argument string. If the option is not found, getNumOptions() is returned.
809//
810unsigned generic_parser_base::findOption(const char *Name) {
811 unsigned i = 0, e = getNumOptions();
Chris Lattnerca6433f2003-05-22 20:06:43 +0000812 std::string N(Name);
Chris Lattneraa852bb2002-07-23 17:15:12 +0000813
814 while (i != e)
815 if (getOption(i) == N)
816 return i;
817 else
818 ++i;
819 return e;
820}
821
822
Chris Lattner331de232002-07-22 02:07:59 +0000823// Return the width of the option tag for printing...
824unsigned generic_parser_base::getOptionWidth(const Option &O) const {
825 if (O.hasArgStr()) {
826 unsigned Size = std::strlen(O.ArgStr)+6;
827 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
828 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
829 return Size;
830 } else {
831 unsigned BaseSize = 0;
832 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
833 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
834 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000835 }
836}
837
Misha Brukmanf976c852005-04-21 22:55:34 +0000838// printOptionInfo - Print out information about this option. The
Chris Lattner331de232002-07-22 02:07:59 +0000839// to-be-maintained width is specified.
840//
841void generic_parser_base::printOptionInfo(const Option &O,
842 unsigned GlobalWidth) const {
843 if (O.hasArgStr()) {
844 unsigned L = std::strlen(O.ArgStr);
Bill Wendlinge8156192006-12-07 01:30:32 +0000845 cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
846 << " - " << O.HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000847
Chris Lattner331de232002-07-22 02:07:59 +0000848 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
849 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Bill Wendlinge8156192006-12-07 01:30:32 +0000850 cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
851 << " - " << getDescription(i) << "\n";
Chris Lattner9c9be482002-01-31 00:42:56 +0000852 }
Chris Lattner331de232002-07-22 02:07:59 +0000853 } else {
854 if (O.HelpStr[0])
Bill Wendlinge8156192006-12-07 01:30:32 +0000855 cout << " " << O.HelpStr << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000856 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
857 unsigned L = std::strlen(getOption(i));
Bill Wendlinge8156192006-12-07 01:30:32 +0000858 cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
859 << " - " << getDescription(i) << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000860 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000861 }
862}
863
864
865//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000866// --help and --help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000867//
Reid Spencerad0846b2004-11-14 22:04:00 +0000868
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000869namespace {
870
Chris Lattner331de232002-07-22 02:07:59 +0000871class HelpPrinter {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000872 unsigned MaxArgLen;
873 const Option *EmptyArg;
874 const bool ShowHidden;
875
Chris Lattner331de232002-07-22 02:07:59 +0000876 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
Chris Lattnerca6433f2003-05-22 20:06:43 +0000877 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000878 return OptPair.second->getOptionHiddenFlag() >= Hidden;
879 }
Chris Lattnerca6433f2003-05-22 20:06:43 +0000880 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000881 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
882 }
883
884public:
885 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
886 EmptyArg = 0;
887 }
888
889 void operator=(bool Value) {
890 if (Value == false) return;
891
Chris Lattner9878d6a2007-04-06 21:06:55 +0000892 // Get all the options.
893 std::vector<Option*> PositionalOpts;
894 std::map<std::string, Option*> OptMap;
895 GetOptionInfo(PositionalOpts, OptMap);
896
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000897 // Copy Options into a vector so we can sort them as we like...
Chris Lattner90aa8392006-10-04 21:52:35 +0000898 std::vector<std::pair<std::string, Option*> > Opts;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000899 copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts));
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000900
901 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Chris Lattner90aa8392006-10-04 21:52:35 +0000902 Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
903 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
904 Opts.end());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000905
906 // Eliminate duplicate entries in table (from enum flags options, f.e.)
Chris Lattner331de232002-07-22 02:07:59 +0000907 { // Give OptionSet a scope
908 std::set<Option*> OptionSet;
Chris Lattner90aa8392006-10-04 21:52:35 +0000909 for (unsigned i = 0; i != Opts.size(); ++i)
910 if (OptionSet.count(Opts[i].second) == 0)
911 OptionSet.insert(Opts[i].second); // Add new entry to set
Chris Lattner331de232002-07-22 02:07:59 +0000912 else
Chris Lattner90aa8392006-10-04 21:52:35 +0000913 Opts.erase(Opts.begin()+i--); // Erase duplicate
Chris Lattner331de232002-07-22 02:07:59 +0000914 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000915
916 if (ProgramOverview)
Bill Wendlinge8156192006-12-07 01:30:32 +0000917 cout << "OVERVIEW:" << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000918
Bill Wendlinge8156192006-12-07 01:30:32 +0000919 cout << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +0000920
Chris Lattner90aa8392006-10-04 21:52:35 +0000921 // Print out the positional options.
Chris Lattner331de232002-07-22 02:07:59 +0000922 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000923 if (!PositionalOpts.empty() &&
924 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
925 CAOpt = PositionalOpts[0];
Chris Lattner331de232002-07-22 02:07:59 +0000926
Chris Lattner9878d6a2007-04-06 21:06:55 +0000927 for (unsigned i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
928 if (PositionalOpts[i]->ArgStr[0])
929 cout << " --" << PositionalOpts[i]->ArgStr;
930 cout << " " << PositionalOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000931 }
Chris Lattner331de232002-07-22 02:07:59 +0000932
933 // Print the consume after option info if it exists...
Bill Wendlinge8156192006-12-07 01:30:32 +0000934 if (CAOpt) cout << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +0000935
Bill Wendlinge8156192006-12-07 01:30:32 +0000936 cout << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000937
938 // Compute the maximum argument length...
939 MaxArgLen = 0;
Chris Lattner90aa8392006-10-04 21:52:35 +0000940 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
941 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000942
Bill Wendlinge8156192006-12-07 01:30:32 +0000943 cout << "OPTIONS:\n";
Chris Lattner90aa8392006-10-04 21:52:35 +0000944 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
945 Opts[i].second->printOptionInfo(MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000946
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000947 // Print any extra help the user has declared.
Chris Lattner90aa8392006-10-04 21:52:35 +0000948 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
949 E = MoreHelp->end(); I != E; ++I)
Bill Wendlinge8156192006-12-07 01:30:32 +0000950 cout << *I;
Chris Lattner90aa8392006-10-04 21:52:35 +0000951 MoreHelp->clear();
Reid Spencerad0846b2004-11-14 22:04:00 +0000952
Reid Spencer9bbba0912004-11-16 06:11:52 +0000953 // Halt the program since help information was printed
Chris Lattner331de232002-07-22 02:07:59 +0000954 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000955 }
956};
Chris Lattner500d8bf2006-10-12 22:09:17 +0000957} // End anonymous namespace
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000958
Chris Lattner331de232002-07-22 02:07:59 +0000959// Define the two HelpPrinter instances that are used to print out help, or
960// help-hidden...
961//
Chris Lattner500d8bf2006-10-12 22:09:17 +0000962static HelpPrinter NormalPrinter(false);
963static HelpPrinter HiddenPrinter(true);
Chris Lattner331de232002-07-22 02:07:59 +0000964
Chris Lattner500d8bf2006-10-12 22:09:17 +0000965static cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +0000966HOp("help", cl::desc("Display available options (--help-hidden for more)"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000967 cl::location(NormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +0000968
Chris Lattner500d8bf2006-10-12 22:09:17 +0000969static cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +0000970HHOp("help-hidden", cl::desc("Display all available options"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000971 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000972
Chris Lattner500d8bf2006-10-12 22:09:17 +0000973static void (*OverrideVersionPrinter)() = 0;
Reid Spencer515b5b32006-06-05 16:22:56 +0000974
Chris Lattner500d8bf2006-10-12 22:09:17 +0000975namespace {
Reid Spencer515b5b32006-06-05 16:22:56 +0000976class VersionPrinter {
977public:
Devang Patelaed293d2007-02-01 01:43:37 +0000978 void print() {
Bill Wendlinge8156192006-12-07 01:30:32 +0000979 cout << "Low Level Virtual Machine (http://llvm.org/):\n";
980 cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner3fc2f4e2006-07-06 18:33:03 +0000981#ifdef LLVM_VERSION_INFO
Bill Wendlinge8156192006-12-07 01:30:32 +0000982 cout << LLVM_VERSION_INFO;
Reid Spencer515b5b32006-06-05 16:22:56 +0000983#endif
Bill Wendlinge8156192006-12-07 01:30:32 +0000984 cout << "\n ";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +0000985#ifndef __OPTIMIZE__
Bill Wendlinge8156192006-12-07 01:30:32 +0000986 cout << "DEBUG build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +0000987#else
Bill Wendlinge8156192006-12-07 01:30:32 +0000988 cout << "Optimized build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +0000989#endif
990#ifndef NDEBUG
Bill Wendlinge8156192006-12-07 01:30:32 +0000991 cout << " with assertions";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +0000992#endif
Bill Wendlinge8156192006-12-07 01:30:32 +0000993 cout << ".\n";
Devang Patelaed293d2007-02-01 01:43:37 +0000994 }
995 void operator=(bool OptionWasSpecified) {
996 if (OptionWasSpecified) {
997 if (OverrideVersionPrinter == 0) {
998 print();
Reid Spencer515b5b32006-06-05 16:22:56 +0000999 exit(1);
1000 } else {
1001 (*OverrideVersionPrinter)();
1002 exit(1);
1003 }
1004 }
1005 }
1006};
Chris Lattner500d8bf2006-10-12 22:09:17 +00001007} // End anonymous namespace
Reid Spencer515b5b32006-06-05 16:22:56 +00001008
1009
Reid Spencer69105f32004-08-04 00:36:06 +00001010// Define the --version option that prints out the LLVM version for the tool
Chris Lattner500d8bf2006-10-12 22:09:17 +00001011static VersionPrinter VersionPrinterInstance;
1012
1013static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001014VersOp("version", cl::desc("Display the version of this program"),
Reid Spencer69105f32004-08-04 00:36:06 +00001015 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1016
Reid Spencer9bbba0912004-11-16 06:11:52 +00001017// Utility function for printing the help message.
1018void cl::PrintHelpMessage() {
Misha Brukmanf976c852005-04-21 22:55:34 +00001019 // This looks weird, but it actually prints the help message. The
Reid Spencer5cc498f2004-11-16 06:50:36 +00001020 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1021 // its operator= is invoked. That's because the "normal" usages of the
Misha Brukmanf976c852005-04-21 22:55:34 +00001022 // help printer is to be assigned true/false depending on whether the
Reid Spencer5cc498f2004-11-16 06:50:36 +00001023 // --help option was given or not. Since we're circumventing that we have
1024 // to make it look like --help was given, so we assign true.
Reid Spencer9bbba0912004-11-16 06:11:52 +00001025 NormalPrinter = true;
1026}
Reid Spencer515b5b32006-06-05 16:22:56 +00001027
Devang Patelaed293d2007-02-01 01:43:37 +00001028/// Utility function for printing version number.
1029void cl::PrintVersionMessage() {
1030 VersionPrinterInstance.print();
1031}
1032
Reid Spencer515b5b32006-06-05 16:22:56 +00001033void cl::SetVersionPrinter(void (*func)()) {
1034 OverrideVersionPrinter = func;
1035}