1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements a command line argument processor that is useful when
11 // creating a tool. It provides a simple, minimalistic interface that is easily
12 // extensible and supports nonlocal (library) command line options.
14 // Note that rather than trying to figure out what this code does, you could try
15 // reading the library documentation located in docs/CommandLine.html
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Config/config.h"
20 #include "llvm/Support/CommandLine.h"
32 // Globals for name and overview of program
33 static const char *ProgramName = "<unknown>";
34 static const char *ProgramOverview = 0;
36 // This collects additional help to be printed.
37 static std::vector<const char*> &MoreHelp() {
38 static std::vector<const char*> moreHelp;
42 extrahelp::extrahelp(const char* Help)
44 MoreHelp().push_back(Help);
47 //===----------------------------------------------------------------------===//
48 // Basic, shared command line option processing machinery...
51 // Return the global command line option vector. Making it a function scoped
52 // static ensures that it will be initialized correctly before its first use.
54 static std::map<std::string, Option*> &getOpts() {
55 static std::map<std::string, Option*> CommandLineOptions;
56 return CommandLineOptions;
59 static Option *getOption(const std::string &Str) {
60 std::map<std::string,Option*>::iterator I = getOpts().find(Str);
61 return I != getOpts().end() ? I->second : 0;
64 static std::vector<Option*> &getPositionalOpts() {
65 static std::vector<Option*> Positional;
69 static void AddArgument(const char *ArgName, Option *Opt) {
70 if (getOption(ArgName)) {
71 std::cerr << ProgramName << ": CommandLine Error: Argument '"
72 << ArgName << "' defined more than once!\n";
74 // Add argument to the argument map!
75 getOpts()[ArgName] = Opt;
79 // RemoveArgument - It's possible that the argument is no longer in the map if
80 // options have already been processed and the map has been deleted!
82 static void RemoveArgument(const char *ArgName, Option *Opt) {
83 if(getOpts().empty()) return;
86 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
87 // If we pass ArgName directly into getOption here.
88 std::string Tmp = ArgName;
89 assert(getOption(Tmp) == Opt && "Arg not in map!");
91 getOpts().erase(ArgName);
94 static inline bool ProvideOption(Option *Handler, const char *ArgName,
95 const char *Value, int argc, char **argv,
97 // Enforce value requirements
98 switch (Handler->getValueExpectedFlag()) {
100 if (Value == 0) { // No value specified?
101 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
104 return Handler->error(" requires a value!");
108 case ValueDisallowed:
110 return Handler->error(" does not allow a value! '" +
111 std::string(Value) + "' specified.");
116 std::cerr << ProgramName
117 << ": Bad ValueMask flag! CommandLine usage error:"
118 << Handler->getValueExpectedFlag() << "\n";
123 // Run the handler now!
124 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
127 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
130 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
134 // Option predicates...
135 static inline bool isGrouping(const Option *O) {
136 return O->getFormattingFlag() == cl::Grouping;
138 static inline bool isPrefixedOrGrouping(const Option *O) {
139 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
142 // getOptionPred - Check to see if there are any options that satisfy the
143 // specified predicate with names that are the prefixes in Name. This is
144 // checked by progressively stripping characters off of the name, checking to
145 // see if there options that satisfy the predicate. If we find one, return it,
146 // otherwise return null.
148 static Option *getOptionPred(std::string Name, unsigned &Length,
149 bool (*Pred)(const Option*)) {
151 Option *Op = getOption(Name);
152 if (Op && Pred(Op)) {
153 Length = Name.length();
157 if (Name.size() == 1) return 0;
159 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
160 Op = getOption(Name);
162 // Loop while we haven't found an option and Name still has at least two
163 // characters in it (so that the next iteration will not be the empty
165 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
167 if (Op && Pred(Op)) {
168 Length = Name.length();
169 return Op; // Found one!
171 return 0; // No option found!
174 static bool RequiresValue(const Option *O) {
175 return O->getNumOccurrencesFlag() == cl::Required ||
176 O->getNumOccurrencesFlag() == cl::OneOrMore;
179 static bool EatsUnboundedNumberOfValues(const Option *O) {
180 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
181 O->getNumOccurrencesFlag() == cl::OneOrMore;
184 /// ParseCStringVector - Break INPUT up wherever one or more
185 /// whitespace characters are found, and store the resulting tokens in
186 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
187 /// using strdup (), so it is the caller's responsibility to free ()
190 static void ParseCStringVector (std::vector<char *> &output,
192 // Characters which will be treated as token separators:
193 static const char *delims = " \v\f\t\r\n";
195 std::string work (input);
196 // Skip past any delims at head of input string.
197 size_t pos = work.find_first_not_of (delims);
198 // If the string consists entirely of delims, then exit early.
199 if (pos == std::string::npos) return;
200 // Otherwise, jump forward to beginning of first word.
201 work = work.substr (pos);
202 // Find position of first delimiter.
203 pos = work.find_first_of (delims);
205 while (!work.empty() && pos != std::string::npos) {
206 // Everything from 0 to POS is the next word to copy.
207 output.push_back (strdup (work.substr (0,pos).c_str ()));
208 // Is there another word in the string?
209 size_t nextpos = work.find_first_not_of (delims, pos + 1);
210 if (nextpos != std::string::npos) {
211 // Yes? Then remove delims from beginning ...
212 work = work.substr (work.find_first_not_of (delims, pos + 1));
213 // and find the end of the word.
214 pos = work.find_first_of (delims);
216 // No? (Remainder of string is delims.) End the loop.
218 pos = std::string::npos;
222 // If `input' ended with non-delim char, then we'll get here with
223 // the last word of `input' in `work'; copy it now.
224 if (!work.empty ()) {
225 output.push_back (strdup (work.c_str ()));
229 /// ParseEnvironmentOptions - An alternative entry point to the
230 /// CommandLine library, which allows you to read the program's name
231 /// from the caller (as PROGNAME) and its command-line arguments from
232 /// an environment variable (whose name is given in ENVVAR).
234 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
235 const char *Overview) {
237 assert(progName && "Program name not specified");
238 assert(envVar && "Environment variable name missing");
240 // Get the environment variable they want us to parse options out of.
241 const char *envValue = getenv (envVar);
245 // Get program's "name", which we wouldn't know without the caller
247 std::vector<char *> newArgv;
248 newArgv.push_back (strdup (progName));
250 // Parse the value of the environment variable into a "command line"
251 // and hand it off to ParseCommandLineOptions().
252 ParseCStringVector (newArgv, envValue);
253 int newArgc = newArgv.size ();
254 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
256 // Free all the strdup()ed strings.
257 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
263 /// LookupOption - Lookup the option specified by the specified option on the
264 /// command line. If there is a value specified (after an equal sign) return
266 static Option *LookupOption(const char *&Arg, const char *&Value) {
267 while (*Arg == '-') ++Arg; // Eat leading dashes
269 const char *ArgEnd = Arg;
270 while (*ArgEnd && *ArgEnd != '=')
271 ++ArgEnd; // Scan till end of argument name.
273 if (*ArgEnd == '=') // If we have an equals sign...
274 Value = ArgEnd+1; // Get the value, not the equals
277 if (*Arg == 0) return 0;
279 // Look up the option.
280 std::map<std::string, Option*> &Opts = getOpts();
281 std::map<std::string, Option*>::iterator I =
282 Opts.find(std::string(Arg, ArgEnd));
283 return (I != Opts.end()) ? I->second : 0;
286 void cl::ParseCommandLineOptions(int &argc, char **argv,
287 const char *Overview) {
288 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
289 "No options specified, or ParseCommandLineOptions called more"
291 ProgramName = argv[0]; // Save this away safe and snug
292 ProgramOverview = Overview;
293 bool ErrorParsing = false;
295 std::map<std::string, Option*> &Opts = getOpts();
296 std::vector<Option*> &PositionalOpts = getPositionalOpts();
298 // Check out the positional arguments to collect information about them.
299 unsigned NumPositionalRequired = 0;
301 // Determine whether or not there are an unlimited number of positionals
302 bool HasUnlimitedPositionals = false;
304 Option *ConsumeAfterOpt = 0;
305 if (!PositionalOpts.empty()) {
306 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
307 assert(PositionalOpts.size() > 1 &&
308 "Cannot specify cl::ConsumeAfter without a positional argument!");
309 ConsumeAfterOpt = PositionalOpts[0];
312 // Calculate how many positional values are _required_.
313 bool UnboundedFound = false;
314 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
316 Option *Opt = PositionalOpts[i];
317 if (RequiresValue(Opt))
318 ++NumPositionalRequired;
319 else if (ConsumeAfterOpt) {
320 // ConsumeAfter cannot be combined with "optional" positional options
321 // unless there is only one positional argument...
322 if (PositionalOpts.size() > 2)
324 Opt->error(" error - this positional option will never be matched, "
325 "because it does not Require a value, and a "
326 "cl::ConsumeAfter option is active!");
327 } else if (UnboundedFound && !Opt->ArgStr[0]) {
328 // This option does not "require" a value... Make sure this option is
329 // not specified after an option that eats all extra arguments, or this
330 // one will never get any!
332 ErrorParsing |= Opt->error(" error - option can never match, because "
333 "another positional argument will match an "
334 "unbounded number of values, and this option"
335 " does not require a value!");
337 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
339 if (Opt->getNumOccurrencesFlag() == cl::ZeroOrMore
340 || Opt->getNumOccurrencesFlag() == cl::OneOrMore)
341 HasUnlimitedPositionals = true;
345 // PositionalVals - A vector of "positional" arguments we accumulate into
346 // the process at the end...
348 std::vector<std::pair<std::string,unsigned> > PositionalVals;
350 // If the program has named positional arguments, and the name has been run
351 // across, keep track of which positional argument was named. Otherwise put
352 // the positional args into the PositionalVals list...
353 Option *ActivePositionalArg = 0;
355 // Loop over all of the arguments... processing them.
356 bool DashDashFound = false; // Have we read '--'?
357 for (int i = 1; i < argc; ++i) {
359 const char *Value = 0;
360 const char *ArgName = "";
362 // Check to see if this is a positional argument. This argument is
363 // considered to be positional if it doesn't start with '-', if it is "-"
364 // itself, or if we have seen "--" already.
366 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
367 // Positional argument!
368 if (ActivePositionalArg) {
369 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
370 continue; // We are done!
371 } else if (!PositionalOpts.empty()) {
372 PositionalVals.push_back(std::make_pair(argv[i],i));
374 // All of the positional arguments have been fulfulled, give the rest to
375 // the consume after option... if it's specified...
377 if (PositionalVals.size() >= NumPositionalRequired &&
378 ConsumeAfterOpt != 0) {
379 for (++i; i < argc; ++i)
380 PositionalVals.push_back(std::make_pair(argv[i],i));
381 break; // Handle outside of the argument processing loop...
384 // Delay processing positional arguments until the end...
387 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
389 DashDashFound = true; // This is the mythical "--"?
390 continue; // Don't try to process it as an argument itself.
391 } else if (ActivePositionalArg &&
392 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
393 // If there is a positional argument eating options, check to see if this
394 // option is another positional argument. If so, treat it as an argument,
395 // otherwise feed it to the eating positional.
397 Handler = LookupOption(ArgName, Value);
398 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
399 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
400 continue; // We are done!
403 } else { // We start with a '-', must be an argument...
405 Handler = LookupOption(ArgName, Value);
407 // Check to see if this "option" is really a prefixed or grouped argument.
409 std::string RealName(ArgName);
410 if (RealName.size() > 1) {
412 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
414 // If the option is a prefixed option, then the value is simply the
415 // rest of the name... so fall through to later processing, by
416 // setting up the argument name flags and value fields.
418 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
419 Value = ArgName+Length;
420 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
421 Opts.find(std::string(ArgName, Value))->second == PGOpt);
424 // This must be a grouped option... handle them now.
425 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
428 // Move current arg name out of RealName into RealArgName...
429 std::string RealArgName(RealName.begin(),
430 RealName.begin() + Length);
431 RealName.erase(RealName.begin(), RealName.begin() + Length);
433 // Because ValueRequired is an invalid flag for grouped arguments,
434 // we don't need to pass argc/argv in...
436 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
437 "Option can not be cl::Grouping AND cl::ValueRequired!");
439 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
442 // Get the next grouping option...
443 PGOpt = getOptionPred(RealName, Length, isGrouping);
444 } while (PGOpt && Length != RealName.size());
446 Handler = PGOpt; // Ate all of the options.
453 std::cerr << ProgramName << ": Unknown command line argument '" << argv[i]
454 << "'. Try: '" << argv[0] << " --help'\n";
459 // Check to see if this option accepts a comma separated list of values. If
460 // it does, we have to split up the value into multiple values...
461 if (Value && Handler->getMiscFlags() & CommaSeparated) {
462 std::string Val(Value);
463 std::string::size_type Pos = Val.find(',');
465 while (Pos != std::string::npos) {
466 // Process the portion before the comma...
467 ErrorParsing |= ProvideOption(Handler, ArgName,
468 std::string(Val.begin(),
469 Val.begin()+Pos).c_str(),
471 // Erase the portion before the comma, AND the comma...
472 Val.erase(Val.begin(), Val.begin()+Pos+1);
473 Value += Pos+1; // Increment the original value pointer as well...
475 // Check for another comma...
480 // If this is a named positional argument, just remember that it is the
482 if (Handler->getFormattingFlag() == cl::Positional)
483 ActivePositionalArg = Handler;
485 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
488 // Check and handle positional arguments now...
489 if (NumPositionalRequired > PositionalVals.size()) {
490 std::cerr << ProgramName
491 << ": Not enough positional command line arguments specified!\n"
492 << "Must specify at least " << NumPositionalRequired
493 << " positional arguments: See: " << argv[0] << " --help\n";
495 } else if (!HasUnlimitedPositionals
496 && PositionalVals.size() > PositionalOpts.size()) {
497 std::cerr << ProgramName
498 << ": Too many positional arguments specified!\n"
499 << "Can specify at most " << PositionalOpts.size()
500 << " positional arguments: See: " << argv[0] << " --help\n";
503 } else if (ConsumeAfterOpt == 0) {
504 // Positional args have already been handled if ConsumeAfter is specified...
505 unsigned ValNo = 0, NumVals = PositionalVals.size();
506 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
507 if (RequiresValue(PositionalOpts[i])) {
508 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
509 PositionalVals[ValNo].second);
511 --NumPositionalRequired; // We fulfilled our duty...
514 // If we _can_ give this option more arguments, do so now, as long as we
515 // do not give it values that others need. 'Done' controls whether the
516 // option even _WANTS_ any more.
518 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
519 while (NumVals-ValNo > NumPositionalRequired && !Done) {
520 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
522 Done = true; // Optional arguments want _at most_ one value
524 case cl::ZeroOrMore: // Zero or more will take all they can get...
525 case cl::OneOrMore: // One or more will take all they can get...
526 ProvidePositionalOption(PositionalOpts[i],
527 PositionalVals[ValNo].first,
528 PositionalVals[ValNo].second);
532 assert(0 && "Internal error, unexpected NumOccurrences flag in "
533 "positional argument processing!");
538 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
540 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
541 if (RequiresValue(PositionalOpts[j])) {
542 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
543 PositionalVals[ValNo].first,
544 PositionalVals[ValNo].second);
548 // Handle the case where there is just one positional option, and it's
549 // optional. In this case, we want to give JUST THE FIRST option to the
550 // positional option and keep the rest for the consume after. The above
551 // loop would have assigned no values to positional options in this case.
553 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
554 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
555 PositionalVals[ValNo].first,
556 PositionalVals[ValNo].second);
560 // Handle over all of the rest of the arguments to the
561 // cl::ConsumeAfter command line option...
562 for (; ValNo != PositionalVals.size(); ++ValNo)
563 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
564 PositionalVals[ValNo].first,
565 PositionalVals[ValNo].second);
568 // Loop over args and make sure all required args are specified!
569 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
570 E = Opts.end(); I != E; ++I) {
571 switch (I->second->getNumOccurrencesFlag()) {
574 if (I->second->getNumOccurrences() == 0) {
575 I->second->error(" must be specified at least once!");
584 // Free all of the memory allocated to the map. Command line options may only
585 // be processed once!
587 PositionalOpts.clear();
590 // If we had an error processing our arguments, don't let the program execute
591 if (ErrorParsing) exit(1);
594 //===----------------------------------------------------------------------===//
595 // Option Base class implementation
598 bool Option::error(std::string Message, const char *ArgName) {
599 if (ArgName == 0) ArgName = ArgStr;
601 std::cerr << HelpStr; // Be nice for positional arguments
603 std::cerr << ProgramName << ": for the -" << ArgName;
604 std::cerr << " option: " << Message << "\n";
608 bool Option::addOccurrence(unsigned pos, const char *ArgName,
609 const std::string &Value) {
610 NumOccurrences++; // Increment the number of times we have been seen
612 switch (getNumOccurrencesFlag()) {
614 if (NumOccurrences > 1)
615 return error(": may only occur zero or one times!", ArgName);
618 if (NumOccurrences > 1)
619 return error(": must occur exactly one time!", ArgName);
623 case ConsumeAfter: break;
624 default: return error(": bad num occurrences flag value!");
627 return handleOccurrence(pos, ArgName, Value);
630 // addArgument - Tell the system that this Option subclass will handle all
631 // occurrences of -ArgStr on the command line.
633 void Option::addArgument(const char *ArgStr) {
635 AddArgument(ArgStr, this);
637 if (getFormattingFlag() == Positional)
638 getPositionalOpts().push_back(this);
639 else if (getNumOccurrencesFlag() == ConsumeAfter) {
640 if (!getPositionalOpts().empty() &&
641 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
642 error("Cannot specify more than one option with cl::ConsumeAfter!");
643 getPositionalOpts().insert(getPositionalOpts().begin(), this);
647 void Option::removeArgument(const char *ArgStr) {
649 RemoveArgument(ArgStr, this);
651 if (getFormattingFlag() == Positional) {
652 std::vector<Option*>::iterator I =
653 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
654 assert(I != getPositionalOpts().end() && "Arg not registered!");
655 getPositionalOpts().erase(I);
656 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
657 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
658 "Arg not registered correctly!");
659 getPositionalOpts().erase(getPositionalOpts().begin());
664 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
665 // has been specified yet.
667 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
668 if (O.ValueStr[0] == 0) return DefaultMsg;
672 //===----------------------------------------------------------------------===//
673 // cl::alias class implementation
676 // Return the width of the option tag for printing...
677 unsigned alias::getOptionWidth() const {
678 return std::strlen(ArgStr)+6;
681 // Print out the option for the alias...
682 void alias::printOptionInfo(unsigned GlobalWidth) const {
683 unsigned L = std::strlen(ArgStr);
684 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
690 //===----------------------------------------------------------------------===//
691 // Parser Implementation code...
694 // basic_parser implementation
697 // Return the width of the option tag for printing...
698 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
699 unsigned Len = std::strlen(O.ArgStr);
700 if (const char *ValName = getValueName())
701 Len += std::strlen(getValueStr(O, ValName))+3;
706 // printOptionInfo - Print out information about this option. The
707 // to-be-maintained width is specified.
709 void basic_parser_impl::printOptionInfo(const Option &O,
710 unsigned GlobalWidth) const {
711 std::cerr << " -" << O.ArgStr;
713 if (const char *ValName = getValueName())
714 std::cerr << "=<" << getValueStr(O, ValName) << ">";
716 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
717 << O.HelpStr << "\n";
723 // parser<bool> implementation
725 bool parser<bool>::parse(Option &O, const char *ArgName,
726 const std::string &Arg, bool &Value) {
727 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
730 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
733 return O.error(": '" + Arg +
734 "' is invalid value for boolean argument! Try 0 or 1");
739 // parser<int> implementation
741 bool parser<int>::parse(Option &O, const char *ArgName,
742 const std::string &Arg, int &Value) {
744 Value = (int)strtol(Arg.c_str(), &End, 0);
746 return O.error(": '" + Arg + "' value invalid for integer argument!");
750 // parser<unsigned> implementation
752 bool parser<unsigned>::parse(Option &O, const char *ArgName,
753 const std::string &Arg, unsigned &Value) {
756 unsigned long V = strtoul(Arg.c_str(), &End, 0);
758 if (((V == ULONG_MAX) && (errno == ERANGE))
761 return O.error(": '" + Arg + "' value invalid for uint argument!");
765 // parser<double>/parser<float> implementation
767 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
768 const char *ArgStart = Arg.c_str();
770 Value = strtod(ArgStart, &End);
772 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
776 bool parser<double>::parse(Option &O, const char *AN,
777 const std::string &Arg, double &Val) {
778 return parseDouble(O, Arg, Val);
781 bool parser<float>::parse(Option &O, const char *AN,
782 const std::string &Arg, float &Val) {
784 if (parseDouble(O, Arg, dVal))
792 // generic_parser_base implementation
795 // findOption - Return the option number corresponding to the specified
796 // argument string. If the option is not found, getNumOptions() is returned.
798 unsigned generic_parser_base::findOption(const char *Name) {
799 unsigned i = 0, e = getNumOptions();
803 if (getOption(i) == N)
811 // Return the width of the option tag for printing...
812 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
814 unsigned Size = std::strlen(O.ArgStr)+6;
815 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
816 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
819 unsigned BaseSize = 0;
820 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
821 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
826 // printOptionInfo - Print out information about this option. The
827 // to-be-maintained width is specified.
829 void generic_parser_base::printOptionInfo(const Option &O,
830 unsigned GlobalWidth) const {
832 unsigned L = std::strlen(O.ArgStr);
833 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
834 << " - " << O.HelpStr << "\n";
836 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
837 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
838 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
839 << " - " << getDescription(i) << "\n";
843 std::cerr << " " << O.HelpStr << "\n";
844 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
845 unsigned L = std::strlen(getOption(i));
846 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
847 << " - " << getDescription(i) << "\n";
853 //===----------------------------------------------------------------------===//
854 // --help and --help-hidden option implementation
861 const Option *EmptyArg;
862 const bool ShowHidden;
864 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
865 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
866 return OptPair.second->getOptionHiddenFlag() >= Hidden;
868 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
869 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
873 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
877 void operator=(bool Value) {
878 if (Value == false) return;
880 // Copy Options into a vector so we can sort them as we like...
881 std::vector<std::pair<std::string, Option*> > Options;
882 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
884 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
885 Options.erase(std::remove_if(Options.begin(), Options.end(),
886 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
889 // Eliminate duplicate entries in table (from enum flags options, f.e.)
890 { // Give OptionSet a scope
891 std::set<Option*> OptionSet;
892 for (unsigned i = 0; i != Options.size(); ++i)
893 if (OptionSet.count(Options[i].second) == 0)
894 OptionSet.insert(Options[i].second); // Add new entry to set
896 Options.erase(Options.begin()+i--); // Erase duplicate
900 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
902 std::cerr << "USAGE: " << ProgramName << " [options]";
904 // Print out the positional options...
905 std::vector<Option*> &PosOpts = getPositionalOpts();
906 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
907 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
910 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
911 if (PosOpts[i]->ArgStr[0])
912 std::cerr << " --" << PosOpts[i]->ArgStr;
913 std::cerr << " " << PosOpts[i]->HelpStr;
916 // Print the consume after option info if it exists...
917 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
921 // Compute the maximum argument length...
923 for (unsigned i = 0, e = Options.size(); i != e; ++i)
924 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
926 std::cerr << "OPTIONS:\n";
927 for (unsigned i = 0, e = Options.size(); i != e; ++i)
928 Options[i].second->printOptionInfo(MaxArgLen);
930 // Print any extra help the user has declared.
931 for (std::vector<const char *>::iterator I = MoreHelp().begin(),
932 E = MoreHelp().end(); I != E; ++I)
936 // Halt the program since help information was printed
937 getOpts().clear(); // Don't bother making option dtors remove from map.
942 class VersionPrinter {
944 void operator=(bool OptionWasSpecified) {
945 if (OptionWasSpecified) {
946 std::cerr << "Low Level Virtual Machine (" << PACKAGE_NAME << ") "
947 << PACKAGE_VERSION << " (see http://llvm.cs.uiuc.edu/)\n";
948 getOpts().clear(); // Don't bother making option dtors remove from map.
955 // Define the two HelpPrinter instances that are used to print out help, or
958 HelpPrinter NormalPrinter(false);
959 HelpPrinter HiddenPrinter(true);
961 cl::opt<HelpPrinter, true, parser<bool> >
962 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
963 cl::location(NormalPrinter), cl::ValueDisallowed);
965 cl::opt<HelpPrinter, true, parser<bool> >
966 HHOp("help-hidden", cl::desc("Display all available options"),
967 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
969 // Define the --version option that prints out the LLVM version for the tool
970 VersionPrinter VersionPrinterInstance;
971 cl::opt<VersionPrinter, true, parser<bool> >
972 VersOp("version", cl::desc("Display the version of this program"),
973 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
976 } // End anonymous namespace
978 // Utility function for printing the help message.
979 void cl::PrintHelpMessage() {
980 // This looks weird, but it actually prints the help message. The
981 // NormalPrinter variable is a HelpPrinter and the help gets printed when
982 // its operator= is invoked. That's because the "normal" usages of the
983 // help printer is to be assigned true/false depending on whether the
984 // --help option was given or not. Since we're circumventing that we have
985 // to make it look like --help was given, so we assign true.
986 NormalPrinter = true;