blob: 2b0798aa77053e618526e308379a27f9b8323217 [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 Lattner69d6f132007-04-12 00:36:29 +000074static bool OptionListChanged = false;
75
76// MarkOptionsChanged - Internal helper function.
77void cl::MarkOptionsChanged() {
78 OptionListChanged = true;
79}
80
Chris Lattner9878d6a2007-04-06 21:06:55 +000081/// RegisteredOptionList - This is the list of the command line options that
82/// have statically constructed themselves.
83static Option *RegisteredOptionList = 0;
84
85void Option::addArgument() {
86 assert(NextRegistered == 0 && "argument multiply registered!");
87
88 NextRegistered = RegisteredOptionList;
89 RegisteredOptionList = this;
Chris Lattner69d6f132007-04-12 00:36:29 +000090 MarkOptionsChanged();
Chris Lattner9878d6a2007-04-06 21:06:55 +000091}
92
Chris Lattner69d6f132007-04-12 00:36:29 +000093
Chris Lattner331de232002-07-22 02:07:59 +000094//===----------------------------------------------------------------------===//
Chris Lattner7422a762006-08-27 12:45:47 +000095// Basic, shared command line option processing machinery.
Chris Lattner331de232002-07-22 02:07:59 +000096//
97
Chris Lattner9878d6a2007-04-06 21:06:55 +000098/// GetOptionInfo - Scan the list of registered options, turning them into data
99/// structures that are easier to handle.
100static void GetOptionInfo(std::vector<Option*> &PositionalOpts,
101 std::map<std::string, Option*> &OptionsMap) {
102 std::vector<const char*> OptionNames;
Chris Lattneree2b3202007-04-07 05:38:53 +0000103 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000104 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
105 // If this option wants to handle multiple option names, get the full set.
106 // This handles enum options like "-O1 -O2" etc.
107 O->getExtraOptionNames(OptionNames);
108 if (O->ArgStr[0])
109 OptionNames.push_back(O->ArgStr);
110
111 // Handle named options.
112 for (unsigned i = 0, e = OptionNames.size(); i != e; ++i) {
113 // Add argument to the argument map!
114 if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i],
115 O)).second) {
116 cerr << ProgramName << ": CommandLine Error: Argument '"
117 << OptionNames[0] << "' defined more than once!\n";
118 }
119 }
120
121 OptionNames.clear();
122
123 // Remember information about positional options.
124 if (O->getFormattingFlag() == cl::Positional)
125 PositionalOpts.push_back(O);
126 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattneree2b3202007-04-07 05:38:53 +0000127 if (CAOpt)
Chris Lattner9878d6a2007-04-06 21:06:55 +0000128 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattneree2b3202007-04-07 05:38:53 +0000129 CAOpt = O;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000130 }
Chris Lattnere8e258b2002-07-29 20:58:42 +0000131 }
Chris Lattneree2b3202007-04-07 05:38:53 +0000132
133 if (CAOpt)
134 PositionalOpts.push_back(CAOpt);
135
136 // Make sure that they are in order of registration not backwards.
137 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
Chris Lattnere8e258b2002-07-29 20:58:42 +0000138}
139
Chris Lattner9878d6a2007-04-06 21:06:55 +0000140
Chris Lattneraf035f32007-04-05 21:58:17 +0000141/// LookupOption - Lookup the option specified by the specified option on the
142/// command line. If there is a value specified (after an equal sign) return
143/// that as well.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000144static Option *LookupOption(const char *&Arg, const char *&Value,
145 std::map<std::string, Option*> &OptionsMap) {
Chris Lattneraf035f32007-04-05 21:58:17 +0000146 while (*Arg == '-') ++Arg; // Eat leading dashes
147
148 const char *ArgEnd = Arg;
149 while (*ArgEnd && *ArgEnd != '=')
150 ++ArgEnd; // Scan till end of argument name.
151
152 if (*ArgEnd == '=') // If we have an equals sign...
153 Value = ArgEnd+1; // Get the value, not the equals
154
155
156 if (*Arg == 0) return 0;
157
158 // Look up the option.
Chris Lattneraf035f32007-04-05 21:58:17 +0000159 std::map<std::string, Option*>::iterator I =
Chris Lattner9878d6a2007-04-06 21:06:55 +0000160 OptionsMap.find(std::string(Arg, ArgEnd));
161 return I != OptionsMap.end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000162}
163
Chris Lattnercaccd762001-10-27 05:54:17 +0000164static inline bool ProvideOption(Option *Handler, const char *ArgName,
165 const char *Value, int argc, char **argv,
166 int &i) {
167 // Enforce value requirements
168 switch (Handler->getValueExpectedFlag()) {
169 case ValueRequired:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000170 if (Value == 0) { // No value specified?
Chris Lattnercaccd762001-10-27 05:54:17 +0000171 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
172 Value = argv[++i];
173 } else {
174 return Handler->error(" requires a value!");
175 }
176 }
177 break;
178 case ValueDisallowed:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000179 if (Value)
Misha Brukmanf976c852005-04-21 22:55:34 +0000180 return Handler->error(" does not allow a value! '" +
Chris Lattnerca6433f2003-05-22 20:06:43 +0000181 std::string(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +0000182 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000183 case ValueOptional:
Reid Spencere1cc1502004-09-01 04:41:28 +0000184 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000185 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000186 cerr << ProgramName
187 << ": Bad ValueMask flag! CommandLine usage error:"
188 << Handler->getValueExpectedFlag() << "\n";
Reid Spencere1cc1502004-09-01 04:41:28 +0000189 abort();
190 break;
Chris Lattnercaccd762001-10-27 05:54:17 +0000191 }
192
193 // Run the handler now!
Chris Lattner6d5857e2005-05-10 23:20:17 +0000194 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
Chris Lattnercaccd762001-10-27 05:54:17 +0000195}
196
Misha Brukmanf976c852005-04-21 22:55:34 +0000197static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000198 int i) {
199 int Dummy = i;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000200 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000201}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000202
Chris Lattner331de232002-07-22 02:07:59 +0000203
204// Option predicates...
205static inline bool isGrouping(const Option *O) {
206 return O->getFormattingFlag() == cl::Grouping;
207}
208static inline bool isPrefixedOrGrouping(const Option *O) {
209 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
210}
211
212// getOptionPred - Check to see if there are any options that satisfy the
213// specified predicate with names that are the prefixes in Name. This is
214// checked by progressively stripping characters off of the name, checking to
215// see if there options that satisfy the predicate. If we find one, return it,
216// otherwise return null.
217//
218static Option *getOptionPred(std::string Name, unsigned &Length,
Chris Lattner9878d6a2007-04-06 21:06:55 +0000219 bool (*Pred)(const Option*),
220 std::map<std::string, Option*> &OptionsMap) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000221
Chris Lattner9878d6a2007-04-06 21:06:55 +0000222 std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name);
223 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner331de232002-07-22 02:07:59 +0000224 Length = Name.length();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000225 return OMI->second;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000226 }
227
Chris Lattner331de232002-07-22 02:07:59 +0000228 if (Name.size() == 1) return 0;
229 do {
230 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000231 OMI = OptionsMap.find(Name);
Chris Lattner331de232002-07-22 02:07:59 +0000232
233 // Loop while we haven't found an option and Name still has at least two
234 // characters in it (so that the next iteration will not be the empty
235 // string...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000236 } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1);
Chris Lattner331de232002-07-22 02:07:59 +0000237
Chris Lattner9878d6a2007-04-06 21:06:55 +0000238 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner331de232002-07-22 02:07:59 +0000239 Length = Name.length();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000240 return OMI->second; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000241 }
242 return 0; // No option found!
243}
244
245static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000246 return O->getNumOccurrencesFlag() == cl::Required ||
247 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000248}
249
250static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000251 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
252 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000253}
Chris Lattnercaccd762001-10-27 05:54:17 +0000254
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000255/// ParseCStringVector - Break INPUT up wherever one or more
256/// whitespace characters are found, and store the resulting tokens in
257/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
258/// using strdup (), so it is the caller's responsibility to free ()
259/// them later.
Brian Gaeke06b06c52003-08-14 22:00:59 +0000260///
Chris Lattner23288582006-08-27 22:10:29 +0000261static void ParseCStringVector(std::vector<char *> &output,
262 const char *input) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000263 // Characters which will be treated as token separators:
264 static const char *delims = " \v\f\t\r\n";
265
266 std::string work (input);
267 // Skip past any delims at head of input string.
268 size_t pos = work.find_first_not_of (delims);
269 // If the string consists entirely of delims, then exit early.
270 if (pos == std::string::npos) return;
271 // Otherwise, jump forward to beginning of first word.
272 work = work.substr (pos);
273 // Find position of first delimiter.
274 pos = work.find_first_of (delims);
275
276 while (!work.empty() && pos != std::string::npos) {
277 // Everything from 0 to POS is the next word to copy.
278 output.push_back (strdup (work.substr (0,pos).c_str ()));
279 // Is there another word in the string?
280 size_t nextpos = work.find_first_not_of (delims, pos + 1);
281 if (nextpos != std::string::npos) {
282 // Yes? Then remove delims from beginning ...
283 work = work.substr (work.find_first_not_of (delims, pos + 1));
284 // and find the end of the word.
285 pos = work.find_first_of (delims);
286 } else {
287 // No? (Remainder of string is delims.) End the loop.
288 work = "";
289 pos = std::string::npos;
290 }
291 }
292
293 // If `input' ended with non-delim char, then we'll get here with
294 // the last word of `input' in `work'; copy it now.
295 if (!work.empty ()) {
296 output.push_back (strdup (work.c_str ()));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000297 }
298}
299
300/// ParseEnvironmentOptions - An alternative entry point to the
301/// CommandLine library, which allows you to read the program's name
302/// from the caller (as PROGNAME) and its command-line arguments from
303/// an environment variable (whose name is given in ENVVAR).
304///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000305void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
306 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000307 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000308 assert(progName && "Program name not specified");
309 assert(envVar && "Environment variable name missing");
Misha Brukmanf976c852005-04-21 22:55:34 +0000310
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000311 // Get the environment variable they want us to parse options out of.
Chris Lattner23288582006-08-27 22:10:29 +0000312 const char *envValue = getenv(envVar);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000313 if (!envValue)
314 return;
315
Brian Gaeke06b06c52003-08-14 22:00:59 +0000316 // Get program's "name", which we wouldn't know without the caller
317 // telling us.
Chris Lattner23288582006-08-27 22:10:29 +0000318 std::vector<char*> newArgv;
319 newArgv.push_back(strdup(progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000320
321 // Parse the value of the environment variable into a "command line"
322 // and hand it off to ParseCommandLineOptions().
Chris Lattner23288582006-08-27 22:10:29 +0000323 ParseCStringVector(newArgv, envValue);
324 int newArgc = newArgv.size();
325 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000326
327 // Free all the strdup()ed strings.
Chris Lattner23288582006-08-27 22:10:29 +0000328 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
329 i != e; ++i)
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000330 free (*i);
Brian Gaeke06b06c52003-08-14 22:00:59 +0000331}
332
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000333void cl::ParseCommandLineOptions(int &argc, char **argv,
Chris Lattner0c0edf82002-07-25 06:17:51 +0000334 const char *Overview) {
Chris Lattner9878d6a2007-04-06 21:06:55 +0000335 // Process all registered options.
336 std::vector<Option*> PositionalOpts;
337 std::map<std::string, Option*> Opts;
338 GetOptionInfo(PositionalOpts, Opts);
339
340 assert((!Opts.empty() || !PositionalOpts.empty()) &&
341 "No options specified!");
Reid Spencer6f4c6072006-08-23 07:10:06 +0000342 sys::Path progname(argv[0]);
Chris Lattnerefa3da52006-10-13 00:06:24 +0000343
344 // Copy the program name into ProgName, making sure not to overflow it.
345 std::string ProgName = sys::Path(argv[0]).getLast();
346 if (ProgName.size() > 79) ProgName.resize(79);
347 strcpy(ProgramName, ProgName.c_str());
348
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000349 ProgramOverview = Overview;
350 bool ErrorParsing = false;
351
Chris Lattner331de232002-07-22 02:07:59 +0000352 // Check out the positional arguments to collect information about them.
353 unsigned NumPositionalRequired = 0;
Chris Lattnerde013242005-08-08 17:25:38 +0000354
355 // Determine whether or not there are an unlimited number of positionals
356 bool HasUnlimitedPositionals = false;
357
Chris Lattner331de232002-07-22 02:07:59 +0000358 Option *ConsumeAfterOpt = 0;
359 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000360 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000361 assert(PositionalOpts.size() > 1 &&
362 "Cannot specify cl::ConsumeAfter without a positional argument!");
363 ConsumeAfterOpt = PositionalOpts[0];
364 }
365
366 // Calculate how many positional values are _required_.
367 bool UnboundedFound = false;
368 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
369 i != e; ++i) {
370 Option *Opt = PositionalOpts[i];
371 if (RequiresValue(Opt))
372 ++NumPositionalRequired;
373 else if (ConsumeAfterOpt) {
374 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000375 // unless there is only one positional argument...
376 if (PositionalOpts.size() > 2)
377 ErrorParsing |=
378 Opt->error(" error - this positional option will never be matched, "
379 "because it does not Require a value, and a "
380 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000381 } else if (UnboundedFound && !Opt->ArgStr[0]) {
382 // This option does not "require" a value... Make sure this option is
383 // not specified after an option that eats all extra arguments, or this
384 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000385 //
386 ErrorParsing |= Opt->error(" error - option can never match, because "
387 "another positional argument will match an "
388 "unbounded number of values, and this option"
389 " does not require a value!");
390 }
391 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
392 }
Chris Lattner21e1a792005-08-08 21:57:27 +0000393 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000394 }
395
Reid Spencer1e13fd22004-08-13 19:47:30 +0000396 // PositionalVals - A vector of "positional" arguments we accumulate into
397 // the process at the end...
Chris Lattner331de232002-07-22 02:07:59 +0000398 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000399 std::vector<std::pair<std::string,unsigned> > PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000400
Chris Lattner9cf3d472003-07-30 17:34:02 +0000401 // If the program has named positional arguments, and the name has been run
402 // across, keep track of which positional argument was named. Otherwise put
403 // the positional args into the PositionalVals list...
404 Option *ActivePositionalArg = 0;
405
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000406 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000407 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000408 for (int i = 1; i < argc; ++i) {
409 Option *Handler = 0;
Chris Lattner6d5857e2005-05-10 23:20:17 +0000410 const char *Value = 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000411 const char *ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000412
Chris Lattner69d6f132007-04-12 00:36:29 +0000413 // If the option list changed, this means that some command line
Chris Lattner159b0a432007-04-11 15:35:18 +0000414 // option has just been registered or deregistered. This can occur in
415 // response to things like -load, etc. If this happens, rescan the options.
Chris Lattner69d6f132007-04-12 00:36:29 +0000416 if (OptionListChanged) {
Chris Lattner159b0a432007-04-11 15:35:18 +0000417 PositionalOpts.clear();
418 Opts.clear();
419 GetOptionInfo(PositionalOpts, Opts);
Chris Lattner69d6f132007-04-12 00:36:29 +0000420 OptionListChanged = false;
Chris Lattner159b0a432007-04-11 15:35:18 +0000421 }
422
Chris Lattner331de232002-07-22 02:07:59 +0000423 // Check to see if this is a positional argument. This argument is
424 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000425 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000426 //
427 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
428 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000429 if (ActivePositionalArg) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000430 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000431 continue; // We are done!
432 } else if (!PositionalOpts.empty()) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000433 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000434
435 // All of the positional arguments have been fulfulled, give the rest to
436 // the consume after option... if it's specified...
437 //
Misha Brukmanf976c852005-04-21 22:55:34 +0000438 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000439 ConsumeAfterOpt != 0) {
440 for (++i; i < argc; ++i)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000441 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000442 break; // Handle outside of the argument processing loop...
443 }
444
445 // Delay processing positional arguments until the end...
446 continue;
447 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000448 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
449 !DashDashFound) {
450 DashDashFound = true; // This is the mythical "--"?
451 continue; // Don't try to process it as an argument itself.
452 } else if (ActivePositionalArg &&
453 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
454 // If there is a positional argument eating options, check to see if this
455 // option is another positional argument. If so, treat it as an argument,
456 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000457 ArgName = argv[i]+1;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000458 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000459 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000460 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000461 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000462 }
463
Chris Lattnerbf455c22004-05-06 22:04:31 +0000464 } else { // We start with a '-', must be an argument...
465 ArgName = argv[i]+1;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000466 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000467
Chris Lattnerbf455c22004-05-06 22:04:31 +0000468 // Check to see if this "option" is really a prefixed or grouped argument.
Reid Spencer5f8448f2004-11-24 06:13:42 +0000469 if (Handler == 0) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000470 std::string RealName(ArgName);
471 if (RealName.size() > 1) {
Chris Lattner331de232002-07-22 02:07:59 +0000472 unsigned Length = 0;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000473 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping,
474 Opts);
Misha Brukmanf976c852005-04-21 22:55:34 +0000475
Chris Lattner331de232002-07-22 02:07:59 +0000476 // If the option is a prefixed option, then the value is simply the
477 // rest of the name... so fall through to later processing, by
478 // setting up the argument name flags and value fields.
479 //
480 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000481 Value = ArgName+Length;
482 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
483 Opts.find(std::string(ArgName, Value))->second == PGOpt);
484 Handler = PGOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000485 } else if (PGOpt) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000486 // This must be a grouped option... handle them now.
Chris Lattner331de232002-07-22 02:07:59 +0000487 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000488
Chris Lattner331de232002-07-22 02:07:59 +0000489 do {
490 // Move current arg name out of RealName into RealArgName...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000491 std::string RealArgName(RealName.begin(),
492 RealName.begin() + Length);
493 RealName.erase(RealName.begin(), RealName.begin() + Length);
Misha Brukmanf976c852005-04-21 22:55:34 +0000494
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000495 // Because ValueRequired is an invalid flag for grouped arguments,
496 // we don't need to pass argc/argv in...
497 //
Chris Lattner331de232002-07-22 02:07:59 +0000498 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
499 "Option can not be cl::Grouping AND cl::ValueRequired!");
500 int Dummy;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000501 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
Chris Lattner6d5857e2005-05-10 23:20:17 +0000502 0, 0, 0, Dummy);
Misha Brukmanf976c852005-04-21 22:55:34 +0000503
Chris Lattner331de232002-07-22 02:07:59 +0000504 // Get the next grouping option...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000505 PGOpt = getOptionPred(RealName, Length, isGrouping, Opts);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000506 } while (PGOpt && Length != RealName.size());
Misha Brukmanf976c852005-04-21 22:55:34 +0000507
Chris Lattnerbf455c22004-05-06 22:04:31 +0000508 Handler = PGOpt; // Ate all of the options.
Chris Lattner331de232002-07-22 02:07:59 +0000509 }
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000510 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000511 }
512 }
513
514 if (Handler == 0) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000515 cerr << ProgramName << ": Unknown command line argument '"
516 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000517 ErrorParsing = true;
518 continue;
519 }
520
Chris Lattner72fb8e52003-05-22 20:26:17 +0000521 // Check to see if this option accepts a comma separated list of values. If
522 // it does, we have to split up the value into multiple values...
Chris Lattner6d5857e2005-05-10 23:20:17 +0000523 if (Value && Handler->getMiscFlags() & CommaSeparated) {
Chris Lattner72fb8e52003-05-22 20:26:17 +0000524 std::string Val(Value);
525 std::string::size_type Pos = Val.find(',');
526
527 while (Pos != std::string::npos) {
528 // Process the portion before the comma...
529 ErrorParsing |= ProvideOption(Handler, ArgName,
530 std::string(Val.begin(),
531 Val.begin()+Pos).c_str(),
532 argc, argv, i);
533 // Erase the portion before the comma, AND the comma...
534 Val.erase(Val.begin(), Val.begin()+Pos+1);
535 Value += Pos+1; // Increment the original value pointer as well...
536
537 // Check for another comma...
538 Pos = Val.find(',');
539 }
540 }
Chris Lattner9cf3d472003-07-30 17:34:02 +0000541
542 // If this is a named positional argument, just remember that it is the
543 // active one...
544 if (Handler->getFormattingFlag() == cl::Positional)
545 ActivePositionalArg = Handler;
Misha Brukmanf976c852005-04-21 22:55:34 +0000546 else
Chris Lattner9cf3d472003-07-30 17:34:02 +0000547 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000548 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000549
Chris Lattner331de232002-07-22 02:07:59 +0000550 // Check and handle positional arguments now...
551 if (NumPositionalRequired > PositionalVals.size()) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000552 cerr << ProgramName
553 << ": Not enough positional command line arguments specified!\n"
554 << "Must specify at least " << NumPositionalRequired
555 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattner79959d22006-01-17 00:32:28 +0000556
Chris Lattner331de232002-07-22 02:07:59 +0000557 ErrorParsing = true;
Chris Lattnerde013242005-08-08 17:25:38 +0000558 } else if (!HasUnlimitedPositionals
559 && PositionalVals.size() > PositionalOpts.size()) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000560 cerr << ProgramName
561 << ": Too many positional arguments specified!\n"
562 << "Can specify at most " << PositionalOpts.size()
563 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattnerde013242005-08-08 17:25:38 +0000564 ErrorParsing = true;
Chris Lattner331de232002-07-22 02:07:59 +0000565
566 } else if (ConsumeAfterOpt == 0) {
567 // Positional args have already been handled if ConsumeAfter is specified...
568 unsigned ValNo = 0, NumVals = PositionalVals.size();
569 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
570 if (RequiresValue(PositionalOpts[i])) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000571 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000572 PositionalVals[ValNo].second);
573 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000574 --NumPositionalRequired; // We fulfilled our duty...
575 }
576
577 // If we _can_ give this option more arguments, do so now, as long as we
578 // do not give it values that others need. 'Done' controls whether the
579 // option even _WANTS_ any more.
580 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000581 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000582 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000583 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000584 case cl::Optional:
585 Done = true; // Optional arguments want _at most_ one value
586 // FALL THROUGH
587 case cl::ZeroOrMore: // Zero or more will take all they can get...
588 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer1e13fd22004-08-13 19:47:30 +0000589 ProvidePositionalOption(PositionalOpts[i],
590 PositionalVals[ValNo].first,
591 PositionalVals[ValNo].second);
592 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000593 break;
594 default:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000595 assert(0 && "Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000596 "positional argument processing!");
597 }
598 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000599 }
Chris Lattner331de232002-07-22 02:07:59 +0000600 } else {
601 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
602 unsigned ValNo = 0;
603 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000604 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000605 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000606 PositionalVals[ValNo].first,
607 PositionalVals[ValNo].second);
608 ValNo++;
609 }
Chris Lattnerfaba8092002-07-24 20:15:13 +0000610
611 // Handle the case where there is just one positional option, and it's
612 // optional. In this case, we want to give JUST THE FIRST option to the
613 // positional option and keep the rest for the consume after. The above
614 // loop would have assigned no values to positional options in this case.
615 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000616 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000617 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000618 PositionalVals[ValNo].first,
619 PositionalVals[ValNo].second);
620 ValNo++;
621 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000622
Chris Lattner331de232002-07-22 02:07:59 +0000623 // Handle over all of the rest of the arguments to the
624 // cl::ConsumeAfter command line option...
625 for (; ValNo != PositionalVals.size(); ++ValNo)
626 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000627 PositionalVals[ValNo].first,
628 PositionalVals[ValNo].second);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000629 }
630
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000631 // Loop over args and make sure all required args are specified!
Misha Brukmanf976c852005-04-21 22:55:34 +0000632 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000633 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000634 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000635 case Required:
636 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000637 if (I->second->getNumOccurrences() == 0) {
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000638 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000639 ErrorParsing = true;
640 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000641 // Fall through
642 default:
643 break;
644 }
645 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000646
Chris Lattner331de232002-07-22 02:07:59 +0000647 // Free all of the memory allocated to the map. Command line options may only
648 // be processed once!
Chris Lattner90aa8392006-10-04 21:52:35 +0000649 Opts.clear();
Chris Lattner331de232002-07-22 02:07:59 +0000650 PositionalOpts.clear();
Chris Lattner90aa8392006-10-04 21:52:35 +0000651 MoreHelp->clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000652
653 // If we had an error processing our arguments, don't let the program execute
654 if (ErrorParsing) exit(1);
655}
656
657//===----------------------------------------------------------------------===//
658// Option Base class implementation
659//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000660
Chris Lattnerca6433f2003-05-22 20:06:43 +0000661bool Option::error(std::string Message, const char *ArgName) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000662 if (ArgName == 0) ArgName = ArgStr;
Chris Lattner331de232002-07-22 02:07:59 +0000663 if (ArgName[0] == 0)
Bill Wendlinge8156192006-12-07 01:30:32 +0000664 cerr << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000665 else
Bill Wendlinge8156192006-12-07 01:30:32 +0000666 cerr << ProgramName << ": for the -" << ArgName;
Jim Laskeyabe0e3e2006-08-02 20:15:56 +0000667
Bill Wendlinge8156192006-12-07 01:30:32 +0000668 cerr << " option: " << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000669 return true;
670}
671
Chris Lattner6d5857e2005-05-10 23:20:17 +0000672bool Option::addOccurrence(unsigned pos, const char *ArgName,
673 const std::string &Value) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000674 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000675
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000676 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000677 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000678 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000679 return error(": may only occur zero or one times!", ArgName);
680 break;
681 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000682 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000683 return error(": must occur exactly one time!", ArgName);
684 // Fall through
685 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000686 case ZeroOrMore:
687 case ConsumeAfter: break;
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000688 default: return error(": bad num occurrences flag value!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000689 }
690
Reid Spencer1e13fd22004-08-13 19:47:30 +0000691 return handleOccurrence(pos, ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000692}
693
Chris Lattner331de232002-07-22 02:07:59 +0000694
695// getValueStr - Get the value description string, using "DefaultMsg" if nothing
696// has been specified yet.
697//
698static const char *getValueStr(const Option &O, const char *DefaultMsg) {
699 if (O.ValueStr[0] == 0) return DefaultMsg;
700 return O.ValueStr;
701}
702
703//===----------------------------------------------------------------------===//
704// cl::alias class implementation
705//
706
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000707// Return the width of the option tag for printing...
Chris Lattner331de232002-07-22 02:07:59 +0000708unsigned alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000709 return std::strlen(ArgStr)+6;
710}
711
Chris Lattnera0de8432006-04-28 05:36:25 +0000712// Print out the option for the alias.
Chris Lattner331de232002-07-22 02:07:59 +0000713void alias::printOptionInfo(unsigned GlobalWidth) const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000714 unsigned L = std::strlen(ArgStr);
Bill Wendlinge8156192006-12-07 01:30:32 +0000715 cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
716 << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000717}
718
719
Chris Lattner331de232002-07-22 02:07:59 +0000720
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000721//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000722// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000723//
724
Chris Lattner9b14eb52002-08-07 18:36:37 +0000725// basic_parser implementation
726//
727
728// Return the width of the option tag for printing...
729unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
730 unsigned Len = std::strlen(O.ArgStr);
731 if (const char *ValName = getValueName())
732 Len += std::strlen(getValueStr(O, ValName))+3;
733
734 return Len + 6;
735}
736
Misha Brukmanf976c852005-04-21 22:55:34 +0000737// printOptionInfo - Print out information about this option. The
Chris Lattner9b14eb52002-08-07 18:36:37 +0000738// to-be-maintained width is specified.
739//
740void basic_parser_impl::printOptionInfo(const Option &O,
741 unsigned GlobalWidth) const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000742 cout << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000743
744 if (const char *ValName = getValueName())
Bill Wendlinge8156192006-12-07 01:30:32 +0000745 cout << "=<" << getValueStr(O, ValName) << ">";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000746
Bill Wendlinge8156192006-12-07 01:30:32 +0000747 cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
748 << O.HelpStr << "\n";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000749}
750
751
752
753
Chris Lattner331de232002-07-22 02:07:59 +0000754// parser<bool> implementation
755//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000756bool parser<bool>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000757 const std::string &Arg, bool &Value) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000758 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000759 Arg == "1") {
760 Value = true;
761 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
762 Value = false;
763 } else {
Chris Lattner331de232002-07-22 02:07:59 +0000764 return O.error(": '" + Arg +
765 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000766 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000767 return false;
768}
769
Chris Lattner331de232002-07-22 02:07:59 +0000770// parser<int> implementation
771//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000772bool parser<int>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000773 const std::string &Arg, int &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000774 char *End;
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000775 Value = (int)strtol(Arg.c_str(), &End, 0);
Misha Brukmanf976c852005-04-21 22:55:34 +0000776 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000777 return O.error(": '" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000778 return false;
779}
780
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000781// parser<unsigned> implementation
782//
783bool parser<unsigned>::parse(Option &O, const char *ArgName,
784 const std::string &Arg, unsigned &Value) {
785 char *End;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000786 errno = 0;
787 unsigned long V = strtoul(Arg.c_str(), &End, 0);
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000788 Value = (unsigned)V;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000789 if (((V == ULONG_MAX) && (errno == ERANGE))
790 || (*End != 0)
791 || (Value != V))
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000792 return O.error(": '" + Arg + "' value invalid for uint argument!");
793 return false;
794}
795
Chris Lattner9b14eb52002-08-07 18:36:37 +0000796// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +0000797//
Chris Lattnerca6433f2003-05-22 20:06:43 +0000798static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
Chris Lattner331de232002-07-22 02:07:59 +0000799 const char *ArgStart = Arg.c_str();
800 char *End;
801 Value = strtod(ArgStart, &End);
Misha Brukmanf976c852005-04-21 22:55:34 +0000802 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000803 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +0000804 return false;
805}
806
Chris Lattner9b14eb52002-08-07 18:36:37 +0000807bool parser<double>::parse(Option &O, const char *AN,
808 const std::string &Arg, double &Val) {
809 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +0000810}
811
Chris Lattner9b14eb52002-08-07 18:36:37 +0000812bool parser<float>::parse(Option &O, const char *AN,
813 const std::string &Arg, float &Val) {
814 double dVal;
815 if (parseDouble(O, Arg, dVal))
816 return true;
817 Val = (float)dVal;
818 return false;
Chris Lattner331de232002-07-22 02:07:59 +0000819}
820
821
Chris Lattner331de232002-07-22 02:07:59 +0000822
823// generic_parser_base implementation
824//
825
Chris Lattneraa852bb2002-07-23 17:15:12 +0000826// findOption - Return the option number corresponding to the specified
827// argument string. If the option is not found, getNumOptions() is returned.
828//
829unsigned generic_parser_base::findOption(const char *Name) {
830 unsigned i = 0, e = getNumOptions();
Chris Lattnerca6433f2003-05-22 20:06:43 +0000831 std::string N(Name);
Chris Lattneraa852bb2002-07-23 17:15:12 +0000832
833 while (i != e)
834 if (getOption(i) == N)
835 return i;
836 else
837 ++i;
838 return e;
839}
840
841
Chris Lattner331de232002-07-22 02:07:59 +0000842// Return the width of the option tag for printing...
843unsigned generic_parser_base::getOptionWidth(const Option &O) const {
844 if (O.hasArgStr()) {
845 unsigned Size = std::strlen(O.ArgStr)+6;
846 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
847 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
848 return Size;
849 } else {
850 unsigned BaseSize = 0;
851 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
852 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
853 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000854 }
855}
856
Misha Brukmanf976c852005-04-21 22:55:34 +0000857// printOptionInfo - Print out information about this option. The
Chris Lattner331de232002-07-22 02:07:59 +0000858// to-be-maintained width is specified.
859//
860void generic_parser_base::printOptionInfo(const Option &O,
861 unsigned GlobalWidth) const {
862 if (O.hasArgStr()) {
863 unsigned L = std::strlen(O.ArgStr);
Bill Wendlinge8156192006-12-07 01:30:32 +0000864 cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
865 << " - " << O.HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000866
Chris Lattner331de232002-07-22 02:07:59 +0000867 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
868 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Bill Wendlinge8156192006-12-07 01:30:32 +0000869 cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
870 << " - " << getDescription(i) << "\n";
Chris Lattner9c9be482002-01-31 00:42:56 +0000871 }
Chris Lattner331de232002-07-22 02:07:59 +0000872 } else {
873 if (O.HelpStr[0])
Bill Wendlinge8156192006-12-07 01:30:32 +0000874 cout << " " << O.HelpStr << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000875 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
876 unsigned L = std::strlen(getOption(i));
Bill Wendlinge8156192006-12-07 01:30:32 +0000877 cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
878 << " - " << getDescription(i) << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000879 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000880 }
881}
882
883
884//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000885// --help and --help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000886//
Reid Spencerad0846b2004-11-14 22:04:00 +0000887
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000888namespace {
889
Chris Lattner331de232002-07-22 02:07:59 +0000890class HelpPrinter {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000891 unsigned MaxArgLen;
892 const Option *EmptyArg;
893 const bool ShowHidden;
894
Chris Lattner331de232002-07-22 02:07:59 +0000895 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
Chris Lattnerca6433f2003-05-22 20:06:43 +0000896 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000897 return OptPair.second->getOptionHiddenFlag() >= Hidden;
898 }
Chris Lattnerca6433f2003-05-22 20:06:43 +0000899 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000900 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
901 }
902
903public:
904 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
905 EmptyArg = 0;
906 }
907
908 void operator=(bool Value) {
909 if (Value == false) return;
910
Chris Lattner9878d6a2007-04-06 21:06:55 +0000911 // Get all the options.
912 std::vector<Option*> PositionalOpts;
913 std::map<std::string, Option*> OptMap;
914 GetOptionInfo(PositionalOpts, OptMap);
915
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000916 // Copy Options into a vector so we can sort them as we like...
Chris Lattner90aa8392006-10-04 21:52:35 +0000917 std::vector<std::pair<std::string, Option*> > Opts;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000918 copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts));
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000919
920 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Chris Lattner90aa8392006-10-04 21:52:35 +0000921 Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
922 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
923 Opts.end());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000924
925 // Eliminate duplicate entries in table (from enum flags options, f.e.)
Chris Lattner331de232002-07-22 02:07:59 +0000926 { // Give OptionSet a scope
927 std::set<Option*> OptionSet;
Chris Lattner90aa8392006-10-04 21:52:35 +0000928 for (unsigned i = 0; i != Opts.size(); ++i)
929 if (OptionSet.count(Opts[i].second) == 0)
930 OptionSet.insert(Opts[i].second); // Add new entry to set
Chris Lattner331de232002-07-22 02:07:59 +0000931 else
Chris Lattner90aa8392006-10-04 21:52:35 +0000932 Opts.erase(Opts.begin()+i--); // Erase duplicate
Chris Lattner331de232002-07-22 02:07:59 +0000933 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000934
935 if (ProgramOverview)
Bill Wendlinge8156192006-12-07 01:30:32 +0000936 cout << "OVERVIEW:" << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000937
Bill Wendlinge8156192006-12-07 01:30:32 +0000938 cout << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +0000939
Chris Lattner90aa8392006-10-04 21:52:35 +0000940 // Print out the positional options.
Chris Lattner331de232002-07-22 02:07:59 +0000941 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000942 if (!PositionalOpts.empty() &&
943 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
944 CAOpt = PositionalOpts[0];
Chris Lattner331de232002-07-22 02:07:59 +0000945
Chris Lattner9878d6a2007-04-06 21:06:55 +0000946 for (unsigned i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
947 if (PositionalOpts[i]->ArgStr[0])
948 cout << " --" << PositionalOpts[i]->ArgStr;
949 cout << " " << PositionalOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000950 }
Chris Lattner331de232002-07-22 02:07:59 +0000951
952 // Print the consume after option info if it exists...
Bill Wendlinge8156192006-12-07 01:30:32 +0000953 if (CAOpt) cout << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +0000954
Bill Wendlinge8156192006-12-07 01:30:32 +0000955 cout << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000956
957 // Compute the maximum argument length...
958 MaxArgLen = 0;
Chris Lattner90aa8392006-10-04 21:52:35 +0000959 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
960 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000961
Bill Wendlinge8156192006-12-07 01:30:32 +0000962 cout << "OPTIONS:\n";
Chris Lattner90aa8392006-10-04 21:52:35 +0000963 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
964 Opts[i].second->printOptionInfo(MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000965
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000966 // Print any extra help the user has declared.
Chris Lattner90aa8392006-10-04 21:52:35 +0000967 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
968 E = MoreHelp->end(); I != E; ++I)
Bill Wendlinge8156192006-12-07 01:30:32 +0000969 cout << *I;
Chris Lattner90aa8392006-10-04 21:52:35 +0000970 MoreHelp->clear();
Reid Spencerad0846b2004-11-14 22:04:00 +0000971
Reid Spencer9bbba0912004-11-16 06:11:52 +0000972 // Halt the program since help information was printed
Chris Lattner331de232002-07-22 02:07:59 +0000973 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000974 }
975};
Chris Lattner500d8bf2006-10-12 22:09:17 +0000976} // End anonymous namespace
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000977
Chris Lattner331de232002-07-22 02:07:59 +0000978// Define the two HelpPrinter instances that are used to print out help, or
979// help-hidden...
980//
Chris Lattner500d8bf2006-10-12 22:09:17 +0000981static HelpPrinter NormalPrinter(false);
982static HelpPrinter HiddenPrinter(true);
Chris Lattner331de232002-07-22 02:07:59 +0000983
Chris Lattner500d8bf2006-10-12 22:09:17 +0000984static cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +0000985HOp("help", cl::desc("Display available options (--help-hidden for more)"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000986 cl::location(NormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +0000987
Chris Lattner500d8bf2006-10-12 22:09:17 +0000988static cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +0000989HHOp("help-hidden", cl::desc("Display all available options"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000990 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000991
Chris Lattner500d8bf2006-10-12 22:09:17 +0000992static void (*OverrideVersionPrinter)() = 0;
Reid Spencer515b5b32006-06-05 16:22:56 +0000993
Chris Lattner500d8bf2006-10-12 22:09:17 +0000994namespace {
Reid Spencer515b5b32006-06-05 16:22:56 +0000995class VersionPrinter {
996public:
Devang Patelaed293d2007-02-01 01:43:37 +0000997 void print() {
Bill Wendlinge8156192006-12-07 01:30:32 +0000998 cout << "Low Level Virtual Machine (http://llvm.org/):\n";
999 cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001000#ifdef LLVM_VERSION_INFO
Bill Wendlinge8156192006-12-07 01:30:32 +00001001 cout << LLVM_VERSION_INFO;
Reid Spencer515b5b32006-06-05 16:22:56 +00001002#endif
Bill Wendlinge8156192006-12-07 01:30:32 +00001003 cout << "\n ";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001004#ifndef __OPTIMIZE__
Bill Wendlinge8156192006-12-07 01:30:32 +00001005 cout << "DEBUG build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001006#else
Bill Wendlinge8156192006-12-07 01:30:32 +00001007 cout << "Optimized build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001008#endif
1009#ifndef NDEBUG
Bill Wendlinge8156192006-12-07 01:30:32 +00001010 cout << " with assertions";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001011#endif
Bill Wendlinge8156192006-12-07 01:30:32 +00001012 cout << ".\n";
Devang Patelaed293d2007-02-01 01:43:37 +00001013 }
1014 void operator=(bool OptionWasSpecified) {
1015 if (OptionWasSpecified) {
1016 if (OverrideVersionPrinter == 0) {
1017 print();
Reid Spencer515b5b32006-06-05 16:22:56 +00001018 exit(1);
1019 } else {
1020 (*OverrideVersionPrinter)();
1021 exit(1);
1022 }
1023 }
1024 }
1025};
Chris Lattner500d8bf2006-10-12 22:09:17 +00001026} // End anonymous namespace
Reid Spencer515b5b32006-06-05 16:22:56 +00001027
1028
Reid Spencer69105f32004-08-04 00:36:06 +00001029// Define the --version option that prints out the LLVM version for the tool
Chris Lattner500d8bf2006-10-12 22:09:17 +00001030static VersionPrinter VersionPrinterInstance;
1031
1032static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001033VersOp("version", cl::desc("Display the version of this program"),
Reid Spencer69105f32004-08-04 00:36:06 +00001034 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1035
Reid Spencer9bbba0912004-11-16 06:11:52 +00001036// Utility function for printing the help message.
1037void cl::PrintHelpMessage() {
Misha Brukmanf976c852005-04-21 22:55:34 +00001038 // This looks weird, but it actually prints the help message. The
Reid Spencer5cc498f2004-11-16 06:50:36 +00001039 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1040 // its operator= is invoked. That's because the "normal" usages of the
Misha Brukmanf976c852005-04-21 22:55:34 +00001041 // help printer is to be assigned true/false depending on whether the
Reid Spencer5cc498f2004-11-16 06:50:36 +00001042 // --help option was given or not. Since we're circumventing that we have
1043 // to make it look like --help was given, so we assign true.
Reid Spencer9bbba0912004-11-16 06:11:52 +00001044 NormalPrinter = true;
1045}
Reid Spencer515b5b32006-06-05 16:22:56 +00001046
Devang Patelaed293d2007-02-01 01:43:37 +00001047/// Utility function for printing version number.
1048void cl::PrintVersionMessage() {
1049 VersionPrinterInstance.print();
1050}
1051
Reid Spencer515b5b32006-06-05 16:22:56 +00001052void cl::SetVersionPrinter(void (*func)()) {
1053 OverrideVersionPrinter = func;
1054}