blob: 4e3a92fec29bae77f85f6de33e30d12e5d02c002 [file] [log] [blame]
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
2//
3// This class implements a command line argument processor that is useful when
4// creating a tool. It provides a simple, minimalistic interface that is easily
5// extensible and supports nonlocal (library) command line options.
6//
Chris Lattner03fe1bd2001-07-23 23:04:07 +00007// Note that rather than trying to figure out what this code does, you could try
8// reading the library documentation located in docs/CommandLine.html
9//
Chris Lattnerdbab15a2001-07-23 17:17:47 +000010//===----------------------------------------------------------------------===//
11
Chris Lattnercee8f9a2001-11-27 00:03:19 +000012#include "Support/CommandLine.h"
Chris Lattnerdbab15a2001-07-23 17:17:47 +000013#include <algorithm>
14#include <map>
15#include <set>
Chris Lattner697954c2002-01-20 22:54:45 +000016#include <iostream>
Chris Lattner7f1576f2002-02-24 23:02:12 +000017
Chris Lattnerdbab15a2001-07-23 17:17:47 +000018using namespace cl;
19
Chris Lattner331de232002-07-22 02:07:59 +000020//===----------------------------------------------------------------------===//
21// Basic, shared command line option processing machinery...
22//
23
Chris Lattnerdbab15a2001-07-23 17:17:47 +000024// Return the global command line option vector. Making it a function scoped
Chris Lattnerf78032f2001-11-26 18:58:34 +000025// static ensures that it will be initialized correctly before its first use.
Chris Lattnerdbab15a2001-07-23 17:17:47 +000026//
Chris Lattnerca6433f2003-05-22 20:06:43 +000027static std::map<std::string, Option*> *CommandLineOptions = 0;
28static std::map<std::string, Option*> &getOpts() {
29 if (CommandLineOptions == 0)
30 CommandLineOptions = new std::map<std::string,Option*>();
Chris Lattnere8e258b2002-07-29 20:58:42 +000031 return *CommandLineOptions;
32}
33
Chris Lattnerca6433f2003-05-22 20:06:43 +000034static Option *getOption(const std::string &Str) {
Chris Lattnere8e258b2002-07-29 20:58:42 +000035 if (CommandLineOptions == 0) return 0;
Chris Lattnerca6433f2003-05-22 20:06:43 +000036 std::map<std::string,Option*>::iterator I = CommandLineOptions->find(Str);
Chris Lattnere8e258b2002-07-29 20:58:42 +000037 return I != CommandLineOptions->end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000038}
39
Chris Lattnerca6433f2003-05-22 20:06:43 +000040static std::vector<Option*> &getPositionalOpts() {
41 static std::vector<Option*> Positional;
Chris Lattner331de232002-07-22 02:07:59 +000042 return Positional;
43}
44
Chris Lattnere8e258b2002-07-29 20:58:42 +000045static void AddArgument(const char *ArgName, Option *Opt) {
46 if (getOption(ArgName)) {
Chris Lattnerca6433f2003-05-22 20:06:43 +000047 std::cerr << "CommandLine Error: Argument '" << ArgName
48 << "' defined more than once!\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +000049 } else {
Chris Lattnerf78032f2001-11-26 18:58:34 +000050 // Add argument to the argument map!
Chris Lattnere8e258b2002-07-29 20:58:42 +000051 getOpts()[ArgName] = Opt;
52 }
53}
54
55// RemoveArgument - It's possible that the argument is no longer in the map if
56// options have already been processed and the map has been deleted!
57//
58static void RemoveArgument(const char *ArgName, Option *Opt) {
59 if (CommandLineOptions == 0) return;
60 assert(getOption(ArgName) == Opt && "Arg not in map!");
61 CommandLineOptions->erase(ArgName);
62 if (CommandLineOptions->empty()) {
63 delete CommandLineOptions;
64 CommandLineOptions = 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000065 }
66}
67
68static const char *ProgramName = 0;
69static const char *ProgramOverview = 0;
70
Chris Lattnercaccd762001-10-27 05:54:17 +000071static inline bool ProvideOption(Option *Handler, const char *ArgName,
72 const char *Value, int argc, char **argv,
73 int &i) {
74 // Enforce value requirements
75 switch (Handler->getValueExpectedFlag()) {
76 case ValueRequired:
77 if (Value == 0 || *Value == 0) { // No value specified?
78 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
79 Value = argv[++i];
80 } else {
81 return Handler->error(" requires a value!");
82 }
83 }
84 break;
85 case ValueDisallowed:
86 if (*Value != 0)
87 return Handler->error(" does not allow a value! '" +
Chris Lattnerca6433f2003-05-22 20:06:43 +000088 std::string(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +000089 break;
90 case ValueOptional: break;
Chris Lattnerca6433f2003-05-22 20:06:43 +000091 default: std::cerr << "Bad ValueMask flag! CommandLine usage error:"
92 << Handler->getValueExpectedFlag() << "\n"; abort();
Chris Lattnercaccd762001-10-27 05:54:17 +000093 }
94
95 // Run the handler now!
Misha Brukmandd6cb6a2003-07-10 16:49:51 +000096 return Handler->addOccurrence(ArgName, Value);
Chris Lattnercaccd762001-10-27 05:54:17 +000097}
98
Chris Lattner9cf3d472003-07-30 17:34:02 +000099static bool ProvidePositionalOption(Option *Handler, const std::string &Arg) {
Chris Lattner331de232002-07-22 02:07:59 +0000100 int Dummy;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000101 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000102}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000103
Chris Lattner331de232002-07-22 02:07:59 +0000104
105// Option predicates...
106static inline bool isGrouping(const Option *O) {
107 return O->getFormattingFlag() == cl::Grouping;
108}
109static inline bool isPrefixedOrGrouping(const Option *O) {
110 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
111}
112
113// getOptionPred - Check to see if there are any options that satisfy the
114// specified predicate with names that are the prefixes in Name. This is
115// checked by progressively stripping characters off of the name, checking to
116// see if there options that satisfy the predicate. If we find one, return it,
117// otherwise return null.
118//
119static Option *getOptionPred(std::string Name, unsigned &Length,
120 bool (*Pred)(const Option*)) {
121
Chris Lattnere8e258b2002-07-29 20:58:42 +0000122 Option *Op = getOption(Name);
123 if (Op && Pred(Op)) {
Chris Lattner331de232002-07-22 02:07:59 +0000124 Length = Name.length();
Chris Lattnere8e258b2002-07-29 20:58:42 +0000125 return Op;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000126 }
127
Chris Lattner331de232002-07-22 02:07:59 +0000128 if (Name.size() == 1) return 0;
129 do {
130 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
Chris Lattnere8e258b2002-07-29 20:58:42 +0000131 Op = getOption(Name);
Chris Lattner331de232002-07-22 02:07:59 +0000132
133 // Loop while we haven't found an option and Name still has at least two
134 // characters in it (so that the next iteration will not be the empty
135 // string...
Chris Lattnere8e258b2002-07-29 20:58:42 +0000136 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
Chris Lattner331de232002-07-22 02:07:59 +0000137
Chris Lattnere8e258b2002-07-29 20:58:42 +0000138 if (Op && Pred(Op)) {
Chris Lattner331de232002-07-22 02:07:59 +0000139 Length = Name.length();
Chris Lattnere8e258b2002-07-29 20:58:42 +0000140 return Op; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000141 }
142 return 0; // No option found!
143}
144
145static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000146 return O->getNumOccurrencesFlag() == cl::Required ||
147 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000148}
149
150static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000151 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
152 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000153}
Chris Lattnercaccd762001-10-27 05:54:17 +0000154
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000155void cl::ParseCommandLineOptions(int &argc, char **argv,
Chris Lattner0c0edf82002-07-25 06:17:51 +0000156 const char *Overview) {
Chris Lattner331de232002-07-22 02:07:59 +0000157 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
158 "No options specified, or ParseCommandLineOptions called more"
159 " than once!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000160 ProgramName = argv[0]; // Save this away safe and snug
161 ProgramOverview = Overview;
162 bool ErrorParsing = false;
163
Chris Lattnerca6433f2003-05-22 20:06:43 +0000164 std::map<std::string, Option*> &Opts = getOpts();
165 std::vector<Option*> &PositionalOpts = getPositionalOpts();
Chris Lattner331de232002-07-22 02:07:59 +0000166
167 // Check out the positional arguments to collect information about them.
168 unsigned NumPositionalRequired = 0;
169 Option *ConsumeAfterOpt = 0;
170 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000171 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000172 assert(PositionalOpts.size() > 1 &&
173 "Cannot specify cl::ConsumeAfter without a positional argument!");
174 ConsumeAfterOpt = PositionalOpts[0];
175 }
176
177 // Calculate how many positional values are _required_.
178 bool UnboundedFound = false;
179 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
180 i != e; ++i) {
181 Option *Opt = PositionalOpts[i];
182 if (RequiresValue(Opt))
183 ++NumPositionalRequired;
184 else if (ConsumeAfterOpt) {
185 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000186 // unless there is only one positional argument...
187 if (PositionalOpts.size() > 2)
188 ErrorParsing |=
189 Opt->error(" error - this positional option will never be matched, "
190 "because it does not Require a value, and a "
191 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000192 } else if (UnboundedFound && !Opt->ArgStr[0]) {
193 // This option does not "require" a value... Make sure this option is
194 // not specified after an option that eats all extra arguments, or this
195 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000196 //
197 ErrorParsing |= Opt->error(" error - option can never match, because "
198 "another positional argument will match an "
199 "unbounded number of values, and this option"
200 " does not require a value!");
201 }
202 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
203 }
204 }
205
206 // PositionalVals - A vector of "positional" arguments we accumulate into to
207 // processes at the end...
208 //
Chris Lattnerca6433f2003-05-22 20:06:43 +0000209 std::vector<std::string> PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000210
Chris Lattner9cf3d472003-07-30 17:34:02 +0000211 // If the program has named positional arguments, and the name has been run
212 // across, keep track of which positional argument was named. Otherwise put
213 // the positional args into the PositionalVals list...
214 Option *ActivePositionalArg = 0;
215
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000216 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000217 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000218 for (int i = 1; i < argc; ++i) {
219 Option *Handler = 0;
220 const char *Value = "";
221 const char *ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000222
223 // Check to see if this is a positional argument. This argument is
224 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000225 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000226 //
227 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
228 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000229 if (ActivePositionalArg) {
230 ProvidePositionalOption(ActivePositionalArg, argv[i]);
231 continue; // We are done!
232 } else if (!PositionalOpts.empty()) {
Chris Lattner331de232002-07-22 02:07:59 +0000233 PositionalVals.push_back(argv[i]);
234
235 // All of the positional arguments have been fulfulled, give the rest to
236 // the consume after option... if it's specified...
237 //
Chris Lattnerd16714b2002-07-31 16:29:43 +0000238 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000239 ConsumeAfterOpt != 0) {
240 for (++i; i < argc; ++i)
241 PositionalVals.push_back(argv[i]);
242 break; // Handle outside of the argument processing loop...
243 }
244
245 // Delay processing positional arguments until the end...
246 continue;
247 }
248 } else { // We start with a '-', must be an argument...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000249 ArgName = argv[i]+1;
250 while (*ArgName == '-') ++ArgName; // Eat leading dashes
251
Chris Lattner331de232002-07-22 02:07:59 +0000252 if (*ArgName == 0 && !DashDashFound) { // Is this the mythical "--"?
253 DashDashFound = true; // Yup, take note of that fact...
254 continue; // Don't try to process it as an argument iself.
255 }
256
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000257 const char *ArgNameEnd = ArgName;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000258 while (*ArgNameEnd && *ArgNameEnd != '=')
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000259 ++ArgNameEnd; // Scan till end of argument name...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000260
261 Value = ArgNameEnd;
262 if (*Value) // If we have an equals sign...
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000263 ++Value; // Advance to value...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000264
265 if (*ArgName != 0) {
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000266 std::string RealName(ArgName, ArgNameEnd);
267 // Extract arg name part
Chris Lattnerca6433f2003-05-22 20:06:43 +0000268 std::map<std::string, Option*>::iterator I = Opts.find(RealName);
Chris Lattnerf78032f2001-11-26 18:58:34 +0000269
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000270 if (I == Opts.end() && !*Value && RealName.size() > 1) {
Chris Lattner331de232002-07-22 02:07:59 +0000271 // Check to see if this "option" is really a prefixed or grouped
272 // argument...
273 //
274 unsigned Length = 0;
275 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
Chris Lattnerf78032f2001-11-26 18:58:34 +0000276
Chris Lattner331de232002-07-22 02:07:59 +0000277 // If the option is a prefixed option, then the value is simply the
278 // rest of the name... so fall through to later processing, by
279 // setting up the argument name flags and value fields.
280 //
281 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
282 ArgNameEnd = ArgName+Length;
283 Value = ArgNameEnd;
Chris Lattnerca6433f2003-05-22 20:06:43 +0000284 I = Opts.find(std::string(ArgName, ArgNameEnd));
Chris Lattner331de232002-07-22 02:07:59 +0000285 assert(I->second == PGOpt);
286 } else if (PGOpt) {
287 // This must be a grouped option... handle all of them now...
288 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
289
290 do {
291 // Move current arg name out of RealName into RealArgName...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000292 std::string RealArgName(RealName.begin(),RealName.begin()+Length);
Chris Lattner331de232002-07-22 02:07:59 +0000293 RealName.erase(RealName.begin(), RealName.begin()+Length);
Chris Lattnerf78032f2001-11-26 18:58:34 +0000294
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000295 // Because ValueRequired is an invalid flag for grouped arguments,
296 // we don't need to pass argc/argv in...
297 //
Chris Lattner331de232002-07-22 02:07:59 +0000298 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
299 "Option can not be cl::Grouping AND cl::ValueRequired!");
300 int Dummy;
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000301 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(), "",
Chris Lattner331de232002-07-22 02:07:59 +0000302 0, 0, Dummy);
303
304 // Get the next grouping option...
305 if (!RealName.empty())
306 PGOpt = getOptionPred(RealName, Length, isGrouping);
307 } while (!RealName.empty() && PGOpt);
308
309 if (RealName.empty()) // Processed all of the options, move on
310 continue; // to the next argv[] value...
311
312 // If RealName is not empty, that means we did not match one of the
313 // options! This is an error.
314 //
315 I = Opts.end();
316 }
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000317 }
Chris Lattnerf78032f2001-11-26 18:58:34 +0000318
Chris Lattner331de232002-07-22 02:07:59 +0000319 Handler = I != Opts.end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000320 }
321 }
322
323 if (Handler == 0) {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000324 std::cerr << "Unknown command line argument '" << argv[i] << "'. Try: "
325 << argv[0] << " --help'\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000326 ErrorParsing = true;
327 continue;
328 }
329
Chris Lattner72fb8e52003-05-22 20:26:17 +0000330 // Check to see if this option accepts a comma separated list of values. If
331 // it does, we have to split up the value into multiple values...
332 if (Handler->getMiscFlags() & CommaSeparated) {
333 std::string Val(Value);
334 std::string::size_type Pos = Val.find(',');
335
336 while (Pos != std::string::npos) {
337 // Process the portion before the comma...
338 ErrorParsing |= ProvideOption(Handler, ArgName,
339 std::string(Val.begin(),
340 Val.begin()+Pos).c_str(),
341 argc, argv, i);
342 // Erase the portion before the comma, AND the comma...
343 Val.erase(Val.begin(), Val.begin()+Pos+1);
344 Value += Pos+1; // Increment the original value pointer as well...
345
346 // Check for another comma...
347 Pos = Val.find(',');
348 }
349 }
Chris Lattner9cf3d472003-07-30 17:34:02 +0000350
351 // If this is a named positional argument, just remember that it is the
352 // active one...
353 if (Handler->getFormattingFlag() == cl::Positional)
354 ActivePositionalArg = Handler;
355 else
356 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000357 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000358
Chris Lattner331de232002-07-22 02:07:59 +0000359 // Check and handle positional arguments now...
360 if (NumPositionalRequired > PositionalVals.size()) {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000361 std::cerr << "Not enough positional command line arguments specified!\n"
362 << "Must specify at least " << NumPositionalRequired
363 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattner331de232002-07-22 02:07:59 +0000364 ErrorParsing = true;
365
366
367 } else if (ConsumeAfterOpt == 0) {
368 // Positional args have already been handled if ConsumeAfter is specified...
369 unsigned ValNo = 0, NumVals = PositionalVals.size();
370 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
371 if (RequiresValue(PositionalOpts[i])) {
372 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
373 --NumPositionalRequired; // We fulfilled our duty...
374 }
375
376 // If we _can_ give this option more arguments, do so now, as long as we
377 // do not give it values that others need. 'Done' controls whether the
378 // option even _WANTS_ any more.
379 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000380 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000381 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000382 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000383 case cl::Optional:
384 Done = true; // Optional arguments want _at most_ one value
385 // FALL THROUGH
386 case cl::ZeroOrMore: // Zero or more will take all they can get...
387 case cl::OneOrMore: // One or more will take all they can get...
388 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
389 break;
390 default:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000391 assert(0 && "Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000392 "positional argument processing!");
393 }
394 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000395 }
Chris Lattner331de232002-07-22 02:07:59 +0000396 } else {
397 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
398 unsigned ValNo = 0;
399 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
400 if (RequiresValue(PositionalOpts[j]))
Chris Lattnerfaba8092002-07-24 20:15:13 +0000401 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
402 PositionalVals[ValNo++]);
403
404 // Handle the case where there is just one positional option, and it's
405 // optional. In this case, we want to give JUST THE FIRST option to the
406 // positional option and keep the rest for the consume after. The above
407 // loop would have assigned no values to positional options in this case.
408 //
Chris Lattnerb490c202002-08-02 21:51:29 +0000409 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty())
Chris Lattnerfaba8092002-07-24 20:15:13 +0000410 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
411 PositionalVals[ValNo++]);
Chris Lattner331de232002-07-22 02:07:59 +0000412
413 // Handle over all of the rest of the arguments to the
414 // cl::ConsumeAfter command line option...
415 for (; ValNo != PositionalVals.size(); ++ValNo)
416 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
417 PositionalVals[ValNo]);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000418 }
419
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000420 // Loop over args and make sure all required args are specified!
Chris Lattnerca6433f2003-05-22 20:06:43 +0000421 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000422 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000423 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000424 case Required:
425 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000426 if (I->second->getNumOccurrences() == 0) {
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000427 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000428 ErrorParsing = true;
429 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000430 // Fall through
431 default:
432 break;
433 }
434 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000435
Chris Lattner331de232002-07-22 02:07:59 +0000436 // Free all of the memory allocated to the map. Command line options may only
437 // be processed once!
Chris Lattnere8e258b2002-07-29 20:58:42 +0000438 delete CommandLineOptions;
439 CommandLineOptions = 0;
Chris Lattner331de232002-07-22 02:07:59 +0000440 PositionalOpts.clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000441
442 // If we had an error processing our arguments, don't let the program execute
443 if (ErrorParsing) exit(1);
444}
445
446//===----------------------------------------------------------------------===//
447// Option Base class implementation
448//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000449
Chris Lattnerca6433f2003-05-22 20:06:43 +0000450bool Option::error(std::string Message, const char *ArgName) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000451 if (ArgName == 0) ArgName = ArgStr;
Chris Lattner331de232002-07-22 02:07:59 +0000452 if (ArgName[0] == 0)
Chris Lattnerca6433f2003-05-22 20:06:43 +0000453 std::cerr << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000454 else
Chris Lattnerca6433f2003-05-22 20:06:43 +0000455 std::cerr << "-" << ArgName;
456 std::cerr << " option" << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000457 return true;
458}
459
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000460bool Option::addOccurrence(const char *ArgName, const std::string &Value) {
461 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000462
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000463 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000464 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000465 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000466 return error(": may only occur zero or one times!", ArgName);
467 break;
468 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000469 if (NumOccurrences > 1)
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000470 return error(": must occur exactly one time!", ArgName);
471 // Fall through
472 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000473 case ZeroOrMore:
474 case ConsumeAfter: break;
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000475 default: return error(": bad num occurrences flag value!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000476 }
477
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000478 return handleOccurrence(ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000479}
480
Chris Lattner331de232002-07-22 02:07:59 +0000481// addArgument - Tell the system that this Option subclass will handle all
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000482// occurrences of -ArgStr on the command line.
Chris Lattner331de232002-07-22 02:07:59 +0000483//
484void Option::addArgument(const char *ArgStr) {
485 if (ArgStr[0])
486 AddArgument(ArgStr, this);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000487
488 if (getFormattingFlag() == Positional)
Chris Lattner331de232002-07-22 02:07:59 +0000489 getPositionalOpts().push_back(this);
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000490 else if (getNumOccurrencesFlag() == ConsumeAfter) {
Chris Lattner9cf3d472003-07-30 17:34:02 +0000491 if (!getPositionalOpts().empty() &&
492 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
493 error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattner331de232002-07-22 02:07:59 +0000494 getPositionalOpts().insert(getPositionalOpts().begin(), this);
495 }
496}
497
Chris Lattneraa852bb2002-07-23 17:15:12 +0000498void Option::removeArgument(const char *ArgStr) {
Chris Lattner9cf3d472003-07-30 17:34:02 +0000499 if (ArgStr[0])
Chris Lattnere8e258b2002-07-29 20:58:42 +0000500 RemoveArgument(ArgStr, this);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000501
502 if (getFormattingFlag() == Positional) {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000503 std::vector<Option*>::iterator I =
Chris Lattneraa852bb2002-07-23 17:15:12 +0000504 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
505 assert(I != getPositionalOpts().end() && "Arg not registered!");
506 getPositionalOpts().erase(I);
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000507 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
Chris Lattneraa852bb2002-07-23 17:15:12 +0000508 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
509 "Arg not registered correctly!");
510 getPositionalOpts().erase(getPositionalOpts().begin());
511 }
512}
513
Chris Lattner331de232002-07-22 02:07:59 +0000514
515// getValueStr - Get the value description string, using "DefaultMsg" if nothing
516// has been specified yet.
517//
518static const char *getValueStr(const Option &O, const char *DefaultMsg) {
519 if (O.ValueStr[0] == 0) return DefaultMsg;
520 return O.ValueStr;
521}
522
523//===----------------------------------------------------------------------===//
524// cl::alias class implementation
525//
526
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000527// Return the width of the option tag for printing...
Chris Lattner331de232002-07-22 02:07:59 +0000528unsigned alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000529 return std::strlen(ArgStr)+6;
530}
531
Chris Lattner331de232002-07-22 02:07:59 +0000532// Print out the option for the alias...
533void alias::printOptionInfo(unsigned GlobalWidth) const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000534 unsigned L = std::strlen(ArgStr);
Chris Lattnerca6433f2003-05-22 20:06:43 +0000535 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
536 << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000537}
538
539
Chris Lattner331de232002-07-22 02:07:59 +0000540
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000541//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000542// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000543//
544
Chris Lattner9b14eb52002-08-07 18:36:37 +0000545// basic_parser implementation
546//
547
548// Return the width of the option tag for printing...
549unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
550 unsigned Len = std::strlen(O.ArgStr);
551 if (const char *ValName = getValueName())
552 Len += std::strlen(getValueStr(O, ValName))+3;
553
554 return Len + 6;
555}
556
557// printOptionInfo - Print out information about this option. The
558// to-be-maintained width is specified.
559//
560void basic_parser_impl::printOptionInfo(const Option &O,
561 unsigned GlobalWidth) const {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000562 std::cerr << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000563
564 if (const char *ValName = getValueName())
Chris Lattnerca6433f2003-05-22 20:06:43 +0000565 std::cerr << "=<" << getValueStr(O, ValName) << ">";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000566
Chris Lattnerca6433f2003-05-22 20:06:43 +0000567 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
568 << O.HelpStr << "\n";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000569}
570
571
572
573
Chris Lattner331de232002-07-22 02:07:59 +0000574// parser<bool> implementation
575//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000576bool parser<bool>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000577 const std::string &Arg, bool &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000578 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
579 Arg == "1") {
580 Value = true;
581 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
582 Value = false;
583 } else {
Chris Lattner331de232002-07-22 02:07:59 +0000584 return O.error(": '" + Arg +
585 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000586 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000587 return false;
588}
589
Chris Lattner331de232002-07-22 02:07:59 +0000590// parser<int> implementation
591//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000592bool parser<int>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000593 const std::string &Arg, int &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000594 char *End;
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000595 Value = (int)strtol(Arg.c_str(), &End, 0);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000596 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000597 return O.error(": '" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000598 return false;
599}
600
Chris Lattnerd2a6fc32003-06-28 15:47:20 +0000601// parser<unsigned> implementation
602//
603bool parser<unsigned>::parse(Option &O, const char *ArgName,
604 const std::string &Arg, unsigned &Value) {
605 char *End;
606 long long int V = strtoll(Arg.c_str(), &End, 0);
607 Value = (unsigned)V;
608 if (*End != 0 || V < 0 || Value != V)
609 return O.error(": '" + Arg + "' value invalid for uint argument!");
610 return false;
611}
612
Chris Lattner9b14eb52002-08-07 18:36:37 +0000613// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +0000614//
Chris Lattnerca6433f2003-05-22 20:06:43 +0000615static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
Chris Lattner331de232002-07-22 02:07:59 +0000616 const char *ArgStart = Arg.c_str();
617 char *End;
618 Value = strtod(ArgStart, &End);
619 if (*End != 0)
620 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +0000621 return false;
622}
623
Chris Lattner9b14eb52002-08-07 18:36:37 +0000624bool parser<double>::parse(Option &O, const char *AN,
625 const std::string &Arg, double &Val) {
626 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +0000627}
628
Chris Lattner9b14eb52002-08-07 18:36:37 +0000629bool parser<float>::parse(Option &O, const char *AN,
630 const std::string &Arg, float &Val) {
631 double dVal;
632 if (parseDouble(O, Arg, dVal))
633 return true;
634 Val = (float)dVal;
635 return false;
Chris Lattner331de232002-07-22 02:07:59 +0000636}
637
638
Chris Lattner331de232002-07-22 02:07:59 +0000639
640// generic_parser_base implementation
641//
642
Chris Lattneraa852bb2002-07-23 17:15:12 +0000643// findOption - Return the option number corresponding to the specified
644// argument string. If the option is not found, getNumOptions() is returned.
645//
646unsigned generic_parser_base::findOption(const char *Name) {
647 unsigned i = 0, e = getNumOptions();
Chris Lattnerca6433f2003-05-22 20:06:43 +0000648 std::string N(Name);
Chris Lattneraa852bb2002-07-23 17:15:12 +0000649
650 while (i != e)
651 if (getOption(i) == N)
652 return i;
653 else
654 ++i;
655 return e;
656}
657
658
Chris Lattner331de232002-07-22 02:07:59 +0000659// Return the width of the option tag for printing...
660unsigned generic_parser_base::getOptionWidth(const Option &O) const {
661 if (O.hasArgStr()) {
662 unsigned Size = std::strlen(O.ArgStr)+6;
663 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
664 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
665 return Size;
666 } else {
667 unsigned BaseSize = 0;
668 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
669 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
670 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000671 }
672}
673
Chris Lattner331de232002-07-22 02:07:59 +0000674// printOptionInfo - Print out information about this option. The
675// to-be-maintained width is specified.
676//
677void generic_parser_base::printOptionInfo(const Option &O,
678 unsigned GlobalWidth) const {
679 if (O.hasArgStr()) {
680 unsigned L = std::strlen(O.ArgStr);
Chris Lattnerca6433f2003-05-22 20:06:43 +0000681 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
682 << " - " << O.HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000683
Chris Lattner331de232002-07-22 02:07:59 +0000684 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
685 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnerca6433f2003-05-22 20:06:43 +0000686 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
687 << " - " << getDescription(i) << "\n";
Chris Lattner9c9be482002-01-31 00:42:56 +0000688 }
Chris Lattner331de232002-07-22 02:07:59 +0000689 } else {
690 if (O.HelpStr[0])
Chris Lattnerca6433f2003-05-22 20:06:43 +0000691 std::cerr << " " << O.HelpStr << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000692 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
693 unsigned L = std::strlen(getOption(i));
Chris Lattnerca6433f2003-05-22 20:06:43 +0000694 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
695 << " - " << getDescription(i) << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000696 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000697 }
698}
699
700
701//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000702// --help and --help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000703//
704namespace {
705
Chris Lattner331de232002-07-22 02:07:59 +0000706class HelpPrinter {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000707 unsigned MaxArgLen;
708 const Option *EmptyArg;
709 const bool ShowHidden;
710
Chris Lattner331de232002-07-22 02:07:59 +0000711 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
Chris Lattnerca6433f2003-05-22 20:06:43 +0000712 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000713 return OptPair.second->getOptionHiddenFlag() >= Hidden;
714 }
Chris Lattnerca6433f2003-05-22 20:06:43 +0000715 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000716 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
717 }
718
719public:
720 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
721 EmptyArg = 0;
722 }
723
724 void operator=(bool Value) {
725 if (Value == false) return;
726
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000727 // Copy Options into a vector so we can sort them as we like...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000728 std::vector<std::pair<std::string, Option*> > Options;
Chris Lattner697954c2002-01-20 22:54:45 +0000729 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000730
731 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Chris Lattner331de232002-07-22 02:07:59 +0000732 Options.erase(std::remove_if(Options.begin(), Options.end(),
733 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000734 Options.end());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000735
736 // Eliminate duplicate entries in table (from enum flags options, f.e.)
Chris Lattner331de232002-07-22 02:07:59 +0000737 { // Give OptionSet a scope
738 std::set<Option*> OptionSet;
739 for (unsigned i = 0; i != Options.size(); ++i)
740 if (OptionSet.count(Options[i].second) == 0)
741 OptionSet.insert(Options[i].second); // Add new entry to set
742 else
743 Options.erase(Options.begin()+i--); // Erase duplicate
744 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000745
746 if (ProgramOverview)
Chris Lattnerca6433f2003-05-22 20:06:43 +0000747 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000748
Chris Lattnerca6433f2003-05-22 20:06:43 +0000749 std::cerr << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +0000750
751 // Print out the positional options...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000752 std::vector<Option*> &PosOpts = getPositionalOpts();
Chris Lattner331de232002-07-22 02:07:59 +0000753 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000754 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
Chris Lattner331de232002-07-22 02:07:59 +0000755 CAOpt = PosOpts[0];
756
Chris Lattner9cf3d472003-07-30 17:34:02 +0000757 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
758 if (PosOpts[i]->ArgStr[0])
759 std::cerr << " --" << PosOpts[i]->ArgStr;
Chris Lattnerca6433f2003-05-22 20:06:43 +0000760 std::cerr << " " << PosOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +0000761 }
Chris Lattner331de232002-07-22 02:07:59 +0000762
763 // Print the consume after option info if it exists...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000764 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +0000765
Chris Lattnerca6433f2003-05-22 20:06:43 +0000766 std::cerr << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000767
768 // Compute the maximum argument length...
769 MaxArgLen = 0;
Chris Lattner331de232002-07-22 02:07:59 +0000770 for (unsigned i = 0, e = Options.size(); i != e; ++i)
771 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000772
Chris Lattnerca6433f2003-05-22 20:06:43 +0000773 std::cerr << "OPTIONS:\n";
Chris Lattner331de232002-07-22 02:07:59 +0000774 for (unsigned i = 0, e = Options.size(); i != e; ++i)
775 Options[i].second->printOptionInfo(MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000776
Chris Lattner331de232002-07-22 02:07:59 +0000777 // Halt the program if help information is printed
778 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000779 }
780};
781
Chris Lattner331de232002-07-22 02:07:59 +0000782
783
784// Define the two HelpPrinter instances that are used to print out help, or
785// help-hidden...
786//
787HelpPrinter NormalPrinter(false);
788HelpPrinter HiddenPrinter(true);
789
790cl::opt<HelpPrinter, true, parser<bool> >
791HOp("help", cl::desc("display available options (--help-hidden for more)"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000792 cl::location(NormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +0000793
794cl::opt<HelpPrinter, true, parser<bool> >
795HHOp("help-hidden", cl::desc("display all available options"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000796 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000797
798} // End anonymous namespace