blob: fc3d62b357024e2107e6250e6a60d0545b77289a [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;
Chris Lattner697954c2002-01-20 22:54:45 +000019using std::map;
20using std::pair;
21using std::vector;
22using std::string;
23using std::cerr;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000024
Chris Lattner331de232002-07-22 02:07:59 +000025//===----------------------------------------------------------------------===//
26// Basic, shared command line option processing machinery...
27//
28
Chris Lattnerdbab15a2001-07-23 17:17:47 +000029// Return the global command line option vector. Making it a function scoped
Chris Lattnerf78032f2001-11-26 18:58:34 +000030// static ensures that it will be initialized correctly before its first use.
Chris Lattnerdbab15a2001-07-23 17:17:47 +000031//
32static map<string, Option*> &getOpts() {
33 static map<string,Option*> CommandLineOptions;
34 return CommandLineOptions;
35}
36
Chris Lattner331de232002-07-22 02:07:59 +000037static vector<Option*> &getPositionalOpts() {
38 static vector<Option*> Positional;
39 return Positional;
40}
41
Chris Lattnerdbab15a2001-07-23 17:17:47 +000042static void AddArgument(const string &ArgName, Option *Opt) {
43 if (getOpts().find(ArgName) != getOpts().end()) {
44 cerr << "CommandLine Error: Argument '" << ArgName
Chris Lattner9c9be482002-01-31 00:42:56 +000045 << "' defined more than once!\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +000046 } else {
Chris Lattnerf78032f2001-11-26 18:58:34 +000047 // Add argument to the argument map!
Chris Lattner697954c2002-01-20 22:54:45 +000048 getOpts().insert(std::make_pair(ArgName, Opt));
Chris Lattnerdbab15a2001-07-23 17:17:47 +000049 }
50}
51
52static const char *ProgramName = 0;
53static const char *ProgramOverview = 0;
54
Chris Lattnercaccd762001-10-27 05:54:17 +000055static inline bool ProvideOption(Option *Handler, const char *ArgName,
56 const char *Value, int argc, char **argv,
57 int &i) {
58 // Enforce value requirements
59 switch (Handler->getValueExpectedFlag()) {
60 case ValueRequired:
61 if (Value == 0 || *Value == 0) { // No value specified?
62 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
63 Value = argv[++i];
64 } else {
65 return Handler->error(" requires a value!");
66 }
67 }
68 break;
69 case ValueDisallowed:
70 if (*Value != 0)
71 return Handler->error(" does not allow a value! '" +
72 string(Value) + "' specified.");
73 break;
74 case ValueOptional: break;
75 default: cerr << "Bad ValueMask flag! CommandLine usage error:"
Chris Lattner697954c2002-01-20 22:54:45 +000076 << Handler->getValueExpectedFlag() << "\n"; abort();
Chris Lattnercaccd762001-10-27 05:54:17 +000077 }
78
79 // Run the handler now!
80 return Handler->addOccurance(ArgName, Value);
81}
82
Chris Lattner331de232002-07-22 02:07:59 +000083static bool ProvidePositionalOption(Option *Handler, string &Arg) {
84 int Dummy;
85 return ProvideOption(Handler, "", Arg.c_str(), 0, 0, Dummy);
86}
Chris Lattnerf78032f2001-11-26 18:58:34 +000087
Chris Lattner331de232002-07-22 02:07:59 +000088
89// Option predicates...
90static inline bool isGrouping(const Option *O) {
91 return O->getFormattingFlag() == cl::Grouping;
92}
93static inline bool isPrefixedOrGrouping(const Option *O) {
94 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
95}
96
97// getOptionPred - Check to see if there are any options that satisfy the
98// specified predicate with names that are the prefixes in Name. This is
99// checked by progressively stripping characters off of the name, checking to
100// see if there options that satisfy the predicate. If we find one, return it,
101// otherwise return null.
102//
103static Option *getOptionPred(std::string Name, unsigned &Length,
104 bool (*Pred)(const Option*)) {
105
106 map<string, Option*>::iterator I = getOpts().find(Name);
107 if (I != getOpts().end() && Pred(I->second)) {
108 Length = Name.length();
109 return I->second;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000110 }
111
Chris Lattner331de232002-07-22 02:07:59 +0000112 if (Name.size() == 1) return 0;
113 do {
114 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
115 I = getOpts().find(Name);
116
117 // Loop while we haven't found an option and Name still has at least two
118 // characters in it (so that the next iteration will not be the empty
119 // string...
120 } while ((I == getOpts().end() || !Pred(I->second)) && Name.size() > 1);
121
122 if (I != getOpts().end() && Pred(I->second)) {
123 Length = Name.length();
124 return I->second; // Found one!
125 }
126 return 0; // No option found!
127}
128
129static bool RequiresValue(const Option *O) {
130 return O->getNumOccurancesFlag() == cl::Required ||
131 O->getNumOccurancesFlag() == cl::OneOrMore;
132}
133
134static bool EatsUnboundedNumberOfValues(const Option *O) {
135 return O->getNumOccurancesFlag() == cl::ZeroOrMore ||
136 O->getNumOccurancesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000137}
Chris Lattnercaccd762001-10-27 05:54:17 +0000138
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000139void cl::ParseCommandLineOptions(int &argc, char **argv,
Chris Lattner0c0edf82002-07-25 06:17:51 +0000140 const char *Overview) {
Chris Lattner331de232002-07-22 02:07:59 +0000141 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
142 "No options specified, or ParseCommandLineOptions called more"
143 " than once!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000144 ProgramName = argv[0]; // Save this away safe and snug
145 ProgramOverview = Overview;
146 bool ErrorParsing = false;
147
Chris Lattner331de232002-07-22 02:07:59 +0000148 map<string, Option*> &Opts = getOpts();
149 vector<Option*> &PositionalOpts = getPositionalOpts();
150
151 // Check out the positional arguments to collect information about them.
152 unsigned NumPositionalRequired = 0;
153 Option *ConsumeAfterOpt = 0;
154 if (!PositionalOpts.empty()) {
155 if (PositionalOpts[0]->getNumOccurancesFlag() == cl::ConsumeAfter) {
156 assert(PositionalOpts.size() > 1 &&
157 "Cannot specify cl::ConsumeAfter without a positional argument!");
158 ConsumeAfterOpt = PositionalOpts[0];
159 }
160
161 // Calculate how many positional values are _required_.
162 bool UnboundedFound = false;
163 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
164 i != e; ++i) {
165 Option *Opt = PositionalOpts[i];
166 if (RequiresValue(Opt))
167 ++NumPositionalRequired;
168 else if (ConsumeAfterOpt) {
169 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000170 // unless there is only one positional argument...
171 if (PositionalOpts.size() > 2)
172 ErrorParsing |=
173 Opt->error(" error - this positional option will never be matched, "
174 "because it does not Require a value, and a "
175 "cl::ConsumeAfter option is active!");
Chris Lattner331de232002-07-22 02:07:59 +0000176 } else if (UnboundedFound) { // This option does not "require" a value...
177 // Make sure this option is not specified after an option that eats all
178 // extra arguments, or this one will never get any!
179 //
180 ErrorParsing |= Opt->error(" error - option can never match, because "
181 "another positional argument will match an "
182 "unbounded number of values, and this option"
183 " does not require a value!");
184 }
185 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
186 }
187 }
188
189 // PositionalVals - A vector of "positional" arguments we accumulate into to
190 // processes at the end...
191 //
192 vector<string> PositionalVals;
193
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000194 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000195 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000196 for (int i = 1; i < argc; ++i) {
197 Option *Handler = 0;
198 const char *Value = "";
199 const char *ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000200
201 // Check to see if this is a positional argument. This argument is
202 // considered to be positional if it doesn't start with '-', if it is "-"
203 // itself, or if we have see "--" already.
204 //
205 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
206 // Positional argument!
207 if (!PositionalOpts.empty()) {
208 PositionalVals.push_back(argv[i]);
209
210 // All of the positional arguments have been fulfulled, give the rest to
211 // the consume after option... if it's specified...
212 //
213 if (PositionalVals.size() == NumPositionalRequired &&
214 ConsumeAfterOpt != 0) {
215 for (++i; i < argc; ++i)
216 PositionalVals.push_back(argv[i]);
217 break; // Handle outside of the argument processing loop...
218 }
219
220 // Delay processing positional arguments until the end...
221 continue;
222 }
223 } else { // We start with a '-', must be an argument...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000224 ArgName = argv[i]+1;
225 while (*ArgName == '-') ++ArgName; // Eat leading dashes
226
Chris Lattner331de232002-07-22 02:07:59 +0000227 if (*ArgName == 0 && !DashDashFound) { // Is this the mythical "--"?
228 DashDashFound = true; // Yup, take note of that fact...
229 continue; // Don't try to process it as an argument iself.
230 }
231
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000232 const char *ArgNameEnd = ArgName;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000233 while (*ArgNameEnd && *ArgNameEnd != '=')
234 ++ArgNameEnd; // Scan till end of argument name...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000235
236 Value = ArgNameEnd;
237 if (*Value) // If we have an equals sign...
238 ++Value; // Advance to value...
239
240 if (*ArgName != 0) {
Chris Lattnerf78032f2001-11-26 18:58:34 +0000241 string RealName(ArgName, ArgNameEnd);
Chris Lattner3805e4c2001-07-25 18:40:49 +0000242 // Extract arg name part
Chris Lattner331de232002-07-22 02:07:59 +0000243 map<string, Option*>::iterator I = Opts.find(RealName);
Chris Lattnerf78032f2001-11-26 18:58:34 +0000244
Chris Lattner331de232002-07-22 02:07:59 +0000245 if (I == Opts.end() && !*Value && RealName.size() > 1) {
246 // Check to see if this "option" is really a prefixed or grouped
247 // argument...
248 //
249 unsigned Length = 0;
250 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
Chris Lattnerf78032f2001-11-26 18:58:34 +0000251
Chris Lattner331de232002-07-22 02:07:59 +0000252 // If the option is a prefixed option, then the value is simply the
253 // rest of the name... so fall through to later processing, by
254 // setting up the argument name flags and value fields.
255 //
256 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
257 ArgNameEnd = ArgName+Length;
258 Value = ArgNameEnd;
259 I = Opts.find(string(ArgName, ArgNameEnd));
260 assert(I->second == PGOpt);
261 } else if (PGOpt) {
262 // This must be a grouped option... handle all of them now...
263 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
264
265 do {
266 // Move current arg name out of RealName into RealArgName...
267 string RealArgName(RealName.begin(), RealName.begin()+Length);
268 RealName.erase(RealName.begin(), RealName.begin()+Length);
Chris Lattnerf78032f2001-11-26 18:58:34 +0000269
270 // Because ValueRequired is an invalid flag for grouped arguments,
271 // we don't need to pass argc/argv in...
272 //
Chris Lattner331de232002-07-22 02:07:59 +0000273 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
274 "Option can not be cl::Grouping AND cl::ValueRequired!");
275 int Dummy;
276 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(), "",
277 0, 0, Dummy);
278
279 // Get the next grouping option...
280 if (!RealName.empty())
281 PGOpt = getOptionPred(RealName, Length, isGrouping);
282 } while (!RealName.empty() && PGOpt);
283
284 if (RealName.empty()) // Processed all of the options, move on
285 continue; // to the next argv[] value...
286
287 // If RealName is not empty, that means we did not match one of the
288 // options! This is an error.
289 //
290 I = Opts.end();
291 }
Chris Lattnerf78032f2001-11-26 18:58:34 +0000292 }
293
Chris Lattner331de232002-07-22 02:07:59 +0000294 Handler = I != Opts.end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000295 }
296 }
297
298 if (Handler == 0) {
299 cerr << "Unknown command line argument '" << argv[i] << "'. Try: "
Chris Lattnerf038acb2001-10-24 06:21:56 +0000300 << argv[0] << " --help'\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000301 ErrorParsing = true;
302 continue;
303 }
304
Chris Lattnercaccd762001-10-27 05:54:17 +0000305 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000306 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000307
Chris Lattner331de232002-07-22 02:07:59 +0000308 // Check and handle positional arguments now...
309 if (NumPositionalRequired > PositionalVals.size()) {
310 cerr << "Not enough positional command line arguments specified!\n";
311 cerr << "Must specify at least " << NumPositionalRequired
312 << " positional arguments: See: " << argv[0] << " --help\n";
313 ErrorParsing = true;
314
315
316 } else if (ConsumeAfterOpt == 0) {
317 // Positional args have already been handled if ConsumeAfter is specified...
318 unsigned ValNo = 0, NumVals = PositionalVals.size();
319 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
320 if (RequiresValue(PositionalOpts[i])) {
321 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
322 --NumPositionalRequired; // We fulfilled our duty...
323 }
324
325 // If we _can_ give this option more arguments, do so now, as long as we
326 // do not give it values that others need. 'Done' controls whether the
327 // option even _WANTS_ any more.
328 //
329 bool Done = PositionalOpts[i]->getNumOccurancesFlag() == cl::Required;
330 while (NumVals-ValNo > NumPositionalRequired && !Done) {
331 switch (PositionalOpts[i]->getNumOccurancesFlag()) {
332 case cl::Optional:
333 Done = true; // Optional arguments want _at most_ one value
334 // FALL THROUGH
335 case cl::ZeroOrMore: // Zero or more will take all they can get...
336 case cl::OneOrMore: // One or more will take all they can get...
337 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
338 break;
339 default:
340 assert(0 && "Internal error, unexpected NumOccurances flag in "
341 "positional argument processing!");
342 }
343 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000344 }
Chris Lattner331de232002-07-22 02:07:59 +0000345 } else {
346 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
347 unsigned ValNo = 0;
348 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
349 if (RequiresValue(PositionalOpts[j]))
Chris Lattnerfaba8092002-07-24 20:15:13 +0000350 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
351 PositionalVals[ValNo++]);
352
353 // Handle the case where there is just one positional option, and it's
354 // optional. In this case, we want to give JUST THE FIRST option to the
355 // positional option and keep the rest for the consume after. The above
356 // loop would have assigned no values to positional options in this case.
357 //
358 if (PositionalOpts.size() == 2 && ValNo == 0)
359 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
360 PositionalVals[ValNo++]);
Chris Lattner331de232002-07-22 02:07:59 +0000361
362 // Handle over all of the rest of the arguments to the
363 // cl::ConsumeAfter command line option...
364 for (; ValNo != PositionalVals.size(); ++ValNo)
365 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
366 PositionalVals[ValNo]);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000367 }
368
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000369 // Loop over args and make sure all required args are specified!
Chris Lattner331de232002-07-22 02:07:59 +0000370 for (map<string, Option*>::iterator I = Opts.begin(),
371 E = Opts.end(); I != E; ++I) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000372 switch (I->second->getNumOccurancesFlag()) {
373 case Required:
374 case OneOrMore:
Chris Lattnerf038acb2001-10-24 06:21:56 +0000375 if (I->second->getNumOccurances() == 0) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000376 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000377 ErrorParsing = true;
378 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000379 // Fall through
380 default:
381 break;
382 }
383 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000384
Chris Lattner331de232002-07-22 02:07:59 +0000385 // Free all of the memory allocated to the map. Command line options may only
386 // be processed once!
387 Opts.clear();
388 PositionalOpts.clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000389
390 // If we had an error processing our arguments, don't let the program execute
391 if (ErrorParsing) exit(1);
392}
393
394//===----------------------------------------------------------------------===//
395// Option Base class implementation
396//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000397
Chris Lattner0c0edf82002-07-25 06:17:51 +0000398bool Option::error(string Message, const char *ArgName) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000399 if (ArgName == 0) ArgName = ArgStr;
Chris Lattner331de232002-07-22 02:07:59 +0000400 if (ArgName[0] == 0)
401 cerr << HelpStr; // Be nice for positional arguments
402 else
403 cerr << "-" << ArgName;
404 cerr << " option" << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000405 return true;
406}
407
408bool Option::addOccurance(const char *ArgName, const string &Value) {
409 NumOccurances++; // Increment the number of times we have been seen
410
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000411 switch (getNumOccurancesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000412 case Optional:
413 if (NumOccurances > 1)
414 return error(": may only occur zero or one times!", ArgName);
415 break;
416 case Required:
417 if (NumOccurances > 1)
418 return error(": must occur exactly one time!", ArgName);
419 // Fall through
420 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000421 case ZeroOrMore:
422 case ConsumeAfter: break;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000423 default: return error(": bad num occurances flag value!");
424 }
425
426 return handleOccurance(ArgName, Value);
427}
428
Chris Lattner331de232002-07-22 02:07:59 +0000429// addArgument - Tell the system that this Option subclass will handle all
430// occurances of -ArgStr on the command line.
431//
432void Option::addArgument(const char *ArgStr) {
433 if (ArgStr[0])
434 AddArgument(ArgStr, this);
435 else if (getFormattingFlag() == Positional)
436 getPositionalOpts().push_back(this);
437 else if (getNumOccurancesFlag() == ConsumeAfter) {
438 assert((getPositionalOpts().empty() ||
439 getPositionalOpts().front()->getNumOccurancesFlag() != ConsumeAfter)
440 && "Cannot specify more than one option with cl::ConsumeAfter "
441 "specified!");
442 getPositionalOpts().insert(getPositionalOpts().begin(), this);
443 }
444}
445
Chris Lattneraa852bb2002-07-23 17:15:12 +0000446void Option::removeArgument(const char *ArgStr) {
447 if (ArgStr[0]) {
448 assert(getOpts()[ArgStr] == this && "Arg not in map!");
449 getOpts().erase(ArgStr);
450 } else if (getFormattingFlag() == Positional) {
451 vector<Option*>::iterator I =
452 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
453 assert(I != getPositionalOpts().end() && "Arg not registered!");
454 getPositionalOpts().erase(I);
455 } else if (getNumOccurancesFlag() == ConsumeAfter) {
456 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
457 "Arg not registered correctly!");
458 getPositionalOpts().erase(getPositionalOpts().begin());
459 }
460}
461
Chris Lattner331de232002-07-22 02:07:59 +0000462
463// getValueStr - Get the value description string, using "DefaultMsg" if nothing
464// has been specified yet.
465//
466static const char *getValueStr(const Option &O, const char *DefaultMsg) {
467 if (O.ValueStr[0] == 0) return DefaultMsg;
468 return O.ValueStr;
469}
470
471//===----------------------------------------------------------------------===//
472// cl::alias class implementation
473//
474
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000475// Return the width of the option tag for printing...
Chris Lattner331de232002-07-22 02:07:59 +0000476unsigned alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000477 return std::strlen(ArgStr)+6;
478}
479
Chris Lattner331de232002-07-22 02:07:59 +0000480// Print out the option for the alias...
481void alias::printOptionInfo(unsigned GlobalWidth) const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000482 unsigned L = std::strlen(ArgStr);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000483 cerr << " -" << ArgStr << string(GlobalWidth-L-6, ' ') << " - "
Chris Lattner697954c2002-01-20 22:54:45 +0000484 << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000485}
486
487
Chris Lattner331de232002-07-22 02:07:59 +0000488
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000489//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000490// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000491//
492
Chris Lattner331de232002-07-22 02:07:59 +0000493// parser<bool> implementation
494//
495bool parser<bool>::parseImpl(Option &O, const string &Arg, bool &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000496 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
497 Arg == "1") {
498 Value = true;
499 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
500 Value = false;
501 } else {
Chris Lattner331de232002-07-22 02:07:59 +0000502 return O.error(": '" + Arg +
503 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000504 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000505 return false;
506}
507
Chris Lattner331de232002-07-22 02:07:59 +0000508// Return the width of the option tag for printing...
509unsigned parser<bool>::getOptionWidth(const Option &O) const {
510 return std::strlen(O.ArgStr)+6;
511}
512
513// printOptionInfo - Print out information about this option. The
514// to-be-maintained width is specified.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000515//
Chris Lattner331de232002-07-22 02:07:59 +0000516void parser<bool>::printOptionInfo(const Option &O, unsigned GlobalWidth) const{
517 unsigned L = std::strlen(O.ArgStr);
518 cerr << " -" << O.ArgStr << string(GlobalWidth-L-6, ' ') << " - "
519 << O.HelpStr << "\n";
520}
521
522
523
524// parser<int> implementation
525//
526bool parser<int>::parseImpl(Option &O, const string &Arg, int &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000527 const char *ArgStart = Arg.c_str();
528 char *End;
529 Value = (int)strtol(ArgStart, &End, 0);
530 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000531 return O.error(": '" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000532 return false;
533}
534
Chris Lattner331de232002-07-22 02:07:59 +0000535// Return the width of the option tag for printing...
536unsigned parser<int>::getOptionWidth(const Option &O) const {
537 return std::strlen(O.ArgStr)+std::strlen(getValueStr(O, "int"))+9;
538}
539
540// printOptionInfo - Print out information about this option. The
541// to-be-maintained width is specified.
Chris Lattnerd215fd12001-10-13 06:53:19 +0000542//
Chris Lattner331de232002-07-22 02:07:59 +0000543void parser<int>::printOptionInfo(const Option &O, unsigned GlobalWidth) const{
544 cerr << " -" << O.ArgStr << "=<" << getValueStr(O, "int") << ">"
545 << string(GlobalWidth-getOptionWidth(O), ' ') << " - "
546 << O.HelpStr << "\n";
547}
548
549
550// parser<double> implementation
551//
552bool parser<double>::parseImpl(Option &O, const string &Arg, double &Value) {
553 const char *ArgStart = Arg.c_str();
554 char *End;
555 Value = strtod(ArgStart, &End);
556 if (*End != 0)
557 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +0000558 return false;
559}
560
Chris Lattner331de232002-07-22 02:07:59 +0000561// Return the width of the option tag for printing...
562unsigned parser<double>::getOptionWidth(const Option &O) const {
563 return std::strlen(O.ArgStr)+std::strlen(getValueStr(O, "number"))+9;
564}
565
566// printOptionInfo - Print out information about this option. The
567// to-be-maintained width is specified.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000568//
Chris Lattner331de232002-07-22 02:07:59 +0000569void parser<double>::printOptionInfo(const Option &O,
570 unsigned GlobalWidth) const{
571 cerr << " -" << O.ArgStr << "=<" << getValueStr(O, "number") << ">"
572 << string(GlobalWidth-getOptionWidth(O), ' ')
573 << " - " << O.HelpStr << "\n";
574}
575
576
577// parser<string> implementation
578//
579
580// Return the width of the option tag for printing...
581unsigned parser<string>::getOptionWidth(const Option &O) const {
582 return std::strlen(O.ArgStr)+std::strlen(getValueStr(O, "string"))+9;
583}
584
585// printOptionInfo - Print out information about this option. The
586// to-be-maintained width is specified.
587//
588void parser<string>::printOptionInfo(const Option &O,
589 unsigned GlobalWidth) const{
590 cerr << " -" << O.ArgStr << " <" << getValueStr(O, "string") << ">"
591 << string(GlobalWidth-getOptionWidth(O), ' ')
592 << " - " << O.HelpStr << "\n";
593}
594
595// generic_parser_base implementation
596//
597
Chris Lattneraa852bb2002-07-23 17:15:12 +0000598// findOption - Return the option number corresponding to the specified
599// argument string. If the option is not found, getNumOptions() is returned.
600//
601unsigned generic_parser_base::findOption(const char *Name) {
602 unsigned i = 0, e = getNumOptions();
603 string N(Name);
604
605 while (i != e)
606 if (getOption(i) == N)
607 return i;
608 else
609 ++i;
610 return e;
611}
612
613
Chris Lattner331de232002-07-22 02:07:59 +0000614// Return the width of the option tag for printing...
615unsigned generic_parser_base::getOptionWidth(const Option &O) const {
616 if (O.hasArgStr()) {
617 unsigned Size = std::strlen(O.ArgStr)+6;
618 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
619 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
620 return Size;
621 } else {
622 unsigned BaseSize = 0;
623 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
624 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
625 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000626 }
627}
628
Chris Lattner331de232002-07-22 02:07:59 +0000629// printOptionInfo - Print out information about this option. The
630// to-be-maintained width is specified.
631//
632void generic_parser_base::printOptionInfo(const Option &O,
633 unsigned GlobalWidth) const {
634 if (O.hasArgStr()) {
635 unsigned L = std::strlen(O.ArgStr);
636 cerr << " -" << O.ArgStr << string(GlobalWidth-L-6, ' ')
637 << " - " << O.HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000638
Chris Lattner331de232002-07-22 02:07:59 +0000639 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
640 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
641 cerr << " =" << getOption(i) << string(NumSpaces, ' ') << " - "
642 << getDescription(i) << "\n";
Chris Lattner9c9be482002-01-31 00:42:56 +0000643 }
Chris Lattner331de232002-07-22 02:07:59 +0000644 } else {
645 if (O.HelpStr[0])
646 cerr << " " << O.HelpStr << "\n";
647 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
648 unsigned L = std::strlen(getOption(i));
649 cerr << " -" << getOption(i) << string(GlobalWidth-L-8, ' ') << " - "
650 << getDescription(i) << "\n";
651 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000652 }
653}
654
655
656//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000657// --help and --help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000658//
659namespace {
660
Chris Lattner331de232002-07-22 02:07:59 +0000661class HelpPrinter {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000662 unsigned MaxArgLen;
663 const Option *EmptyArg;
664 const bool ShowHidden;
665
Chris Lattner331de232002-07-22 02:07:59 +0000666 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
667 inline static bool isHidden(pair<string, Option *> &OptPair) {
668 return OptPair.second->getOptionHiddenFlag() >= Hidden;
669 }
670 inline static bool isReallyHidden(pair<string, Option *> &OptPair) {
671 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
672 }
673
674public:
675 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
676 EmptyArg = 0;
677 }
678
679 void operator=(bool Value) {
680 if (Value == false) return;
681
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000682 // Copy Options into a vector so we can sort them as we like...
683 vector<pair<string, Option*> > Options;
Chris Lattner697954c2002-01-20 22:54:45 +0000684 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000685
686 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Chris Lattner331de232002-07-22 02:07:59 +0000687 Options.erase(std::remove_if(Options.begin(), Options.end(),
688 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000689 Options.end());
690
691 // Eliminate duplicate entries in table (from enum flags options, f.e.)
Chris Lattner331de232002-07-22 02:07:59 +0000692 { // Give OptionSet a scope
693 std::set<Option*> OptionSet;
694 for (unsigned i = 0; i != Options.size(); ++i)
695 if (OptionSet.count(Options[i].second) == 0)
696 OptionSet.insert(Options[i].second); // Add new entry to set
697 else
698 Options.erase(Options.begin()+i--); // Erase duplicate
699 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000700
701 if (ProgramOverview)
Chris Lattner697954c2002-01-20 22:54:45 +0000702 cerr << "OVERVIEW:" << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000703
Chris Lattner331de232002-07-22 02:07:59 +0000704 cerr << "USAGE: " << ProgramName << " [options]";
705
706 // Print out the positional options...
707 vector<Option*> &PosOpts = getPositionalOpts();
708 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
709 if (!PosOpts.empty() && PosOpts[0]->getNumOccurancesFlag() == ConsumeAfter)
710 CAOpt = PosOpts[0];
711
712 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
713 cerr << " " << PosOpts[i]->HelpStr;
714 switch (PosOpts[i]->getNumOccurancesFlag()) {
715 case Optional: cerr << "?"; break;
716 case ZeroOrMore: cerr << "*"; break;
717 case Required: break;
718 case OneOrMore: cerr << "+"; break;
719 case ConsumeAfter:
720 default:
721 assert(0 && "Unknown NumOccurances Flag Value!");
722 }
723 }
724
725 // Print the consume after option info if it exists...
726 if (CAOpt) cerr << " " << CAOpt->HelpStr;
727
728 cerr << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000729
730 // Compute the maximum argument length...
731 MaxArgLen = 0;
Chris Lattner331de232002-07-22 02:07:59 +0000732 for (unsigned i = 0, e = Options.size(); i != e; ++i)
733 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000734
735 cerr << "OPTIONS:\n";
Chris Lattner331de232002-07-22 02:07:59 +0000736 for (unsigned i = 0, e = Options.size(); i != e; ++i)
737 Options[i].second->printOptionInfo(MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000738
Chris Lattner331de232002-07-22 02:07:59 +0000739 // Halt the program if help information is printed
740 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000741 }
742};
743
Chris Lattner331de232002-07-22 02:07:59 +0000744
745
746// Define the two HelpPrinter instances that are used to print out help, or
747// help-hidden...
748//
749HelpPrinter NormalPrinter(false);
750HelpPrinter HiddenPrinter(true);
751
752cl::opt<HelpPrinter, true, parser<bool> >
753HOp("help", cl::desc("display available options (--help-hidden for more)"),
754 cl::location(NormalPrinter));
755
756cl::opt<HelpPrinter, true, parser<bool> >
757HHOp("help-hidden", cl::desc("display all available options"),
758 cl::location(HiddenPrinter), cl::Hidden);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000759
760} // End anonymous namespace