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"
33 // Globals for name and overview of program
34 static const char *ProgramName = "<unknown>";
35 static const char *ProgramOverview = 0;
37 // This collects additional help to be printed.
38 static std::vector<const char*> &MoreHelp() {
39 static std::vector<const char*> moreHelp;
43 extrahelp::extrahelp(const char* Help)
45 MoreHelp().push_back(Help);
48 //===----------------------------------------------------------------------===//
49 // Basic, shared command line option processing machinery...
52 // Return the global command line option vector. Making it a function scoped
53 // static ensures that it will be initialized correctly before its first use.
55 static std::map<std::string, Option*> &getOpts() {
56 static std::map<std::string, Option*> CommandLineOptions;
57 return CommandLineOptions;
60 static Option *getOption(const std::string &Str) {
61 std::map<std::string,Option*>::iterator I = getOpts().find(Str);
62 return I != getOpts().end() ? I->second : 0;
65 static std::vector<Option*> &getPositionalOpts() {
66 static std::vector<Option*> Positional;
70 static void AddArgument(const char *ArgName, Option *Opt) {
71 if (getOption(ArgName)) {
72 std::cerr << ProgramName << ": CommandLine Error: Argument '"
73 << ArgName << "' defined more than once!\n";
75 // Add argument to the argument map!
76 getOpts()[ArgName] = Opt;
80 // RemoveArgument - It's possible that the argument is no longer in the map if
81 // options have already been processed and the map has been deleted!
83 static void RemoveArgument(const char *ArgName, Option *Opt) {
84 if(getOpts().empty()) return;
87 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
88 // If we pass ArgName directly into getOption here.
89 std::string Tmp = ArgName;
90 assert(getOption(Tmp) == Opt && "Arg not in map!");
92 getOpts().erase(ArgName);
95 static inline bool ProvideOption(Option *Handler, const char *ArgName,
96 const char *Value, int argc, char **argv,
98 // Enforce value requirements
99 switch (Handler->getValueExpectedFlag()) {
101 if (Value == 0) { // No value specified?
102 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
105 return Handler->error(" requires a value!");
109 case ValueDisallowed:
111 return Handler->error(" does not allow a value! '" +
112 std::string(Value) + "' specified.");
117 std::cerr << ProgramName
118 << ": Bad ValueMask flag! CommandLine usage error:"
119 << Handler->getValueExpectedFlag() << "\n";
124 // Run the handler now!
125 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
128 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
131 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
135 // Option predicates...
136 static inline bool isGrouping(const Option *O) {
137 return O->getFormattingFlag() == cl::Grouping;
139 static inline bool isPrefixedOrGrouping(const Option *O) {
140 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
143 // getOptionPred - Check to see if there are any options that satisfy the
144 // specified predicate with names that are the prefixes in Name. This is
145 // checked by progressively stripping characters off of the name, checking to
146 // see if there options that satisfy the predicate. If we find one, return it,
147 // otherwise return null.
149 static Option *getOptionPred(std::string Name, unsigned &Length,
150 bool (*Pred)(const Option*)) {
152 Option *Op = getOption(Name);
153 if (Op && Pred(Op)) {
154 Length = Name.length();
158 if (Name.size() == 1) return 0;
160 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
161 Op = getOption(Name);
163 // Loop while we haven't found an option and Name still has at least two
164 // characters in it (so that the next iteration will not be the empty
166 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
168 if (Op && Pred(Op)) {
169 Length = Name.length();
170 return Op; // Found one!
172 return 0; // No option found!
175 static bool RequiresValue(const Option *O) {
176 return O->getNumOccurrencesFlag() == cl::Required ||
177 O->getNumOccurrencesFlag() == cl::OneOrMore;
180 static bool EatsUnboundedNumberOfValues(const Option *O) {
181 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
182 O->getNumOccurrencesFlag() == cl::OneOrMore;
185 /// ParseCStringVector - Break INPUT up wherever one or more
186 /// whitespace characters are found, and store the resulting tokens in
187 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
188 /// using strdup (), so it is the caller's responsibility to free ()
191 static void ParseCStringVector (std::vector<char *> &output,
193 // Characters which will be treated as token separators:
194 static const char *delims = " \v\f\t\r\n";
196 std::string work (input);
197 // Skip past any delims at head of input string.
198 size_t pos = work.find_first_not_of (delims);
199 // If the string consists entirely of delims, then exit early.
200 if (pos == std::string::npos) return;
201 // Otherwise, jump forward to beginning of first word.
202 work = work.substr (pos);
203 // Find position of first delimiter.
204 pos = work.find_first_of (delims);
206 while (!work.empty() && pos != std::string::npos) {
207 // Everything from 0 to POS is the next word to copy.
208 output.push_back (strdup (work.substr (0,pos).c_str ()));
209 // Is there another word in the string?
210 size_t nextpos = work.find_first_not_of (delims, pos + 1);
211 if (nextpos != std::string::npos) {
212 // Yes? Then remove delims from beginning ...
213 work = work.substr (work.find_first_not_of (delims, pos + 1));
214 // and find the end of the word.
215 pos = work.find_first_of (delims);
217 // No? (Remainder of string is delims.) End the loop.
219 pos = std::string::npos;
223 // If `input' ended with non-delim char, then we'll get here with
224 // the last word of `input' in `work'; copy it now.
225 if (!work.empty ()) {
226 output.push_back (strdup (work.c_str ()));
230 /// ParseEnvironmentOptions - An alternative entry point to the
231 /// CommandLine library, which allows you to read the program's name
232 /// from the caller (as PROGNAME) and its command-line arguments from
233 /// an environment variable (whose name is given in ENVVAR).
235 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
236 const char *Overview) {
238 assert(progName && "Program name not specified");
239 assert(envVar && "Environment variable name missing");
241 // Get the environment variable they want us to parse options out of.
242 const char *envValue = getenv (envVar);
246 // Get program's "name", which we wouldn't know without the caller
248 std::vector<char *> newArgv;
249 newArgv.push_back (strdup (progName));
251 // Parse the value of the environment variable into a "command line"
252 // and hand it off to ParseCommandLineOptions().
253 ParseCStringVector (newArgv, envValue);
254 int newArgc = newArgv.size ();
255 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
257 // Free all the strdup()ed strings.
258 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
264 /// LookupOption - Lookup the option specified by the specified option on the
265 /// command line. If there is a value specified (after an equal sign) return
267 static Option *LookupOption(const char *&Arg, const char *&Value) {
268 while (*Arg == '-') ++Arg; // Eat leading dashes
270 const char *ArgEnd = Arg;
271 while (*ArgEnd && *ArgEnd != '=')
272 ++ArgEnd; // Scan till end of argument name.
274 if (*ArgEnd == '=') // If we have an equals sign...
275 Value = ArgEnd+1; // Get the value, not the equals
278 if (*Arg == 0) return 0;
280 // Look up the option.
281 std::map<std::string, Option*> &Opts = getOpts();
282 std::map<std::string, Option*>::iterator I =
283 Opts.find(std::string(Arg, ArgEnd));
284 return (I != Opts.end()) ? I->second : 0;
287 void cl::ParseCommandLineOptions(int &argc, char **argv,
288 const char *Overview) {
289 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
290 "No options specified, or ParseCommandLineOptions called more"
292 ProgramName = argv[0]; // Save this away safe and snug
293 ProgramOverview = Overview;
294 bool ErrorParsing = false;
296 std::map<std::string, Option*> &Opts = getOpts();
297 std::vector<Option*> &PositionalOpts = getPositionalOpts();
299 // Check out the positional arguments to collect information about them.
300 unsigned NumPositionalRequired = 0;
302 // Determine whether or not there are an unlimited number of positionals
303 bool HasUnlimitedPositionals = false;
305 Option *ConsumeAfterOpt = 0;
306 if (!PositionalOpts.empty()) {
307 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
308 assert(PositionalOpts.size() > 1 &&
309 "Cannot specify cl::ConsumeAfter without a positional argument!");
310 ConsumeAfterOpt = PositionalOpts[0];
313 // Calculate how many positional values are _required_.
314 bool UnboundedFound = false;
315 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
317 Option *Opt = PositionalOpts[i];
318 if (RequiresValue(Opt))
319 ++NumPositionalRequired;
320 else if (ConsumeAfterOpt) {
321 // ConsumeAfter cannot be combined with "optional" positional options
322 // unless there is only one positional argument...
323 if (PositionalOpts.size() > 2)
325 Opt->error(" error - this positional option will never be matched, "
326 "because it does not Require a value, and a "
327 "cl::ConsumeAfter option is active!");
328 } else if (UnboundedFound && !Opt->ArgStr[0]) {
329 // This option does not "require" a value... Make sure this option is
330 // not specified after an option that eats all extra arguments, or this
331 // one will never get any!
333 ErrorParsing |= Opt->error(" error - option can never match, because "
334 "another positional argument will match an "
335 "unbounded number of values, and this option"
336 " does not require a value!");
338 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
340 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
343 // PositionalVals - A vector of "positional" arguments we accumulate into
344 // the process at the end...
346 std::vector<std::pair<std::string,unsigned> > PositionalVals;
348 // If the program has named positional arguments, and the name has been run
349 // across, keep track of which positional argument was named. Otherwise put
350 // the positional args into the PositionalVals list...
351 Option *ActivePositionalArg = 0;
353 // Loop over all of the arguments... processing them.
354 bool DashDashFound = false; // Have we read '--'?
355 for (int i = 1; i < argc; ++i) {
357 const char *Value = 0;
358 const char *ArgName = "";
360 // Check to see if this is a positional argument. This argument is
361 // considered to be positional if it doesn't start with '-', if it is "-"
362 // itself, or if we have seen "--" already.
364 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
365 // Positional argument!
366 if (ActivePositionalArg) {
367 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
368 continue; // We are done!
369 } else if (!PositionalOpts.empty()) {
370 PositionalVals.push_back(std::make_pair(argv[i],i));
372 // All of the positional arguments have been fulfulled, give the rest to
373 // the consume after option... if it's specified...
375 if (PositionalVals.size() >= NumPositionalRequired &&
376 ConsumeAfterOpt != 0) {
377 for (++i; i < argc; ++i)
378 PositionalVals.push_back(std::make_pair(argv[i],i));
379 break; // Handle outside of the argument processing loop...
382 // Delay processing positional arguments until the end...
385 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
387 DashDashFound = true; // This is the mythical "--"?
388 continue; // Don't try to process it as an argument itself.
389 } else if (ActivePositionalArg &&
390 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
391 // If there is a positional argument eating options, check to see if this
392 // option is another positional argument. If so, treat it as an argument,
393 // otherwise feed it to the eating positional.
395 Handler = LookupOption(ArgName, Value);
396 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
397 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
398 continue; // We are done!
401 } else { // We start with a '-', must be an argument...
403 Handler = LookupOption(ArgName, Value);
405 // Check to see if this "option" is really a prefixed or grouped argument.
407 std::string RealName(ArgName);
408 if (RealName.size() > 1) {
410 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
412 // If the option is a prefixed option, then the value is simply the
413 // rest of the name... so fall through to later processing, by
414 // setting up the argument name flags and value fields.
416 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
417 Value = ArgName+Length;
418 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
419 Opts.find(std::string(ArgName, Value))->second == PGOpt);
422 // This must be a grouped option... handle them now.
423 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
426 // Move current arg name out of RealName into RealArgName...
427 std::string RealArgName(RealName.begin(),
428 RealName.begin() + Length);
429 RealName.erase(RealName.begin(), RealName.begin() + Length);
431 // Because ValueRequired is an invalid flag for grouped arguments,
432 // we don't need to pass argc/argv in...
434 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
435 "Option can not be cl::Grouping AND cl::ValueRequired!");
437 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
440 // Get the next grouping option...
441 PGOpt = getOptionPred(RealName, Length, isGrouping);
442 } while (PGOpt && Length != RealName.size());
444 Handler = PGOpt; // Ate all of the options.
452 std::cerr << ProgramName << ": Unknown command line argument '"
453 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
455 std::cerr << "Unknown command line argument '" << argv[i] << "'.\n";
460 // Check to see if this option accepts a comma separated list of values. If
461 // it does, we have to split up the value into multiple values...
462 if (Value && Handler->getMiscFlags() & CommaSeparated) {
463 std::string Val(Value);
464 std::string::size_type Pos = Val.find(',');
466 while (Pos != std::string::npos) {
467 // Process the portion before the comma...
468 ErrorParsing |= ProvideOption(Handler, ArgName,
469 std::string(Val.begin(),
470 Val.begin()+Pos).c_str(),
472 // Erase the portion before the comma, AND the comma...
473 Val.erase(Val.begin(), Val.begin()+Pos+1);
474 Value += Pos+1; // Increment the original value pointer as well...
476 // Check for another comma...
481 // If this is a named positional argument, just remember that it is the
483 if (Handler->getFormattingFlag() == cl::Positional)
484 ActivePositionalArg = Handler;
486 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
489 // Check and handle positional arguments now...
490 if (NumPositionalRequired > PositionalVals.size()) {
492 std::cerr << ProgramName
493 << ": Not enough positional command line arguments specified!\n"
494 << "Must specify at least " << NumPositionalRequired
495 << " positional arguments: See: " << argv[0] << " --help\n";
497 std::cerr << "Not enough positional command line arguments specified!\n"
498 << "Must specify at least " << NumPositionalRequired
499 << " positional arguments.";
502 } else if (!HasUnlimitedPositionals
503 && PositionalVals.size() > PositionalOpts.size()) {
505 std::cerr << ProgramName
506 << ": Too many positional arguments specified!\n"
507 << "Can specify at most " << PositionalOpts.size()
508 << " positional arguments: See: " << argv[0] << " --help\n";
510 std::cerr << "Too many positional arguments specified!\n"
511 << "Can specify at most " << PositionalOpts.size()
512 << " positional arguments.\n";
515 } else if (ConsumeAfterOpt == 0) {
516 // Positional args have already been handled if ConsumeAfter is specified...
517 unsigned ValNo = 0, NumVals = PositionalVals.size();
518 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
519 if (RequiresValue(PositionalOpts[i])) {
520 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
521 PositionalVals[ValNo].second);
523 --NumPositionalRequired; // We fulfilled our duty...
526 // If we _can_ give this option more arguments, do so now, as long as we
527 // do not give it values that others need. 'Done' controls whether the
528 // option even _WANTS_ any more.
530 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
531 while (NumVals-ValNo > NumPositionalRequired && !Done) {
532 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
534 Done = true; // Optional arguments want _at most_ one value
536 case cl::ZeroOrMore: // Zero or more will take all they can get...
537 case cl::OneOrMore: // One or more will take all they can get...
538 ProvidePositionalOption(PositionalOpts[i],
539 PositionalVals[ValNo].first,
540 PositionalVals[ValNo].second);
544 assert(0 && "Internal error, unexpected NumOccurrences flag in "
545 "positional argument processing!");
550 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
552 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
553 if (RequiresValue(PositionalOpts[j])) {
554 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
555 PositionalVals[ValNo].first,
556 PositionalVals[ValNo].second);
560 // Handle the case where there is just one positional option, and it's
561 // optional. In this case, we want to give JUST THE FIRST option to the
562 // positional option and keep the rest for the consume after. The above
563 // loop would have assigned no values to positional options in this case.
565 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
566 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
567 PositionalVals[ValNo].first,
568 PositionalVals[ValNo].second);
572 // Handle over all of the rest of the arguments to the
573 // cl::ConsumeAfter command line option...
574 for (; ValNo != PositionalVals.size(); ++ValNo)
575 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
576 PositionalVals[ValNo].first,
577 PositionalVals[ValNo].second);
580 // Loop over args and make sure all required args are specified!
581 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
582 E = Opts.end(); I != E; ++I) {
583 switch (I->second->getNumOccurrencesFlag()) {
586 if (I->second->getNumOccurrences() == 0) {
587 I->second->error(" must be specified at least once!");
596 // Free all of the memory allocated to the map. Command line options may only
597 // be processed once!
599 PositionalOpts.clear();
602 // If we had an error processing our arguments, don't let the program execute
603 if (ErrorParsing) exit(1);
606 //===----------------------------------------------------------------------===//
607 // Option Base class implementation
610 bool Option::error(std::string Message, const char *ArgName) {
611 if (ArgName == 0) ArgName = ArgStr;
613 std::cerr << HelpStr; // Be nice for positional arguments
615 std::cerr << ProgramName << ": for the -" << ArgName;
616 std::cerr << " option: " << Message << "\n";
620 bool Option::addOccurrence(unsigned pos, const char *ArgName,
621 const std::string &Value) {
622 NumOccurrences++; // Increment the number of times we have been seen
624 switch (getNumOccurrencesFlag()) {
626 if (NumOccurrences > 1)
627 return error(": may only occur zero or one times!", ArgName);
630 if (NumOccurrences > 1)
631 return error(": must occur exactly one time!", ArgName);
635 case ConsumeAfter: break;
636 default: return error(": bad num occurrences flag value!");
639 return handleOccurrence(pos, ArgName, Value);
642 // addArgument - Tell the system that this Option subclass will handle all
643 // occurrences of -ArgStr on the command line.
645 void Option::addArgument(const char *ArgStr) {
647 AddArgument(ArgStr, this);
649 if (getFormattingFlag() == Positional)
650 getPositionalOpts().push_back(this);
651 else if (getNumOccurrencesFlag() == ConsumeAfter) {
652 if (!getPositionalOpts().empty() &&
653 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
654 error("Cannot specify more than one option with cl::ConsumeAfter!");
655 getPositionalOpts().insert(getPositionalOpts().begin(), this);
659 void Option::removeArgument(const char *ArgStr) {
661 RemoveArgument(ArgStr, this);
663 if (getFormattingFlag() == Positional) {
664 std::vector<Option*>::iterator I =
665 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
666 assert(I != getPositionalOpts().end() && "Arg not registered!");
667 getPositionalOpts().erase(I);
668 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
669 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
670 "Arg not registered correctly!");
671 getPositionalOpts().erase(getPositionalOpts().begin());
676 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
677 // has been specified yet.
679 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
680 if (O.ValueStr[0] == 0) return DefaultMsg;
684 //===----------------------------------------------------------------------===//
685 // cl::alias class implementation
688 // Return the width of the option tag for printing...
689 unsigned alias::getOptionWidth() const {
690 return std::strlen(ArgStr)+6;
693 // Print out the option for the alias...
694 void alias::printOptionInfo(unsigned GlobalWidth) const {
695 unsigned L = std::strlen(ArgStr);
696 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
702 //===----------------------------------------------------------------------===//
703 // Parser Implementation code...
706 // basic_parser implementation
709 // Return the width of the option tag for printing...
710 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
711 unsigned Len = std::strlen(O.ArgStr);
712 if (const char *ValName = getValueName())
713 Len += std::strlen(getValueStr(O, ValName))+3;
718 // printOptionInfo - Print out information about this option. The
719 // to-be-maintained width is specified.
721 void basic_parser_impl::printOptionInfo(const Option &O,
722 unsigned GlobalWidth) const {
723 std::cerr << " -" << O.ArgStr;
725 if (const char *ValName = getValueName())
726 std::cerr << "=<" << getValueStr(O, ValName) << ">";
728 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
729 << O.HelpStr << "\n";
735 // parser<bool> implementation
737 bool parser<bool>::parse(Option &O, const char *ArgName,
738 const std::string &Arg, bool &Value) {
739 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
742 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
745 return O.error(": '" + Arg +
746 "' is invalid value for boolean argument! Try 0 or 1");
751 // parser<int> implementation
753 bool parser<int>::parse(Option &O, const char *ArgName,
754 const std::string &Arg, int &Value) {
756 Value = (int)strtol(Arg.c_str(), &End, 0);
758 return O.error(": '" + Arg + "' value invalid for integer argument!");
762 // parser<unsigned> implementation
764 bool parser<unsigned>::parse(Option &O, const char *ArgName,
765 const std::string &Arg, unsigned &Value) {
768 unsigned long V = strtoul(Arg.c_str(), &End, 0);
770 if (((V == ULONG_MAX) && (errno == ERANGE))
773 return O.error(": '" + Arg + "' value invalid for uint argument!");
777 // parser<double>/parser<float> implementation
779 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
780 const char *ArgStart = Arg.c_str();
782 Value = strtod(ArgStart, &End);
784 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
788 bool parser<double>::parse(Option &O, const char *AN,
789 const std::string &Arg, double &Val) {
790 return parseDouble(O, Arg, Val);
793 bool parser<float>::parse(Option &O, const char *AN,
794 const std::string &Arg, float &Val) {
796 if (parseDouble(O, Arg, dVal))
804 // generic_parser_base implementation
807 // findOption - Return the option number corresponding to the specified
808 // argument string. If the option is not found, getNumOptions() is returned.
810 unsigned generic_parser_base::findOption(const char *Name) {
811 unsigned i = 0, e = getNumOptions();
815 if (getOption(i) == N)
823 // Return the width of the option tag for printing...
824 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
826 unsigned Size = std::strlen(O.ArgStr)+6;
827 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
828 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
831 unsigned BaseSize = 0;
832 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
833 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
838 // printOptionInfo - Print out information about this option. The
839 // to-be-maintained width is specified.
841 void generic_parser_base::printOptionInfo(const Option &O,
842 unsigned GlobalWidth) const {
844 unsigned L = std::strlen(O.ArgStr);
845 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
846 << " - " << O.HelpStr << "\n";
848 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
849 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
850 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
851 << " - " << getDescription(i) << "\n";
855 std::cerr << " " << O.HelpStr << "\n";
856 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
857 unsigned L = std::strlen(getOption(i));
858 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
859 << " - " << getDescription(i) << "\n";
865 //===----------------------------------------------------------------------===//
866 // --help and --help-hidden option implementation
873 const Option *EmptyArg;
874 const bool ShowHidden;
876 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
877 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
878 return OptPair.second->getOptionHiddenFlag() >= Hidden;
880 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
881 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
885 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
889 void operator=(bool Value) {
890 if (Value == false) return;
892 // Copy Options into a vector so we can sort them as we like...
893 std::vector<std::pair<std::string, Option*> > Options;
894 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
896 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
897 Options.erase(std::remove_if(Options.begin(), Options.end(),
898 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
901 // Eliminate duplicate entries in table (from enum flags options, f.e.)
902 { // Give OptionSet a scope
903 std::set<Option*> OptionSet;
904 for (unsigned i = 0; i != Options.size(); ++i)
905 if (OptionSet.count(Options[i].second) == 0)
906 OptionSet.insert(Options[i].second); // Add new entry to set
908 Options.erase(Options.begin()+i--); // Erase duplicate
912 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
914 std::cerr << "USAGE: " << ProgramName << " [options]";
916 // Print out the positional options...
917 std::vector<Option*> &PosOpts = getPositionalOpts();
918 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
919 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
922 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
923 if (PosOpts[i]->ArgStr[0])
924 std::cerr << " --" << PosOpts[i]->ArgStr;
925 std::cerr << " " << PosOpts[i]->HelpStr;
928 // Print the consume after option info if it exists...
929 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
933 // Compute the maximum argument length...
935 for (unsigned i = 0, e = Options.size(); i != e; ++i)
936 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
938 std::cerr << "OPTIONS:\n";
939 for (unsigned i = 0, e = Options.size(); i != e; ++i)
940 Options[i].second->printOptionInfo(MaxArgLen);
942 // Print any extra help the user has declared.
943 for (std::vector<const char *>::iterator I = MoreHelp().begin(),
944 E = MoreHelp().end(); I != E; ++I)
948 // Halt the program since help information was printed
949 getOpts().clear(); // Don't bother making option dtors remove from map.
954 class VersionPrinter {
956 void operator=(bool OptionWasSpecified) {
957 if (OptionWasSpecified) {
958 std::cerr << "Low Level Virtual Machine (" << PACKAGE_NAME << ") "
959 << PACKAGE_VERSION << " (see http://llvm.org/)";
961 std::cerr << " DEBUG BUILD\n";
965 getOpts().clear(); // Don't bother making option dtors remove from map.
972 // Define the two HelpPrinter instances that are used to print out help, or
975 HelpPrinter NormalPrinter(false);
976 HelpPrinter HiddenPrinter(true);
978 cl::opt<HelpPrinter, true, parser<bool> >
979 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
980 cl::location(NormalPrinter), cl::ValueDisallowed);
982 cl::opt<HelpPrinter, true, parser<bool> >
983 HHOp("help-hidden", cl::desc("Display all available options"),
984 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
986 // Define the --version option that prints out the LLVM version for the tool
987 VersionPrinter VersionPrinterInstance;
988 cl::opt<VersionPrinter, true, parser<bool> >
989 VersOp("version", cl::desc("Display the version of this program"),
990 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
993 } // End anonymous namespace
995 // Utility function for printing the help message.
996 void cl::PrintHelpMessage() {
997 // This looks weird, but it actually prints the help message. The
998 // NormalPrinter variable is a HelpPrinter and the help gets printed when
999 // its operator= is invoked. That's because the "normal" usages of the
1000 // help printer is to be assigned true/false depending on whether the
1001 // --help option was given or not. Since we're circumventing that we have
1002 // to make it look like --help was given, so we assign true.
1003 NormalPrinter = true;