blob: a46c68c986ea3c5d9333e65433e5f07c8be5427e [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!
96 return Handler->addOccurance(ArgName, Value);
97}
98
Chris Lattnerca6433f2003-05-22 20:06:43 +000099static bool ProvidePositionalOption(Option *Handler, std::string &Arg) {
Chris Lattner331de232002-07-22 02:07:59 +0000100 int Dummy;
101 return ProvideOption(Handler, "", Arg.c_str(), 0, 0, Dummy);
102}
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) {
146 return O->getNumOccurancesFlag() == cl::Required ||
147 O->getNumOccurancesFlag() == cl::OneOrMore;
148}
149
150static bool EatsUnboundedNumberOfValues(const Option *O) {
151 return O->getNumOccurancesFlag() == cl::ZeroOrMore ||
152 O->getNumOccurancesFlag() == 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()) {
171 if (PositionalOpts[0]->getNumOccurancesFlag() == cl::ConsumeAfter) {
172 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 Lattner331de232002-07-22 02:07:59 +0000192 } else if (UnboundedFound) { // This option does not "require" a value...
193 // Make sure this option is not specified after an option that eats all
194 // extra arguments, or this one will never get any!
195 //
196 ErrorParsing |= Opt->error(" error - option can never match, because "
197 "another positional argument will match an "
198 "unbounded number of values, and this option"
199 " does not require a value!");
200 }
201 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
202 }
203 }
204
205 // PositionalVals - A vector of "positional" arguments we accumulate into to
206 // processes at the end...
207 //
Chris Lattnerca6433f2003-05-22 20:06:43 +0000208 std::vector<std::string> PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000209
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000210 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000211 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000212 for (int i = 1; i < argc; ++i) {
213 Option *Handler = 0;
214 const char *Value = "";
215 const char *ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000216
217 // Check to see if this is a positional argument. This argument is
218 // considered to be positional if it doesn't start with '-', if it is "-"
219 // itself, or if we have see "--" already.
220 //
221 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
222 // Positional argument!
223 if (!PositionalOpts.empty()) {
224 PositionalVals.push_back(argv[i]);
225
226 // All of the positional arguments have been fulfulled, give the rest to
227 // the consume after option... if it's specified...
228 //
Chris Lattnerd16714b2002-07-31 16:29:43 +0000229 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000230 ConsumeAfterOpt != 0) {
231 for (++i; i < argc; ++i)
232 PositionalVals.push_back(argv[i]);
233 break; // Handle outside of the argument processing loop...
234 }
235
236 // Delay processing positional arguments until the end...
237 continue;
238 }
239 } else { // We start with a '-', must be an argument...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000240 ArgName = argv[i]+1;
241 while (*ArgName == '-') ++ArgName; // Eat leading dashes
242
Chris Lattner331de232002-07-22 02:07:59 +0000243 if (*ArgName == 0 && !DashDashFound) { // Is this the mythical "--"?
244 DashDashFound = true; // Yup, take note of that fact...
245 continue; // Don't try to process it as an argument iself.
246 }
247
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000248 const char *ArgNameEnd = ArgName;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000249 while (*ArgNameEnd && *ArgNameEnd != '=')
250 ++ArgNameEnd; // Scan till end of argument name...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000251
252 Value = ArgNameEnd;
253 if (*Value) // If we have an equals sign...
254 ++Value; // Advance to value...
255
256 if (*ArgName != 0) {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000257 std::string RealName(ArgName, ArgNameEnd);
Chris Lattner3805e4c2001-07-25 18:40:49 +0000258 // Extract arg name part
Chris Lattnerca6433f2003-05-22 20:06:43 +0000259 std::map<std::string, Option*>::iterator I = Opts.find(RealName);
Chris Lattnerf78032f2001-11-26 18:58:34 +0000260
Chris Lattner331de232002-07-22 02:07:59 +0000261 if (I == Opts.end() && !*Value && RealName.size() > 1) {
262 // Check to see if this "option" is really a prefixed or grouped
263 // argument...
264 //
265 unsigned Length = 0;
266 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
Chris Lattnerf78032f2001-11-26 18:58:34 +0000267
Chris Lattner331de232002-07-22 02:07:59 +0000268 // If the option is a prefixed option, then the value is simply the
269 // rest of the name... so fall through to later processing, by
270 // setting up the argument name flags and value fields.
271 //
272 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
273 ArgNameEnd = ArgName+Length;
274 Value = ArgNameEnd;
Chris Lattnerca6433f2003-05-22 20:06:43 +0000275 I = Opts.find(std::string(ArgName, ArgNameEnd));
Chris Lattner331de232002-07-22 02:07:59 +0000276 assert(I->second == PGOpt);
277 } else if (PGOpt) {
278 // This must be a grouped option... handle all of them now...
279 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
280
281 do {
282 // Move current arg name out of RealName into RealArgName...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000283 std::string RealArgName(RealName.begin(),RealName.begin()+Length);
Chris Lattner331de232002-07-22 02:07:59 +0000284 RealName.erase(RealName.begin(), RealName.begin()+Length);
Chris Lattnerf78032f2001-11-26 18:58:34 +0000285
286 // Because ValueRequired is an invalid flag for grouped arguments,
287 // we don't need to pass argc/argv in...
288 //
Chris Lattner331de232002-07-22 02:07:59 +0000289 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
290 "Option can not be cl::Grouping AND cl::ValueRequired!");
291 int Dummy;
292 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(), "",
293 0, 0, Dummy);
294
295 // Get the next grouping option...
296 if (!RealName.empty())
297 PGOpt = getOptionPred(RealName, Length, isGrouping);
298 } while (!RealName.empty() && PGOpt);
299
300 if (RealName.empty()) // Processed all of the options, move on
301 continue; // to the next argv[] value...
302
303 // If RealName is not empty, that means we did not match one of the
304 // options! This is an error.
305 //
306 I = Opts.end();
307 }
Chris Lattnerf78032f2001-11-26 18:58:34 +0000308 }
309
Chris Lattner331de232002-07-22 02:07:59 +0000310 Handler = I != Opts.end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000311 }
312 }
313
314 if (Handler == 0) {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000315 std::cerr << "Unknown command line argument '" << argv[i] << "'. Try: "
316 << argv[0] << " --help'\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000317 ErrorParsing = true;
318 continue;
319 }
320
Chris Lattnercaccd762001-10-27 05:54:17 +0000321 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000322 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000323
Chris Lattner331de232002-07-22 02:07:59 +0000324 // Check and handle positional arguments now...
325 if (NumPositionalRequired > PositionalVals.size()) {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000326 std::cerr << "Not enough positional command line arguments specified!\n"
327 << "Must specify at least " << NumPositionalRequired
328 << " positional arguments: See: " << argv[0] << " --help\n";
Chris Lattner331de232002-07-22 02:07:59 +0000329 ErrorParsing = true;
330
331
332 } else if (ConsumeAfterOpt == 0) {
333 // Positional args have already been handled if ConsumeAfter is specified...
334 unsigned ValNo = 0, NumVals = PositionalVals.size();
335 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
336 if (RequiresValue(PositionalOpts[i])) {
337 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
338 --NumPositionalRequired; // We fulfilled our duty...
339 }
340
341 // If we _can_ give this option more arguments, do so now, as long as we
342 // do not give it values that others need. 'Done' controls whether the
343 // option even _WANTS_ any more.
344 //
345 bool Done = PositionalOpts[i]->getNumOccurancesFlag() == cl::Required;
346 while (NumVals-ValNo > NumPositionalRequired && !Done) {
347 switch (PositionalOpts[i]->getNumOccurancesFlag()) {
348 case cl::Optional:
349 Done = true; // Optional arguments want _at most_ one value
350 // FALL THROUGH
351 case cl::ZeroOrMore: // Zero or more will take all they can get...
352 case cl::OneOrMore: // One or more will take all they can get...
353 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
354 break;
355 default:
356 assert(0 && "Internal error, unexpected NumOccurances flag in "
357 "positional argument processing!");
358 }
359 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000360 }
Chris Lattner331de232002-07-22 02:07:59 +0000361 } else {
362 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
363 unsigned ValNo = 0;
364 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
365 if (RequiresValue(PositionalOpts[j]))
Chris Lattnerfaba8092002-07-24 20:15:13 +0000366 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
367 PositionalVals[ValNo++]);
368
369 // Handle the case where there is just one positional option, and it's
370 // optional. In this case, we want to give JUST THE FIRST option to the
371 // positional option and keep the rest for the consume after. The above
372 // loop would have assigned no values to positional options in this case.
373 //
Chris Lattnerb490c202002-08-02 21:51:29 +0000374 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty())
Chris Lattnerfaba8092002-07-24 20:15:13 +0000375 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
376 PositionalVals[ValNo++]);
Chris Lattner331de232002-07-22 02:07:59 +0000377
378 // Handle over all of the rest of the arguments to the
379 // cl::ConsumeAfter command line option...
380 for (; ValNo != PositionalVals.size(); ++ValNo)
381 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
382 PositionalVals[ValNo]);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000383 }
384
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000385 // Loop over args and make sure all required args are specified!
Chris Lattnerca6433f2003-05-22 20:06:43 +0000386 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
Chris Lattner331de232002-07-22 02:07:59 +0000387 E = Opts.end(); I != E; ++I) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000388 switch (I->second->getNumOccurancesFlag()) {
389 case Required:
390 case OneOrMore:
Chris Lattnerf038acb2001-10-24 06:21:56 +0000391 if (I->second->getNumOccurances() == 0) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000392 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000393 ErrorParsing = true;
394 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000395 // Fall through
396 default:
397 break;
398 }
399 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000400
Chris Lattner331de232002-07-22 02:07:59 +0000401 // Free all of the memory allocated to the map. Command line options may only
402 // be processed once!
Chris Lattnere8e258b2002-07-29 20:58:42 +0000403 delete CommandLineOptions;
404 CommandLineOptions = 0;
Chris Lattner331de232002-07-22 02:07:59 +0000405 PositionalOpts.clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000406
407 // If we had an error processing our arguments, don't let the program execute
408 if (ErrorParsing) exit(1);
409}
410
411//===----------------------------------------------------------------------===//
412// Option Base class implementation
413//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000414
Chris Lattnerca6433f2003-05-22 20:06:43 +0000415bool Option::error(std::string Message, const char *ArgName) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000416 if (ArgName == 0) ArgName = ArgStr;
Chris Lattner331de232002-07-22 02:07:59 +0000417 if (ArgName[0] == 0)
Chris Lattnerca6433f2003-05-22 20:06:43 +0000418 std::cerr << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000419 else
Chris Lattnerca6433f2003-05-22 20:06:43 +0000420 std::cerr << "-" << ArgName;
421 std::cerr << " option" << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000422 return true;
423}
424
Chris Lattnerca6433f2003-05-22 20:06:43 +0000425bool Option::addOccurance(const char *ArgName, const std::string &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000426 NumOccurances++; // Increment the number of times we have been seen
427
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000428 switch (getNumOccurancesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000429 case Optional:
430 if (NumOccurances > 1)
431 return error(": may only occur zero or one times!", ArgName);
432 break;
433 case Required:
434 if (NumOccurances > 1)
435 return error(": must occur exactly one time!", ArgName);
436 // Fall through
437 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000438 case ZeroOrMore:
439 case ConsumeAfter: break;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000440 default: return error(": bad num occurances flag value!");
441 }
442
443 return handleOccurance(ArgName, Value);
444}
445
Chris Lattner331de232002-07-22 02:07:59 +0000446// addArgument - Tell the system that this Option subclass will handle all
447// occurances of -ArgStr on the command line.
448//
449void Option::addArgument(const char *ArgStr) {
450 if (ArgStr[0])
451 AddArgument(ArgStr, this);
452 else if (getFormattingFlag() == Positional)
453 getPositionalOpts().push_back(this);
454 else if (getNumOccurancesFlag() == ConsumeAfter) {
455 assert((getPositionalOpts().empty() ||
456 getPositionalOpts().front()->getNumOccurancesFlag() != ConsumeAfter)
457 && "Cannot specify more than one option with cl::ConsumeAfter "
458 "specified!");
459 getPositionalOpts().insert(getPositionalOpts().begin(), this);
460 }
461}
462
Chris Lattneraa852bb2002-07-23 17:15:12 +0000463void Option::removeArgument(const char *ArgStr) {
464 if (ArgStr[0]) {
Chris Lattnere8e258b2002-07-29 20:58:42 +0000465 RemoveArgument(ArgStr, this);
Chris Lattneraa852bb2002-07-23 17:15:12 +0000466 } else if (getFormattingFlag() == Positional) {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000467 std::vector<Option*>::iterator I =
Chris Lattneraa852bb2002-07-23 17:15:12 +0000468 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
469 assert(I != getPositionalOpts().end() && "Arg not registered!");
470 getPositionalOpts().erase(I);
471 } else if (getNumOccurancesFlag() == ConsumeAfter) {
472 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
473 "Arg not registered correctly!");
474 getPositionalOpts().erase(getPositionalOpts().begin());
475 }
476}
477
Chris Lattner331de232002-07-22 02:07:59 +0000478
479// getValueStr - Get the value description string, using "DefaultMsg" if nothing
480// has been specified yet.
481//
482static const char *getValueStr(const Option &O, const char *DefaultMsg) {
483 if (O.ValueStr[0] == 0) return DefaultMsg;
484 return O.ValueStr;
485}
486
487//===----------------------------------------------------------------------===//
488// cl::alias class implementation
489//
490
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000491// Return the width of the option tag for printing...
Chris Lattner331de232002-07-22 02:07:59 +0000492unsigned alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000493 return std::strlen(ArgStr)+6;
494}
495
Chris Lattner331de232002-07-22 02:07:59 +0000496// Print out the option for the alias...
497void alias::printOptionInfo(unsigned GlobalWidth) const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000498 unsigned L = std::strlen(ArgStr);
Chris Lattnerca6433f2003-05-22 20:06:43 +0000499 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
500 << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000501}
502
503
Chris Lattner331de232002-07-22 02:07:59 +0000504
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000505//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000506// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000507//
508
Chris Lattner9b14eb52002-08-07 18:36:37 +0000509// basic_parser implementation
510//
511
512// Return the width of the option tag for printing...
513unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
514 unsigned Len = std::strlen(O.ArgStr);
515 if (const char *ValName = getValueName())
516 Len += std::strlen(getValueStr(O, ValName))+3;
517
518 return Len + 6;
519}
520
521// printOptionInfo - Print out information about this option. The
522// to-be-maintained width is specified.
523//
524void basic_parser_impl::printOptionInfo(const Option &O,
525 unsigned GlobalWidth) const {
Chris Lattnerca6433f2003-05-22 20:06:43 +0000526 std::cerr << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000527
528 if (const char *ValName = getValueName())
Chris Lattnerca6433f2003-05-22 20:06:43 +0000529 std::cerr << "=<" << getValueStr(O, ValName) << ">";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000530
Chris Lattnerca6433f2003-05-22 20:06:43 +0000531 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
532 << O.HelpStr << "\n";
Chris Lattner9b14eb52002-08-07 18:36:37 +0000533}
534
535
536
537
Chris Lattner331de232002-07-22 02:07:59 +0000538// parser<bool> implementation
539//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000540bool parser<bool>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000541 const std::string &Arg, bool &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000542 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
543 Arg == "1") {
544 Value = true;
545 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
546 Value = false;
547 } else {
Chris Lattner331de232002-07-22 02:07:59 +0000548 return O.error(": '" + Arg +
549 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000550 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000551 return false;
552}
553
Chris Lattner331de232002-07-22 02:07:59 +0000554// parser<int> implementation
555//
Chris Lattner9b14eb52002-08-07 18:36:37 +0000556bool parser<int>::parse(Option &O, const char *ArgName,
Chris Lattnerca6433f2003-05-22 20:06:43 +0000557 const std::string &Arg, int &Value) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000558 const char *ArgStart = Arg.c_str();
559 char *End;
560 Value = (int)strtol(ArgStart, &End, 0);
561 if (*End != 0)
Chris Lattner331de232002-07-22 02:07:59 +0000562 return O.error(": '" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000563 return false;
564}
565
Chris Lattner9b14eb52002-08-07 18:36:37 +0000566// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +0000567//
Chris Lattnerca6433f2003-05-22 20:06:43 +0000568static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
Chris Lattner331de232002-07-22 02:07:59 +0000569 const char *ArgStart = Arg.c_str();
570 char *End;
571 Value = strtod(ArgStart, &End);
572 if (*End != 0)
573 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +0000574 return false;
575}
576
Chris Lattner9b14eb52002-08-07 18:36:37 +0000577bool parser<double>::parse(Option &O, const char *AN,
578 const std::string &Arg, double &Val) {
579 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +0000580}
581
Chris Lattner9b14eb52002-08-07 18:36:37 +0000582bool parser<float>::parse(Option &O, const char *AN,
583 const std::string &Arg, float &Val) {
584 double dVal;
585 if (parseDouble(O, Arg, dVal))
586 return true;
587 Val = (float)dVal;
588 return false;
Chris Lattner331de232002-07-22 02:07:59 +0000589}
590
591
Chris Lattner331de232002-07-22 02:07:59 +0000592
593// generic_parser_base implementation
594//
595
Chris Lattneraa852bb2002-07-23 17:15:12 +0000596// findOption - Return the option number corresponding to the specified
597// argument string. If the option is not found, getNumOptions() is returned.
598//
599unsigned generic_parser_base::findOption(const char *Name) {
600 unsigned i = 0, e = getNumOptions();
Chris Lattnerca6433f2003-05-22 20:06:43 +0000601 std::string N(Name);
Chris Lattneraa852bb2002-07-23 17:15:12 +0000602
603 while (i != e)
604 if (getOption(i) == N)
605 return i;
606 else
607 ++i;
608 return e;
609}
610
611
Chris Lattner331de232002-07-22 02:07:59 +0000612// Return the width of the option tag for printing...
613unsigned generic_parser_base::getOptionWidth(const Option &O) const {
614 if (O.hasArgStr()) {
615 unsigned Size = std::strlen(O.ArgStr)+6;
616 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
617 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
618 return Size;
619 } else {
620 unsigned BaseSize = 0;
621 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
622 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
623 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000624 }
625}
626
Chris Lattner331de232002-07-22 02:07:59 +0000627// printOptionInfo - Print out information about this option. The
628// to-be-maintained width is specified.
629//
630void generic_parser_base::printOptionInfo(const Option &O,
631 unsigned GlobalWidth) const {
632 if (O.hasArgStr()) {
633 unsigned L = std::strlen(O.ArgStr);
Chris Lattnerca6433f2003-05-22 20:06:43 +0000634 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
635 << " - " << O.HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000636
Chris Lattner331de232002-07-22 02:07:59 +0000637 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
638 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnerca6433f2003-05-22 20:06:43 +0000639 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
640 << " - " << getDescription(i) << "\n";
Chris Lattner9c9be482002-01-31 00:42:56 +0000641 }
Chris Lattner331de232002-07-22 02:07:59 +0000642 } else {
643 if (O.HelpStr[0])
Chris Lattnerca6433f2003-05-22 20:06:43 +0000644 std::cerr << " " << O.HelpStr << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000645 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
646 unsigned L = std::strlen(getOption(i));
Chris Lattnerca6433f2003-05-22 20:06:43 +0000647 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
648 << " - " << getDescription(i) << "\n";
Chris Lattner331de232002-07-22 02:07:59 +0000649 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000650 }
651}
652
653
654//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000655// --help and --help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000656//
657namespace {
658
Chris Lattner331de232002-07-22 02:07:59 +0000659class HelpPrinter {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000660 unsigned MaxArgLen;
661 const Option *EmptyArg;
662 const bool ShowHidden;
663
Chris Lattner331de232002-07-22 02:07:59 +0000664 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
Chris Lattnerca6433f2003-05-22 20:06:43 +0000665 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000666 return OptPair.second->getOptionHiddenFlag() >= Hidden;
667 }
Chris Lattnerca6433f2003-05-22 20:06:43 +0000668 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
Chris Lattner331de232002-07-22 02:07:59 +0000669 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
670 }
671
672public:
673 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
674 EmptyArg = 0;
675 }
676
677 void operator=(bool Value) {
678 if (Value == false) return;
679
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000680 // Copy Options into a vector so we can sort them as we like...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000681 std::vector<std::pair<std::string, Option*> > Options;
Chris Lattner697954c2002-01-20 22:54:45 +0000682 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000683
684 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
Chris Lattner331de232002-07-22 02:07:59 +0000685 Options.erase(std::remove_if(Options.begin(), Options.end(),
686 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000687 Options.end());
688
689 // Eliminate duplicate entries in table (from enum flags options, f.e.)
Chris Lattner331de232002-07-22 02:07:59 +0000690 { // Give OptionSet a scope
691 std::set<Option*> OptionSet;
692 for (unsigned i = 0; i != Options.size(); ++i)
693 if (OptionSet.count(Options[i].second) == 0)
694 OptionSet.insert(Options[i].second); // Add new entry to set
695 else
696 Options.erase(Options.begin()+i--); // Erase duplicate
697 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000698
699 if (ProgramOverview)
Chris Lattnerca6433f2003-05-22 20:06:43 +0000700 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000701
Chris Lattnerca6433f2003-05-22 20:06:43 +0000702 std::cerr << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +0000703
704 // Print out the positional options...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000705 std::vector<Option*> &PosOpts = getPositionalOpts();
Chris Lattner331de232002-07-22 02:07:59 +0000706 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
707 if (!PosOpts.empty() && PosOpts[0]->getNumOccurancesFlag() == ConsumeAfter)
708 CAOpt = PosOpts[0];
709
Chris Lattner9b14eb52002-08-07 18:36:37 +0000710 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i)
Chris Lattnerca6433f2003-05-22 20:06:43 +0000711 std::cerr << " " << PosOpts[i]->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +0000712
713 // Print the consume after option info if it exists...
Chris Lattnerca6433f2003-05-22 20:06:43 +0000714 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +0000715
Chris Lattnerca6433f2003-05-22 20:06:43 +0000716 std::cerr << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000717
718 // Compute the maximum argument length...
719 MaxArgLen = 0;
Chris Lattner331de232002-07-22 02:07:59 +0000720 for (unsigned i = 0, e = Options.size(); i != e; ++i)
721 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000722
Chris Lattnerca6433f2003-05-22 20:06:43 +0000723 std::cerr << "OPTIONS:\n";
Chris Lattner331de232002-07-22 02:07:59 +0000724 for (unsigned i = 0, e = Options.size(); i != e; ++i)
725 Options[i].second->printOptionInfo(MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000726
Chris Lattner331de232002-07-22 02:07:59 +0000727 // Halt the program if help information is printed
728 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000729 }
730};
731
Chris Lattner331de232002-07-22 02:07:59 +0000732
733
734// Define the two HelpPrinter instances that are used to print out help, or
735// help-hidden...
736//
737HelpPrinter NormalPrinter(false);
738HelpPrinter HiddenPrinter(true);
739
740cl::opt<HelpPrinter, true, parser<bool> >
741HOp("help", cl::desc("display available options (--help-hidden for more)"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000742 cl::location(NormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +0000743
744cl::opt<HelpPrinter, true, parser<bool> >
745HHOp("help-hidden", cl::desc("display all available options"),
Chris Lattner9b14eb52002-08-07 18:36:37 +0000746 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000747
748} // End anonymous namespace