blob: 804af9577702bc022a7ebf0e85aba218c9a9e18c [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>
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>);
Dale Johannesen81da02b2007-05-22 17:14:46 +000039TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
Chris Lattner7422a762006-08-27 12:45:47 +000040TEMPLATE_INSTANTIATION(class basic_parser<int>);
41TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
42TEMPLATE_INSTANTIATION(class basic_parser<double>);
43TEMPLATE_INSTANTIATION(class basic_parser<float>);
44TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
45
46TEMPLATE_INSTANTIATION(class opt<unsigned>);
47TEMPLATE_INSTANTIATION(class opt<int>);
48TEMPLATE_INSTANTIATION(class opt<std::string>);
49TEMPLATE_INSTANTIATION(class opt<bool>);
50
51void Option::anchor() {}
52void basic_parser_impl::anchor() {}
53void parser<bool>::anchor() {}
Dale Johannesen81da02b2007-05-22 17:14:46 +000054void parser<boolOrDefault>::anchor() {}
Chris Lattner7422a762006-08-27 12:45:47 +000055void parser<int>::anchor() {}
56void parser<unsigned>::anchor() {}
57void parser<double>::anchor() {}
58void parser<float>::anchor() {}
59void parser<std::string>::anchor() {}
60
61//===----------------------------------------------------------------------===//
62
Chris Lattnerefa3da52006-10-13 00:06:24 +000063// Globals for name and overview of program. Program name is not a string to
64// avoid static ctor/dtor issues.
65static char ProgramName[80] = "<premain>";
Reid Spencere1cc1502004-09-01 04:41:28 +000066static const char *ProgramOverview = 0;
67
Chris Lattnerc540ebb2004-11-19 17:08:15 +000068// This collects additional help to be printed.
Chris Lattner90aa8392006-10-04 21:52:35 +000069static ManagedStatic<std::vector<const char*> > MoreHelp;
Chris Lattnerc540ebb2004-11-19 17:08:15 +000070
Chris Lattner90aa8392006-10-04 21:52:35 +000071extrahelp::extrahelp(const char *Help)
Chris Lattnerc540ebb2004-11-19 17:08:15 +000072 : morehelp(Help) {
Chris Lattner90aa8392006-10-04 21:52:35 +000073 MoreHelp->push_back(Help);
Chris Lattnerc540ebb2004-11-19 17:08:15 +000074}
75
Chris Lattner69d6f132007-04-12 00:36:29 +000076static bool OptionListChanged = false;
77
78// MarkOptionsChanged - Internal helper function.
79void cl::MarkOptionsChanged() {
80 OptionListChanged = true;
81}
82
Chris Lattner9878d6a2007-04-06 21:06:55 +000083/// RegisteredOptionList - This is the list of the command line options that
84/// have statically constructed themselves.
85static Option *RegisteredOptionList = 0;
86
87void Option::addArgument() {
88 assert(NextRegistered == 0 && "argument multiply registered!");
89
90 NextRegistered = RegisteredOptionList;
91 RegisteredOptionList = this;
Chris Lattner69d6f132007-04-12 00:36:29 +000092 MarkOptionsChanged();
Chris Lattner9878d6a2007-04-06 21:06:55 +000093}
94
Chris Lattner69d6f132007-04-12 00:36:29 +000095
Chris Lattner331de232002-07-22 02:07:59 +000096//===----------------------------------------------------------------------===//
Chris Lattner7422a762006-08-27 12:45:47 +000097// Basic, shared command line option processing machinery.
Chris Lattner331de232002-07-22 02:07:59 +000098//
99
Chris Lattner9878d6a2007-04-06 21:06:55 +0000100/// GetOptionInfo - Scan the list of registered options, turning them into data
101/// structures that are easier to handle.
102static void GetOptionInfo(std::vector<Option*> &PositionalOpts,
103 std::map<std::string, Option*> &OptionsMap) {
104 std::vector<const char*> OptionNames;
Chris Lattneree2b3202007-04-07 05:38:53 +0000105 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000106 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
107 // If this option wants to handle multiple option names, get the full set.
108 // This handles enum options like "-O1 -O2" etc.
109 O->getExtraOptionNames(OptionNames);
110 if (O->ArgStr[0])
111 OptionNames.push_back(O->ArgStr);
112
113 // Handle named options.
114 for (unsigned i = 0, e = OptionNames.size(); i != e; ++i) {
115 // Add argument to the argument map!
116 if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i],
117 O)).second) {
118 cerr << ProgramName << ": CommandLine Error: Argument '"
119 << OptionNames[0] << "' defined more than once!\n";
120 }
121 }
122
123 OptionNames.clear();
124
125 // Remember information about positional options.
126 if (O->getFormattingFlag() == cl::Positional)
127 PositionalOpts.push_back(O);
128 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattneree2b3202007-04-07 05:38:53 +0000129 if (CAOpt)
Chris Lattner9878d6a2007-04-06 21:06:55 +0000130 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattneree2b3202007-04-07 05:38:53 +0000131 CAOpt = O;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000132 }
Chris Lattnere8e258b2002-07-29 20:58:42 +0000133 }
Chris Lattneree2b3202007-04-07 05:38:53 +0000134
135 if (CAOpt)
136 PositionalOpts.push_back(CAOpt);
137
138 // Make sure that they are in order of registration not backwards.
139 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
Chris Lattnere8e258b2002-07-29 20:58:42 +0000140}
141
Chris Lattner9878d6a2007-04-06 21:06:55 +0000142
Chris Lattneraf035f32007-04-05 21:58:17 +0000143/// LookupOption - Lookup the option specified by the specified option on the
144/// command line. If there is a value specified (after an equal sign) return
145/// that as well.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000146static Option *LookupOption(const char *&Arg, const char *&Value,
147 std::map<std::string, Option*> &OptionsMap) {
Chris Lattneraf035f32007-04-05 21:58:17 +0000148 while (*Arg == '-') ++Arg; // Eat leading dashes
149
150 const char *ArgEnd = Arg;
151 while (*ArgEnd && *ArgEnd != '=')
152 ++ArgEnd; // Scan till end of argument name.
153
154 if (*ArgEnd == '=') // If we have an equals sign...
155 Value = ArgEnd+1; // Get the value, not the equals
156
157
158 if (*Arg == 0) return 0;
159
160 // Look up the option.
Chris Lattneraf035f32007-04-05 21:58:17 +0000161 std::map<std::string, Option*>::iterator I =
Chris Lattner9878d6a2007-04-06 21:06:55 +0000162 OptionsMap.find(std::string(Arg, ArgEnd));
163 return I != OptionsMap.end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000164}
165
Chris Lattnercaccd762001-10-27 05:54:17 +0000166static inline bool ProvideOption(Option *Handler, const char *ArgName,
167 const char *Value, int argc, char **argv,
168 int &i) {
169 // Enforce value requirements
170 switch (Handler->getValueExpectedFlag()) {
171 case ValueRequired:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000172 if (Value == 0) { // No value specified?
Chris Lattnercaccd762001-10-27 05:54:17 +0000173 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
174 Value = argv[++i];
175 } else {
176 return Handler->error(" requires a value!");
177 }
178 }
179 break;
180 case ValueDisallowed:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000181 if (Value)
Misha Brukmanf976c852005-04-21 22:55:34 +0000182 return Handler->error(" does not allow a value! '" +
Chris Lattnerca6433f2003-05-22 20:06:43 +0000183 std::string(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +0000184 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000185 case ValueOptional:
Reid Spencere1cc1502004-09-01 04:41:28 +0000186 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000187 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000188 cerr << ProgramName
189 << ": Bad ValueMask flag! CommandLine usage error:"
190 << Handler->getValueExpectedFlag() << "\n";
Reid Spencere1cc1502004-09-01 04:41:28 +0000191 abort();
192 break;
Chris Lattnercaccd762001-10-27 05:54:17 +0000193 }
194
195 // Run the handler now!
Chris Lattner6d5857e2005-05-10 23:20:17 +0000196 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
Chris Lattnercaccd762001-10-27 05:54:17 +0000197}
198
Misha Brukmanf976c852005-04-21 22:55:34 +0000199static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000200 int i) {
201 int Dummy = i;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000202 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000203}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000204
Chris Lattner331de232002-07-22 02:07:59 +0000205
206// Option predicates...
207static inline bool isGrouping(const Option *O) {
208 return O->getFormattingFlag() == cl::Grouping;
209}
210static inline bool isPrefixedOrGrouping(const Option *O) {
211 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
212}
213
214// getOptionPred - Check to see if there are any options that satisfy the
215// specified predicate with names that are the prefixes in Name. This is
216// checked by progressively stripping characters off of the name, checking to
217// see if there options that satisfy the predicate. If we find one, return it,
218// otherwise return null.
219//
220static Option *getOptionPred(std::string Name, unsigned &Length,
Chris Lattner9878d6a2007-04-06 21:06:55 +0000221 bool (*Pred)(const Option*),
222 std::map<std::string, Option*> &OptionsMap) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000223
Chris Lattner9878d6a2007-04-06 21:06:55 +0000224 std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name);
225 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner331de232002-07-22 02:07:59 +0000226 Length = Name.length();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000227 return OMI->second;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000228 }
229
Chris Lattner331de232002-07-22 02:07:59 +0000230 if (Name.size() == 1) return 0;
231 do {
232 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000233 OMI = OptionsMap.find(Name);
Chris Lattner331de232002-07-22 02:07:59 +0000234
235 // Loop while we haven't found an option and Name still has at least two
236 // characters in it (so that the next iteration will not be the empty
237 // string...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000238 } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1);
Chris Lattner331de232002-07-22 02:07:59 +0000239
Chris Lattner9878d6a2007-04-06 21:06:55 +0000240 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner331de232002-07-22 02:07:59 +0000241 Length = Name.length();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000242 return OMI->second; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000243 }
244 return 0; // No option found!
245}
246
247static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000248 return O->getNumOccurrencesFlag() == cl::Required ||
249 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000250}
251
252static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000253 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
254 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000255}
Chris Lattnercaccd762001-10-27 05:54:17 +0000256
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000257/// ParseCStringVector - Break INPUT up wherever one or more
258/// whitespace characters are found, and store the resulting tokens in
259/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
260/// using strdup (), so it is the caller's responsibility to free ()
261/// them later.
Brian Gaeke06b06c52003-08-14 22:00:59 +0000262///
Chris Lattner23288582006-08-27 22:10:29 +0000263static void ParseCStringVector(std::vector<char *> &output,
264 const char *input) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000265 // Characters which will be treated as token separators:
266 static const char *delims = " \v\f\t\r\n";
267
268 std::string work (input);
269 // Skip past any delims at head of input string.
270 size_t pos = work.find_first_not_of (delims);
271 // If the string consists entirely of delims, then exit early.
272 if (pos == std::string::npos) return;
273 // Otherwise, jump forward to beginning of first word.
274 work = work.substr (pos);
275 // Find position of first delimiter.
276 pos = work.find_first_of (delims);
277
278 while (!work.empty() && pos != std::string::npos) {
279 // Everything from 0 to POS is the next word to copy.
280 output.push_back (strdup (work.substr (0,pos).c_str ()));
281 // Is there another word in the string?
282 size_t nextpos = work.find_first_not_of (delims, pos + 1);
283 if (nextpos != std::string::npos) {
284 // Yes? Then remove delims from beginning ...
285 work = work.substr (work.find_first_not_of (delims, pos + 1));
286 // and find the end of the word.
287 pos = work.find_first_of (delims);
288 } else {
289 // No? (Remainder of string is delims.) End the loop.
290 work = "";
291 pos = std::string::npos;
292 }
293 }
294
295 // If `input' ended with non-delim char, then we'll get here with
296 // the last word of `input' in `work'; copy it now.
297 if (!work.empty ()) {
298 output.push_back (strdup (work.c_str ()));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000299 }
300}
301
302/// ParseEnvironmentOptions - An alternative entry point to the
303/// CommandLine library, which allows you to read the program's name
304/// from the caller (as PROGNAME) and its command-line arguments from
305/// an environment variable (whose name is given in ENVVAR).
306///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000307void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
308 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000309 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000310 assert(progName && "Program name not specified");
311 assert(envVar && "Environment variable name missing");
Misha Brukmanf976c852005-04-21 22:55:34 +0000312
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000313 // Get the environment variable they want us to parse options out of.
Chris Lattner23288582006-08-27 22:10:29 +0000314 const char *envValue = getenv(envVar);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000315 if (!envValue)
316 return;
317
Brian Gaeke06b06c52003-08-14 22:00:59 +0000318 // Get program's "name", which we wouldn't know without the caller
319 // telling us.
Chris Lattner23288582006-08-27 22:10:29 +0000320 std::vector<char*> newArgv;
321 newArgv.push_back(strdup(progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000322
323 // Parse the value of the environment variable into a "command line"
324 // and hand it off to ParseCommandLineOptions().
Chris Lattner23288582006-08-27 22:10:29 +0000325 ParseCStringVector(newArgv, envValue);
326 int newArgc = newArgv.size();
327 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000328
329 // Free all the strdup()ed strings.
Chris Lattner23288582006-08-27 22:10:29 +0000330 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
331 i != e; ++i)
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000332 free (*i);
Brian Gaeke06b06c52003-08-14 22:00:59 +0000333}
334
Dan Gohman9a526322007-10-09 16:04:57 +0000335void cl::ParseCommandLineOptions(int argc, char **argv,
Chris Lattner0c0edf82002-07-25 06:17:51 +0000336 const char *Overview) {
Chris Lattner9878d6a2007-04-06 21:06:55 +0000337 // Process all registered options.
338 std::vector<Option*> PositionalOpts;
339 std::map<std::string, Option*> Opts;
340 GetOptionInfo(PositionalOpts, Opts);
341
342 assert((!Opts.empty() || !PositionalOpts.empty()) &&
343 "No options specified!");
Reid Spencer6f4c6072006-08-23 07:10:06 +0000344 sys::Path progname(argv[0]);
Chris Lattnerefa3da52006-10-13 00:06:24 +0000345
346 // Copy the program name into ProgName, making sure not to overflow it.
347 std::string ProgName = sys::Path(argv[0]).getLast();
348 if (ProgName.size() > 79) ProgName.resize(79);
349 strcpy(ProgramName, ProgName.c_str());
350
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000351 ProgramOverview = Overview;
352 bool ErrorParsing = false;
353
Chris Lattner331de232002-07-22 02:07:59 +0000354 // Check out the positional arguments to collect information about them.
355 unsigned NumPositionalRequired = 0;
Chris Lattnerde013242005-08-08 17:25:38 +0000356
357 // Determine whether or not there are an unlimited number of positionals
358 bool HasUnlimitedPositionals = false;
359
Chris Lattner331de232002-07-22 02:07:59 +0000360 Option *ConsumeAfterOpt = 0;
361 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000362 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000363 assert(PositionalOpts.size() > 1 &&
364 "Cannot specify cl::ConsumeAfter without a positional argument!");
365 ConsumeAfterOpt = PositionalOpts[0];
366 }
367
368 // Calculate how many positional values are _required_.
369 bool UnboundedFound = false;
370 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
371 i != e; ++i) {
372 Option *Opt = PositionalOpts[i];
373 if (RequiresValue(Opt))
374 ++NumPositionalRequired;
375 else if (ConsumeAfterOpt) {
376 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000377 // unless there is only one positional argument...
378 if (PositionalOpts.size() > 2)
379 ErrorParsing |=
380 Opt->error(" error - this positional option will never be matched, "
381 "because it does not Require a value, and a "
382 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000383 } else if (UnboundedFound && !Opt->ArgStr[0]) {
384 // This option does not "require" a value... Make sure this option is
385 // not specified after an option that eats all extra arguments, or this
386 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000387 //
388 ErrorParsing |= Opt->error(" error - option can never match, because "
389 "another positional argument will match an "
390 "unbounded number of values, and this option"
391 " does not require a value!");
392 }
393 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
394 }
Chris Lattner21e1a792005-08-08 21:57:27 +0000395 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000396 }
397
Reid Spencer1e13fd22004-08-13 19:47:30 +0000398 // PositionalVals - A vector of "positional" arguments we accumulate into
399 // the process at the end...
Chris Lattner331de232002-07-22 02:07:59 +0000400 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000401 std::vector<std::pair<std::string,unsigned> > PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000402
Chris Lattner9cf3d472003-07-30 17:34:02 +0000403 // If the program has named positional arguments, and the name has been run
404 // across, keep track of which positional argument was named. Otherwise put
405 // the positional args into the PositionalVals list...
406 Option *ActivePositionalArg = 0;
407
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000408 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000409 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000410 for (int i = 1; i < argc; ++i) {
411 Option *Handler = 0;
Chris Lattner6d5857e2005-05-10 23:20:17 +0000412 const char *Value = 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000413 const char *ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000414
Chris Lattner69d6f132007-04-12 00:36:29 +0000415 // If the option list changed, this means that some command line
Chris Lattner159b0a432007-04-11 15:35:18 +0000416 // option has just been registered or deregistered. This can occur in
417 // response to things like -load, etc. If this happens, rescan the options.
Chris Lattner69d6f132007-04-12 00:36:29 +0000418 if (OptionListChanged) {
Chris Lattner159b0a432007-04-11 15:35:18 +0000419 PositionalOpts.clear();
420 Opts.clear();
421 GetOptionInfo(PositionalOpts, Opts);
Chris Lattner69d6f132007-04-12 00:36:29 +0000422 OptionListChanged = false;
Chris Lattner159b0a432007-04-11 15:35:18 +0000423 }
424
Chris Lattner331de232002-07-22 02:07:59 +0000425 // Check to see if this is a positional argument. This argument is
426 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000427 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000428 //
429 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
430 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000431 if (ActivePositionalArg) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000432 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000433 continue; // We are done!
434 } else if (!PositionalOpts.empty()) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000435 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000436
437 // All of the positional arguments have been fulfulled, give the rest to
438 // the consume after option... if it's specified...
439 //
Misha Brukmanf976c852005-04-21 22:55:34 +0000440 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000441 ConsumeAfterOpt != 0) {
442 for (++i; i < argc; ++i)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000443 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000444 break; // Handle outside of the argument processing loop...
445 }
446
447 // Delay processing positional arguments until the end...
448 continue;
449 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000450 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
451 !DashDashFound) {
452 DashDashFound = true; // This is the mythical "--"?
453 continue; // Don't try to process it as an argument itself.
454 } else if (ActivePositionalArg &&
455 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
456 // If there is a positional argument eating options, check to see if this
457 // option is another positional argument. If so, treat it as an argument,
458 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000459 ArgName = argv[i]+1;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000460 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000461 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000462 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000463 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000464 }
465
Chris Lattnerbf455c22004-05-06 22:04:31 +0000466 } else { // We start with a '-', must be an argument...
467 ArgName = argv[i]+1;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000468 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000469
Chris Lattnerbf455c22004-05-06 22:04:31 +0000470 // Check to see if this "option" is really a prefixed or grouped argument.
Reid Spencer5f8448f2004-11-24 06:13:42 +0000471 if (Handler == 0) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000472 std::string RealName(ArgName);
473 if (RealName.size() > 1) {
Chris Lattner331de232002-07-22 02:07:59 +0000474 unsigned Length = 0;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000475 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping,
476 Opts);
Misha Brukmanf976c852005-04-21 22:55:34 +0000477
Chris Lattner331de232002-07-22 02:07:59 +0000478 // If the option is a prefixed option, then the value is simply the
479 // rest of the name... so fall through to later processing, by
480 // setting up the argument name flags and value fields.
481 //
482 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000483 Value = ArgName+Length;
484 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
485 Opts.find(std::string(ArgName, Value))->second == PGOpt);
486 Handler = PGOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000487 } else if (PGOpt) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000488 // This must be a grouped option... handle them now.
Chris Lattner331de232002-07-22 02:07:59 +0000489 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000490
Chris Lattner331de232002-07-22 02:07:59 +0000491 do {
492 // Move current arg name out of RealName into RealArgName...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000493 std::string RealArgName(RealName.begin(),
494 RealName.begin() + Length);
495 RealName.erase(RealName.begin(), RealName.begin() + Length);
Misha Brukmanf976c852005-04-21 22:55:34 +0000496
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000497 // Because ValueRequired is an invalid flag for grouped arguments,
498 // we don't need to pass argc/argv in...
499 //
Chris Lattner331de232002-07-22 02:07:59 +0000500 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
501 "Option can not be cl::Grouping AND cl::ValueRequired!");
502 int Dummy;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000503 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
Chris Lattner6d5857e2005-05-10 23:20:17 +0000504 0, 0, 0, Dummy);
Misha Brukmanf976c852005-04-21 22:55:34 +0000505
Chris Lattner331de232002-07-22 02:07:59 +0000506 // Get the next grouping option...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000507 PGOpt = getOptionPred(RealName, Length, isGrouping, Opts);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000508 } while (PGOpt && Length != RealName.size());
Misha Brukmanf976c852005-04-21 22:55:34 +0000509
Chris Lattnerbf455c22004-05-06 22:04:31 +0000510 Handler = PGOpt; // Ate all of the options.
Chris Lattner331de232002-07-22 02:07:59 +0000511 }
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000512 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000513 }
514 }
515
516 if (Handler == 0) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000517 cerr << ProgramName << ": Unknown command line argument '"
518 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000519 ErrorParsing = true;
520 continue;
521 }
522
Chris Lattner72fb8e52003-05-22 20:26:17 +0000523 // Check to see if this option accepts a comma separated list of values. If
524 // it does, we have to split up the value into multiple values...
Chris Lattner6d5857e2005-05-10 23:20:17 +0000525 if (Value && Handler->getMiscFlags() & CommaSeparated) {
Chris Lattner72fb8e52003-05-22 20:26:17 +0000526 std::string Val(Value);
527 std::string::size_type Pos = Val.find(',');
528
529 while (Pos != std::string::npos) {
530 // Process the portion before the comma...
531 ErrorParsing |= ProvideOption(Handler, ArgName,
532 std::string(Val.begin(),
533 Val.begin()+Pos).c_str(),
534 argc, argv, i);
535 // Erase the portion before the comma, AND the comma...
536 Val.erase(Val.begin(), Val.begin()+Pos+1);
537 Value += Pos+1; // Increment the original value pointer as well...
538
539 // Check for another comma...
540 Pos = Val.find(',');
541 }
542 }
Chris Lattner9cf3d472003-07-30 17:34:02 +0000543
544 // If this is a named positional argument, just remember that it is the
545 // active one...
546 if (Handler->getFormattingFlag() == cl::Positional)
547 ActivePositionalArg = Handler;
Misha Brukmanf976c852005-04-21 22:55:34 +0000548 else
Chris Lattner9cf3d472003-07-30 17:34:02 +0000549 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000550 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000551
Chris Lattner331de232002-07-22 02:07:59 +0000552 // Check and handle positional arguments now...
553 if (NumPositionalRequired > PositionalVals.size()) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000554 cerr << ProgramName
555 << ": Not enough positional command line arguments specified!\n"
556 << "Must specify at least " << NumPositionalRequired
557 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattner79959d22006-01-17 00:32:28 +0000558
Chris Lattner331de232002-07-22 02:07:59 +0000559 ErrorParsing = true;
Chris Lattnerde013242005-08-08 17:25:38 +0000560 } else if (!HasUnlimitedPositionals
561 && PositionalVals.size() > PositionalOpts.size()) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000562 cerr << ProgramName
563 << ": Too many positional arguments specified!\n"
564 << "Can specify at most " << PositionalOpts.size()
565 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattnerde013242005-08-08 17:25:38 +0000566 ErrorParsing = true;
Chris Lattner331de232002-07-22 02:07:59 +0000567
568 } else if (ConsumeAfterOpt == 0) {
569 // Positional args have already been handled if ConsumeAfter is specified...
570 unsigned ValNo = 0, NumVals = PositionalVals.size();
571 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
572 if (RequiresValue(PositionalOpts[i])) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000573 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000574 PositionalVals[ValNo].second);
575 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000576 --NumPositionalRequired; // We fulfilled our duty...
577 }
578
579 // If we _can_ give this option more arguments, do so now, as long as we
580 // do not give it values that others need. 'Done' controls whether the
581 // option even _WANTS_ any more.
582 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000583 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000584 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000585 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000586 case cl::Optional:
587 Done = true; // Optional arguments want _at most_ one value
588 // FALL THROUGH
589 case cl::ZeroOrMore: // Zero or more will take all they can get...
590 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer1e13fd22004-08-13 19:47:30 +0000591 ProvidePositionalOption(PositionalOpts[i],
592 PositionalVals[ValNo].first,
593 PositionalVals[ValNo].second);
594 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000595 break;
596 default:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000597 assert(0 && "Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000598 "positional argument processing!");
599 }
600 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000601 }
Chris Lattner331de232002-07-22 02:07:59 +0000602 } else {
603 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
604 unsigned ValNo = 0;
605 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000606 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000607 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000608 PositionalVals[ValNo].first,
609 PositionalVals[ValNo].second);
610 ValNo++;
611 }
Chris Lattnerfaba8092002-07-24 20:15:13 +0000612
613 // Handle the case where there is just one positional option, and it's
614 // optional. In this case, we want to give JUST THE FIRST option to the
615 // positional option and keep the rest for the consume after. The above
616 // loop would have assigned no values to positional options in this case.
617 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000618 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000619 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000620 PositionalVals[ValNo].first,
621 PositionalVals[ValNo].second);
622 ValNo++;
623 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000624
Chris Lattner331de232002-07-22 02:07:59 +0000625 // Handle over all of the rest of the arguments to the
626 // cl::ConsumeAfter command line option...
627 for (; ValNo != PositionalVals.size(); ++ValNo)
628 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000629 PositionalVals[ValNo].first,
630 PositionalVals[ValNo].second);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000631 }
632
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000633 // Loop over args and make sure all required args are specified!
Misha Brukmanf976c852005-04-21 22:55:34 +0000634 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000635 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000636 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000637 case Required:
638 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000639 if (I->second->getNumOccurrences() == 0) {
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000640 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000641 ErrorParsing = true;
642 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000643 // Fall through
644 default:
645 break;
646 }
647 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000648
Chris Lattner331de232002-07-22 02:07:59 +0000649 // Free all of the memory allocated to the map. Command line options may only
650 // be processed once!
Chris Lattner90aa8392006-10-04 21:52:35 +0000651 Opts.clear();
Chris Lattner331de232002-07-22 02:07:59 +0000652 PositionalOpts.clear();
Chris Lattner90aa8392006-10-04 21:52:35 +0000653 MoreHelp->clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000654
655 // If we had an error processing our arguments, don't let the program execute
656 if (ErrorParsing) exit(1);
657}
658
659//===----------------------------------------------------------------------===//
660// Option Base class implementation
661//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000662
Chris Lattnerca6433f2003-05-22 20:06:43 +0000663bool Option::error(std::string Message, const char *ArgName) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000664 if (ArgName == 0) ArgName = ArgStr;
Chris Lattner331de232002-07-22 02:07:59 +0000665 if (ArgName[0] == 0)
Bill Wendlinge8156192006-12-07 01:30:32 +0000666 cerr << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000667 else
Bill Wendlinge8156192006-12-07 01:30:32 +0000668 cerr << ProgramName << ": for the -" << ArgName;
Jim Laskeyabe0e3e2006-08-02 20:15:56 +0000669
Bill Wendlinge8156192006-12-07 01:30:32 +0000670 cerr << " option: " << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000671 return true;
672}
673
Chris Lattner6d5857e2005-05-10 23:20:17 +0000674bool Option::addOccurrence(unsigned pos, const char *ArgName,
675 const std::string &Value) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000676 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000677
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000678 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000679 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000680 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000681 return error(": may only occur zero or one times!", ArgName);
682 break;
683 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000684 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000685 return error(": must occur exactly one time!", ArgName);
686 // Fall through
687 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000688 case ZeroOrMore:
689 case ConsumeAfter: break;
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000690 default: return error(": bad num occurrences flag value!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000691 }
692
Reid Spencer1e13fd22004-08-13 19:47:30 +0000693 return handleOccurrence(pos, ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000694}
695
Chris Lattner331de232002-07-22 02:07:59 +0000696
697// getValueStr - Get the value description string, using "DefaultMsg" if nothing
698// has been specified yet.
699//
700static const char *getValueStr(const Option &O, const char *DefaultMsg) {
701 if (O.ValueStr[0] == 0) return DefaultMsg;
702 return O.ValueStr;
703}
704
705//===----------------------------------------------------------------------===//
706// cl::alias class implementation
707//
708
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000709// Return the width of the option tag for printing...
Chris Lattner331de232002-07-22 02:07:59 +0000710unsigned alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000711 return std::strlen(ArgStr)+6;
712}
713
Chris Lattnera0de8432006-04-28 05:36:25 +0000714// Print out the option for the alias.
Chris Lattner331de232002-07-22 02:07:59 +0000715void alias::printOptionInfo(unsigned GlobalWidth) const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000716 unsigned L = std::strlen(ArgStr);
Bill Wendlinge8156192006-12-07 01:30:32 +0000717 cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
718 << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000719}
720
721
Chris Lattner331de232002-07-22 02:07:59 +0000722
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000723//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000724// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000725//
726
Chris Lattner9b14eb52002-08-07 18:36:37 +0000727// basic_parser implementation
728//
729
730// Return the width of the option tag for printing...
731unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
732 unsigned Len = std::strlen(O.ArgStr);
733 if (const char *ValName = getValueName())
734 Len += std::strlen(getValueStr(O, ValName))+3;
735
736 return Len + 6;
737}
738
Misha Brukmanf976c852005-04-21 22:55:34 +0000739// printOptionInfo - Print out information about this option. The
Chris Lattner9b14eb52002-08-07 18:36:37 +0000740// to-be-maintained width is specified.
741//
742void basic_parser_impl::printOptionInfo(const Option &O,
743 unsigned GlobalWidth) const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000744 cout << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000745
746 if (const char *ValName = getValueName())
Bill Wendlinge8156192006-12-07 01:30:32 +0000747 cout << "=<" << getValueStr(O, ValName) << ">";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000748
Bill Wendlinge8156192006-12-07 01:30:32 +0000749 cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
750 << O.HelpStr << "\n";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000751}
752
753
754
755
Chris Lattner331de232002-07-22 02:07:59 +0000756// parser<bool> implementation
757//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000758bool parser<bool>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000759 const std::string &Arg, bool &Value) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000760 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000761 Arg == "1") {
762 Value = true;
763 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
764 Value = false;
765 } else {
Chris Lattner331de232002-07-22 02:07:59 +0000766 return O.error(": '" + Arg +
767 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000768 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000769 return false;
770}
771
Dale Johannesen81da02b2007-05-22 17:14:46 +0000772// parser<boolOrDefault> implementation
773//
774bool parser<boolOrDefault>::parse(Option &O, const char *ArgName,
775 const std::string &Arg, boolOrDefault &Value) {
776 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
777 Arg == "1") {
778 Value = BOU_TRUE;
779 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
780 Value = BOU_FALSE;
781 } else {
782 return O.error(": '" + Arg +
783 "' is invalid value for boolean argument! Try 0 or 1");
784 }
785 return false;
786}
787
Chris Lattner331de232002-07-22 02:07:59 +0000788// parser<int> implementation
789//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000790bool parser<int>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000791 const std::string &Arg, int &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000792 char *End;
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000793 Value = (int)strtol(Arg.c_str(), &End, 0);
Misha Brukmanf976c852005-04-21 22:55:34 +0000794 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000795 return O.error(": '" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000796 return false;
797}
798
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000799// parser<unsigned> implementation
800//
801bool parser<unsigned>::parse(Option &O, const char *ArgName,
802 const std::string &Arg, unsigned &Value) {
803 char *End;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000804 errno = 0;
805 unsigned long V = strtoul(Arg.c_str(), &End, 0);
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000806 Value = (unsigned)V;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000807 if (((V == ULONG_MAX) && (errno == ERANGE))
808 || (*End != 0)
809 || (Value != V))
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000810 return O.error(": '" + Arg + "' value invalid for uint argument!");
811 return false;
812}
813
Chris Lattner9b14eb52002-08-07 18:36:37 +0000814// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +0000815//
Chris Lattnerca6433f2003-05-22 20:06:43 +0000816static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
Chris Lattner331de232002-07-22 02:07:59 +0000817 const char *ArgStart = Arg.c_str();
818 char *End;
819 Value = strtod(ArgStart, &End);
Misha Brukmanf976c852005-04-21 22:55:34 +0000820 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000821 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +0000822 return false;
823}
824
Chris Lattner9b14eb52002-08-07 18:36:37 +0000825bool parser<double>::parse(Option &O, const char *AN,
826 const std::string &Arg, double &Val) {
827 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +0000828}
829
Chris Lattner9b14eb52002-08-07 18:36:37 +0000830bool parser<float>::parse(Option &O, const char *AN,
831 const std::string &Arg, float &Val) {
832 double dVal;
833 if (parseDouble(O, Arg, dVal))
834 return true;
835 Val = (float)dVal;
836 return false;
Chris Lattner331de232002-07-22 02:07:59 +0000837}
838
839
Chris Lattner331de232002-07-22 02:07:59 +0000840
841// generic_parser_base implementation
842//
843
Chris Lattneraa852bb2002-07-23 17:15:12 +0000844// findOption - Return the option number corresponding to the specified
845// argument string. If the option is not found, getNumOptions() is returned.
846//
847unsigned generic_parser_base::findOption(const char *Name) {
848 unsigned i = 0, e = getNumOptions();
Chris Lattnerca6433f2003-05-22 20:06:43 +0000849 std::string N(Name);
Chris Lattneraa852bb2002-07-23 17:15:12 +0000850
851 while (i != e)
852 if (getOption(i) == N)
853 return i;
854 else
855 ++i;
856 return e;
857}
858
859
Chris Lattner331de232002-07-22 02:07:59 +0000860// Return the width of the option tag for printing...
861unsigned generic_parser_base::getOptionWidth(const Option &O) const {
862 if (O.hasArgStr()) {
863 unsigned Size = std::strlen(O.ArgStr)+6;
864 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
865 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
866 return Size;
867 } else {
868 unsigned BaseSize = 0;
869 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
870 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
871 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000872 }
873}
874
Misha Brukmanf976c852005-04-21 22:55:34 +0000875// printOptionInfo - Print out information about this option. The
Chris Lattner331de232002-07-22 02:07:59 +0000876// to-be-maintained width is specified.
877//
878void generic_parser_base::printOptionInfo(const Option &O,
879 unsigned GlobalWidth) const {
880 if (O.hasArgStr()) {
881 unsigned L = std::strlen(O.ArgStr);
Bill Wendlinge8156192006-12-07 01:30:32 +0000882 cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
883 << " - " << O.HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000884
Chris Lattner331de232002-07-22 02:07:59 +0000885 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
886 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Bill Wendlinge8156192006-12-07 01:30:32 +0000887 cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
888 << " - " << getDescription(i) << "\n";
Chris Lattner9c9be482002-01-31 00:42:56 +0000889 }
Chris Lattner331de232002-07-22 02:07:59 +0000890 } else {
891 if (O.HelpStr[0])
Bill Wendlinge8156192006-12-07 01:30:32 +0000892 cout << " " << O.HelpStr << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000893 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
894 unsigned L = std::strlen(getOption(i));
Bill Wendlinge8156192006-12-07 01:30:32 +0000895 cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
896 << " - " << getDescription(i) << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000897 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000898 }
899}
900
901
902//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000903// --help and --help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000904//
Reid Spencerad0846b2004-11-14 22:04:00 +0000905
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000906namespace {
907
Chris Lattner331de232002-07-22 02:07:59 +0000908class HelpPrinter {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000909 unsigned MaxArgLen;
910 const Option *EmptyArg;
911 const bool ShowHidden;
912
Chris Lattner331de232002-07-22 02:07:59 +0000913 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
Chris Lattnerca6433f2003-05-22 20:06:43 +0000914 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000915 return OptPair.second->getOptionHiddenFlag() >= Hidden;
916 }
Chris Lattnerca6433f2003-05-22 20:06:43 +0000917 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000918 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
919 }
920
921public:
922 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
923 EmptyArg = 0;
924 }
925
926 void operator=(bool Value) {
927 if (Value == false) return;
928
Chris Lattner9878d6a2007-04-06 21:06:55 +0000929 // Get all the options.
930 std::vector<Option*> PositionalOpts;
931 std::map<std::string, Option*> OptMap;
932 GetOptionInfo(PositionalOpts, OptMap);
933
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000934 // Copy Options into a vector so we can sort them as we like...
Chris Lattner90aa8392006-10-04 21:52:35 +0000935 std::vector<std::pair<std::string, Option*> > Opts;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000936 copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts));
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000937
938 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Chris Lattner90aa8392006-10-04 21:52:35 +0000939 Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
940 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
941 Opts.end());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000942
943 // Eliminate duplicate entries in table (from enum flags options, f.e.)
Chris Lattner331de232002-07-22 02:07:59 +0000944 { // Give OptionSet a scope
945 std::set<Option*> OptionSet;
Chris Lattner90aa8392006-10-04 21:52:35 +0000946 for (unsigned i = 0; i != Opts.size(); ++i)
947 if (OptionSet.count(Opts[i].second) == 0)
948 OptionSet.insert(Opts[i].second); // Add new entry to set
Chris Lattner331de232002-07-22 02:07:59 +0000949 else
Chris Lattner90aa8392006-10-04 21:52:35 +0000950 Opts.erase(Opts.begin()+i--); // Erase duplicate
Chris Lattner331de232002-07-22 02:07:59 +0000951 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000952
953 if (ProgramOverview)
Dan Gohman82a13c92007-10-08 15:45:12 +0000954 cout << "OVERVIEW: " << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000955
Bill Wendlinge8156192006-12-07 01:30:32 +0000956 cout << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +0000957
Chris Lattner90aa8392006-10-04 21:52:35 +0000958 // Print out the positional options.
Chris Lattner331de232002-07-22 02:07:59 +0000959 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000960 if (!PositionalOpts.empty() &&
961 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
962 CAOpt = PositionalOpts[0];
Chris Lattner331de232002-07-22 02:07:59 +0000963
Chris Lattner9878d6a2007-04-06 21:06:55 +0000964 for (unsigned i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
965 if (PositionalOpts[i]->ArgStr[0])
966 cout << " --" << PositionalOpts[i]->ArgStr;
967 cout << " " << PositionalOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000968 }
Chris Lattner331de232002-07-22 02:07:59 +0000969
970 // Print the consume after option info if it exists...
Bill Wendlinge8156192006-12-07 01:30:32 +0000971 if (CAOpt) cout << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +0000972
Bill Wendlinge8156192006-12-07 01:30:32 +0000973 cout << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000974
975 // Compute the maximum argument length...
976 MaxArgLen = 0;
Chris Lattner90aa8392006-10-04 21:52:35 +0000977 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
978 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000979
Bill Wendlinge8156192006-12-07 01:30:32 +0000980 cout << "OPTIONS:\n";
Chris Lattner90aa8392006-10-04 21:52:35 +0000981 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
982 Opts[i].second->printOptionInfo(MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000983
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000984 // Print any extra help the user has declared.
Chris Lattner90aa8392006-10-04 21:52:35 +0000985 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
986 E = MoreHelp->end(); I != E; ++I)
Bill Wendlinge8156192006-12-07 01:30:32 +0000987 cout << *I;
Chris Lattner90aa8392006-10-04 21:52:35 +0000988 MoreHelp->clear();
Reid Spencerad0846b2004-11-14 22:04:00 +0000989
Reid Spencer9bbba0912004-11-16 06:11:52 +0000990 // Halt the program since help information was printed
Chris Lattner331de232002-07-22 02:07:59 +0000991 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000992 }
993};
Chris Lattner500d8bf2006-10-12 22:09:17 +0000994} // End anonymous namespace
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000995
Chris Lattner331de232002-07-22 02:07:59 +0000996// Define the two HelpPrinter instances that are used to print out help, or
997// help-hidden...
998//
Chris Lattner500d8bf2006-10-12 22:09:17 +0000999static HelpPrinter NormalPrinter(false);
1000static HelpPrinter HiddenPrinter(true);
Chris Lattner331de232002-07-22 02:07:59 +00001001
Chris Lattner500d8bf2006-10-12 22:09:17 +00001002static cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001003HOp("help", cl::desc("Display available options (--help-hidden for more)"),
Chris Lattner9b14eb52002-08-07 18:36:37 +00001004 cl::location(NormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +00001005
Chris Lattner500d8bf2006-10-12 22:09:17 +00001006static cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001007HHOp("help-hidden", cl::desc("Display all available options"),
Chris Lattner9b14eb52002-08-07 18:36:37 +00001008 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001009
Chris Lattner500d8bf2006-10-12 22:09:17 +00001010static void (*OverrideVersionPrinter)() = 0;
Reid Spencer515b5b32006-06-05 16:22:56 +00001011
Chris Lattner500d8bf2006-10-12 22:09:17 +00001012namespace {
Reid Spencer515b5b32006-06-05 16:22:56 +00001013class VersionPrinter {
1014public:
Devang Patelaed293d2007-02-01 01:43:37 +00001015 void print() {
Bill Wendlinge8156192006-12-07 01:30:32 +00001016 cout << "Low Level Virtual Machine (http://llvm.org/):\n";
1017 cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001018#ifdef LLVM_VERSION_INFO
Bill Wendlinge8156192006-12-07 01:30:32 +00001019 cout << LLVM_VERSION_INFO;
Reid Spencer515b5b32006-06-05 16:22:56 +00001020#endif
Bill Wendlinge8156192006-12-07 01:30:32 +00001021 cout << "\n ";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001022#ifndef __OPTIMIZE__
Bill Wendlinge8156192006-12-07 01:30:32 +00001023 cout << "DEBUG build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001024#else
Bill Wendlinge8156192006-12-07 01:30:32 +00001025 cout << "Optimized build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001026#endif
1027#ifndef NDEBUG
Bill Wendlinge8156192006-12-07 01:30:32 +00001028 cout << " with assertions";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001029#endif
Bill Wendlinge8156192006-12-07 01:30:32 +00001030 cout << ".\n";
Devang Patelaed293d2007-02-01 01:43:37 +00001031 }
1032 void operator=(bool OptionWasSpecified) {
1033 if (OptionWasSpecified) {
1034 if (OverrideVersionPrinter == 0) {
1035 print();
Reid Spencer515b5b32006-06-05 16:22:56 +00001036 exit(1);
1037 } else {
1038 (*OverrideVersionPrinter)();
1039 exit(1);
1040 }
1041 }
1042 }
1043};
Chris Lattner500d8bf2006-10-12 22:09:17 +00001044} // End anonymous namespace
Reid Spencer515b5b32006-06-05 16:22:56 +00001045
1046
Reid Spencer69105f32004-08-04 00:36:06 +00001047// Define the --version option that prints out the LLVM version for the tool
Chris Lattner500d8bf2006-10-12 22:09:17 +00001048static VersionPrinter VersionPrinterInstance;
1049
1050static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001051VersOp("version", cl::desc("Display the version of this program"),
Reid Spencer69105f32004-08-04 00:36:06 +00001052 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1053
Reid Spencer9bbba0912004-11-16 06:11:52 +00001054// Utility function for printing the help message.
1055void cl::PrintHelpMessage() {
Misha Brukmanf976c852005-04-21 22:55:34 +00001056 // This looks weird, but it actually prints the help message. The
Reid Spencer5cc498f2004-11-16 06:50:36 +00001057 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1058 // its operator= is invoked. That's because the "normal" usages of the
Misha Brukmanf976c852005-04-21 22:55:34 +00001059 // help printer is to be assigned true/false depending on whether the
Reid Spencer5cc498f2004-11-16 06:50:36 +00001060 // --help option was given or not. Since we're circumventing that we have
1061 // to make it look like --help was given, so we assign true.
Reid Spencer9bbba0912004-11-16 06:11:52 +00001062 NormalPrinter = true;
1063}
Reid Spencer515b5b32006-06-05 16:22:56 +00001064
Devang Patelaed293d2007-02-01 01:43:37 +00001065/// Utility function for printing version number.
1066void cl::PrintVersionMessage() {
1067 VersionPrinterInstance.print();
1068}
1069
Reid Spencer515b5b32006-06-05 16:22:56 +00001070void cl::SetVersionPrinter(void (*func)()) {
1071 OverrideVersionPrinter = func;
1072}