blob: c70ed0da0ccdf02f166082c63e89abfc728a1ae5 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000032#include <climits>
Chris Lattner2cdd21c2003-12-14 21:35:53 +000033using namespace llvm;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000034using namespace cl;
35
Chris Lattner7422a762006-08-27 12:45:47 +000036//===----------------------------------------------------------------------===//
37// Template instantiations and anchors.
38//
39TEMPLATE_INSTANTIATION(class basic_parser<bool>);
Dale Johannesen81da02b2007-05-22 17:14:46 +000040TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
Chris Lattner7422a762006-08-27 12:45:47 +000041TEMPLATE_INSTANTIATION(class basic_parser<int>);
42TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
43TEMPLATE_INSTANTIATION(class basic_parser<double>);
44TEMPLATE_INSTANTIATION(class basic_parser<float>);
45TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
46
47TEMPLATE_INSTANTIATION(class opt<unsigned>);
48TEMPLATE_INSTANTIATION(class opt<int>);
49TEMPLATE_INSTANTIATION(class opt<std::string>);
50TEMPLATE_INSTANTIATION(class opt<bool>);
51
52void Option::anchor() {}
53void basic_parser_impl::anchor() {}
54void parser<bool>::anchor() {}
Dale Johannesen81da02b2007-05-22 17:14:46 +000055void parser<boolOrDefault>::anchor() {}
Chris Lattner7422a762006-08-27 12:45:47 +000056void parser<int>::anchor() {}
57void parser<unsigned>::anchor() {}
58void parser<double>::anchor() {}
59void parser<float>::anchor() {}
60void parser<std::string>::anchor() {}
61
62//===----------------------------------------------------------------------===//
63
Chris Lattnerefa3da52006-10-13 00:06:24 +000064// Globals for name and overview of program. Program name is not a string to
65// avoid static ctor/dtor issues.
66static char ProgramName[80] = "<premain>";
Reid Spencere1cc1502004-09-01 04:41:28 +000067static const char *ProgramOverview = 0;
68
Chris Lattnerc540ebb2004-11-19 17:08:15 +000069// This collects additional help to be printed.
Chris Lattner90aa8392006-10-04 21:52:35 +000070static ManagedStatic<std::vector<const char*> > MoreHelp;
Chris Lattnerc540ebb2004-11-19 17:08:15 +000071
Chris Lattner90aa8392006-10-04 21:52:35 +000072extrahelp::extrahelp(const char *Help)
Chris Lattnerc540ebb2004-11-19 17:08:15 +000073 : morehelp(Help) {
Chris Lattner90aa8392006-10-04 21:52:35 +000074 MoreHelp->push_back(Help);
Chris Lattnerc540ebb2004-11-19 17:08:15 +000075}
76
Chris Lattner69d6f132007-04-12 00:36:29 +000077static bool OptionListChanged = false;
78
79// MarkOptionsChanged - Internal helper function.
80void cl::MarkOptionsChanged() {
81 OptionListChanged = true;
82}
83
Chris Lattner9878d6a2007-04-06 21:06:55 +000084/// RegisteredOptionList - This is the list of the command line options that
85/// have statically constructed themselves.
86static Option *RegisteredOptionList = 0;
87
88void Option::addArgument() {
89 assert(NextRegistered == 0 && "argument multiply registered!");
90
91 NextRegistered = RegisteredOptionList;
92 RegisteredOptionList = this;
Chris Lattner69d6f132007-04-12 00:36:29 +000093 MarkOptionsChanged();
Chris Lattner9878d6a2007-04-06 21:06:55 +000094}
95
Chris Lattner69d6f132007-04-12 00:36:29 +000096
Chris Lattner331de232002-07-22 02:07:59 +000097//===----------------------------------------------------------------------===//
Chris Lattner7422a762006-08-27 12:45:47 +000098// Basic, shared command line option processing machinery.
Chris Lattner331de232002-07-22 02:07:59 +000099//
100
Chris Lattner9878d6a2007-04-06 21:06:55 +0000101/// GetOptionInfo - Scan the list of registered options, turning them into data
102/// structures that are easier to handle.
103static void GetOptionInfo(std::vector<Option*> &PositionalOpts,
104 std::map<std::string, Option*> &OptionsMap) {
105 std::vector<const char*> OptionNames;
Chris Lattneree2b3202007-04-07 05:38:53 +0000106 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000107 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
108 // If this option wants to handle multiple option names, get the full set.
109 // This handles enum options like "-O1 -O2" etc.
110 O->getExtraOptionNames(OptionNames);
111 if (O->ArgStr[0])
112 OptionNames.push_back(O->ArgStr);
113
114 // Handle named options.
115 for (unsigned i = 0, e = OptionNames.size(); i != e; ++i) {
116 // Add argument to the argument map!
117 if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i],
118 O)).second) {
119 cerr << ProgramName << ": CommandLine Error: Argument '"
120 << OptionNames[0] << "' defined more than once!\n";
121 }
122 }
123
124 OptionNames.clear();
125
126 // Remember information about positional options.
127 if (O->getFormattingFlag() == cl::Positional)
128 PositionalOpts.push_back(O);
129 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattneree2b3202007-04-07 05:38:53 +0000130 if (CAOpt)
Chris Lattner9878d6a2007-04-06 21:06:55 +0000131 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattneree2b3202007-04-07 05:38:53 +0000132 CAOpt = O;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000133 }
Chris Lattnere8e258b2002-07-29 20:58:42 +0000134 }
Chris Lattneree2b3202007-04-07 05:38:53 +0000135
136 if (CAOpt)
137 PositionalOpts.push_back(CAOpt);
138
139 // Make sure that they are in order of registration not backwards.
140 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
Chris Lattnere8e258b2002-07-29 20:58:42 +0000141}
142
Chris Lattner9878d6a2007-04-06 21:06:55 +0000143
Chris Lattneraf035f32007-04-05 21:58:17 +0000144/// LookupOption - Lookup the option specified by the specified option on the
145/// command line. If there is a value specified (after an equal sign) return
146/// that as well.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000147static Option *LookupOption(const char *&Arg, const char *&Value,
148 std::map<std::string, Option*> &OptionsMap) {
Chris Lattneraf035f32007-04-05 21:58:17 +0000149 while (*Arg == '-') ++Arg; // Eat leading dashes
150
151 const char *ArgEnd = Arg;
152 while (*ArgEnd && *ArgEnd != '=')
153 ++ArgEnd; // Scan till end of argument name.
154
155 if (*ArgEnd == '=') // If we have an equals sign...
156 Value = ArgEnd+1; // Get the value, not the equals
157
158
159 if (*Arg == 0) return 0;
160
161 // Look up the option.
Chris Lattneraf035f32007-04-05 21:58:17 +0000162 std::map<std::string, Option*>::iterator I =
Chris Lattner9878d6a2007-04-06 21:06:55 +0000163 OptionsMap.find(std::string(Arg, ArgEnd));
164 return I != OptionsMap.end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000165}
166
Chris Lattnercaccd762001-10-27 05:54:17 +0000167static inline bool ProvideOption(Option *Handler, const char *ArgName,
168 const char *Value, int argc, char **argv,
169 int &i) {
170 // Enforce value requirements
171 switch (Handler->getValueExpectedFlag()) {
172 case ValueRequired:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000173 if (Value == 0) { // No value specified?
Chris Lattnercaccd762001-10-27 05:54:17 +0000174 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
175 Value = argv[++i];
176 } else {
177 return Handler->error(" requires a value!");
178 }
179 }
180 break;
181 case ValueDisallowed:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000182 if (Value)
Misha Brukmanf976c852005-04-21 22:55:34 +0000183 return Handler->error(" does not allow a value! '" +
Chris Lattnerca6433f2003-05-22 20:06:43 +0000184 std::string(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +0000185 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000186 case ValueOptional:
Reid Spencere1cc1502004-09-01 04:41:28 +0000187 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000188 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000189 cerr << ProgramName
190 << ": Bad ValueMask flag! CommandLine usage error:"
191 << Handler->getValueExpectedFlag() << "\n";
Reid Spencere1cc1502004-09-01 04:41:28 +0000192 abort();
193 break;
Chris Lattnercaccd762001-10-27 05:54:17 +0000194 }
195
196 // Run the handler now!
Chris Lattner6d5857e2005-05-10 23:20:17 +0000197 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
Chris Lattnercaccd762001-10-27 05:54:17 +0000198}
199
Misha Brukmanf976c852005-04-21 22:55:34 +0000200static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000201 int i) {
202 int Dummy = i;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000203 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000204}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000205
Chris Lattner331de232002-07-22 02:07:59 +0000206
207// Option predicates...
208static inline bool isGrouping(const Option *O) {
209 return O->getFormattingFlag() == cl::Grouping;
210}
211static inline bool isPrefixedOrGrouping(const Option *O) {
212 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
213}
214
215// getOptionPred - Check to see if there are any options that satisfy the
216// specified predicate with names that are the prefixes in Name. This is
217// checked by progressively stripping characters off of the name, checking to
218// see if there options that satisfy the predicate. If we find one, return it,
219// otherwise return null.
220//
221static Option *getOptionPred(std::string Name, unsigned &Length,
Chris Lattner9878d6a2007-04-06 21:06:55 +0000222 bool (*Pred)(const Option*),
223 std::map<std::string, Option*> &OptionsMap) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000224
Chris Lattner9878d6a2007-04-06 21:06:55 +0000225 std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name);
226 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner331de232002-07-22 02:07:59 +0000227 Length = Name.length();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000228 return OMI->second;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000229 }
230
Chris Lattner331de232002-07-22 02:07:59 +0000231 if (Name.size() == 1) return 0;
232 do {
233 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000234 OMI = OptionsMap.find(Name);
Chris Lattner331de232002-07-22 02:07:59 +0000235
236 // Loop while we haven't found an option and Name still has at least two
237 // characters in it (so that the next iteration will not be the empty
238 // string...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000239 } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1);
Chris Lattner331de232002-07-22 02:07:59 +0000240
Chris Lattner9878d6a2007-04-06 21:06:55 +0000241 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner331de232002-07-22 02:07:59 +0000242 Length = Name.length();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000243 return OMI->second; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000244 }
245 return 0; // No option found!
246}
247
248static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000249 return O->getNumOccurrencesFlag() == cl::Required ||
250 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000251}
252
253static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000254 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
255 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000256}
Chris Lattnercaccd762001-10-27 05:54:17 +0000257
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000258/// ParseCStringVector - Break INPUT up wherever one or more
259/// whitespace characters are found, and store the resulting tokens in
260/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
261/// using strdup (), so it is the caller's responsibility to free ()
262/// them later.
Brian Gaeke06b06c52003-08-14 22:00:59 +0000263///
Chris Lattner23288582006-08-27 22:10:29 +0000264static void ParseCStringVector(std::vector<char *> &output,
265 const char *input) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000266 // Characters which will be treated as token separators:
267 static const char *delims = " \v\f\t\r\n";
268
269 std::string work (input);
270 // Skip past any delims at head of input string.
271 size_t pos = work.find_first_not_of (delims);
272 // If the string consists entirely of delims, then exit early.
273 if (pos == std::string::npos) return;
274 // Otherwise, jump forward to beginning of first word.
275 work = work.substr (pos);
276 // Find position of first delimiter.
277 pos = work.find_first_of (delims);
278
279 while (!work.empty() && pos != std::string::npos) {
280 // Everything from 0 to POS is the next word to copy.
281 output.push_back (strdup (work.substr (0,pos).c_str ()));
282 // Is there another word in the string?
283 size_t nextpos = work.find_first_not_of (delims, pos + 1);
284 if (nextpos != std::string::npos) {
285 // Yes? Then remove delims from beginning ...
286 work = work.substr (work.find_first_not_of (delims, pos + 1));
287 // and find the end of the word.
288 pos = work.find_first_of (delims);
289 } else {
290 // No? (Remainder of string is delims.) End the loop.
291 work = "";
292 pos = std::string::npos;
293 }
294 }
295
296 // If `input' ended with non-delim char, then we'll get here with
297 // the last word of `input' in `work'; copy it now.
298 if (!work.empty ()) {
299 output.push_back (strdup (work.c_str ()));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000300 }
301}
302
303/// ParseEnvironmentOptions - An alternative entry point to the
304/// CommandLine library, which allows you to read the program's name
305/// from the caller (as PROGNAME) and its command-line arguments from
306/// an environment variable (whose name is given in ENVVAR).
307///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000308void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
309 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000310 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000311 assert(progName && "Program name not specified");
312 assert(envVar && "Environment variable name missing");
Misha Brukmanf976c852005-04-21 22:55:34 +0000313
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000314 // Get the environment variable they want us to parse options out of.
Chris Lattner23288582006-08-27 22:10:29 +0000315 const char *envValue = getenv(envVar);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000316 if (!envValue)
317 return;
318
Brian Gaeke06b06c52003-08-14 22:00:59 +0000319 // Get program's "name", which we wouldn't know without the caller
320 // telling us.
Chris Lattner23288582006-08-27 22:10:29 +0000321 std::vector<char*> newArgv;
322 newArgv.push_back(strdup(progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000323
324 // Parse the value of the environment variable into a "command line"
325 // and hand it off to ParseCommandLineOptions().
Chris Lattner23288582006-08-27 22:10:29 +0000326 ParseCStringVector(newArgv, envValue);
327 int newArgc = newArgv.size();
328 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000329
330 // Free all the strdup()ed strings.
Chris Lattner23288582006-08-27 22:10:29 +0000331 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
332 i != e; ++i)
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000333 free (*i);
Brian Gaeke06b06c52003-08-14 22:00:59 +0000334}
335
Dan Gohman9a526322007-10-09 16:04:57 +0000336void cl::ParseCommandLineOptions(int argc, char **argv,
Chris Lattner0c0edf82002-07-25 06:17:51 +0000337 const char *Overview) {
Chris Lattner9878d6a2007-04-06 21:06:55 +0000338 // Process all registered options.
339 std::vector<Option*> PositionalOpts;
340 std::map<std::string, Option*> Opts;
341 GetOptionInfo(PositionalOpts, Opts);
342
343 assert((!Opts.empty() || !PositionalOpts.empty()) &&
344 "No options specified!");
Reid Spencer6f4c6072006-08-23 07:10:06 +0000345 sys::Path progname(argv[0]);
Chris Lattnerefa3da52006-10-13 00:06:24 +0000346
347 // Copy the program name into ProgName, making sure not to overflow it.
348 std::string ProgName = sys::Path(argv[0]).getLast();
349 if (ProgName.size() > 79) ProgName.resize(79);
350 strcpy(ProgramName, ProgName.c_str());
351
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000352 ProgramOverview = Overview;
353 bool ErrorParsing = false;
354
Chris Lattner331de232002-07-22 02:07:59 +0000355 // Check out the positional arguments to collect information about them.
356 unsigned NumPositionalRequired = 0;
Chris Lattnerde013242005-08-08 17:25:38 +0000357
358 // Determine whether or not there are an unlimited number of positionals
359 bool HasUnlimitedPositionals = false;
360
Chris Lattner331de232002-07-22 02:07:59 +0000361 Option *ConsumeAfterOpt = 0;
362 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000363 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000364 assert(PositionalOpts.size() > 1 &&
365 "Cannot specify cl::ConsumeAfter without a positional argument!");
366 ConsumeAfterOpt = PositionalOpts[0];
367 }
368
369 // Calculate how many positional values are _required_.
370 bool UnboundedFound = false;
371 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
372 i != e; ++i) {
373 Option *Opt = PositionalOpts[i];
374 if (RequiresValue(Opt))
375 ++NumPositionalRequired;
376 else if (ConsumeAfterOpt) {
377 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000378 // unless there is only one positional argument...
379 if (PositionalOpts.size() > 2)
380 ErrorParsing |=
381 Opt->error(" error - this positional option will never be matched, "
382 "because it does not Require a value, and a "
383 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000384 } else if (UnboundedFound && !Opt->ArgStr[0]) {
385 // This option does not "require" a value... Make sure this option is
386 // not specified after an option that eats all extra arguments, or this
387 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000388 //
389 ErrorParsing |= Opt->error(" error - option can never match, because "
390 "another positional argument will match an "
391 "unbounded number of values, and this option"
392 " does not require a value!");
393 }
394 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
395 }
Chris Lattner21e1a792005-08-08 21:57:27 +0000396 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000397 }
398
Reid Spencer1e13fd22004-08-13 19:47:30 +0000399 // PositionalVals - A vector of "positional" arguments we accumulate into
400 // the process at the end...
Chris Lattner331de232002-07-22 02:07:59 +0000401 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000402 std::vector<std::pair<std::string,unsigned> > PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000403
Chris Lattner9cf3d472003-07-30 17:34:02 +0000404 // If the program has named positional arguments, and the name has been run
405 // across, keep track of which positional argument was named. Otherwise put
406 // the positional args into the PositionalVals list...
407 Option *ActivePositionalArg = 0;
408
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000409 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000410 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000411 for (int i = 1; i < argc; ++i) {
412 Option *Handler = 0;
Chris Lattner6d5857e2005-05-10 23:20:17 +0000413 const char *Value = 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000414 const char *ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000415
Chris Lattner69d6f132007-04-12 00:36:29 +0000416 // If the option list changed, this means that some command line
Chris Lattner159b0a432007-04-11 15:35:18 +0000417 // option has just been registered or deregistered. This can occur in
418 // response to things like -load, etc. If this happens, rescan the options.
Chris Lattner69d6f132007-04-12 00:36:29 +0000419 if (OptionListChanged) {
Chris Lattner159b0a432007-04-11 15:35:18 +0000420 PositionalOpts.clear();
421 Opts.clear();
422 GetOptionInfo(PositionalOpts, Opts);
Chris Lattner69d6f132007-04-12 00:36:29 +0000423 OptionListChanged = false;
Chris Lattner159b0a432007-04-11 15:35:18 +0000424 }
425
Chris Lattner331de232002-07-22 02:07:59 +0000426 // Check to see if this is a positional argument. This argument is
427 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000428 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000429 //
430 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
431 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000432 if (ActivePositionalArg) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000433 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000434 continue; // We are done!
435 } else if (!PositionalOpts.empty()) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000436 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000437
438 // All of the positional arguments have been fulfulled, give the rest to
439 // the consume after option... if it's specified...
440 //
Misha Brukmanf976c852005-04-21 22:55:34 +0000441 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000442 ConsumeAfterOpt != 0) {
443 for (++i; i < argc; ++i)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000444 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000445 break; // Handle outside of the argument processing loop...
446 }
447
448 // Delay processing positional arguments until the end...
449 continue;
450 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000451 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
452 !DashDashFound) {
453 DashDashFound = true; // This is the mythical "--"?
454 continue; // Don't try to process it as an argument itself.
455 } else if (ActivePositionalArg &&
456 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
457 // If there is a positional argument eating options, check to see if this
458 // option is another positional argument. If so, treat it as an argument,
459 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000460 ArgName = argv[i]+1;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000461 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000462 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000463 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000464 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000465 }
466
Chris Lattnerbf455c22004-05-06 22:04:31 +0000467 } else { // We start with a '-', must be an argument...
468 ArgName = argv[i]+1;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000469 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000470
Chris Lattnerbf455c22004-05-06 22:04:31 +0000471 // Check to see if this "option" is really a prefixed or grouped argument.
Reid Spencer5f8448f2004-11-24 06:13:42 +0000472 if (Handler == 0) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000473 std::string RealName(ArgName);
474 if (RealName.size() > 1) {
Chris Lattner331de232002-07-22 02:07:59 +0000475 unsigned Length = 0;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000476 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping,
477 Opts);
Misha Brukmanf976c852005-04-21 22:55:34 +0000478
Chris Lattner331de232002-07-22 02:07:59 +0000479 // If the option is a prefixed option, then the value is simply the
480 // rest of the name... so fall through to later processing, by
481 // setting up the argument name flags and value fields.
482 //
483 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000484 Value = ArgName+Length;
485 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
486 Opts.find(std::string(ArgName, Value))->second == PGOpt);
487 Handler = PGOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000488 } else if (PGOpt) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000489 // This must be a grouped option... handle them now.
Chris Lattner331de232002-07-22 02:07:59 +0000490 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000491
Chris Lattner331de232002-07-22 02:07:59 +0000492 do {
493 // Move current arg name out of RealName into RealArgName...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000494 std::string RealArgName(RealName.begin(),
495 RealName.begin() + Length);
496 RealName.erase(RealName.begin(), RealName.begin() + Length);
Misha Brukmanf976c852005-04-21 22:55:34 +0000497
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000498 // Because ValueRequired is an invalid flag for grouped arguments,
499 // we don't need to pass argc/argv in...
500 //
Chris Lattner331de232002-07-22 02:07:59 +0000501 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
502 "Option can not be cl::Grouping AND cl::ValueRequired!");
503 int Dummy;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000504 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
Chris Lattner6d5857e2005-05-10 23:20:17 +0000505 0, 0, 0, Dummy);
Misha Brukmanf976c852005-04-21 22:55:34 +0000506
Chris Lattner331de232002-07-22 02:07:59 +0000507 // Get the next grouping option...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000508 PGOpt = getOptionPred(RealName, Length, isGrouping, Opts);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000509 } while (PGOpt && Length != RealName.size());
Misha Brukmanf976c852005-04-21 22:55:34 +0000510
Chris Lattnerbf455c22004-05-06 22:04:31 +0000511 Handler = PGOpt; // Ate all of the options.
Chris Lattner331de232002-07-22 02:07:59 +0000512 }
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000513 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000514 }
515 }
516
517 if (Handler == 0) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000518 cerr << ProgramName << ": Unknown command line argument '"
519 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000520 ErrorParsing = true;
521 continue;
522 }
523
Chris Lattner72fb8e52003-05-22 20:26:17 +0000524 // Check to see if this option accepts a comma separated list of values. If
525 // it does, we have to split up the value into multiple values...
Chris Lattner6d5857e2005-05-10 23:20:17 +0000526 if (Value && Handler->getMiscFlags() & CommaSeparated) {
Chris Lattner72fb8e52003-05-22 20:26:17 +0000527 std::string Val(Value);
528 std::string::size_type Pos = Val.find(',');
529
530 while (Pos != std::string::npos) {
531 // Process the portion before the comma...
532 ErrorParsing |= ProvideOption(Handler, ArgName,
533 std::string(Val.begin(),
534 Val.begin()+Pos).c_str(),
535 argc, argv, i);
536 // Erase the portion before the comma, AND the comma...
537 Val.erase(Val.begin(), Val.begin()+Pos+1);
538 Value += Pos+1; // Increment the original value pointer as well...
539
540 // Check for another comma...
541 Pos = Val.find(',');
542 }
543 }
Chris Lattner9cf3d472003-07-30 17:34:02 +0000544
545 // If this is a named positional argument, just remember that it is the
546 // active one...
547 if (Handler->getFormattingFlag() == cl::Positional)
548 ActivePositionalArg = Handler;
Misha Brukmanf976c852005-04-21 22:55:34 +0000549 else
Chris Lattner9cf3d472003-07-30 17:34:02 +0000550 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000551 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000552
Chris Lattner331de232002-07-22 02:07:59 +0000553 // Check and handle positional arguments now...
554 if (NumPositionalRequired > PositionalVals.size()) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000555 cerr << ProgramName
556 << ": Not enough positional command line arguments specified!\n"
557 << "Must specify at least " << NumPositionalRequired
558 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattner79959d22006-01-17 00:32:28 +0000559
Chris Lattner331de232002-07-22 02:07:59 +0000560 ErrorParsing = true;
Chris Lattnerde013242005-08-08 17:25:38 +0000561 } else if (!HasUnlimitedPositionals
562 && PositionalVals.size() > PositionalOpts.size()) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000563 cerr << ProgramName
564 << ": Too many positional arguments specified!\n"
565 << "Can specify at most " << PositionalOpts.size()
566 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattnerde013242005-08-08 17:25:38 +0000567 ErrorParsing = true;
Chris Lattner331de232002-07-22 02:07:59 +0000568
569 } else if (ConsumeAfterOpt == 0) {
570 // Positional args have already been handled if ConsumeAfter is specified...
571 unsigned ValNo = 0, NumVals = PositionalVals.size();
572 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
573 if (RequiresValue(PositionalOpts[i])) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000574 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000575 PositionalVals[ValNo].second);
576 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000577 --NumPositionalRequired; // We fulfilled our duty...
578 }
579
580 // If we _can_ give this option more arguments, do so now, as long as we
581 // do not give it values that others need. 'Done' controls whether the
582 // option even _WANTS_ any more.
583 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000584 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000585 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000586 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000587 case cl::Optional:
588 Done = true; // Optional arguments want _at most_ one value
589 // FALL THROUGH
590 case cl::ZeroOrMore: // Zero or more will take all they can get...
591 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer1e13fd22004-08-13 19:47:30 +0000592 ProvidePositionalOption(PositionalOpts[i],
593 PositionalVals[ValNo].first,
594 PositionalVals[ValNo].second);
595 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000596 break;
597 default:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000598 assert(0 && "Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000599 "positional argument processing!");
600 }
601 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000602 }
Chris Lattner331de232002-07-22 02:07:59 +0000603 } else {
604 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
605 unsigned ValNo = 0;
606 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000607 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000608 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000609 PositionalVals[ValNo].first,
610 PositionalVals[ValNo].second);
611 ValNo++;
612 }
Chris Lattnerfaba8092002-07-24 20:15:13 +0000613
614 // Handle the case where there is just one positional option, and it's
615 // optional. In this case, we want to give JUST THE FIRST option to the
616 // positional option and keep the rest for the consume after. The above
617 // loop would have assigned no values to positional options in this case.
618 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000619 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000620 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000621 PositionalVals[ValNo].first,
622 PositionalVals[ValNo].second);
623 ValNo++;
624 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000625
Chris Lattner331de232002-07-22 02:07:59 +0000626 // Handle over all of the rest of the arguments to the
627 // cl::ConsumeAfter command line option...
628 for (; ValNo != PositionalVals.size(); ++ValNo)
629 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000630 PositionalVals[ValNo].first,
631 PositionalVals[ValNo].second);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000632 }
633
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000634 // Loop over args and make sure all required args are specified!
Misha Brukmanf976c852005-04-21 22:55:34 +0000635 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000636 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000637 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000638 case Required:
639 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000640 if (I->second->getNumOccurrences() == 0) {
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000641 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000642 ErrorParsing = true;
643 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000644 // Fall through
645 default:
646 break;
647 }
648 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000649
Chris Lattner331de232002-07-22 02:07:59 +0000650 // Free all of the memory allocated to the map. Command line options may only
651 // be processed once!
Chris Lattner90aa8392006-10-04 21:52:35 +0000652 Opts.clear();
Chris Lattner331de232002-07-22 02:07:59 +0000653 PositionalOpts.clear();
Chris Lattner90aa8392006-10-04 21:52:35 +0000654 MoreHelp->clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000655
656 // If we had an error processing our arguments, don't let the program execute
657 if (ErrorParsing) exit(1);
658}
659
660//===----------------------------------------------------------------------===//
661// Option Base class implementation
662//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000663
Chris Lattnerca6433f2003-05-22 20:06:43 +0000664bool Option::error(std::string Message, const char *ArgName) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000665 if (ArgName == 0) ArgName = ArgStr;
Chris Lattner331de232002-07-22 02:07:59 +0000666 if (ArgName[0] == 0)
Bill Wendlinge8156192006-12-07 01:30:32 +0000667 cerr << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000668 else
Bill Wendlinge8156192006-12-07 01:30:32 +0000669 cerr << ProgramName << ": for the -" << ArgName;
Jim Laskeyabe0e3e2006-08-02 20:15:56 +0000670
Bill Wendlinge8156192006-12-07 01:30:32 +0000671 cerr << " option: " << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000672 return true;
673}
674
Chris Lattner6d5857e2005-05-10 23:20:17 +0000675bool Option::addOccurrence(unsigned pos, const char *ArgName,
676 const std::string &Value) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000677 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000678
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000679 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000680 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000681 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000682 return error(": may only occur zero or one times!", ArgName);
683 break;
684 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000685 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000686 return error(": must occur exactly one time!", ArgName);
687 // Fall through
688 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000689 case ZeroOrMore:
690 case ConsumeAfter: break;
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000691 default: return error(": bad num occurrences flag value!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000692 }
693
Reid Spencer1e13fd22004-08-13 19:47:30 +0000694 return handleOccurrence(pos, ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000695}
696
Chris Lattner331de232002-07-22 02:07:59 +0000697
698// getValueStr - Get the value description string, using "DefaultMsg" if nothing
699// has been specified yet.
700//
701static const char *getValueStr(const Option &O, const char *DefaultMsg) {
702 if (O.ValueStr[0] == 0) return DefaultMsg;
703 return O.ValueStr;
704}
705
706//===----------------------------------------------------------------------===//
707// cl::alias class implementation
708//
709
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000710// Return the width of the option tag for printing...
Chris Lattner331de232002-07-22 02:07:59 +0000711unsigned alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000712 return std::strlen(ArgStr)+6;
713}
714
Chris Lattnera0de8432006-04-28 05:36:25 +0000715// Print out the option for the alias.
Chris Lattner331de232002-07-22 02:07:59 +0000716void alias::printOptionInfo(unsigned GlobalWidth) const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000717 unsigned L = std::strlen(ArgStr);
Bill Wendlinge8156192006-12-07 01:30:32 +0000718 cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
719 << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000720}
721
722
Chris Lattner331de232002-07-22 02:07:59 +0000723
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000724//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000725// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000726//
727
Chris Lattner9b14eb52002-08-07 18:36:37 +0000728// basic_parser implementation
729//
730
731// Return the width of the option tag for printing...
732unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
733 unsigned Len = std::strlen(O.ArgStr);
734 if (const char *ValName = getValueName())
735 Len += std::strlen(getValueStr(O, ValName))+3;
736
737 return Len + 6;
738}
739
Misha Brukmanf976c852005-04-21 22:55:34 +0000740// printOptionInfo - Print out information about this option. The
Chris Lattner9b14eb52002-08-07 18:36:37 +0000741// to-be-maintained width is specified.
742//
743void basic_parser_impl::printOptionInfo(const Option &O,
744 unsigned GlobalWidth) const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000745 cout << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000746
747 if (const char *ValName = getValueName())
Bill Wendlinge8156192006-12-07 01:30:32 +0000748 cout << "=<" << getValueStr(O, ValName) << ">";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000749
Bill Wendlinge8156192006-12-07 01:30:32 +0000750 cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
751 << O.HelpStr << "\n";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000752}
753
754
755
756
Chris Lattner331de232002-07-22 02:07:59 +0000757// parser<bool> implementation
758//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000759bool parser<bool>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000760 const std::string &Arg, bool &Value) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000761 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000762 Arg == "1") {
763 Value = true;
764 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
765 Value = false;
766 } else {
Chris Lattner331de232002-07-22 02:07:59 +0000767 return O.error(": '" + Arg +
768 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000769 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000770 return false;
771}
772
Dale Johannesen81da02b2007-05-22 17:14:46 +0000773// parser<boolOrDefault> implementation
774//
775bool parser<boolOrDefault>::parse(Option &O, const char *ArgName,
776 const std::string &Arg, boolOrDefault &Value) {
777 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
778 Arg == "1") {
779 Value = BOU_TRUE;
780 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
781 Value = BOU_FALSE;
782 } else {
783 return O.error(": '" + Arg +
784 "' is invalid value for boolean argument! Try 0 or 1");
785 }
786 return false;
787}
788
Chris Lattner331de232002-07-22 02:07:59 +0000789// parser<int> implementation
790//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000791bool parser<int>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000792 const std::string &Arg, int &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000793 char *End;
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000794 Value = (int)strtol(Arg.c_str(), &End, 0);
Misha Brukmanf976c852005-04-21 22:55:34 +0000795 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000796 return O.error(": '" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000797 return false;
798}
799
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000800// parser<unsigned> implementation
801//
802bool parser<unsigned>::parse(Option &O, const char *ArgName,
803 const std::string &Arg, unsigned &Value) {
804 char *End;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000805 errno = 0;
806 unsigned long V = strtoul(Arg.c_str(), &End, 0);
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000807 Value = (unsigned)V;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000808 if (((V == ULONG_MAX) && (errno == ERANGE))
809 || (*End != 0)
810 || (Value != V))
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000811 return O.error(": '" + Arg + "' value invalid for uint argument!");
812 return false;
813}
814
Chris Lattner9b14eb52002-08-07 18:36:37 +0000815// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +0000816//
Chris Lattnerca6433f2003-05-22 20:06:43 +0000817static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
Chris Lattner331de232002-07-22 02:07:59 +0000818 const char *ArgStart = Arg.c_str();
819 char *End;
820 Value = strtod(ArgStart, &End);
Misha Brukmanf976c852005-04-21 22:55:34 +0000821 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000822 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +0000823 return false;
824}
825
Chris Lattner9b14eb52002-08-07 18:36:37 +0000826bool parser<double>::parse(Option &O, const char *AN,
827 const std::string &Arg, double &Val) {
828 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +0000829}
830
Chris Lattner9b14eb52002-08-07 18:36:37 +0000831bool parser<float>::parse(Option &O, const char *AN,
832 const std::string &Arg, float &Val) {
833 double dVal;
834 if (parseDouble(O, Arg, dVal))
835 return true;
836 Val = (float)dVal;
837 return false;
Chris Lattner331de232002-07-22 02:07:59 +0000838}
839
840
Chris Lattner331de232002-07-22 02:07:59 +0000841
842// generic_parser_base implementation
843//
844
Chris Lattneraa852bb2002-07-23 17:15:12 +0000845// findOption - Return the option number corresponding to the specified
846// argument string. If the option is not found, getNumOptions() is returned.
847//
848unsigned generic_parser_base::findOption(const char *Name) {
849 unsigned i = 0, e = getNumOptions();
Chris Lattnerca6433f2003-05-22 20:06:43 +0000850 std::string N(Name);
Chris Lattneraa852bb2002-07-23 17:15:12 +0000851
852 while (i != e)
853 if (getOption(i) == N)
854 return i;
855 else
856 ++i;
857 return e;
858}
859
860
Chris Lattner331de232002-07-22 02:07:59 +0000861// Return the width of the option tag for printing...
862unsigned generic_parser_base::getOptionWidth(const Option &O) const {
863 if (O.hasArgStr()) {
864 unsigned Size = std::strlen(O.ArgStr)+6;
865 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
866 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
867 return Size;
868 } else {
869 unsigned BaseSize = 0;
870 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
871 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
872 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000873 }
874}
875
Misha Brukmanf976c852005-04-21 22:55:34 +0000876// printOptionInfo - Print out information about this option. The
Chris Lattner331de232002-07-22 02:07:59 +0000877// to-be-maintained width is specified.
878//
879void generic_parser_base::printOptionInfo(const Option &O,
880 unsigned GlobalWidth) const {
881 if (O.hasArgStr()) {
882 unsigned L = std::strlen(O.ArgStr);
Bill Wendlinge8156192006-12-07 01:30:32 +0000883 cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
884 << " - " << O.HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000885
Chris Lattner331de232002-07-22 02:07:59 +0000886 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
887 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Bill Wendlinge8156192006-12-07 01:30:32 +0000888 cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
889 << " - " << getDescription(i) << "\n";
Chris Lattner9c9be482002-01-31 00:42:56 +0000890 }
Chris Lattner331de232002-07-22 02:07:59 +0000891 } else {
892 if (O.HelpStr[0])
Bill Wendlinge8156192006-12-07 01:30:32 +0000893 cout << " " << O.HelpStr << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000894 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
895 unsigned L = std::strlen(getOption(i));
Bill Wendlinge8156192006-12-07 01:30:32 +0000896 cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
897 << " - " << getDescription(i) << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000898 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000899 }
900}
901
902
903//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000904// --help and --help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000905//
Reid Spencerad0846b2004-11-14 22:04:00 +0000906
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000907namespace {
908
Chris Lattner331de232002-07-22 02:07:59 +0000909class HelpPrinter {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000910 unsigned MaxArgLen;
911 const Option *EmptyArg;
912 const bool ShowHidden;
913
Chris Lattner331de232002-07-22 02:07:59 +0000914 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
Chris Lattnerca6433f2003-05-22 20:06:43 +0000915 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000916 return OptPair.second->getOptionHiddenFlag() >= Hidden;
917 }
Chris Lattnerca6433f2003-05-22 20:06:43 +0000918 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000919 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
920 }
921
922public:
923 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
924 EmptyArg = 0;
925 }
926
927 void operator=(bool Value) {
928 if (Value == false) return;
929
Chris Lattner9878d6a2007-04-06 21:06:55 +0000930 // Get all the options.
931 std::vector<Option*> PositionalOpts;
932 std::map<std::string, Option*> OptMap;
933 GetOptionInfo(PositionalOpts, OptMap);
934
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000935 // Copy Options into a vector so we can sort them as we like...
Chris Lattner90aa8392006-10-04 21:52:35 +0000936 std::vector<std::pair<std::string, Option*> > Opts;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000937 copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts));
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000938
939 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Chris Lattner90aa8392006-10-04 21:52:35 +0000940 Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
941 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
942 Opts.end());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000943
944 // Eliminate duplicate entries in table (from enum flags options, f.e.)
Chris Lattner331de232002-07-22 02:07:59 +0000945 { // Give OptionSet a scope
946 std::set<Option*> OptionSet;
Chris Lattner90aa8392006-10-04 21:52:35 +0000947 for (unsigned i = 0; i != Opts.size(); ++i)
948 if (OptionSet.count(Opts[i].second) == 0)
949 OptionSet.insert(Opts[i].second); // Add new entry to set
Chris Lattner331de232002-07-22 02:07:59 +0000950 else
Chris Lattner90aa8392006-10-04 21:52:35 +0000951 Opts.erase(Opts.begin()+i--); // Erase duplicate
Chris Lattner331de232002-07-22 02:07:59 +0000952 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000953
954 if (ProgramOverview)
Dan Gohman82a13c92007-10-08 15:45:12 +0000955 cout << "OVERVIEW: " << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000956
Bill Wendlinge8156192006-12-07 01:30:32 +0000957 cout << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +0000958
Chris Lattner90aa8392006-10-04 21:52:35 +0000959 // Print out the positional options.
Chris Lattner331de232002-07-22 02:07:59 +0000960 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000961 if (!PositionalOpts.empty() &&
962 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
963 CAOpt = PositionalOpts[0];
Chris Lattner331de232002-07-22 02:07:59 +0000964
Chris Lattner9878d6a2007-04-06 21:06:55 +0000965 for (unsigned i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
966 if (PositionalOpts[i]->ArgStr[0])
967 cout << " --" << PositionalOpts[i]->ArgStr;
968 cout << " " << PositionalOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000969 }
Chris Lattner331de232002-07-22 02:07:59 +0000970
971 // Print the consume after option info if it exists...
Bill Wendlinge8156192006-12-07 01:30:32 +0000972 if (CAOpt) cout << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +0000973
Bill Wendlinge8156192006-12-07 01:30:32 +0000974 cout << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000975
976 // Compute the maximum argument length...
977 MaxArgLen = 0;
Chris Lattner90aa8392006-10-04 21:52:35 +0000978 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
979 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000980
Bill Wendlinge8156192006-12-07 01:30:32 +0000981 cout << "OPTIONS:\n";
Chris Lattner90aa8392006-10-04 21:52:35 +0000982 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
983 Opts[i].second->printOptionInfo(MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000984
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000985 // Print any extra help the user has declared.
Chris Lattner90aa8392006-10-04 21:52:35 +0000986 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
987 E = MoreHelp->end(); I != E; ++I)
Bill Wendlinge8156192006-12-07 01:30:32 +0000988 cout << *I;
Chris Lattner90aa8392006-10-04 21:52:35 +0000989 MoreHelp->clear();
Reid Spencerad0846b2004-11-14 22:04:00 +0000990
Reid Spencer9bbba0912004-11-16 06:11:52 +0000991 // Halt the program since help information was printed
Chris Lattner331de232002-07-22 02:07:59 +0000992 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000993 }
994};
Chris Lattner500d8bf2006-10-12 22:09:17 +0000995} // End anonymous namespace
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000996
Chris Lattner331de232002-07-22 02:07:59 +0000997// Define the two HelpPrinter instances that are used to print out help, or
998// help-hidden...
999//
Chris Lattner500d8bf2006-10-12 22:09:17 +00001000static HelpPrinter NormalPrinter(false);
1001static HelpPrinter HiddenPrinter(true);
Chris Lattner331de232002-07-22 02:07:59 +00001002
Chris Lattner500d8bf2006-10-12 22:09:17 +00001003static cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001004HOp("help", cl::desc("Display available options (--help-hidden for more)"),
Chris Lattner9b14eb52002-08-07 18:36:37 +00001005 cl::location(NormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +00001006
Chris Lattner500d8bf2006-10-12 22:09:17 +00001007static cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001008HHOp("help-hidden", cl::desc("Display all available options"),
Chris Lattner9b14eb52002-08-07 18:36:37 +00001009 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001010
Chris Lattner500d8bf2006-10-12 22:09:17 +00001011static void (*OverrideVersionPrinter)() = 0;
Reid Spencer515b5b32006-06-05 16:22:56 +00001012
Chris Lattner500d8bf2006-10-12 22:09:17 +00001013namespace {
Reid Spencer515b5b32006-06-05 16:22:56 +00001014class VersionPrinter {
1015public:
Devang Patelaed293d2007-02-01 01:43:37 +00001016 void print() {
Bill Wendlinge8156192006-12-07 01:30:32 +00001017 cout << "Low Level Virtual Machine (http://llvm.org/):\n";
1018 cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001019#ifdef LLVM_VERSION_INFO
Bill Wendlinge8156192006-12-07 01:30:32 +00001020 cout << LLVM_VERSION_INFO;
Reid Spencer515b5b32006-06-05 16:22:56 +00001021#endif
Bill Wendlinge8156192006-12-07 01:30:32 +00001022 cout << "\n ";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001023#ifndef __OPTIMIZE__
Bill Wendlinge8156192006-12-07 01:30:32 +00001024 cout << "DEBUG build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001025#else
Bill Wendlinge8156192006-12-07 01:30:32 +00001026 cout << "Optimized build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001027#endif
1028#ifndef NDEBUG
Bill Wendlinge8156192006-12-07 01:30:32 +00001029 cout << " with assertions";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001030#endif
Bill Wendlinge8156192006-12-07 01:30:32 +00001031 cout << ".\n";
Devang Patelaed293d2007-02-01 01:43:37 +00001032 }
1033 void operator=(bool OptionWasSpecified) {
1034 if (OptionWasSpecified) {
1035 if (OverrideVersionPrinter == 0) {
1036 print();
Reid Spencer515b5b32006-06-05 16:22:56 +00001037 exit(1);
1038 } else {
1039 (*OverrideVersionPrinter)();
1040 exit(1);
1041 }
1042 }
1043 }
1044};
Chris Lattner500d8bf2006-10-12 22:09:17 +00001045} // End anonymous namespace
Reid Spencer515b5b32006-06-05 16:22:56 +00001046
1047
Reid Spencer69105f32004-08-04 00:36:06 +00001048// Define the --version option that prints out the LLVM version for the tool
Chris Lattner500d8bf2006-10-12 22:09:17 +00001049static VersionPrinter VersionPrinterInstance;
1050
1051static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001052VersOp("version", cl::desc("Display the version of this program"),
Reid Spencer69105f32004-08-04 00:36:06 +00001053 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1054
Reid Spencer9bbba0912004-11-16 06:11:52 +00001055// Utility function for printing the help message.
1056void cl::PrintHelpMessage() {
Misha Brukmanf976c852005-04-21 22:55:34 +00001057 // This looks weird, but it actually prints the help message. The
Reid Spencer5cc498f2004-11-16 06:50:36 +00001058 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1059 // its operator= is invoked. That's because the "normal" usages of the
Misha Brukmanf976c852005-04-21 22:55:34 +00001060 // help printer is to be assigned true/false depending on whether the
Reid Spencer5cc498f2004-11-16 06:50:36 +00001061 // --help option was given or not. Since we're circumventing that we have
1062 // to make it look like --help was given, so we assign true.
Reid Spencer9bbba0912004-11-16 06:11:52 +00001063 NormalPrinter = true;
1064}
Reid Spencer515b5b32006-06-05 16:22:56 +00001065
Devang Patelaed293d2007-02-01 01:43:37 +00001066/// Utility function for printing version number.
1067void cl::PrintVersionMessage() {
1068 VersionPrinterInstance.print();
1069}
1070
Reid Spencer515b5b32006-06-05 16:22:56 +00001071void cl::SetVersionPrinter(void (*func)()) {
1072 OverrideVersionPrinter = func;
1073}