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(ArgName, Value);
117 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg) {
119 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
123 // Option predicates...
124 static inline bool isGrouping(const Option *O) {
125 return O->getFormattingFlag() == cl::Grouping;
127 static inline bool isPrefixedOrGrouping(const Option *O) {
128 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
131 // getOptionPred - Check to see if there are any options that satisfy the
132 // specified predicate with names that are the prefixes in Name. This is
133 // checked by progressively stripping characters off of the name, checking to
134 // see if there options that satisfy the predicate. If we find one, return it,
135 // otherwise return null.
137 static Option *getOptionPred(std::string Name, unsigned &Length,
138 bool (*Pred)(const Option*)) {
140 Option *Op = getOption(Name);
141 if (Op && Pred(Op)) {
142 Length = Name.length();
146 if (Name.size() == 1) return 0;
148 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
149 Op = getOption(Name);
151 // Loop while we haven't found an option and Name still has at least two
152 // characters in it (so that the next iteration will not be the empty
154 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
156 if (Op && Pred(Op)) {
157 Length = Name.length();
158 return Op; // Found one!
160 return 0; // No option found!
163 static bool RequiresValue(const Option *O) {
164 return O->getNumOccurrencesFlag() == cl::Required ||
165 O->getNumOccurrencesFlag() == cl::OneOrMore;
168 static bool EatsUnboundedNumberOfValues(const Option *O) {
169 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
170 O->getNumOccurrencesFlag() == cl::OneOrMore;
173 /// ParseCStringVector - Break INPUT up wherever one or more
174 /// whitespace characters are found, and store the resulting tokens in
175 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
176 /// using strdup (), so it is the caller's responsibility to free ()
179 static void ParseCStringVector (std::vector<char *> &output,
181 // Characters which will be treated as token separators:
182 static const char *delims = " \v\f\t\r\n";
184 std::string work (input);
185 // Skip past any delims at head of input string.
186 size_t pos = work.find_first_not_of (delims);
187 // If the string consists entirely of delims, then exit early.
188 if (pos == std::string::npos) return;
189 // Otherwise, jump forward to beginning of first word.
190 work = work.substr (pos);
191 // Find position of first delimiter.
192 pos = work.find_first_of (delims);
194 while (!work.empty() && pos != std::string::npos) {
195 // Everything from 0 to POS is the next word to copy.
196 output.push_back (strdup (work.substr (0,pos).c_str ()));
197 // Is there another word in the string?
198 size_t nextpos = work.find_first_not_of (delims, pos + 1);
199 if (nextpos != std::string::npos) {
200 // Yes? Then remove delims from beginning ...
201 work = work.substr (work.find_first_not_of (delims, pos + 1));
202 // and find the end of the word.
203 pos = work.find_first_of (delims);
205 // No? (Remainder of string is delims.) End the loop.
207 pos = std::string::npos;
211 // If `input' ended with non-delim char, then we'll get here with
212 // the last word of `input' in `work'; copy it now.
213 if (!work.empty ()) {
214 output.push_back (strdup (work.c_str ()));
218 /// ParseEnvironmentOptions - An alternative entry point to the
219 /// CommandLine library, which allows you to read the program's name
220 /// from the caller (as PROGNAME) and its command-line arguments from
221 /// an environment variable (whose name is given in ENVVAR).
223 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
224 const char *Overview) {
226 assert(progName && "Program name not specified");
227 assert(envVar && "Environment variable name missing");
229 // Get the environment variable they want us to parse options out of.
230 const char *envValue = getenv (envVar);
234 // Get program's "name", which we wouldn't know without the caller
236 std::vector<char *> newArgv;
237 newArgv.push_back (strdup (progName));
239 // Parse the value of the environment variable into a "command line"
240 // and hand it off to ParseCommandLineOptions().
241 ParseCStringVector (newArgv, envValue);
242 int newArgc = newArgv.size ();
243 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
245 // Free all the strdup()ed strings.
246 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
252 /// LookupOption - Lookup the option specified by the specified option on the
253 /// command line. If there is a value specified (after an equal sign) return
255 static Option *LookupOption(const char *&Arg, const char *&Value) {
256 while (*Arg == '-') ++Arg; // Eat leading dashes
258 const char *ArgEnd = Arg;
259 while (*ArgEnd && *ArgEnd != '=')
260 ++ArgEnd; // Scan till end of argument name...
263 if (*Value) // If we have an equals sign...
264 ++Value; // Advance to value...
266 if (*Arg == 0) return 0;
268 // Look up the option.
269 std::map<std::string, Option*> &Opts = getOpts();
270 std::map<std::string, Option*>::iterator I =
271 Opts.find(std::string(Arg, ArgEnd));
272 return (I != Opts.end()) ? I->second : 0;
275 void cl::ParseCommandLineOptions(int &argc, char **argv,
276 const char *Overview) {
277 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
278 "No options specified, or ParseCommandLineOptions called more"
280 ProgramName = argv[0]; // Save this away safe and snug
281 ProgramOverview = Overview;
282 bool ErrorParsing = false;
284 std::map<std::string, Option*> &Opts = getOpts();
285 std::vector<Option*> &PositionalOpts = getPositionalOpts();
287 // Check out the positional arguments to collect information about them.
288 unsigned NumPositionalRequired = 0;
289 Option *ConsumeAfterOpt = 0;
290 if (!PositionalOpts.empty()) {
291 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
292 assert(PositionalOpts.size() > 1 &&
293 "Cannot specify cl::ConsumeAfter without a positional argument!");
294 ConsumeAfterOpt = PositionalOpts[0];
297 // Calculate how many positional values are _required_.
298 bool UnboundedFound = false;
299 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
301 Option *Opt = PositionalOpts[i];
302 if (RequiresValue(Opt))
303 ++NumPositionalRequired;
304 else if (ConsumeAfterOpt) {
305 // ConsumeAfter cannot be combined with "optional" positional options
306 // unless there is only one positional argument...
307 if (PositionalOpts.size() > 2)
309 Opt->error(" error - this positional option will never be matched, "
310 "because it does not Require a value, and a "
311 "cl::ConsumeAfter option is active!");
312 } else if (UnboundedFound && !Opt->ArgStr[0]) {
313 // This option does not "require" a value... Make sure this option is
314 // not specified after an option that eats all extra arguments, or this
315 // one will never get any!
317 ErrorParsing |= Opt->error(" error - option can never match, because "
318 "another positional argument will match an "
319 "unbounded number of values, and this option"
320 " does not require a value!");
322 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
326 // PositionalVals - A vector of "positional" arguments we accumulate into to
327 // processes at the end...
329 std::vector<std::string> PositionalVals;
331 // If the program has named positional arguments, and the name has been run
332 // across, keep track of which positional argument was named. Otherwise put
333 // the positional args into the PositionalVals list...
334 Option *ActivePositionalArg = 0;
336 // Loop over all of the arguments... processing them.
337 bool DashDashFound = false; // Have we read '--'?
338 for (int i = 1; i < argc; ++i) {
340 const char *Value = "";
341 const char *ArgName = "";
343 // Check to see if this is a positional argument. This argument is
344 // considered to be positional if it doesn't start with '-', if it is "-"
345 // itself, or if we have seen "--" already.
347 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
348 // Positional argument!
349 if (ActivePositionalArg) {
350 ProvidePositionalOption(ActivePositionalArg, argv[i]);
351 continue; // We are done!
352 } else if (!PositionalOpts.empty()) {
353 PositionalVals.push_back(argv[i]);
355 // All of the positional arguments have been fulfulled, give the rest to
356 // the consume after option... if it's specified...
358 if (PositionalVals.size() >= NumPositionalRequired &&
359 ConsumeAfterOpt != 0) {
360 for (++i; i < argc; ++i)
361 PositionalVals.push_back(argv[i]);
362 break; // Handle outside of the argument processing loop...
365 // Delay processing positional arguments until the end...
368 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
370 DashDashFound = true; // This is the mythical "--"?
371 continue; // Don't try to process it as an argument itself.
372 } else if (ActivePositionalArg &&
373 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
374 // If there is a positional argument eating options, check to see if this
375 // option is another positional argument. If so, treat it as an argument,
376 // otherwise feed it to the eating positional.
378 Handler = LookupOption(ArgName, Value);
379 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
380 ProvidePositionalOption(ActivePositionalArg, argv[i]);
381 continue; // We are done!
384 } else { // We start with a '-', must be an argument...
386 Handler = LookupOption(ArgName, Value);
388 // Check to see if this "option" is really a prefixed or grouped argument.
389 if (Handler == 0 && *Value == 0) {
390 std::string RealName(ArgName);
391 if (RealName.size() > 1) {
393 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
395 // If the option is a prefixed option, then the value is simply the
396 // rest of the name... so fall through to later processing, by
397 // setting up the argument name flags and value fields.
399 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
400 Value = ArgName+Length;
401 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
402 Opts.find(std::string(ArgName, Value))->second == PGOpt);
405 // This must be a grouped option... handle them now.
406 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
409 // Move current arg name out of RealName into RealArgName...
410 std::string RealArgName(RealName.begin(),
411 RealName.begin() + Length);
412 RealName.erase(RealName.begin(), RealName.begin() + Length);
414 // Because ValueRequired is an invalid flag for grouped arguments,
415 // we don't need to pass argc/argv in...
417 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
418 "Option can not be cl::Grouping AND cl::ValueRequired!");
420 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
423 // Get the next grouping option...
424 PGOpt = getOptionPred(RealName, Length, isGrouping);
425 } while (PGOpt && Length != RealName.size());
427 Handler = PGOpt; // Ate all of the options.
434 std::cerr << "Unknown command line argument '" << argv[i] << "'. Try: '"
435 << argv[0] << " --help'\n";
440 // Check to see if this option accepts a comma separated list of values. If
441 // it does, we have to split up the value into multiple values...
442 if (Handler->getMiscFlags() & CommaSeparated) {
443 std::string Val(Value);
444 std::string::size_type Pos = Val.find(',');
446 while (Pos != std::string::npos) {
447 // Process the portion before the comma...
448 ErrorParsing |= ProvideOption(Handler, ArgName,
449 std::string(Val.begin(),
450 Val.begin()+Pos).c_str(),
452 // Erase the portion before the comma, AND the comma...
453 Val.erase(Val.begin(), Val.begin()+Pos+1);
454 Value += Pos+1; // Increment the original value pointer as well...
456 // Check for another comma...
461 // If this is a named positional argument, just remember that it is the
463 if (Handler->getFormattingFlag() == cl::Positional)
464 ActivePositionalArg = Handler;
466 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
469 // Check and handle positional arguments now...
470 if (NumPositionalRequired > PositionalVals.size()) {
471 std::cerr << "Not enough positional command line arguments specified!\n"
472 << "Must specify at least " << NumPositionalRequired
473 << " positional arguments: See: " << argv[0] << " --help\n";
477 } else if (ConsumeAfterOpt == 0) {
478 // Positional args have already been handled if ConsumeAfter is specified...
479 unsigned ValNo = 0, NumVals = PositionalVals.size();
480 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
481 if (RequiresValue(PositionalOpts[i])) {
482 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
483 --NumPositionalRequired; // We fulfilled our duty...
486 // If we _can_ give this option more arguments, do so now, as long as we
487 // do not give it values that others need. 'Done' controls whether the
488 // option even _WANTS_ any more.
490 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
491 while (NumVals-ValNo > NumPositionalRequired && !Done) {
492 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
494 Done = true; // Optional arguments want _at most_ one value
496 case cl::ZeroOrMore: // Zero or more will take all they can get...
497 case cl::OneOrMore: // One or more will take all they can get...
498 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
501 assert(0 && "Internal error, unexpected NumOccurrences flag in "
502 "positional argument processing!");
507 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
509 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
510 if (RequiresValue(PositionalOpts[j]))
511 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
512 PositionalVals[ValNo++]);
514 // Handle the case where there is just one positional option, and it's
515 // optional. In this case, we want to give JUST THE FIRST option to the
516 // positional option and keep the rest for the consume after. The above
517 // loop would have assigned no values to positional options in this case.
519 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty())
520 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
521 PositionalVals[ValNo++]);
523 // Handle over all of the rest of the arguments to the
524 // cl::ConsumeAfter command line option...
525 for (; ValNo != PositionalVals.size(); ++ValNo)
526 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
527 PositionalVals[ValNo]);
530 // Loop over args and make sure all required args are specified!
531 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
532 E = Opts.end(); I != E; ++I) {
533 switch (I->second->getNumOccurrencesFlag()) {
536 if (I->second->getNumOccurrences() == 0) {
537 I->second->error(" must be specified at least once!");
546 // Free all of the memory allocated to the map. Command line options may only
547 // be processed once!
548 delete CommandLineOptions;
549 CommandLineOptions = 0;
550 PositionalOpts.clear();
552 // If we had an error processing our arguments, don't let the program execute
553 if (ErrorParsing) exit(1);
556 //===----------------------------------------------------------------------===//
557 // Option Base class implementation
560 bool Option::error(std::string Message, const char *ArgName) {
561 if (ArgName == 0) ArgName = ArgStr;
563 std::cerr << HelpStr; // Be nice for positional arguments
565 std::cerr << "-" << ArgName;
566 std::cerr << " option" << Message << "\n";
570 bool Option::addOccurrence(const char *ArgName, const std::string &Value) {
571 NumOccurrences++; // Increment the number of times we have been seen
573 switch (getNumOccurrencesFlag()) {
575 if (NumOccurrences > 1)
576 return error(": may only occur zero or one times!", ArgName);
579 if (NumOccurrences > 1)
580 return error(": must occur exactly one time!", ArgName);
584 case ConsumeAfter: break;
585 default: return error(": bad num occurrences flag value!");
588 return handleOccurrence(ArgName, Value);
591 // addArgument - Tell the system that this Option subclass will handle all
592 // occurrences of -ArgStr on the command line.
594 void Option::addArgument(const char *ArgStr) {
596 AddArgument(ArgStr, this);
598 if (getFormattingFlag() == Positional)
599 getPositionalOpts().push_back(this);
600 else if (getNumOccurrencesFlag() == ConsumeAfter) {
601 if (!getPositionalOpts().empty() &&
602 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
603 error("Cannot specify more than one option with cl::ConsumeAfter!");
604 getPositionalOpts().insert(getPositionalOpts().begin(), this);
608 void Option::removeArgument(const char *ArgStr) {
610 RemoveArgument(ArgStr, this);
612 if (getFormattingFlag() == Positional) {
613 std::vector<Option*>::iterator I =
614 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
615 assert(I != getPositionalOpts().end() && "Arg not registered!");
616 getPositionalOpts().erase(I);
617 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
618 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
619 "Arg not registered correctly!");
620 getPositionalOpts().erase(getPositionalOpts().begin());
625 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
626 // has been specified yet.
628 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
629 if (O.ValueStr[0] == 0) return DefaultMsg;
633 //===----------------------------------------------------------------------===//
634 // cl::alias class implementation
637 // Return the width of the option tag for printing...
638 unsigned alias::getOptionWidth() const {
639 return std::strlen(ArgStr)+6;
642 // Print out the option for the alias...
643 void alias::printOptionInfo(unsigned GlobalWidth) const {
644 unsigned L = std::strlen(ArgStr);
645 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
651 //===----------------------------------------------------------------------===//
652 // Parser Implementation code...
655 // basic_parser implementation
658 // Return the width of the option tag for printing...
659 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
660 unsigned Len = std::strlen(O.ArgStr);
661 if (const char *ValName = getValueName())
662 Len += std::strlen(getValueStr(O, ValName))+3;
667 // printOptionInfo - Print out information about this option. The
668 // to-be-maintained width is specified.
670 void basic_parser_impl::printOptionInfo(const Option &O,
671 unsigned GlobalWidth) const {
672 std::cerr << " -" << O.ArgStr;
674 if (const char *ValName = getValueName())
675 std::cerr << "=<" << getValueStr(O, ValName) << ">";
677 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
678 << O.HelpStr << "\n";
684 // parser<bool> implementation
686 bool parser<bool>::parse(Option &O, const char *ArgName,
687 const std::string &Arg, bool &Value) {
688 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
691 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
694 return O.error(": '" + Arg +
695 "' is invalid value for boolean argument! Try 0 or 1");
700 // parser<int> implementation
702 bool parser<int>::parse(Option &O, const char *ArgName,
703 const std::string &Arg, int &Value) {
705 Value = (int)strtol(Arg.c_str(), &End, 0);
707 return O.error(": '" + Arg + "' value invalid for integer argument!");
711 // parser<unsigned> implementation
713 bool parser<unsigned>::parse(Option &O, const char *ArgName,
714 const std::string &Arg, unsigned &Value) {
717 unsigned long V = strtoul(Arg.c_str(), &End, 0);
719 if (((V == ULONG_MAX) && (errno == ERANGE))
722 return O.error(": '" + Arg + "' value invalid for uint argument!");
726 // parser<double>/parser<float> implementation
728 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
729 const char *ArgStart = Arg.c_str();
731 Value = strtod(ArgStart, &End);
733 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
737 bool parser<double>::parse(Option &O, const char *AN,
738 const std::string &Arg, double &Val) {
739 return parseDouble(O, Arg, Val);
742 bool parser<float>::parse(Option &O, const char *AN,
743 const std::string &Arg, float &Val) {
745 if (parseDouble(O, Arg, dVal))
753 // generic_parser_base implementation
756 // findOption - Return the option number corresponding to the specified
757 // argument string. If the option is not found, getNumOptions() is returned.
759 unsigned generic_parser_base::findOption(const char *Name) {
760 unsigned i = 0, e = getNumOptions();
764 if (getOption(i) == N)
772 // Return the width of the option tag for printing...
773 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
775 unsigned Size = std::strlen(O.ArgStr)+6;
776 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
777 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
780 unsigned BaseSize = 0;
781 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
782 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
787 // printOptionInfo - Print out information about this option. The
788 // to-be-maintained width is specified.
790 void generic_parser_base::printOptionInfo(const Option &O,
791 unsigned GlobalWidth) const {
793 unsigned L = std::strlen(O.ArgStr);
794 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
795 << " - " << O.HelpStr << "\n";
797 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
798 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
799 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
800 << " - " << getDescription(i) << "\n";
804 std::cerr << " " << O.HelpStr << "\n";
805 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
806 unsigned L = std::strlen(getOption(i));
807 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
808 << " - " << getDescription(i) << "\n";
814 //===----------------------------------------------------------------------===//
815 // --help and --help-hidden option implementation
821 const Option *EmptyArg;
822 const bool ShowHidden;
824 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
825 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
826 return OptPair.second->getOptionHiddenFlag() >= Hidden;
828 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
829 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
833 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
837 void operator=(bool Value) {
838 if (Value == false) return;
840 // Copy Options into a vector so we can sort them as we like...
841 std::vector<std::pair<std::string, Option*> > Options;
842 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
844 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
845 Options.erase(std::remove_if(Options.begin(), Options.end(),
846 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
849 // Eliminate duplicate entries in table (from enum flags options, f.e.)
850 { // Give OptionSet a scope
851 std::set<Option*> OptionSet;
852 for (unsigned i = 0; i != Options.size(); ++i)
853 if (OptionSet.count(Options[i].second) == 0)
854 OptionSet.insert(Options[i].second); // Add new entry to set
856 Options.erase(Options.begin()+i--); // Erase duplicate
860 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
862 std::cerr << "USAGE: " << ProgramName << " [options]";
864 // Print out the positional options...
865 std::vector<Option*> &PosOpts = getPositionalOpts();
866 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
867 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
870 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
871 if (PosOpts[i]->ArgStr[0])
872 std::cerr << " --" << PosOpts[i]->ArgStr;
873 std::cerr << " " << PosOpts[i]->HelpStr;
876 // Print the consume after option info if it exists...
877 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
881 // Compute the maximum argument length...
883 for (unsigned i = 0, e = Options.size(); i != e; ++i)
884 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
886 std::cerr << "OPTIONS:\n";
887 for (unsigned i = 0, e = Options.size(); i != e; ++i)
888 Options[i].second->printOptionInfo(MaxArgLen);
890 // Halt the program if help information is printed
895 class VersionPrinter {
897 void operator=(bool OptionWasSpecified) {
898 if (OptionWasSpecified) {
899 std::cerr << "Low Level Virtual Machine (" << PACKAGE_NAME << ") "
900 << PACKAGE_VERSION << " (see http://llvm.org/)\n";
907 // Define the two HelpPrinter instances that are used to print out help, or
910 HelpPrinter NormalPrinter(false);
911 HelpPrinter HiddenPrinter(true);
913 cl::opt<HelpPrinter, true, parser<bool> >
914 HOp("help", cl::desc("display available options (--help-hidden for more)"),
915 cl::location(NormalPrinter), cl::ValueDisallowed);
917 cl::opt<HelpPrinter, true, parser<bool> >
918 HHOp("help-hidden", cl::desc("display all available options"),
919 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
921 // Define the --version option that prints out the LLVM version for the tool
922 VersionPrinter VersionPrinterInstance;
923 cl::opt<VersionPrinter, true, parser<bool> >
924 VersOp("version", cl::desc("display the version"),
925 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
927 } // End anonymous namespace