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 //===----------------------------------------------------------------------===//
37 // Basic, shared command line option processing machinery...
40 // Return the global command line option vector. Making it a function scoped
41 // static ensures that it will be initialized correctly before its first use.
43 static std::map<std::string, Option*> *CommandLineOptions = 0;
44 static std::map<std::string, Option*> &getOpts() {
45 if (CommandLineOptions == 0)
46 CommandLineOptions = new std::map<std::string,Option*>();
47 return *CommandLineOptions;
50 static Option *getOption(const std::string &Str) {
51 if (CommandLineOptions == 0) return 0;
52 std::map<std::string,Option*>::iterator I = CommandLineOptions->find(Str);
53 return I != CommandLineOptions->end() ? I->second : 0;
56 static std::vector<Option*> &getPositionalOpts() {
57 static std::vector<Option*> *Positional = 0;
58 if (!Positional) Positional = new std::vector<Option*>();
62 static void AddArgument(const char *ArgName, Option *Opt) {
63 if (getOption(ArgName)) {
64 std::cerr << ProgramName << ": CommandLine Error: Argument '"
65 << ArgName << "' defined more than once!\n";
67 // Add argument to the argument map!
68 getOpts()[ArgName] = Opt;
72 // RemoveArgument - It's possible that the argument is no longer in the map if
73 // options have already been processed and the map has been deleted!
75 static void RemoveArgument(const char *ArgName, Option *Opt) {
76 if (CommandLineOptions == 0) return;
78 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
79 // If we pass ArgName directly into getOption here.
80 std::string Tmp = ArgName;
81 assert(getOption(Tmp) == Opt && "Arg not in map!");
83 CommandLineOptions->erase(ArgName);
84 if (CommandLineOptions->empty()) {
85 delete CommandLineOptions;
86 CommandLineOptions = 0;
90 static inline bool ProvideOption(Option *Handler, const char *ArgName,
91 const char *Value, int argc, char **argv,
93 // Enforce value requirements
94 switch (Handler->getValueExpectedFlag()) {
96 if (Value == 0 || *Value == 0) { // No value specified?
97 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
100 return Handler->error(" requires a value!");
104 case ValueDisallowed:
106 return Handler->error(" does not allow a value! '" +
107 std::string(Value) + "' specified.");
112 std::cerr << ProgramName
113 << ": Bad ValueMask flag! CommandLine usage error:"
114 << Handler->getValueExpectedFlag() << "\n";
119 // Run the handler now!
120 return Handler->addOccurrence(i, ArgName, Value);
123 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
126 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
130 // Option predicates...
131 static inline bool isGrouping(const Option *O) {
132 return O->getFormattingFlag() == cl::Grouping;
134 static inline bool isPrefixedOrGrouping(const Option *O) {
135 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
138 // getOptionPred - Check to see if there are any options that satisfy the
139 // specified predicate with names that are the prefixes in Name. This is
140 // checked by progressively stripping characters off of the name, checking to
141 // see if there options that satisfy the predicate. If we find one, return it,
142 // otherwise return null.
144 static Option *getOptionPred(std::string Name, unsigned &Length,
145 bool (*Pred)(const Option*)) {
147 Option *Op = getOption(Name);
148 if (Op && Pred(Op)) {
149 Length = Name.length();
153 if (Name.size() == 1) return 0;
155 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
156 Op = getOption(Name);
158 // Loop while we haven't found an option and Name still has at least two
159 // characters in it (so that the next iteration will not be the empty
161 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
163 if (Op && Pred(Op)) {
164 Length = Name.length();
165 return Op; // Found one!
167 return 0; // No option found!
170 static bool RequiresValue(const Option *O) {
171 return O->getNumOccurrencesFlag() == cl::Required ||
172 O->getNumOccurrencesFlag() == cl::OneOrMore;
175 static bool EatsUnboundedNumberOfValues(const Option *O) {
176 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
177 O->getNumOccurrencesFlag() == cl::OneOrMore;
180 /// ParseCStringVector - Break INPUT up wherever one or more
181 /// whitespace characters are found, and store the resulting tokens in
182 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
183 /// using strdup (), so it is the caller's responsibility to free ()
186 static void ParseCStringVector (std::vector<char *> &output,
188 // Characters which will be treated as token separators:
189 static const char *delims = " \v\f\t\r\n";
191 std::string work (input);
192 // Skip past any delims at head of input string.
193 size_t pos = work.find_first_not_of (delims);
194 // If the string consists entirely of delims, then exit early.
195 if (pos == std::string::npos) return;
196 // Otherwise, jump forward to beginning of first word.
197 work = work.substr (pos);
198 // Find position of first delimiter.
199 pos = work.find_first_of (delims);
201 while (!work.empty() && pos != std::string::npos) {
202 // Everything from 0 to POS is the next word to copy.
203 output.push_back (strdup (work.substr (0,pos).c_str ()));
204 // Is there another word in the string?
205 size_t nextpos = work.find_first_not_of (delims, pos + 1);
206 if (nextpos != std::string::npos) {
207 // Yes? Then remove delims from beginning ...
208 work = work.substr (work.find_first_not_of (delims, pos + 1));
209 // and find the end of the word.
210 pos = work.find_first_of (delims);
212 // No? (Remainder of string is delims.) End the loop.
214 pos = std::string::npos;
218 // If `input' ended with non-delim char, then we'll get here with
219 // the last word of `input' in `work'; copy it now.
220 if (!work.empty ()) {
221 output.push_back (strdup (work.c_str ()));
225 /// ParseEnvironmentOptions - An alternative entry point to the
226 /// CommandLine library, which allows you to read the program's name
227 /// from the caller (as PROGNAME) and its command-line arguments from
228 /// an environment variable (whose name is given in ENVVAR).
230 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
231 const char *Overview) {
233 assert(progName && "Program name not specified");
234 assert(envVar && "Environment variable name missing");
236 // Get the environment variable they want us to parse options out of.
237 const char *envValue = getenv (envVar);
241 // Get program's "name", which we wouldn't know without the caller
243 std::vector<char *> newArgv;
244 newArgv.push_back (strdup (progName));
246 // Parse the value of the environment variable into a "command line"
247 // and hand it off to ParseCommandLineOptions().
248 ParseCStringVector (newArgv, envValue);
249 int newArgc = newArgv.size ();
250 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
252 // Free all the strdup()ed strings.
253 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
259 /// LookupOption - Lookup the option specified by the specified option on the
260 /// command line. If there is a value specified (after an equal sign) return
262 static Option *LookupOption(const char *&Arg, const char *&Value) {
263 while (*Arg == '-') ++Arg; // Eat leading dashes
265 const char *ArgEnd = Arg;
266 while (*ArgEnd && *ArgEnd != '=')
267 ++ArgEnd; // Scan till end of argument name...
270 if (*Value) // If we have an equals sign...
271 ++Value; // Advance to value...
273 if (*Arg == 0) return 0;
275 // Look up the option.
276 std::map<std::string, Option*> &Opts = getOpts();
277 std::map<std::string, Option*>::iterator I =
278 Opts.find(std::string(Arg, ArgEnd));
279 return (I != Opts.end()) ? I->second : 0;
282 void cl::ParseCommandLineOptions(int &argc, char **argv,
283 const char *Overview) {
284 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
285 "No options specified, or ParseCommandLineOptions called more"
287 ProgramName = argv[0]; // Save this away safe and snug
288 ProgramOverview = Overview;
289 bool ErrorParsing = false;
291 std::map<std::string, Option*> &Opts = getOpts();
292 std::vector<Option*> &PositionalOpts = getPositionalOpts();
294 // Check out the positional arguments to collect information about them.
295 unsigned NumPositionalRequired = 0;
296 Option *ConsumeAfterOpt = 0;
297 if (!PositionalOpts.empty()) {
298 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
299 assert(PositionalOpts.size() > 1 &&
300 "Cannot specify cl::ConsumeAfter without a positional argument!");
301 ConsumeAfterOpt = PositionalOpts[0];
304 // Calculate how many positional values are _required_.
305 bool UnboundedFound = false;
306 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
308 Option *Opt = PositionalOpts[i];
309 if (RequiresValue(Opt))
310 ++NumPositionalRequired;
311 else if (ConsumeAfterOpt) {
312 // ConsumeAfter cannot be combined with "optional" positional options
313 // unless there is only one positional argument...
314 if (PositionalOpts.size() > 2)
316 Opt->error(" error - this positional option will never be matched, "
317 "because it does not Require a value, and a "
318 "cl::ConsumeAfter option is active!");
319 } else if (UnboundedFound && !Opt->ArgStr[0]) {
320 // This option does not "require" a value... Make sure this option is
321 // not specified after an option that eats all extra arguments, or this
322 // one will never get any!
324 ErrorParsing |= Opt->error(" error - option can never match, because "
325 "another positional argument will match an "
326 "unbounded number of values, and this option"
327 " does not require a value!");
329 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
333 // PositionalVals - A vector of "positional" arguments we accumulate into
334 // the process at the end...
336 std::vector<std::pair<std::string,unsigned> > PositionalVals;
338 // If the program has named positional arguments, and the name has been run
339 // across, keep track of which positional argument was named. Otherwise put
340 // the positional args into the PositionalVals list...
341 Option *ActivePositionalArg = 0;
343 // Loop over all of the arguments... processing them.
344 bool DashDashFound = false; // Have we read '--'?
345 for (int i = 1; i < argc; ++i) {
347 const char *Value = "";
348 const char *ArgName = "";
350 // Check to see if this is a positional argument. This argument is
351 // considered to be positional if it doesn't start with '-', if it is "-"
352 // itself, or if we have seen "--" already.
354 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
355 // Positional argument!
356 if (ActivePositionalArg) {
357 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
358 continue; // We are done!
359 } else if (!PositionalOpts.empty()) {
360 PositionalVals.push_back(std::make_pair(argv[i],i));
362 // All of the positional arguments have been fulfulled, give the rest to
363 // the consume after option... if it's specified...
365 if (PositionalVals.size() >= NumPositionalRequired &&
366 ConsumeAfterOpt != 0) {
367 for (++i; i < argc; ++i)
368 PositionalVals.push_back(std::make_pair(argv[i],i));
369 break; // Handle outside of the argument processing loop...
372 // Delay processing positional arguments until the end...
375 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
377 DashDashFound = true; // This is the mythical "--"?
378 continue; // Don't try to process it as an argument itself.
379 } else if (ActivePositionalArg &&
380 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
381 // If there is a positional argument eating options, check to see if this
382 // option is another positional argument. If so, treat it as an argument,
383 // otherwise feed it to the eating positional.
385 Handler = LookupOption(ArgName, Value);
386 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
387 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
388 continue; // We are done!
391 } else { // We start with a '-', must be an argument...
393 Handler = LookupOption(ArgName, Value);
395 // Check to see if this "option" is really a prefixed or grouped argument.
396 if (Handler == 0 && *Value == 0) {
397 std::string RealName(ArgName);
398 if (RealName.size() > 1) {
400 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
402 // If the option is a prefixed option, then the value is simply the
403 // rest of the name... so fall through to later processing, by
404 // setting up the argument name flags and value fields.
406 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
407 Value = ArgName+Length;
408 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
409 Opts.find(std::string(ArgName, Value))->second == PGOpt);
412 // This must be a grouped option... handle them now.
413 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
416 // Move current arg name out of RealName into RealArgName...
417 std::string RealArgName(RealName.begin(),
418 RealName.begin() + Length);
419 RealName.erase(RealName.begin(), RealName.begin() + Length);
421 // Because ValueRequired is an invalid flag for grouped arguments,
422 // we don't need to pass argc/argv in...
424 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
425 "Option can not be cl::Grouping AND cl::ValueRequired!");
427 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
430 // Get the next grouping option...
431 PGOpt = getOptionPred(RealName, Length, isGrouping);
432 } while (PGOpt && Length != RealName.size());
434 Handler = PGOpt; // Ate all of the options.
441 std::cerr << ProgramName << ": Unknown command line argument '" << argv[i]
442 << "'. Try: '" << argv[0] << " --help'\n";
447 // Check to see if this option accepts a comma separated list of values. If
448 // it does, we have to split up the value into multiple values...
449 if (Handler->getMiscFlags() & CommaSeparated) {
450 std::string Val(Value);
451 std::string::size_type Pos = Val.find(',');
453 while (Pos != std::string::npos) {
454 // Process the portion before the comma...
455 ErrorParsing |= ProvideOption(Handler, ArgName,
456 std::string(Val.begin(),
457 Val.begin()+Pos).c_str(),
459 // Erase the portion before the comma, AND the comma...
460 Val.erase(Val.begin(), Val.begin()+Pos+1);
461 Value += Pos+1; // Increment the original value pointer as well...
463 // Check for another comma...
468 // If this is a named positional argument, just remember that it is the
470 if (Handler->getFormattingFlag() == cl::Positional)
471 ActivePositionalArg = Handler;
473 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
476 // Check and handle positional arguments now...
477 if (NumPositionalRequired > PositionalVals.size()) {
478 std::cerr << ProgramName
479 << ": Not enough positional command line arguments specified!\n"
480 << "Must specify at least " << NumPositionalRequired
481 << " positional arguments: See: " << argv[0] << " --help\n";
485 } else if (ConsumeAfterOpt == 0) {
486 // Positional args have already been handled if ConsumeAfter is specified...
487 unsigned ValNo = 0, NumVals = PositionalVals.size();
488 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
489 if (RequiresValue(PositionalOpts[i])) {
490 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
491 PositionalVals[ValNo].second);
493 --NumPositionalRequired; // We fulfilled our duty...
496 // If we _can_ give this option more arguments, do so now, as long as we
497 // do not give it values that others need. 'Done' controls whether the
498 // option even _WANTS_ any more.
500 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
501 while (NumVals-ValNo > NumPositionalRequired && !Done) {
502 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
504 Done = true; // Optional arguments want _at most_ one value
506 case cl::ZeroOrMore: // Zero or more will take all they can get...
507 case cl::OneOrMore: // One or more will take all they can get...
508 ProvidePositionalOption(PositionalOpts[i],
509 PositionalVals[ValNo].first,
510 PositionalVals[ValNo].second);
514 assert(0 && "Internal error, unexpected NumOccurrences flag in "
515 "positional argument processing!");
520 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
522 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
523 if (RequiresValue(PositionalOpts[j])) {
524 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
525 PositionalVals[ValNo].first,
526 PositionalVals[ValNo].second);
530 // Handle the case where there is just one positional option, and it's
531 // optional. In this case, we want to give JUST THE FIRST option to the
532 // positional option and keep the rest for the consume after. The above
533 // loop would have assigned no values to positional options in this case.
535 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
536 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
537 PositionalVals[ValNo].first,
538 PositionalVals[ValNo].second);
542 // Handle over all of the rest of the arguments to the
543 // cl::ConsumeAfter command line option...
544 for (; ValNo != PositionalVals.size(); ++ValNo)
545 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
546 PositionalVals[ValNo].first,
547 PositionalVals[ValNo].second);
550 // Loop over args and make sure all required args are specified!
551 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
552 E = Opts.end(); I != E; ++I) {
553 switch (I->second->getNumOccurrencesFlag()) {
556 if (I->second->getNumOccurrences() == 0) {
557 I->second->error(" must be specified at least once!");
566 // Free all of the memory allocated to the map. Command line options may only
567 // be processed once!
568 delete CommandLineOptions;
569 CommandLineOptions = 0;
570 PositionalOpts.clear();
572 // If we had an error processing our arguments, don't let the program execute
573 if (ErrorParsing) exit(1);
576 //===----------------------------------------------------------------------===//
577 // Option Base class implementation
580 bool Option::error(std::string Message, const char *ArgName) {
581 if (ArgName == 0) ArgName = ArgStr;
583 std::cerr << HelpStr; // Be nice for positional arguments
585 std::cerr << ProgramName << ": for the -" << ArgName;
586 std::cerr << " option: " << Message << "\n";
590 bool Option::addOccurrence(unsigned pos, const char *ArgName, const std::string &Value) {
591 NumOccurrences++; // Increment the number of times we have been seen
593 switch (getNumOccurrencesFlag()) {
595 if (NumOccurrences > 1)
596 return error(": may only occur zero or one times!", ArgName);
599 if (NumOccurrences > 1)
600 return error(": must occur exactly one time!", ArgName);
604 case ConsumeAfter: break;
605 default: return error(": bad num occurrences flag value!");
608 return handleOccurrence(pos, ArgName, Value);
611 // addArgument - Tell the system that this Option subclass will handle all
612 // occurrences of -ArgStr on the command line.
614 void Option::addArgument(const char *ArgStr) {
616 AddArgument(ArgStr, this);
618 if (getFormattingFlag() == Positional)
619 getPositionalOpts().push_back(this);
620 else if (getNumOccurrencesFlag() == ConsumeAfter) {
621 if (!getPositionalOpts().empty() &&
622 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
623 error("Cannot specify more than one option with cl::ConsumeAfter!");
624 getPositionalOpts().insert(getPositionalOpts().begin(), this);
628 void Option::removeArgument(const char *ArgStr) {
630 RemoveArgument(ArgStr, this);
632 if (getFormattingFlag() == Positional) {
633 std::vector<Option*>::iterator I =
634 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
635 assert(I != getPositionalOpts().end() && "Arg not registered!");
636 getPositionalOpts().erase(I);
637 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
638 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
639 "Arg not registered correctly!");
640 getPositionalOpts().erase(getPositionalOpts().begin());
645 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
646 // has been specified yet.
648 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
649 if (O.ValueStr[0] == 0) return DefaultMsg;
653 //===----------------------------------------------------------------------===//
654 // cl::alias class implementation
657 // Return the width of the option tag for printing...
658 unsigned alias::getOptionWidth() const {
659 return std::strlen(ArgStr)+6;
662 // Print out the option for the alias...
663 void alias::printOptionInfo(unsigned GlobalWidth) const {
664 unsigned L = std::strlen(ArgStr);
665 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
671 //===----------------------------------------------------------------------===//
672 // Parser Implementation code...
675 // basic_parser implementation
678 // Return the width of the option tag for printing...
679 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
680 unsigned Len = std::strlen(O.ArgStr);
681 if (const char *ValName = getValueName())
682 Len += std::strlen(getValueStr(O, ValName))+3;
687 // printOptionInfo - Print out information about this option. The
688 // to-be-maintained width is specified.
690 void basic_parser_impl::printOptionInfo(const Option &O,
691 unsigned GlobalWidth) const {
692 std::cerr << " -" << O.ArgStr;
694 if (const char *ValName = getValueName())
695 std::cerr << "=<" << getValueStr(O, ValName) << ">";
697 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
698 << O.HelpStr << "\n";
704 // parser<bool> implementation
706 bool parser<bool>::parse(Option &O, const char *ArgName,
707 const std::string &Arg, bool &Value) {
708 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
711 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
714 return O.error(": '" + Arg +
715 "' is invalid value for boolean argument! Try 0 or 1");
720 // parser<int> implementation
722 bool parser<int>::parse(Option &O, const char *ArgName,
723 const std::string &Arg, int &Value) {
725 Value = (int)strtol(Arg.c_str(), &End, 0);
727 return O.error(": '" + Arg + "' value invalid for integer argument!");
731 // parser<unsigned> implementation
733 bool parser<unsigned>::parse(Option &O, const char *ArgName,
734 const std::string &Arg, unsigned &Value) {
737 unsigned long V = strtoul(Arg.c_str(), &End, 0);
739 if (((V == ULONG_MAX) && (errno == ERANGE))
742 return O.error(": '" + Arg + "' value invalid for uint argument!");
746 // parser<double>/parser<float> implementation
748 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
749 const char *ArgStart = Arg.c_str();
751 Value = strtod(ArgStart, &End);
753 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
757 bool parser<double>::parse(Option &O, const char *AN,
758 const std::string &Arg, double &Val) {
759 return parseDouble(O, Arg, Val);
762 bool parser<float>::parse(Option &O, const char *AN,
763 const std::string &Arg, float &Val) {
765 if (parseDouble(O, Arg, dVal))
773 // generic_parser_base implementation
776 // findOption - Return the option number corresponding to the specified
777 // argument string. If the option is not found, getNumOptions() is returned.
779 unsigned generic_parser_base::findOption(const char *Name) {
780 unsigned i = 0, e = getNumOptions();
784 if (getOption(i) == N)
792 // Return the width of the option tag for printing...
793 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
795 unsigned Size = std::strlen(O.ArgStr)+6;
796 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
797 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
800 unsigned BaseSize = 0;
801 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
802 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
807 // printOptionInfo - Print out information about this option. The
808 // to-be-maintained width is specified.
810 void generic_parser_base::printOptionInfo(const Option &O,
811 unsigned GlobalWidth) const {
813 unsigned L = std::strlen(O.ArgStr);
814 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
815 << " - " << O.HelpStr << "\n";
817 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
818 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
819 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
820 << " - " << getDescription(i) << "\n";
824 std::cerr << " " << O.HelpStr << "\n";
825 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
826 unsigned L = std::strlen(getOption(i));
827 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
828 << " - " << getDescription(i) << "\n";
834 //===----------------------------------------------------------------------===//
835 // --help and --help-hidden option implementation
838 // If this variable is set, it is a pointer to a function that the user wants
839 // us to call after we print out the help info. Basically a hook to allow
840 // additional help to be printed.
841 static std::vector<const char*>* MoreHelp = 0;
843 extrahelp::extrahelp(const char* Help)
846 MoreHelp = new std::vector<const char*>;
848 MoreHelp->push_back(Help);
855 const Option *EmptyArg;
856 const bool ShowHidden;
858 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
859 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
860 return OptPair.second->getOptionHiddenFlag() >= Hidden;
862 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
863 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
867 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
871 void operator=(bool Value) {
872 if (Value == false) return;
874 // Copy Options into a vector so we can sort them as we like...
875 std::vector<std::pair<std::string, Option*> > Options;
876 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
878 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
879 Options.erase(std::remove_if(Options.begin(), Options.end(),
880 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
883 // Eliminate duplicate entries in table (from enum flags options, f.e.)
884 { // Give OptionSet a scope
885 std::set<Option*> OptionSet;
886 for (unsigned i = 0; i != Options.size(); ++i)
887 if (OptionSet.count(Options[i].second) == 0)
888 OptionSet.insert(Options[i].second); // Add new entry to set
890 Options.erase(Options.begin()+i--); // Erase duplicate
894 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
896 std::cerr << "USAGE: " << ProgramName << " [options]";
898 // Print out the positional options...
899 std::vector<Option*> &PosOpts = getPositionalOpts();
900 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
901 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
904 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
905 if (PosOpts[i]->ArgStr[0])
906 std::cerr << " --" << PosOpts[i]->ArgStr;
907 std::cerr << " " << PosOpts[i]->HelpStr;
910 // Print the consume after option info if it exists...
911 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
915 // Compute the maximum argument length...
917 for (unsigned i = 0, e = Options.size(); i != e; ++i)
918 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
920 std::cerr << "OPTIONS:\n";
921 for (unsigned i = 0, e = Options.size(); i != e; ++i)
922 Options[i].second->printOptionInfo(MaxArgLen);
924 // Print any extra help the user has declared. If MoreHelp is not null,
925 // then the user used at least one cl::extrahelp instance to provide
926 // additional help. We just print it out now.
928 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
929 E = MoreHelp->end(); I != E; ++I)
933 // Halt the program since help information was printed
938 class VersionPrinter {
940 void operator=(bool OptionWasSpecified) {
941 if (OptionWasSpecified) {
942 std::cerr << "Low Level Virtual Machine (" << PACKAGE_NAME << ") "
943 << PACKAGE_VERSION << " (see http://llvm.cs.uiuc.edu/)\n";
950 // Define the two HelpPrinter instances that are used to print out help, or
953 HelpPrinter NormalPrinter(false);
954 HelpPrinter HiddenPrinter(true);
956 cl::opt<HelpPrinter, true, parser<bool> >
957 HOp("help", cl::desc("display available options (--help-hidden for more)"),
958 cl::location(NormalPrinter), cl::ValueDisallowed);
960 cl::opt<HelpPrinter, true, parser<bool> >
961 HHOp("help-hidden", cl::desc("display all available options"),
962 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
964 // Define the --version option that prints out the LLVM version for the tool
965 VersionPrinter VersionPrinterInstance;
966 cl::opt<VersionPrinter, true, parser<bool> >
967 VersOp("version", cl::desc("display the version"),
968 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
971 } // End anonymous namespace
973 // Utility function for printing the help message.
974 void cl::PrintHelpMessage() {
975 NormalPrinter = true;