blob: 486875210fd14735ae562996dd80b2e976dd4096 [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,
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000104 std::vector<Option*> &SinkOpts,
Chris Lattner9878d6a2007-04-06 21:06:55 +0000105 std::map<std::string, Option*> &OptionsMap) {
106 std::vector<const char*> OptionNames;
Chris Lattneree2b3202007-04-07 05:38:53 +0000107 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000108 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
109 // If this option wants to handle multiple option names, get the full set.
110 // This handles enum options like "-O1 -O2" etc.
111 O->getExtraOptionNames(OptionNames);
112 if (O->ArgStr[0])
113 OptionNames.push_back(O->ArgStr);
114
115 // Handle named options.
116 for (unsigned i = 0, e = OptionNames.size(); i != e; ++i) {
117 // Add argument to the argument map!
118 if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i],
119 O)).second) {
120 cerr << ProgramName << ": CommandLine Error: Argument '"
121 << OptionNames[0] << "' defined more than once!\n";
122 }
123 }
124
125 OptionNames.clear();
126
127 // Remember information about positional options.
128 if (O->getFormattingFlag() == cl::Positional)
129 PositionalOpts.push_back(O);
Dan Gohman61e015f2008-02-23 01:55:25 +0000130 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000131 SinkOpts.push_back(O);
Chris Lattner9878d6a2007-04-06 21:06:55 +0000132 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattneree2b3202007-04-07 05:38:53 +0000133 if (CAOpt)
Chris Lattner9878d6a2007-04-06 21:06:55 +0000134 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattneree2b3202007-04-07 05:38:53 +0000135 CAOpt = O;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000136 }
Chris Lattnere8e258b2002-07-29 20:58:42 +0000137 }
Chris Lattneree2b3202007-04-07 05:38:53 +0000138
139 if (CAOpt)
140 PositionalOpts.push_back(CAOpt);
141
142 // Make sure that they are in order of registration not backwards.
143 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
Chris Lattnere8e258b2002-07-29 20:58:42 +0000144}
145
Chris Lattner9878d6a2007-04-06 21:06:55 +0000146
Chris Lattneraf035f32007-04-05 21:58:17 +0000147/// LookupOption - Lookup the option specified by the specified option on the
148/// command line. If there is a value specified (after an equal sign) return
149/// that as well.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000150static Option *LookupOption(const char *&Arg, const char *&Value,
151 std::map<std::string, Option*> &OptionsMap) {
Chris Lattneraf035f32007-04-05 21:58:17 +0000152 while (*Arg == '-') ++Arg; // Eat leading dashes
153
154 const char *ArgEnd = Arg;
155 while (*ArgEnd && *ArgEnd != '=')
156 ++ArgEnd; // Scan till end of argument name.
157
158 if (*ArgEnd == '=') // If we have an equals sign...
159 Value = ArgEnd+1; // Get the value, not the equals
160
161
162 if (*Arg == 0) return 0;
163
164 // Look up the option.
Chris Lattneraf035f32007-04-05 21:58:17 +0000165 std::map<std::string, Option*>::iterator I =
Chris Lattner9878d6a2007-04-06 21:06:55 +0000166 OptionsMap.find(std::string(Arg, ArgEnd));
167 return I != OptionsMap.end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000168}
169
Chris Lattnercaccd762001-10-27 05:54:17 +0000170static inline bool ProvideOption(Option *Handler, const char *ArgName,
171 const char *Value, int argc, char **argv,
172 int &i) {
173 // Enforce value requirements
174 switch (Handler->getValueExpectedFlag()) {
175 case ValueRequired:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000176 if (Value == 0) { // No value specified?
Chris Lattnercaccd762001-10-27 05:54:17 +0000177 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
178 Value = argv[++i];
179 } else {
180 return Handler->error(" requires a value!");
181 }
182 }
183 break;
184 case ValueDisallowed:
Chris Lattner6d5857e2005-05-10 23:20:17 +0000185 if (Value)
Misha Brukmanf976c852005-04-21 22:55:34 +0000186 return Handler->error(" does not allow a value! '" +
Chris Lattnerca6433f2003-05-22 20:06:43 +0000187 std::string(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +0000188 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000189 case ValueOptional:
Reid Spencere1cc1502004-09-01 04:41:28 +0000190 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000191 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000192 cerr << ProgramName
193 << ": Bad ValueMask flag! CommandLine usage error:"
194 << Handler->getValueExpectedFlag() << "\n";
Reid Spencere1cc1502004-09-01 04:41:28 +0000195 abort();
196 break;
Chris Lattnercaccd762001-10-27 05:54:17 +0000197 }
198
199 // Run the handler now!
Chris Lattner6d5857e2005-05-10 23:20:17 +0000200 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
Chris Lattnercaccd762001-10-27 05:54:17 +0000201}
202
Misha Brukmanf976c852005-04-21 22:55:34 +0000203static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000204 int i) {
205 int Dummy = i;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000206 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000207}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000208
Chris Lattner331de232002-07-22 02:07:59 +0000209
210// Option predicates...
211static inline bool isGrouping(const Option *O) {
212 return O->getFormattingFlag() == cl::Grouping;
213}
214static inline bool isPrefixedOrGrouping(const Option *O) {
215 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
216}
217
218// getOptionPred - Check to see if there are any options that satisfy the
219// specified predicate with names that are the prefixes in Name. This is
220// checked by progressively stripping characters off of the name, checking to
221// see if there options that satisfy the predicate. If we find one, return it,
222// otherwise return null.
223//
224static Option *getOptionPred(std::string Name, unsigned &Length,
Chris Lattner9878d6a2007-04-06 21:06:55 +0000225 bool (*Pred)(const Option*),
226 std::map<std::string, Option*> &OptionsMap) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000227
Chris Lattner9878d6a2007-04-06 21:06:55 +0000228 std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name);
229 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner331de232002-07-22 02:07:59 +0000230 Length = Name.length();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000231 return OMI->second;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000232 }
233
Chris Lattner331de232002-07-22 02:07:59 +0000234 if (Name.size() == 1) return 0;
235 do {
236 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000237 OMI = OptionsMap.find(Name);
Chris Lattner331de232002-07-22 02:07:59 +0000238
239 // Loop while we haven't found an option and Name still has at least two
240 // characters in it (so that the next iteration will not be the empty
241 // string...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000242 } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1);
Chris Lattner331de232002-07-22 02:07:59 +0000243
Chris Lattner9878d6a2007-04-06 21:06:55 +0000244 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner331de232002-07-22 02:07:59 +0000245 Length = Name.length();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000246 return OMI->second; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000247 }
248 return 0; // No option found!
249}
250
251static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000252 return O->getNumOccurrencesFlag() == cl::Required ||
253 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000254}
255
256static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000257 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
258 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000259}
Chris Lattnercaccd762001-10-27 05:54:17 +0000260
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000261/// ParseCStringVector - Break INPUT up wherever one or more
262/// whitespace characters are found, and store the resulting tokens in
263/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
264/// using strdup (), so it is the caller's responsibility to free ()
265/// them later.
Brian Gaeke06b06c52003-08-14 22:00:59 +0000266///
Chris Lattner23288582006-08-27 22:10:29 +0000267static void ParseCStringVector(std::vector<char *> &output,
268 const char *input) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000269 // Characters which will be treated as token separators:
270 static const char *delims = " \v\f\t\r\n";
271
272 std::string work (input);
273 // Skip past any delims at head of input string.
274 size_t pos = work.find_first_not_of (delims);
275 // If the string consists entirely of delims, then exit early.
276 if (pos == std::string::npos) return;
277 // Otherwise, jump forward to beginning of first word.
278 work = work.substr (pos);
279 // Find position of first delimiter.
280 pos = work.find_first_of (delims);
281
282 while (!work.empty() && pos != std::string::npos) {
283 // Everything from 0 to POS is the next word to copy.
284 output.push_back (strdup (work.substr (0,pos).c_str ()));
285 // Is there another word in the string?
286 size_t nextpos = work.find_first_not_of (delims, pos + 1);
287 if (nextpos != std::string::npos) {
288 // Yes? Then remove delims from beginning ...
289 work = work.substr (work.find_first_not_of (delims, pos + 1));
290 // and find the end of the word.
291 pos = work.find_first_of (delims);
292 } else {
293 // No? (Remainder of string is delims.) End the loop.
294 work = "";
295 pos = std::string::npos;
296 }
297 }
298
299 // If `input' ended with non-delim char, then we'll get here with
300 // the last word of `input' in `work'; copy it now.
301 if (!work.empty ()) {
302 output.push_back (strdup (work.c_str ()));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000303 }
304}
305
306/// ParseEnvironmentOptions - An alternative entry point to the
307/// CommandLine library, which allows you to read the program's name
308/// from the caller (as PROGNAME) and its command-line arguments from
309/// an environment variable (whose name is given in ENVVAR).
310///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000311void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
312 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000313 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000314 assert(progName && "Program name not specified");
315 assert(envVar && "Environment variable name missing");
Misha Brukmanf976c852005-04-21 22:55:34 +0000316
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000317 // Get the environment variable they want us to parse options out of.
Chris Lattner23288582006-08-27 22:10:29 +0000318 const char *envValue = getenv(envVar);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000319 if (!envValue)
320 return;
321
Brian Gaeke06b06c52003-08-14 22:00:59 +0000322 // Get program's "name", which we wouldn't know without the caller
323 // telling us.
Chris Lattner23288582006-08-27 22:10:29 +0000324 std::vector<char*> newArgv;
325 newArgv.push_back(strdup(progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000326
327 // Parse the value of the environment variable into a "command line"
328 // and hand it off to ParseCommandLineOptions().
Chris Lattner23288582006-08-27 22:10:29 +0000329 ParseCStringVector(newArgv, envValue);
330 int newArgc = newArgv.size();
331 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000332
333 // Free all the strdup()ed strings.
Chris Lattner23288582006-08-27 22:10:29 +0000334 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
335 i != e; ++i)
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000336 free (*i);
Brian Gaeke06b06c52003-08-14 22:00:59 +0000337}
338
Dan Gohman9a526322007-10-09 16:04:57 +0000339void cl::ParseCommandLineOptions(int argc, char **argv,
Chris Lattner0c0edf82002-07-25 06:17:51 +0000340 const char *Overview) {
Chris Lattner9878d6a2007-04-06 21:06:55 +0000341 // Process all registered options.
342 std::vector<Option*> PositionalOpts;
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000343 std::vector<Option*> SinkOpts;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000344 std::map<std::string, Option*> Opts;
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000345 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Chris Lattner9878d6a2007-04-06 21:06:55 +0000346
347 assert((!Opts.empty() || !PositionalOpts.empty()) &&
348 "No options specified!");
Reid Spencer6f4c6072006-08-23 07:10:06 +0000349 sys::Path progname(argv[0]);
Chris Lattnerefa3da52006-10-13 00:06:24 +0000350
351 // Copy the program name into ProgName, making sure not to overflow it.
352 std::string ProgName = sys::Path(argv[0]).getLast();
353 if (ProgName.size() > 79) ProgName.resize(79);
354 strcpy(ProgramName, ProgName.c_str());
355
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000356 ProgramOverview = Overview;
357 bool ErrorParsing = false;
358
Chris Lattner331de232002-07-22 02:07:59 +0000359 // Check out the positional arguments to collect information about them.
360 unsigned NumPositionalRequired = 0;
Chris Lattnerde013242005-08-08 17:25:38 +0000361
362 // Determine whether or not there are an unlimited number of positionals
363 bool HasUnlimitedPositionals = false;
364
Chris Lattner331de232002-07-22 02:07:59 +0000365 Option *ConsumeAfterOpt = 0;
366 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000367 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000368 assert(PositionalOpts.size() > 1 &&
369 "Cannot specify cl::ConsumeAfter without a positional argument!");
370 ConsumeAfterOpt = PositionalOpts[0];
371 }
372
373 // Calculate how many positional values are _required_.
374 bool UnboundedFound = false;
375 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
376 i != e; ++i) {
377 Option *Opt = PositionalOpts[i];
378 if (RequiresValue(Opt))
379 ++NumPositionalRequired;
380 else if (ConsumeAfterOpt) {
381 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000382 // unless there is only one positional argument...
383 if (PositionalOpts.size() > 2)
384 ErrorParsing |=
385 Opt->error(" error - this positional option will never be matched, "
386 "because it does not Require a value, and a "
387 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000388 } else if (UnboundedFound && !Opt->ArgStr[0]) {
389 // This option does not "require" a value... Make sure this option is
390 // not specified after an option that eats all extra arguments, or this
391 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000392 //
393 ErrorParsing |= Opt->error(" error - option can never match, because "
394 "another positional argument will match an "
395 "unbounded number of values, and this option"
396 " does not require a value!");
397 }
398 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
399 }
Chris Lattner21e1a792005-08-08 21:57:27 +0000400 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000401 }
402
Reid Spencer1e13fd22004-08-13 19:47:30 +0000403 // PositionalVals - A vector of "positional" arguments we accumulate into
404 // the process at the end...
Chris Lattner331de232002-07-22 02:07:59 +0000405 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000406 std::vector<std::pair<std::string,unsigned> > PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000407
Chris Lattner9cf3d472003-07-30 17:34:02 +0000408 // If the program has named positional arguments, and the name has been run
409 // across, keep track of which positional argument was named. Otherwise put
410 // the positional args into the PositionalVals list...
411 Option *ActivePositionalArg = 0;
412
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000413 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000414 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000415 for (int i = 1; i < argc; ++i) {
416 Option *Handler = 0;
Chris Lattner6d5857e2005-05-10 23:20:17 +0000417 const char *Value = 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000418 const char *ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000419
Chris Lattner69d6f132007-04-12 00:36:29 +0000420 // If the option list changed, this means that some command line
Chris Lattner159b0a432007-04-11 15:35:18 +0000421 // option has just been registered or deregistered. This can occur in
422 // response to things like -load, etc. If this happens, rescan the options.
Chris Lattner69d6f132007-04-12 00:36:29 +0000423 if (OptionListChanged) {
Chris Lattner159b0a432007-04-11 15:35:18 +0000424 PositionalOpts.clear();
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000425 SinkOpts.clear();
Chris Lattner159b0a432007-04-11 15:35:18 +0000426 Opts.clear();
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000427 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Chris Lattner69d6f132007-04-12 00:36:29 +0000428 OptionListChanged = false;
Chris Lattner159b0a432007-04-11 15:35:18 +0000429 }
430
Chris Lattner331de232002-07-22 02:07:59 +0000431 // Check to see if this is a positional argument. This argument is
432 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000433 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000434 //
435 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
436 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000437 if (ActivePositionalArg) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000438 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000439 continue; // We are done!
440 } else if (!PositionalOpts.empty()) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000441 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000442
443 // All of the positional arguments have been fulfulled, give the rest to
444 // the consume after option... if it's specified...
445 //
Misha Brukmanf976c852005-04-21 22:55:34 +0000446 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000447 ConsumeAfterOpt != 0) {
448 for (++i; i < argc; ++i)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000449 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000450 break; // Handle outside of the argument processing loop...
451 }
452
453 // Delay processing positional arguments until the end...
454 continue;
455 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000456 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
457 !DashDashFound) {
458 DashDashFound = true; // This is the mythical "--"?
459 continue; // Don't try to process it as an argument itself.
460 } else if (ActivePositionalArg &&
461 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
462 // If there is a positional argument eating options, check to see if this
463 // option is another positional argument. If so, treat it as an argument,
464 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000465 ArgName = argv[i]+1;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000466 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000467 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000468 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000469 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000470 }
471
Chris Lattnerbf455c22004-05-06 22:04:31 +0000472 } else { // We start with a '-', must be an argument...
473 ArgName = argv[i]+1;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000474 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000475
Chris Lattnerbf455c22004-05-06 22:04:31 +0000476 // Check to see if this "option" is really a prefixed or grouped argument.
Reid Spencer5f8448f2004-11-24 06:13:42 +0000477 if (Handler == 0) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000478 std::string RealName(ArgName);
479 if (RealName.size() > 1) {
Chris Lattner331de232002-07-22 02:07:59 +0000480 unsigned Length = 0;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000481 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping,
482 Opts);
Misha Brukmanf976c852005-04-21 22:55:34 +0000483
Chris Lattner331de232002-07-22 02:07:59 +0000484 // If the option is a prefixed option, then the value is simply the
485 // rest of the name... so fall through to later processing, by
486 // setting up the argument name flags and value fields.
487 //
488 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000489 Value = ArgName+Length;
490 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
491 Opts.find(std::string(ArgName, Value))->second == PGOpt);
492 Handler = PGOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000493 } else if (PGOpt) {
Chris Lattnerbf455c22004-05-06 22:04:31 +0000494 // This must be a grouped option... handle them now.
Chris Lattner331de232002-07-22 02:07:59 +0000495 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000496
Chris Lattner331de232002-07-22 02:07:59 +0000497 do {
498 // Move current arg name out of RealName into RealArgName...
Chris Lattnerbf455c22004-05-06 22:04:31 +0000499 std::string RealArgName(RealName.begin(),
500 RealName.begin() + Length);
501 RealName.erase(RealName.begin(), RealName.begin() + Length);
Misha Brukmanf976c852005-04-21 22:55:34 +0000502
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000503 // Because ValueRequired is an invalid flag for grouped arguments,
504 // we don't need to pass argc/argv in...
505 //
Chris Lattner331de232002-07-22 02:07:59 +0000506 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
507 "Option can not be cl::Grouping AND cl::ValueRequired!");
508 int Dummy;
Chris Lattnerbf455c22004-05-06 22:04:31 +0000509 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
Chris Lattner6d5857e2005-05-10 23:20:17 +0000510 0, 0, 0, Dummy);
Misha Brukmanf976c852005-04-21 22:55:34 +0000511
Chris Lattner331de232002-07-22 02:07:59 +0000512 // Get the next grouping option...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000513 PGOpt = getOptionPred(RealName, Length, isGrouping, Opts);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000514 } while (PGOpt && Length != RealName.size());
Misha Brukmanf976c852005-04-21 22:55:34 +0000515
Chris Lattnerbf455c22004-05-06 22:04:31 +0000516 Handler = PGOpt; // Ate all of the options.
Chris Lattner331de232002-07-22 02:07:59 +0000517 }
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000518 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000519 }
520 }
521
522 if (Handler == 0) {
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000523 if (SinkOpts.empty()) {
524 cerr << ProgramName << ": Unknown command line argument '"
525 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
526 ErrorParsing = true;
527 } else {
528 for (std::vector<Option*>::iterator I = SinkOpts.begin(),
529 E = SinkOpts.end(); I != E ; ++I)
530 (*I)->addOccurrence(i, "", argv[i]);
531 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000532 continue;
533 }
534
Chris Lattner72fb8e52003-05-22 20:26:17 +0000535 // Check to see if this option accepts a comma separated list of values. If
536 // it does, we have to split up the value into multiple values...
Chris Lattner6d5857e2005-05-10 23:20:17 +0000537 if (Value && Handler->getMiscFlags() & CommaSeparated) {
Chris Lattner72fb8e52003-05-22 20:26:17 +0000538 std::string Val(Value);
539 std::string::size_type Pos = Val.find(',');
540
541 while (Pos != std::string::npos) {
542 // Process the portion before the comma...
543 ErrorParsing |= ProvideOption(Handler, ArgName,
544 std::string(Val.begin(),
545 Val.begin()+Pos).c_str(),
546 argc, argv, i);
547 // Erase the portion before the comma, AND the comma...
548 Val.erase(Val.begin(), Val.begin()+Pos+1);
549 Value += Pos+1; // Increment the original value pointer as well...
550
551 // Check for another comma...
552 Pos = Val.find(',');
553 }
554 }
Chris Lattner9cf3d472003-07-30 17:34:02 +0000555
556 // If this is a named positional argument, just remember that it is the
557 // active one...
558 if (Handler->getFormattingFlag() == cl::Positional)
559 ActivePositionalArg = Handler;
Misha Brukmanf976c852005-04-21 22:55:34 +0000560 else
Chris Lattner9cf3d472003-07-30 17:34:02 +0000561 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000562 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000563
Chris Lattner331de232002-07-22 02:07:59 +0000564 // Check and handle positional arguments now...
565 if (NumPositionalRequired > PositionalVals.size()) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000566 cerr << ProgramName
567 << ": Not enough positional command line arguments specified!\n"
568 << "Must specify at least " << NumPositionalRequired
569 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattner79959d22006-01-17 00:32:28 +0000570
Chris Lattner331de232002-07-22 02:07:59 +0000571 ErrorParsing = true;
Chris Lattnerde013242005-08-08 17:25:38 +0000572 } else if (!HasUnlimitedPositionals
573 && PositionalVals.size() > PositionalOpts.size()) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000574 cerr << ProgramName
575 << ": Too many positional arguments specified!\n"
576 << "Can specify at most " << PositionalOpts.size()
577 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattnerde013242005-08-08 17:25:38 +0000578 ErrorParsing = true;
Chris Lattner331de232002-07-22 02:07:59 +0000579
580 } else if (ConsumeAfterOpt == 0) {
581 // Positional args have already been handled if ConsumeAfter is specified...
582 unsigned ValNo = 0, NumVals = PositionalVals.size();
583 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
584 if (RequiresValue(PositionalOpts[i])) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000585 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000586 PositionalVals[ValNo].second);
587 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000588 --NumPositionalRequired; // We fulfilled our duty...
589 }
590
591 // If we _can_ give this option more arguments, do so now, as long as we
592 // do not give it values that others need. 'Done' controls whether the
593 // option even _WANTS_ any more.
594 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000595 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000596 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000597 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000598 case cl::Optional:
599 Done = true; // Optional arguments want _at most_ one value
600 // FALL THROUGH
601 case cl::ZeroOrMore: // Zero or more will take all they can get...
602 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer1e13fd22004-08-13 19:47:30 +0000603 ProvidePositionalOption(PositionalOpts[i],
604 PositionalVals[ValNo].first,
605 PositionalVals[ValNo].second);
606 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000607 break;
608 default:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000609 assert(0 && "Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000610 "positional argument processing!");
611 }
612 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000613 }
Chris Lattner331de232002-07-22 02:07:59 +0000614 } else {
615 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
616 unsigned ValNo = 0;
617 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000618 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000619 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000620 PositionalVals[ValNo].first,
621 PositionalVals[ValNo].second);
622 ValNo++;
623 }
Chris Lattnerfaba8092002-07-24 20:15:13 +0000624
625 // Handle the case where there is just one positional option, and it's
626 // optional. In this case, we want to give JUST THE FIRST option to the
627 // positional option and keep the rest for the consume after. The above
628 // loop would have assigned no values to positional options in this case.
629 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000630 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000631 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000632 PositionalVals[ValNo].first,
633 PositionalVals[ValNo].second);
634 ValNo++;
635 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000636
Chris Lattner331de232002-07-22 02:07:59 +0000637 // Handle over all of the rest of the arguments to the
638 // cl::ConsumeAfter command line option...
639 for (; ValNo != PositionalVals.size(); ++ValNo)
640 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000641 PositionalVals[ValNo].first,
642 PositionalVals[ValNo].second);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000643 }
644
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000645 // Loop over args and make sure all required args are specified!
Misha Brukmanf976c852005-04-21 22:55:34 +0000646 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000647 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000648 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000649 case Required:
650 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000651 if (I->second->getNumOccurrences() == 0) {
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000652 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000653 ErrorParsing = true;
654 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000655 // Fall through
656 default:
657 break;
658 }
659 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000660
Chris Lattner331de232002-07-22 02:07:59 +0000661 // Free all of the memory allocated to the map. Command line options may only
662 // be processed once!
Chris Lattner90aa8392006-10-04 21:52:35 +0000663 Opts.clear();
Chris Lattner331de232002-07-22 02:07:59 +0000664 PositionalOpts.clear();
Chris Lattner90aa8392006-10-04 21:52:35 +0000665 MoreHelp->clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000666
667 // If we had an error processing our arguments, don't let the program execute
668 if (ErrorParsing) exit(1);
669}
670
671//===----------------------------------------------------------------------===//
672// Option Base class implementation
673//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000674
Chris Lattnerca6433f2003-05-22 20:06:43 +0000675bool Option::error(std::string Message, const char *ArgName) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000676 if (ArgName == 0) ArgName = ArgStr;
Chris Lattner331de232002-07-22 02:07:59 +0000677 if (ArgName[0] == 0)
Bill Wendlinge8156192006-12-07 01:30:32 +0000678 cerr << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000679 else
Bill Wendlinge8156192006-12-07 01:30:32 +0000680 cerr << ProgramName << ": for the -" << ArgName;
Jim Laskeyabe0e3e2006-08-02 20:15:56 +0000681
Bill Wendlinge8156192006-12-07 01:30:32 +0000682 cerr << " option: " << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000683 return true;
684}
685
Chris Lattner6d5857e2005-05-10 23:20:17 +0000686bool Option::addOccurrence(unsigned pos, const char *ArgName,
687 const std::string &Value) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000688 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000689
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000690 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000691 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000692 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000693 return error(": may only occur zero or one times!", ArgName);
694 break;
695 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000696 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000697 return error(": must occur exactly one time!", ArgName);
698 // Fall through
699 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000700 case ZeroOrMore:
701 case ConsumeAfter: break;
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000702 default: return error(": bad num occurrences flag value!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000703 }
704
Reid Spencer1e13fd22004-08-13 19:47:30 +0000705 return handleOccurrence(pos, ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000706}
707
Chris Lattner331de232002-07-22 02:07:59 +0000708
709// getValueStr - Get the value description string, using "DefaultMsg" if nothing
710// has been specified yet.
711//
712static const char *getValueStr(const Option &O, const char *DefaultMsg) {
713 if (O.ValueStr[0] == 0) return DefaultMsg;
714 return O.ValueStr;
715}
716
717//===----------------------------------------------------------------------===//
718// cl::alias class implementation
719//
720
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000721// Return the width of the option tag for printing...
Chris Lattner331de232002-07-22 02:07:59 +0000722unsigned alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000723 return std::strlen(ArgStr)+6;
724}
725
Chris Lattnera0de8432006-04-28 05:36:25 +0000726// Print out the option for the alias.
Chris Lattner331de232002-07-22 02:07:59 +0000727void alias::printOptionInfo(unsigned GlobalWidth) const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000728 unsigned L = std::strlen(ArgStr);
Bill Wendlinge8156192006-12-07 01:30:32 +0000729 cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
730 << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000731}
732
733
Chris Lattner331de232002-07-22 02:07:59 +0000734
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000735//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000736// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000737//
738
Chris Lattner9b14eb52002-08-07 18:36:37 +0000739// basic_parser implementation
740//
741
742// Return the width of the option tag for printing...
743unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
744 unsigned Len = std::strlen(O.ArgStr);
745 if (const char *ValName = getValueName())
746 Len += std::strlen(getValueStr(O, ValName))+3;
747
748 return Len + 6;
749}
750
Misha Brukmanf976c852005-04-21 22:55:34 +0000751// printOptionInfo - Print out information about this option. The
Chris Lattner9b14eb52002-08-07 18:36:37 +0000752// to-be-maintained width is specified.
753//
754void basic_parser_impl::printOptionInfo(const Option &O,
755 unsigned GlobalWidth) const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000756 cout << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000757
758 if (const char *ValName = getValueName())
Bill Wendlinge8156192006-12-07 01:30:32 +0000759 cout << "=<" << getValueStr(O, ValName) << ">";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000760
Bill Wendlinge8156192006-12-07 01:30:32 +0000761 cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
762 << O.HelpStr << "\n";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000763}
764
765
766
767
Chris Lattner331de232002-07-22 02:07:59 +0000768// parser<bool> implementation
769//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000770bool parser<bool>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000771 const std::string &Arg, bool &Value) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000772 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000773 Arg == "1") {
774 Value = true;
775 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
776 Value = false;
777 } else {
Chris Lattner331de232002-07-22 02:07:59 +0000778 return O.error(": '" + Arg +
779 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000780 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000781 return false;
782}
783
Dale Johannesen81da02b2007-05-22 17:14:46 +0000784// parser<boolOrDefault> implementation
785//
786bool parser<boolOrDefault>::parse(Option &O, const char *ArgName,
787 const std::string &Arg, boolOrDefault &Value) {
788 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
789 Arg == "1") {
790 Value = BOU_TRUE;
791 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
792 Value = BOU_FALSE;
793 } else {
794 return O.error(": '" + Arg +
795 "' is invalid value for boolean argument! Try 0 or 1");
796 }
797 return false;
798}
799
Chris Lattner331de232002-07-22 02:07:59 +0000800// parser<int> implementation
801//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000802bool parser<int>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000803 const std::string &Arg, int &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000804 char *End;
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000805 Value = (int)strtol(Arg.c_str(), &End, 0);
Misha Brukmanf976c852005-04-21 22:55:34 +0000806 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000807 return O.error(": '" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000808 return false;
809}
810
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000811// parser<unsigned> implementation
812//
813bool parser<unsigned>::parse(Option &O, const char *ArgName,
814 const std::string &Arg, unsigned &Value) {
815 char *End;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000816 errno = 0;
817 unsigned long V = strtoul(Arg.c_str(), &End, 0);
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000818 Value = (unsigned)V;
Brian Gaeke2d6a2362003-10-10 17:01:36 +0000819 if (((V == ULONG_MAX) && (errno == ERANGE))
820 || (*End != 0)
821 || (Value != V))
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000822 return O.error(": '" + Arg + "' value invalid for uint argument!");
823 return false;
824}
825
Chris Lattner9b14eb52002-08-07 18:36:37 +0000826// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +0000827//
Chris Lattnerca6433f2003-05-22 20:06:43 +0000828static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
Chris Lattner331de232002-07-22 02:07:59 +0000829 const char *ArgStart = Arg.c_str();
830 char *End;
831 Value = strtod(ArgStart, &End);
Misha Brukmanf976c852005-04-21 22:55:34 +0000832 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000833 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +0000834 return false;
835}
836
Chris Lattner9b14eb52002-08-07 18:36:37 +0000837bool parser<double>::parse(Option &O, const char *AN,
838 const std::string &Arg, double &Val) {
839 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +0000840}
841
Chris Lattner9b14eb52002-08-07 18:36:37 +0000842bool parser<float>::parse(Option &O, const char *AN,
843 const std::string &Arg, float &Val) {
844 double dVal;
845 if (parseDouble(O, Arg, dVal))
846 return true;
847 Val = (float)dVal;
848 return false;
Chris Lattner331de232002-07-22 02:07:59 +0000849}
850
851
Chris Lattner331de232002-07-22 02:07:59 +0000852
853// generic_parser_base implementation
854//
855
Chris Lattneraa852bb2002-07-23 17:15:12 +0000856// findOption - Return the option number corresponding to the specified
857// argument string. If the option is not found, getNumOptions() is returned.
858//
859unsigned generic_parser_base::findOption(const char *Name) {
860 unsigned i = 0, e = getNumOptions();
Chris Lattnerca6433f2003-05-22 20:06:43 +0000861 std::string N(Name);
Chris Lattneraa852bb2002-07-23 17:15:12 +0000862
863 while (i != e)
864 if (getOption(i) == N)
865 return i;
866 else
867 ++i;
868 return e;
869}
870
871
Chris Lattner331de232002-07-22 02:07:59 +0000872// Return the width of the option tag for printing...
873unsigned generic_parser_base::getOptionWidth(const Option &O) const {
874 if (O.hasArgStr()) {
875 unsigned Size = std::strlen(O.ArgStr)+6;
876 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
877 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
878 return Size;
879 } else {
880 unsigned BaseSize = 0;
881 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
882 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
883 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000884 }
885}
886
Misha Brukmanf976c852005-04-21 22:55:34 +0000887// printOptionInfo - Print out information about this option. The
Chris Lattner331de232002-07-22 02:07:59 +0000888// to-be-maintained width is specified.
889//
890void generic_parser_base::printOptionInfo(const Option &O,
891 unsigned GlobalWidth) const {
892 if (O.hasArgStr()) {
893 unsigned L = std::strlen(O.ArgStr);
Bill Wendlinge8156192006-12-07 01:30:32 +0000894 cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
895 << " - " << O.HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000896
Chris Lattner331de232002-07-22 02:07:59 +0000897 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
898 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Bill Wendlinge8156192006-12-07 01:30:32 +0000899 cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
900 << " - " << getDescription(i) << "\n";
Chris Lattner9c9be482002-01-31 00:42:56 +0000901 }
Chris Lattner331de232002-07-22 02:07:59 +0000902 } else {
903 if (O.HelpStr[0])
Bill Wendlinge8156192006-12-07 01:30:32 +0000904 cout << " " << O.HelpStr << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000905 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
906 unsigned L = std::strlen(getOption(i));
Bill Wendlinge8156192006-12-07 01:30:32 +0000907 cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
908 << " - " << getDescription(i) << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000909 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000910 }
911}
912
913
914//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000915// --help and --help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000916//
Reid Spencerad0846b2004-11-14 22:04:00 +0000917
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000918namespace {
919
Chris Lattner331de232002-07-22 02:07:59 +0000920class HelpPrinter {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000921 unsigned MaxArgLen;
922 const Option *EmptyArg;
923 const bool ShowHidden;
924
Chris Lattner331de232002-07-22 02:07:59 +0000925 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
Chris Lattnerca6433f2003-05-22 20:06:43 +0000926 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000927 return OptPair.second->getOptionHiddenFlag() >= Hidden;
928 }
Chris Lattnerca6433f2003-05-22 20:06:43 +0000929 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000930 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
931 }
932
933public:
934 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
935 EmptyArg = 0;
936 }
937
938 void operator=(bool Value) {
939 if (Value == false) return;
940
Chris Lattner9878d6a2007-04-06 21:06:55 +0000941 // Get all the options.
942 std::vector<Option*> PositionalOpts;
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000943 std::vector<Option*> SinkOpts;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000944 std::map<std::string, Option*> OptMap;
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000945 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
Chris Lattner9878d6a2007-04-06 21:06:55 +0000946
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000947 // Copy Options into a vector so we can sort them as we like...
Chris Lattner90aa8392006-10-04 21:52:35 +0000948 std::vector<std::pair<std::string, Option*> > Opts;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000949 copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts));
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000950
951 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Chris Lattner90aa8392006-10-04 21:52:35 +0000952 Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
953 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
954 Opts.end());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000955
956 // Eliminate duplicate entries in table (from enum flags options, f.e.)
Chris Lattner331de232002-07-22 02:07:59 +0000957 { // Give OptionSet a scope
958 std::set<Option*> OptionSet;
Chris Lattner90aa8392006-10-04 21:52:35 +0000959 for (unsigned i = 0; i != Opts.size(); ++i)
960 if (OptionSet.count(Opts[i].second) == 0)
961 OptionSet.insert(Opts[i].second); // Add new entry to set
Chris Lattner331de232002-07-22 02:07:59 +0000962 else
Chris Lattner90aa8392006-10-04 21:52:35 +0000963 Opts.erase(Opts.begin()+i--); // Erase duplicate
Chris Lattner331de232002-07-22 02:07:59 +0000964 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000965
966 if (ProgramOverview)
Dan Gohman82a13c92007-10-08 15:45:12 +0000967 cout << "OVERVIEW: " << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000968
Bill Wendlinge8156192006-12-07 01:30:32 +0000969 cout << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +0000970
Chris Lattner90aa8392006-10-04 21:52:35 +0000971 // Print out the positional options.
Chris Lattner331de232002-07-22 02:07:59 +0000972 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Chris Lattner9878d6a2007-04-06 21:06:55 +0000973 if (!PositionalOpts.empty() &&
974 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
975 CAOpt = PositionalOpts[0];
Chris Lattner331de232002-07-22 02:07:59 +0000976
Chris Lattner9878d6a2007-04-06 21:06:55 +0000977 for (unsigned i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
978 if (PositionalOpts[i]->ArgStr[0])
979 cout << " --" << PositionalOpts[i]->ArgStr;
980 cout << " " << PositionalOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000981 }
Chris Lattner331de232002-07-22 02:07:59 +0000982
983 // Print the consume after option info if it exists...
Bill Wendlinge8156192006-12-07 01:30:32 +0000984 if (CAOpt) cout << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +0000985
Bill Wendlinge8156192006-12-07 01:30:32 +0000986 cout << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000987
988 // Compute the maximum argument length...
989 MaxArgLen = 0;
Chris Lattner90aa8392006-10-04 21:52:35 +0000990 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
991 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000992
Bill Wendlinge8156192006-12-07 01:30:32 +0000993 cout << "OPTIONS:\n";
Chris Lattner90aa8392006-10-04 21:52:35 +0000994 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
995 Opts[i].second->printOptionInfo(MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000996
Chris Lattnerc540ebb2004-11-19 17:08:15 +0000997 // Print any extra help the user has declared.
Chris Lattner90aa8392006-10-04 21:52:35 +0000998 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
999 E = MoreHelp->end(); I != E; ++I)
Bill Wendlinge8156192006-12-07 01:30:32 +00001000 cout << *I;
Chris Lattner90aa8392006-10-04 21:52:35 +00001001 MoreHelp->clear();
Reid Spencerad0846b2004-11-14 22:04:00 +00001002
Reid Spencer9bbba0912004-11-16 06:11:52 +00001003 // Halt the program since help information was printed
Chris Lattner331de232002-07-22 02:07:59 +00001004 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001005 }
1006};
Chris Lattner500d8bf2006-10-12 22:09:17 +00001007} // End anonymous namespace
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001008
Chris Lattner331de232002-07-22 02:07:59 +00001009// Define the two HelpPrinter instances that are used to print out help, or
1010// help-hidden...
1011//
Chris Lattner500d8bf2006-10-12 22:09:17 +00001012static HelpPrinter NormalPrinter(false);
1013static HelpPrinter HiddenPrinter(true);
Chris Lattner331de232002-07-22 02:07:59 +00001014
Chris Lattner500d8bf2006-10-12 22:09:17 +00001015static cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001016HOp("help", cl::desc("Display available options (--help-hidden for more)"),
Chris Lattner9b14eb52002-08-07 18:36:37 +00001017 cl::location(NormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +00001018
Chris Lattner500d8bf2006-10-12 22:09:17 +00001019static cl::opt<HelpPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001020HHOp("help-hidden", cl::desc("Display all available options"),
Chris Lattner9b14eb52002-08-07 18:36:37 +00001021 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001022
Chris Lattner500d8bf2006-10-12 22:09:17 +00001023static void (*OverrideVersionPrinter)() = 0;
Reid Spencer515b5b32006-06-05 16:22:56 +00001024
Chris Lattner500d8bf2006-10-12 22:09:17 +00001025namespace {
Reid Spencer515b5b32006-06-05 16:22:56 +00001026class VersionPrinter {
1027public:
Devang Patelaed293d2007-02-01 01:43:37 +00001028 void print() {
Bill Wendlinge8156192006-12-07 01:30:32 +00001029 cout << "Low Level Virtual Machine (http://llvm.org/):\n";
1030 cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001031#ifdef LLVM_VERSION_INFO
Bill Wendlinge8156192006-12-07 01:30:32 +00001032 cout << LLVM_VERSION_INFO;
Reid Spencer515b5b32006-06-05 16:22:56 +00001033#endif
Bill Wendlinge8156192006-12-07 01:30:32 +00001034 cout << "\n ";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001035#ifndef __OPTIMIZE__
Bill Wendlinge8156192006-12-07 01:30:32 +00001036 cout << "DEBUG build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001037#else
Bill Wendlinge8156192006-12-07 01:30:32 +00001038 cout << "Optimized build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001039#endif
1040#ifndef NDEBUG
Bill Wendlinge8156192006-12-07 01:30:32 +00001041 cout << " with assertions";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001042#endif
Bill Wendlinge8156192006-12-07 01:30:32 +00001043 cout << ".\n";
Devang Patelaed293d2007-02-01 01:43:37 +00001044 }
1045 void operator=(bool OptionWasSpecified) {
1046 if (OptionWasSpecified) {
1047 if (OverrideVersionPrinter == 0) {
1048 print();
Reid Spencer515b5b32006-06-05 16:22:56 +00001049 exit(1);
1050 } else {
1051 (*OverrideVersionPrinter)();
1052 exit(1);
1053 }
1054 }
1055 }
1056};
Chris Lattner500d8bf2006-10-12 22:09:17 +00001057} // End anonymous namespace
Reid Spencer515b5b32006-06-05 16:22:56 +00001058
1059
Reid Spencer69105f32004-08-04 00:36:06 +00001060// Define the --version option that prints out the LLVM version for the tool
Chris Lattner500d8bf2006-10-12 22:09:17 +00001061static VersionPrinter VersionPrinterInstance;
1062
1063static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001064VersOp("version", cl::desc("Display the version of this program"),
Reid Spencer69105f32004-08-04 00:36:06 +00001065 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1066
Reid Spencer9bbba0912004-11-16 06:11:52 +00001067// Utility function for printing the help message.
1068void cl::PrintHelpMessage() {
Misha Brukmanf976c852005-04-21 22:55:34 +00001069 // This looks weird, but it actually prints the help message. The
Reid Spencer5cc498f2004-11-16 06:50:36 +00001070 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1071 // its operator= is invoked. That's because the "normal" usages of the
Misha Brukmanf976c852005-04-21 22:55:34 +00001072 // help printer is to be assigned true/false depending on whether the
Reid Spencer5cc498f2004-11-16 06:50:36 +00001073 // --help option was given or not. Since we're circumventing that we have
1074 // to make it look like --help was given, so we assign true.
Reid Spencer9bbba0912004-11-16 06:11:52 +00001075 NormalPrinter = true;
1076}
Reid Spencer515b5b32006-06-05 16:22:56 +00001077
Devang Patelaed293d2007-02-01 01:43:37 +00001078/// Utility function for printing version number.
1079void cl::PrintVersionMessage() {
1080 VersionPrinterInstance.print();
1081}
1082
Reid Spencer515b5b32006-06-05 16:22:56 +00001083void cl::SetVersionPrinter(void (*func)()) {
1084 OverrideVersionPrinter = func;
1085}