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 "Config/config.h"
20 #include "Support/CommandLine.h"
32 //===----------------------------------------------------------------------===//
33 // Basic, shared command line option processing machinery...
36 // Return the global command line option vector. Making it a function scoped
37 // static ensures that it will be initialized correctly before its first use.
39 static std::map<std::string, Option*> *CommandLineOptions = 0;
40 static std::map<std::string, Option*> &getOpts() {
41 if (CommandLineOptions == 0)
42 CommandLineOptions = new std::map<std::string,Option*>();
43 return *CommandLineOptions;
46 static Option *getOption(const std::string &Str) {
47 if (CommandLineOptions == 0) return 0;
48 std::map<std::string,Option*>::iterator I = CommandLineOptions->find(Str);
49 return I != CommandLineOptions->end() ? I->second : 0;
52 static std::vector<Option*> &getPositionalOpts() {
53 static std::vector<Option*> *Positional = 0;
54 if (!Positional) Positional = new std::vector<Option*>();
58 static void AddArgument(const char *ArgName, Option *Opt) {
59 if (getOption(ArgName)) {
60 std::cerr << "CommandLine Error: Argument '" << ArgName
61 << "' defined more than once!\n";
63 // Add argument to the argument map!
64 getOpts()[ArgName] = Opt;
68 // RemoveArgument - It's possible that the argument is no longer in the map if
69 // options have already been processed and the map has been deleted!
71 static void RemoveArgument(const char *ArgName, Option *Opt) {
72 if (CommandLineOptions == 0) return;
74 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
75 // If we pass ArgName directly into getOption here.
76 std::string Tmp = ArgName;
77 assert(getOption(Tmp) == Opt && "Arg not in map!");
79 CommandLineOptions->erase(ArgName);
80 if (CommandLineOptions->empty()) {
81 delete CommandLineOptions;
82 CommandLineOptions = 0;
86 static const char *ProgramName = 0;
87 static const char *ProgramOverview = 0;
89 static inline bool ProvideOption(Option *Handler, const char *ArgName,
90 const char *Value, int argc, char **argv,
92 // Enforce value requirements
93 switch (Handler->getValueExpectedFlag()) {
95 if (Value == 0 || *Value == 0) { // No value specified?
96 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
99 return Handler->error(" requires a value!");
103 case ValueDisallowed:
105 return Handler->error(" does not allow a value! '" +
106 std::string(Value) + "' specified.");
108 case ValueOptional: break;
109 default: std::cerr << "Bad ValueMask flag! CommandLine usage error:"
110 << Handler->getValueExpectedFlag() << "\n"; abort();
113 // Run the handler now!
114 return Handler->addOccurrence(i, ArgName, Value);
117 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
120 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
124 // Option predicates...
125 static inline bool isGrouping(const Option *O) {
126 return O->getFormattingFlag() == cl::Grouping;
128 static inline bool isPrefixedOrGrouping(const Option *O) {
129 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
132 // getOptionPred - Check to see if there are any options that satisfy the
133 // specified predicate with names that are the prefixes in Name. This is
134 // checked by progressively stripping characters off of the name, checking to
135 // see if there options that satisfy the predicate. If we find one, return it,
136 // otherwise return null.
138 static Option *getOptionPred(std::string Name, unsigned &Length,
139 bool (*Pred)(const Option*)) {
141 Option *Op = getOption(Name);
142 if (Op && Pred(Op)) {
143 Length = Name.length();
147 if (Name.size() == 1) return 0;
149 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
150 Op = getOption(Name);
152 // Loop while we haven't found an option and Name still has at least two
153 // characters in it (so that the next iteration will not be the empty
155 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
157 if (Op && Pred(Op)) {
158 Length = Name.length();
159 return Op; // Found one!
161 return 0; // No option found!
164 static bool RequiresValue(const Option *O) {
165 return O->getNumOccurrencesFlag() == cl::Required ||
166 O->getNumOccurrencesFlag() == cl::OneOrMore;
169 static bool EatsUnboundedNumberOfValues(const Option *O) {
170 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
171 O->getNumOccurrencesFlag() == cl::OneOrMore;
174 /// ParseCStringVector - Break INPUT up wherever one or more
175 /// whitespace characters are found, and store the resulting tokens in
176 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
177 /// using strdup (), so it is the caller's responsibility to free ()
180 static void ParseCStringVector (std::vector<char *> &output,
182 // Characters which will be treated as token separators:
183 static const char *delims = " \v\f\t\r\n";
185 std::string work (input);
186 // Skip past any delims at head of input string.
187 size_t pos = work.find_first_not_of (delims);
188 // If the string consists entirely of delims, then exit early.
189 if (pos == std::string::npos) return;
190 // Otherwise, jump forward to beginning of first word.
191 work = work.substr (pos);
192 // Find position of first delimiter.
193 pos = work.find_first_of (delims);
195 while (!work.empty() && pos != std::string::npos) {
196 // Everything from 0 to POS is the next word to copy.
197 output.push_back (strdup (work.substr (0,pos).c_str ()));
198 // Is there another word in the string?
199 size_t nextpos = work.find_first_not_of (delims, pos + 1);
200 if (nextpos != std::string::npos) {
201 // Yes? Then remove delims from beginning ...
202 work = work.substr (work.find_first_not_of (delims, pos + 1));
203 // and find the end of the word.
204 pos = work.find_first_of (delims);
206 // No? (Remainder of string is delims.) End the loop.
208 pos = std::string::npos;
212 // If `input' ended with non-delim char, then we'll get here with
213 // the last word of `input' in `work'; copy it now.
214 if (!work.empty ()) {
215 output.push_back (strdup (work.c_str ()));
219 /// ParseEnvironmentOptions - An alternative entry point to the
220 /// CommandLine library, which allows you to read the program's name
221 /// from the caller (as PROGNAME) and its command-line arguments from
222 /// an environment variable (whose name is given in ENVVAR).
224 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
225 const char *Overview) {
227 assert(progName && "Program name not specified");
228 assert(envVar && "Environment variable name missing");
230 // Get the environment variable they want us to parse options out of.
231 const char *envValue = getenv (envVar);
235 // Get program's "name", which we wouldn't know without the caller
237 std::vector<char *> newArgv;
238 newArgv.push_back (strdup (progName));
240 // Parse the value of the environment variable into a "command line"
241 // and hand it off to ParseCommandLineOptions().
242 ParseCStringVector (newArgv, envValue);
243 int newArgc = newArgv.size ();
244 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
246 // Free all the strdup()ed strings.
247 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
253 /// LookupOption - Lookup the option specified by the specified option on the
254 /// command line. If there is a value specified (after an equal sign) return
256 static Option *LookupOption(const char *&Arg, const char *&Value) {
257 while (*Arg == '-') ++Arg; // Eat leading dashes
259 const char *ArgEnd = Arg;
260 while (*ArgEnd && *ArgEnd != '=')
261 ++ArgEnd; // Scan till end of argument name...
264 if (*Value) // If we have an equals sign...
265 ++Value; // Advance to value...
267 if (*Arg == 0) return 0;
269 // Look up the option.
270 std::map<std::string, Option*> &Opts = getOpts();
271 std::map<std::string, Option*>::iterator I =
272 Opts.find(std::string(Arg, ArgEnd));
273 return (I != Opts.end()) ? I->second : 0;
276 void cl::ParseCommandLineOptions(int &argc, char **argv,
277 const char *Overview) {
278 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
279 "No options specified, or ParseCommandLineOptions called more"
281 ProgramName = argv[0]; // Save this away safe and snug
282 ProgramOverview = Overview;
283 bool ErrorParsing = false;
285 std::map<std::string, Option*> &Opts = getOpts();
286 std::vector<Option*> &PositionalOpts = getPositionalOpts();
288 // Check out the positional arguments to collect information about them.
289 unsigned NumPositionalRequired = 0;
290 Option *ConsumeAfterOpt = 0;
291 if (!PositionalOpts.empty()) {
292 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
293 assert(PositionalOpts.size() > 1 &&
294 "Cannot specify cl::ConsumeAfter without a positional argument!");
295 ConsumeAfterOpt = PositionalOpts[0];
298 // Calculate how many positional values are _required_.
299 bool UnboundedFound = false;
300 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
302 Option *Opt = PositionalOpts[i];
303 if (RequiresValue(Opt))
304 ++NumPositionalRequired;
305 else if (ConsumeAfterOpt) {
306 // ConsumeAfter cannot be combined with "optional" positional options
307 // unless there is only one positional argument...
308 if (PositionalOpts.size() > 2)
310 Opt->error(" error - this positional option will never be matched, "
311 "because it does not Require a value, and a "
312 "cl::ConsumeAfter option is active!");
313 } else if (UnboundedFound && !Opt->ArgStr[0]) {
314 // This option does not "require" a value... Make sure this option is
315 // not specified after an option that eats all extra arguments, or this
316 // one will never get any!
318 ErrorParsing |= Opt->error(" error - option can never match, because "
319 "another positional argument will match an "
320 "unbounded number of values, and this option"
321 " does not require a value!");
323 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
327 // PositionalVals - A vector of "positional" arguments we accumulate into
328 // the process at the end...
330 std::vector<std::pair<std::string,unsigned> > PositionalVals;
332 // If the program has named positional arguments, and the name has been run
333 // across, keep track of which positional argument was named. Otherwise put
334 // the positional args into the PositionalVals list...
335 Option *ActivePositionalArg = 0;
337 // Loop over all of the arguments... processing them.
338 bool DashDashFound = false; // Have we read '--'?
339 for (int i = 1; i < argc; ++i) {
341 const char *Value = "";
342 const char *ArgName = "";
344 // Check to see if this is a positional argument. This argument is
345 // considered to be positional if it doesn't start with '-', if it is "-"
346 // itself, or if we have seen "--" already.
348 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
349 // Positional argument!
350 if (ActivePositionalArg) {
351 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
352 continue; // We are done!
353 } else if (!PositionalOpts.empty()) {
354 PositionalVals.push_back(std::make_pair(argv[i],i));
356 // All of the positional arguments have been fulfulled, give the rest to
357 // the consume after option... if it's specified...
359 if (PositionalVals.size() >= NumPositionalRequired &&
360 ConsumeAfterOpt != 0) {
361 for (++i; i < argc; ++i)
362 PositionalVals.push_back(std::make_pair(argv[i],i));
363 break; // Handle outside of the argument processing loop...
366 // Delay processing positional arguments until the end...
369 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
371 DashDashFound = true; // This is the mythical "--"?
372 continue; // Don't try to process it as an argument itself.
373 } else if (ActivePositionalArg &&
374 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
375 // If there is a positional argument eating options, check to see if this
376 // option is another positional argument. If so, treat it as an argument,
377 // otherwise feed it to the eating positional.
379 Handler = LookupOption(ArgName, Value);
380 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
381 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
382 continue; // We are done!
385 } else { // We start with a '-', must be an argument...
387 Handler = LookupOption(ArgName, Value);
389 // Check to see if this "option" is really a prefixed or grouped argument.
390 if (Handler == 0 && *Value == 0) {
391 std::string RealName(ArgName);
392 if (RealName.size() > 1) {
394 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
396 // If the option is a prefixed option, then the value is simply the
397 // rest of the name... so fall through to later processing, by
398 // setting up the argument name flags and value fields.
400 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
401 Value = ArgName+Length;
402 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
403 Opts.find(std::string(ArgName, Value))->second == PGOpt);
406 // This must be a grouped option... handle them now.
407 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
410 // Move current arg name out of RealName into RealArgName...
411 std::string RealArgName(RealName.begin(),
412 RealName.begin() + Length);
413 RealName.erase(RealName.begin(), RealName.begin() + Length);
415 // Because ValueRequired is an invalid flag for grouped arguments,
416 // we don't need to pass argc/argv in...
418 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
419 "Option can not be cl::Grouping AND cl::ValueRequired!");
421 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
424 // Get the next grouping option...
425 PGOpt = getOptionPred(RealName, Length, isGrouping);
426 } while (PGOpt && Length != RealName.size());
428 Handler = PGOpt; // Ate all of the options.
435 std::cerr << "Unknown command line argument '" << argv[i] << "'. Try: '"
436 << argv[0] << " --help'\n";
441 // Check to see if this option accepts a comma separated list of values. If
442 // it does, we have to split up the value into multiple values...
443 if (Handler->getMiscFlags() & CommaSeparated) {
444 std::string Val(Value);
445 std::string::size_type Pos = Val.find(',');
447 while (Pos != std::string::npos) {
448 // Process the portion before the comma...
449 ErrorParsing |= ProvideOption(Handler, ArgName,
450 std::string(Val.begin(),
451 Val.begin()+Pos).c_str(),
453 // Erase the portion before the comma, AND the comma...
454 Val.erase(Val.begin(), Val.begin()+Pos+1);
455 Value += Pos+1; // Increment the original value pointer as well...
457 // Check for another comma...
462 // If this is a named positional argument, just remember that it is the
464 if (Handler->getFormattingFlag() == cl::Positional)
465 ActivePositionalArg = Handler;
467 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
470 // Check and handle positional arguments now...
471 if (NumPositionalRequired > PositionalVals.size()) {
472 std::cerr << "Not enough positional command line arguments specified!\n"
473 << "Must specify at least " << NumPositionalRequired
474 << " positional arguments: See: " << argv[0] << " --help\n";
478 } else if (ConsumeAfterOpt == 0) {
479 // Positional args have already been handled if ConsumeAfter is specified...
480 unsigned ValNo = 0, NumVals = PositionalVals.size();
481 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
482 if (RequiresValue(PositionalOpts[i])) {
483 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
484 PositionalVals[ValNo].second);
486 --NumPositionalRequired; // We fulfilled our duty...
489 // If we _can_ give this option more arguments, do so now, as long as we
490 // do not give it values that others need. 'Done' controls whether the
491 // option even _WANTS_ any more.
493 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
494 while (NumVals-ValNo > NumPositionalRequired && !Done) {
495 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
497 Done = true; // Optional arguments want _at most_ one value
499 case cl::ZeroOrMore: // Zero or more will take all they can get...
500 case cl::OneOrMore: // One or more will take all they can get...
501 ProvidePositionalOption(PositionalOpts[i],
502 PositionalVals[ValNo].first,
503 PositionalVals[ValNo].second);
507 assert(0 && "Internal error, unexpected NumOccurrences flag in "
508 "positional argument processing!");
513 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
515 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
516 if (RequiresValue(PositionalOpts[j])) {
517 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
518 PositionalVals[ValNo].first,
519 PositionalVals[ValNo].second);
523 // Handle the case where there is just one positional option, and it's
524 // optional. In this case, we want to give JUST THE FIRST option to the
525 // positional option and keep the rest for the consume after. The above
526 // loop would have assigned no values to positional options in this case.
528 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
529 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
530 PositionalVals[ValNo].first,
531 PositionalVals[ValNo].second);
535 // Handle over all of the rest of the arguments to the
536 // cl::ConsumeAfter command line option...
537 for (; ValNo != PositionalVals.size(); ++ValNo)
538 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
539 PositionalVals[ValNo].first,
540 PositionalVals[ValNo].second);
543 // Loop over args and make sure all required args are specified!
544 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
545 E = Opts.end(); I != E; ++I) {
546 switch (I->second->getNumOccurrencesFlag()) {
549 if (I->second->getNumOccurrences() == 0) {
550 I->second->error(" must be specified at least once!");
559 // Free all of the memory allocated to the map. Command line options may only
560 // be processed once!
561 delete CommandLineOptions;
562 CommandLineOptions = 0;
563 PositionalOpts.clear();
565 // If we had an error processing our arguments, don't let the program execute
566 if (ErrorParsing) exit(1);
569 //===----------------------------------------------------------------------===//
570 // Option Base class implementation
573 bool Option::error(std::string Message, const char *ArgName) {
574 if (ArgName == 0) ArgName = ArgStr;
576 std::cerr << HelpStr; // Be nice for positional arguments
578 std::cerr << "-" << ArgName;
579 std::cerr << " option" << Message << "\n";
583 bool Option::addOccurrence(unsigned pos, const char *ArgName, const std::string &Value) {
584 NumOccurrences++; // Increment the number of times we have been seen
586 switch (getNumOccurrencesFlag()) {
588 if (NumOccurrences > 1)
589 return error(": may only occur zero or one times!", ArgName);
592 if (NumOccurrences > 1)
593 return error(": must occur exactly one time!", ArgName);
597 case ConsumeAfter: break;
598 default: return error(": bad num occurrences flag value!");
601 return handleOccurrence(pos, ArgName, Value);
604 // addArgument - Tell the system that this Option subclass will handle all
605 // occurrences of -ArgStr on the command line.
607 void Option::addArgument(const char *ArgStr) {
609 AddArgument(ArgStr, this);
611 if (getFormattingFlag() == Positional)
612 getPositionalOpts().push_back(this);
613 else if (getNumOccurrencesFlag() == ConsumeAfter) {
614 if (!getPositionalOpts().empty() &&
615 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
616 error("Cannot specify more than one option with cl::ConsumeAfter!");
617 getPositionalOpts().insert(getPositionalOpts().begin(), this);
621 void Option::removeArgument(const char *ArgStr) {
623 RemoveArgument(ArgStr, this);
625 if (getFormattingFlag() == Positional) {
626 std::vector<Option*>::iterator I =
627 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
628 assert(I != getPositionalOpts().end() && "Arg not registered!");
629 getPositionalOpts().erase(I);
630 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
631 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
632 "Arg not registered correctly!");
633 getPositionalOpts().erase(getPositionalOpts().begin());
638 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
639 // has been specified yet.
641 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
642 if (O.ValueStr[0] == 0) return DefaultMsg;
646 //===----------------------------------------------------------------------===//
647 // cl::alias class implementation
650 // Return the width of the option tag for printing...
651 unsigned alias::getOptionWidth() const {
652 return std::strlen(ArgStr)+6;
655 // Print out the option for the alias...
656 void alias::printOptionInfo(unsigned GlobalWidth) const {
657 unsigned L = std::strlen(ArgStr);
658 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
664 //===----------------------------------------------------------------------===//
665 // Parser Implementation code...
668 // basic_parser implementation
671 // Return the width of the option tag for printing...
672 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
673 unsigned Len = std::strlen(O.ArgStr);
674 if (const char *ValName = getValueName())
675 Len += std::strlen(getValueStr(O, ValName))+3;
680 // printOptionInfo - Print out information about this option. The
681 // to-be-maintained width is specified.
683 void basic_parser_impl::printOptionInfo(const Option &O,
684 unsigned GlobalWidth) const {
685 std::cerr << " -" << O.ArgStr;
687 if (const char *ValName = getValueName())
688 std::cerr << "=<" << getValueStr(O, ValName) << ">";
690 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
691 << O.HelpStr << "\n";
697 // parser<bool> implementation
699 bool parser<bool>::parse(Option &O, const char *ArgName,
700 const std::string &Arg, bool &Value) {
701 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
704 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
707 return O.error(": '" + Arg +
708 "' is invalid value for boolean argument! Try 0 or 1");
713 // parser<int> implementation
715 bool parser<int>::parse(Option &O, const char *ArgName,
716 const std::string &Arg, int &Value) {
718 Value = (int)strtol(Arg.c_str(), &End, 0);
720 return O.error(": '" + Arg + "' value invalid for integer argument!");
724 // parser<unsigned> implementation
726 bool parser<unsigned>::parse(Option &O, const char *ArgName,
727 const std::string &Arg, unsigned &Value) {
730 unsigned long V = strtoul(Arg.c_str(), &End, 0);
732 if (((V == ULONG_MAX) && (errno == ERANGE))
735 return O.error(": '" + Arg + "' value invalid for uint argument!");
739 // parser<double>/parser<float> implementation
741 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
742 const char *ArgStart = Arg.c_str();
744 Value = strtod(ArgStart, &End);
746 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
750 bool parser<double>::parse(Option &O, const char *AN,
751 const std::string &Arg, double &Val) {
752 return parseDouble(O, Arg, Val);
755 bool parser<float>::parse(Option &O, const char *AN,
756 const std::string &Arg, float &Val) {
758 if (parseDouble(O, Arg, dVal))
766 // generic_parser_base implementation
769 // findOption - Return the option number corresponding to the specified
770 // argument string. If the option is not found, getNumOptions() is returned.
772 unsigned generic_parser_base::findOption(const char *Name) {
773 unsigned i = 0, e = getNumOptions();
777 if (getOption(i) == N)
785 // Return the width of the option tag for printing...
786 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
788 unsigned Size = std::strlen(O.ArgStr)+6;
789 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
790 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
793 unsigned BaseSize = 0;
794 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
795 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
800 // printOptionInfo - Print out information about this option. The
801 // to-be-maintained width is specified.
803 void generic_parser_base::printOptionInfo(const Option &O,
804 unsigned GlobalWidth) const {
806 unsigned L = std::strlen(O.ArgStr);
807 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
808 << " - " << O.HelpStr << "\n";
810 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
811 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
812 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
813 << " - " << getDescription(i) << "\n";
817 std::cerr << " " << O.HelpStr << "\n";
818 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
819 unsigned L = std::strlen(getOption(i));
820 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
821 << " - " << getDescription(i) << "\n";
827 //===----------------------------------------------------------------------===//
828 // --help and --help-hidden option implementation
834 const Option *EmptyArg;
835 const bool ShowHidden;
837 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
838 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
839 return OptPair.second->getOptionHiddenFlag() >= Hidden;
841 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
842 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
846 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
850 void operator=(bool Value) {
851 if (Value == false) return;
853 // Copy Options into a vector so we can sort them as we like...
854 std::vector<std::pair<std::string, Option*> > Options;
855 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
857 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
858 Options.erase(std::remove_if(Options.begin(), Options.end(),
859 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
862 // Eliminate duplicate entries in table (from enum flags options, f.e.)
863 { // Give OptionSet a scope
864 std::set<Option*> OptionSet;
865 for (unsigned i = 0; i != Options.size(); ++i)
866 if (OptionSet.count(Options[i].second) == 0)
867 OptionSet.insert(Options[i].second); // Add new entry to set
869 Options.erase(Options.begin()+i--); // Erase duplicate
873 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
875 std::cerr << "USAGE: " << ProgramName << " [options]";
877 // Print out the positional options...
878 std::vector<Option*> &PosOpts = getPositionalOpts();
879 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
880 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
883 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
884 if (PosOpts[i]->ArgStr[0])
885 std::cerr << " --" << PosOpts[i]->ArgStr;
886 std::cerr << " " << PosOpts[i]->HelpStr;
889 // Print the consume after option info if it exists...
890 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
894 // Compute the maximum argument length...
896 for (unsigned i = 0, e = Options.size(); i != e; ++i)
897 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
899 std::cerr << "OPTIONS:\n";
900 for (unsigned i = 0, e = Options.size(); i != e; ++i)
901 Options[i].second->printOptionInfo(MaxArgLen);
903 // Halt the program if help information is printed
908 class VersionPrinter {
910 void operator=(bool OptionWasSpecified) {
911 if (OptionWasSpecified) {
912 std::cerr << "Low Level Virtual Machine (" << PACKAGE_NAME << ") "
913 << PACKAGE_VERSION << " (see http://llvm.org/)\n";
920 // Define the two HelpPrinter instances that are used to print out help, or
923 HelpPrinter NormalPrinter(false);
924 HelpPrinter HiddenPrinter(true);
926 cl::opt<HelpPrinter, true, parser<bool> >
927 HOp("help", cl::desc("display available options (--help-hidden for more)"),
928 cl::location(NormalPrinter), cl::ValueDisallowed);
930 cl::opt<HelpPrinter, true, parser<bool> >
931 HHOp("help-hidden", cl::desc("display all available options"),
932 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
934 // Define the --version option that prints out the LLVM version for the tool
935 VersionPrinter VersionPrinterInstance;
936 cl::opt<VersionPrinter, true, parser<bool> >
937 VersOp("version", cl::desc("display the version"),
938 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
940 } // End anonymous namespace