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 "Support/CommandLine.h"
31 //===----------------------------------------------------------------------===//
32 // Basic, shared command line option processing machinery...
35 // Return the global command line option vector. Making it a function scoped
36 // static ensures that it will be initialized correctly before its first use.
38 static std::map<std::string, Option*> *CommandLineOptions = 0;
39 static std::map<std::string, Option*> &getOpts() {
40 if (CommandLineOptions == 0)
41 CommandLineOptions = new std::map<std::string,Option*>();
42 return *CommandLineOptions;
45 static Option *getOption(const std::string &Str) {
46 if (CommandLineOptions == 0) return 0;
47 std::map<std::string,Option*>::iterator I = CommandLineOptions->find(Str);
48 return I != CommandLineOptions->end() ? I->second : 0;
51 static std::vector<Option*> &getPositionalOpts() {
52 static std::vector<Option*> *Positional = 0;
53 if (!Positional) Positional = new std::vector<Option*>();
57 static void AddArgument(const char *ArgName, Option *Opt) {
58 if (getOption(ArgName)) {
59 std::cerr << "CommandLine Error: Argument '" << ArgName
60 << "' defined more than once!\n";
62 // Add argument to the argument map!
63 getOpts()[ArgName] = Opt;
67 // RemoveArgument - It's possible that the argument is no longer in the map if
68 // options have already been processed and the map has been deleted!
70 static void RemoveArgument(const char *ArgName, Option *Opt) {
71 if (CommandLineOptions == 0) return;
72 assert(getOption(ArgName) == Opt && "Arg not in map!");
73 CommandLineOptions->erase(ArgName);
74 if (CommandLineOptions->empty()) {
75 delete CommandLineOptions;
76 CommandLineOptions = 0;
80 static const char *ProgramName = 0;
81 static const char *ProgramOverview = 0;
83 static inline bool ProvideOption(Option *Handler, const char *ArgName,
84 const char *Value, int argc, char **argv,
86 // Enforce value requirements
87 switch (Handler->getValueExpectedFlag()) {
89 if (Value == 0 || *Value == 0) { // No value specified?
90 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
93 return Handler->error(" requires a value!");
99 return Handler->error(" does not allow a value! '" +
100 std::string(Value) + "' specified.");
102 case ValueOptional: break;
103 default: std::cerr << "Bad ValueMask flag! CommandLine usage error:"
104 << Handler->getValueExpectedFlag() << "\n"; abort();
107 // Run the handler now!
108 return Handler->addOccurrence(ArgName, Value);
111 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg) {
113 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
117 // Option predicates...
118 static inline bool isGrouping(const Option *O) {
119 return O->getFormattingFlag() == cl::Grouping;
121 static inline bool isPrefixedOrGrouping(const Option *O) {
122 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
125 // getOptionPred - Check to see if there are any options that satisfy the
126 // specified predicate with names that are the prefixes in Name. This is
127 // checked by progressively stripping characters off of the name, checking to
128 // see if there options that satisfy the predicate. If we find one, return it,
129 // otherwise return null.
131 static Option *getOptionPred(std::string Name, unsigned &Length,
132 bool (*Pred)(const Option*)) {
134 Option *Op = getOption(Name);
135 if (Op && Pred(Op)) {
136 Length = Name.length();
140 if (Name.size() == 1) return 0;
142 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
143 Op = getOption(Name);
145 // Loop while we haven't found an option and Name still has at least two
146 // characters in it (so that the next iteration will not be the empty
148 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
150 if (Op && Pred(Op)) {
151 Length = Name.length();
152 return Op; // Found one!
154 return 0; // No option found!
157 static bool RequiresValue(const Option *O) {
158 return O->getNumOccurrencesFlag() == cl::Required ||
159 O->getNumOccurrencesFlag() == cl::OneOrMore;
162 static bool EatsUnboundedNumberOfValues(const Option *O) {
163 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
164 O->getNumOccurrencesFlag() == cl::OneOrMore;
167 /// ParseCStringVector - Break INPUT up wherever one or more
168 /// whitespace characters are found, and store the resulting tokens in
169 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
170 /// using strdup (), so it is the caller's responsibility to free ()
173 static void ParseCStringVector (std::vector<char *> &output,
175 // Characters which will be treated as token separators:
176 static const char *delims = " \v\f\t\r\n";
178 std::string work (input);
179 // Skip past any delims at head of input string.
180 size_t pos = work.find_first_not_of (delims);
181 // If the string consists entirely of delims, then exit early.
182 if (pos == std::string::npos) return;
183 // Otherwise, jump forward to beginning of first word.
184 work = work.substr (pos);
185 // Find position of first delimiter.
186 pos = work.find_first_of (delims);
188 while (!work.empty() && pos != std::string::npos) {
189 // Everything from 0 to POS is the next word to copy.
190 output.push_back (strdup (work.substr (0,pos).c_str ()));
191 // Is there another word in the string?
192 size_t nextpos = work.find_first_not_of (delims, pos + 1);
193 if (nextpos != std::string::npos) {
194 // Yes? Then remove delims from beginning ...
195 work = work.substr (work.find_first_not_of (delims, pos + 1));
196 // and find the end of the word.
197 pos = work.find_first_of (delims);
199 // No? (Remainder of string is delims.) End the loop.
201 pos = std::string::npos;
205 // If `input' ended with non-delim char, then we'll get here with
206 // the last word of `input' in `work'; copy it now.
207 if (!work.empty ()) {
208 output.push_back (strdup (work.c_str ()));
212 /// ParseEnvironmentOptions - An alternative entry point to the
213 /// CommandLine library, which allows you to read the program's name
214 /// from the caller (as PROGNAME) and its command-line arguments from
215 /// an environment variable (whose name is given in ENVVAR).
217 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
218 const char *Overview) {
220 assert(progName && "Program name not specified");
221 assert(envVar && "Environment variable name missing");
223 // Get the environment variable they want us to parse options out of.
224 const char *envValue = getenv (envVar);
228 // Get program's "name", which we wouldn't know without the caller
230 std::vector<char *> newArgv;
231 newArgv.push_back (strdup (progName));
233 // Parse the value of the environment variable into a "command line"
234 // and hand it off to ParseCommandLineOptions().
235 ParseCStringVector (newArgv, envValue);
236 int newArgc = newArgv.size ();
237 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
239 // Free all the strdup()ed strings.
240 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
246 /// LookupOption - Lookup the option specified by the specified option on the
247 /// command line. If there is a value specified (after an equal sign) return
249 static Option *LookupOption(const char *&Arg, const char *&Value) {
250 while (*Arg == '-') ++Arg; // Eat leading dashes
252 const char *ArgEnd = Arg;
253 while (*ArgEnd && *ArgEnd != '=')
254 ++ArgEnd; // Scan till end of argument name...
257 if (*Value) // If we have an equals sign...
258 ++Value; // Advance to value...
260 if (*Arg == 0) return 0;
262 // Look up the option.
263 std::map<std::string, Option*> &Opts = getOpts();
264 std::map<std::string, Option*>::iterator I =
265 Opts.find(std::string(Arg, ArgEnd));
266 return (I != Opts.end()) ? I->second : 0;
269 void cl::ParseCommandLineOptions(int &argc, char **argv,
270 const char *Overview) {
271 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
272 "No options specified, or ParseCommandLineOptions called more"
274 ProgramName = argv[0]; // Save this away safe and snug
275 ProgramOverview = Overview;
276 bool ErrorParsing = false;
278 std::map<std::string, Option*> &Opts = getOpts();
279 std::vector<Option*> &PositionalOpts = getPositionalOpts();
281 // Check out the positional arguments to collect information about them.
282 unsigned NumPositionalRequired = 0;
283 Option *ConsumeAfterOpt = 0;
284 if (!PositionalOpts.empty()) {
285 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
286 assert(PositionalOpts.size() > 1 &&
287 "Cannot specify cl::ConsumeAfter without a positional argument!");
288 ConsumeAfterOpt = PositionalOpts[0];
291 // Calculate how many positional values are _required_.
292 bool UnboundedFound = false;
293 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
295 Option *Opt = PositionalOpts[i];
296 if (RequiresValue(Opt))
297 ++NumPositionalRequired;
298 else if (ConsumeAfterOpt) {
299 // ConsumeAfter cannot be combined with "optional" positional options
300 // unless there is only one positional argument...
301 if (PositionalOpts.size() > 2)
303 Opt->error(" error - this positional option will never be matched, "
304 "because it does not Require a value, and a "
305 "cl::ConsumeAfter option is active!");
306 } else if (UnboundedFound && !Opt->ArgStr[0]) {
307 // This option does not "require" a value... Make sure this option is
308 // not specified after an option that eats all extra arguments, or this
309 // one will never get any!
311 ErrorParsing |= Opt->error(" error - option can never match, because "
312 "another positional argument will match an "
313 "unbounded number of values, and this option"
314 " does not require a value!");
316 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
320 // PositionalVals - A vector of "positional" arguments we accumulate into to
321 // processes at the end...
323 std::vector<std::string> PositionalVals;
325 // If the program has named positional arguments, and the name has been run
326 // across, keep track of which positional argument was named. Otherwise put
327 // the positional args into the PositionalVals list...
328 Option *ActivePositionalArg = 0;
330 // Loop over all of the arguments... processing them.
331 bool DashDashFound = false; // Have we read '--'?
332 for (int i = 1; i < argc; ++i) {
334 const char *Value = "";
335 const char *ArgName = "";
337 // Check to see if this is a positional argument. This argument is
338 // considered to be positional if it doesn't start with '-', if it is "-"
339 // itself, or if we have seen "--" already.
341 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
342 // Positional argument!
343 if (ActivePositionalArg) {
344 ProvidePositionalOption(ActivePositionalArg, argv[i]);
345 continue; // We are done!
346 } else if (!PositionalOpts.empty()) {
347 PositionalVals.push_back(argv[i]);
349 // All of the positional arguments have been fulfulled, give the rest to
350 // the consume after option... if it's specified...
352 if (PositionalVals.size() >= NumPositionalRequired &&
353 ConsumeAfterOpt != 0) {
354 for (++i; i < argc; ++i)
355 PositionalVals.push_back(argv[i]);
356 break; // Handle outside of the argument processing loop...
359 // Delay processing positional arguments until the end...
362 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
364 DashDashFound = true; // This is the mythical "--"?
365 continue; // Don't try to process it as an argument itself.
366 } else if (ActivePositionalArg &&
367 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
368 // If there is a positional argument eating options, check to see if this
369 // option is another positional argument. If so, treat it as an argument,
370 // otherwise feed it to the eating positional.
372 Handler = LookupOption(ArgName, Value);
373 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
374 ProvidePositionalOption(ActivePositionalArg, argv[i]);
375 continue; // We are done!
378 } else { // We start with a '-', must be an argument...
380 Handler = LookupOption(ArgName, Value);
382 // Check to see if this "option" is really a prefixed or grouped argument.
383 if (Handler == 0 && *Value == 0) {
384 std::string RealName(ArgName);
385 if (RealName.size() > 1) {
387 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
389 // If the option is a prefixed option, then the value is simply the
390 // rest of the name... so fall through to later processing, by
391 // setting up the argument name flags and value fields.
393 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
394 Value = ArgName+Length;
395 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
396 Opts.find(std::string(ArgName, Value))->second == PGOpt);
399 // This must be a grouped option... handle them now.
400 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
403 // Move current arg name out of RealName into RealArgName...
404 std::string RealArgName(RealName.begin(),
405 RealName.begin() + Length);
406 RealName.erase(RealName.begin(), RealName.begin() + Length);
408 // Because ValueRequired is an invalid flag for grouped arguments,
409 // we don't need to pass argc/argv in...
411 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
412 "Option can not be cl::Grouping AND cl::ValueRequired!");
414 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
417 // Get the next grouping option...
418 PGOpt = getOptionPred(RealName, Length, isGrouping);
419 } while (PGOpt && Length != RealName.size());
421 Handler = PGOpt; // Ate all of the options.
428 std::cerr << "Unknown command line argument '" << argv[i] << "'. Try: '"
429 << argv[0] << " --help'\n";
434 // Check to see if this option accepts a comma separated list of values. If
435 // it does, we have to split up the value into multiple values...
436 if (Handler->getMiscFlags() & CommaSeparated) {
437 std::string Val(Value);
438 std::string::size_type Pos = Val.find(',');
440 while (Pos != std::string::npos) {
441 // Process the portion before the comma...
442 ErrorParsing |= ProvideOption(Handler, ArgName,
443 std::string(Val.begin(),
444 Val.begin()+Pos).c_str(),
446 // Erase the portion before the comma, AND the comma...
447 Val.erase(Val.begin(), Val.begin()+Pos+1);
448 Value += Pos+1; // Increment the original value pointer as well...
450 // Check for another comma...
455 // If this is a named positional argument, just remember that it is the
457 if (Handler->getFormattingFlag() == cl::Positional)
458 ActivePositionalArg = Handler;
460 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
463 // Check and handle positional arguments now...
464 if (NumPositionalRequired > PositionalVals.size()) {
465 std::cerr << "Not enough positional command line arguments specified!\n"
466 << "Must specify at least " << NumPositionalRequired
467 << " positional arguments: See: " << argv[0] << " --help\n";
471 } else if (ConsumeAfterOpt == 0) {
472 // Positional args have already been handled if ConsumeAfter is specified...
473 unsigned ValNo = 0, NumVals = PositionalVals.size();
474 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
475 if (RequiresValue(PositionalOpts[i])) {
476 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
477 --NumPositionalRequired; // We fulfilled our duty...
480 // If we _can_ give this option more arguments, do so now, as long as we
481 // do not give it values that others need. 'Done' controls whether the
482 // option even _WANTS_ any more.
484 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
485 while (NumVals-ValNo > NumPositionalRequired && !Done) {
486 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
488 Done = true; // Optional arguments want _at most_ one value
490 case cl::ZeroOrMore: // Zero or more will take all they can get...
491 case cl::OneOrMore: // One or more will take all they can get...
492 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
495 assert(0 && "Internal error, unexpected NumOccurrences flag in "
496 "positional argument processing!");
501 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
503 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
504 if (RequiresValue(PositionalOpts[j]))
505 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
506 PositionalVals[ValNo++]);
508 // Handle the case where there is just one positional option, and it's
509 // optional. In this case, we want to give JUST THE FIRST option to the
510 // positional option and keep the rest for the consume after. The above
511 // loop would have assigned no values to positional options in this case.
513 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty())
514 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
515 PositionalVals[ValNo++]);
517 // Handle over all of the rest of the arguments to the
518 // cl::ConsumeAfter command line option...
519 for (; ValNo != PositionalVals.size(); ++ValNo)
520 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
521 PositionalVals[ValNo]);
524 // Loop over args and make sure all required args are specified!
525 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
526 E = Opts.end(); I != E; ++I) {
527 switch (I->second->getNumOccurrencesFlag()) {
530 if (I->second->getNumOccurrences() == 0) {
531 I->second->error(" must be specified at least once!");
540 // Free all of the memory allocated to the map. Command line options may only
541 // be processed once!
542 delete CommandLineOptions;
543 CommandLineOptions = 0;
544 PositionalOpts.clear();
546 // If we had an error processing our arguments, don't let the program execute
547 if (ErrorParsing) exit(1);
550 //===----------------------------------------------------------------------===//
551 // Option Base class implementation
554 bool Option::error(std::string Message, const char *ArgName) {
555 if (ArgName == 0) ArgName = ArgStr;
557 std::cerr << HelpStr; // Be nice for positional arguments
559 std::cerr << "-" << ArgName;
560 std::cerr << " option" << Message << "\n";
564 bool Option::addOccurrence(const char *ArgName, const std::string &Value) {
565 NumOccurrences++; // Increment the number of times we have been seen
567 switch (getNumOccurrencesFlag()) {
569 if (NumOccurrences > 1)
570 return error(": may only occur zero or one times!", ArgName);
573 if (NumOccurrences > 1)
574 return error(": must occur exactly one time!", ArgName);
578 case ConsumeAfter: break;
579 default: return error(": bad num occurrences flag value!");
582 return handleOccurrence(ArgName, Value);
585 // addArgument - Tell the system that this Option subclass will handle all
586 // occurrences of -ArgStr on the command line.
588 void Option::addArgument(const char *ArgStr) {
590 AddArgument(ArgStr, this);
592 if (getFormattingFlag() == Positional)
593 getPositionalOpts().push_back(this);
594 else if (getNumOccurrencesFlag() == ConsumeAfter) {
595 if (!getPositionalOpts().empty() &&
596 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
597 error("Cannot specify more than one option with cl::ConsumeAfter!");
598 getPositionalOpts().insert(getPositionalOpts().begin(), this);
602 void Option::removeArgument(const char *ArgStr) {
604 RemoveArgument(ArgStr, this);
606 if (getFormattingFlag() == Positional) {
607 std::vector<Option*>::iterator I =
608 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
609 assert(I != getPositionalOpts().end() && "Arg not registered!");
610 getPositionalOpts().erase(I);
611 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
612 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
613 "Arg not registered correctly!");
614 getPositionalOpts().erase(getPositionalOpts().begin());
619 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
620 // has been specified yet.
622 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
623 if (O.ValueStr[0] == 0) return DefaultMsg;
627 //===----------------------------------------------------------------------===//
628 // cl::alias class implementation
631 // Return the width of the option tag for printing...
632 unsigned alias::getOptionWidth() const {
633 return std::strlen(ArgStr)+6;
636 // Print out the option for the alias...
637 void alias::printOptionInfo(unsigned GlobalWidth) const {
638 unsigned L = std::strlen(ArgStr);
639 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
645 //===----------------------------------------------------------------------===//
646 // Parser Implementation code...
649 // basic_parser implementation
652 // Return the width of the option tag for printing...
653 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
654 unsigned Len = std::strlen(O.ArgStr);
655 if (const char *ValName = getValueName())
656 Len += std::strlen(getValueStr(O, ValName))+3;
661 // printOptionInfo - Print out information about this option. The
662 // to-be-maintained width is specified.
664 void basic_parser_impl::printOptionInfo(const Option &O,
665 unsigned GlobalWidth) const {
666 std::cerr << " -" << O.ArgStr;
668 if (const char *ValName = getValueName())
669 std::cerr << "=<" << getValueStr(O, ValName) << ">";
671 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
672 << O.HelpStr << "\n";
678 // parser<bool> implementation
680 bool parser<bool>::parse(Option &O, const char *ArgName,
681 const std::string &Arg, bool &Value) {
682 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
685 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
688 return O.error(": '" + Arg +
689 "' is invalid value for boolean argument! Try 0 or 1");
694 // parser<int> implementation
696 bool parser<int>::parse(Option &O, const char *ArgName,
697 const std::string &Arg, int &Value) {
699 Value = (int)strtol(Arg.c_str(), &End, 0);
701 return O.error(": '" + Arg + "' value invalid for integer argument!");
705 // parser<unsigned> implementation
707 bool parser<unsigned>::parse(Option &O, const char *ArgName,
708 const std::string &Arg, unsigned &Value) {
711 unsigned long V = strtoul(Arg.c_str(), &End, 0);
713 if (((V == ULONG_MAX) && (errno == ERANGE))
716 return O.error(": '" + Arg + "' value invalid for uint argument!");
720 // parser<double>/parser<float> implementation
722 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
723 const char *ArgStart = Arg.c_str();
725 Value = strtod(ArgStart, &End);
727 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
731 bool parser<double>::parse(Option &O, const char *AN,
732 const std::string &Arg, double &Val) {
733 return parseDouble(O, Arg, Val);
736 bool parser<float>::parse(Option &O, const char *AN,
737 const std::string &Arg, float &Val) {
739 if (parseDouble(O, Arg, dVal))
747 // generic_parser_base implementation
750 // findOption - Return the option number corresponding to the specified
751 // argument string. If the option is not found, getNumOptions() is returned.
753 unsigned generic_parser_base::findOption(const char *Name) {
754 unsigned i = 0, e = getNumOptions();
758 if (getOption(i) == N)
766 // Return the width of the option tag for printing...
767 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
769 unsigned Size = std::strlen(O.ArgStr)+6;
770 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
771 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
774 unsigned BaseSize = 0;
775 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
776 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
781 // printOptionInfo - Print out information about this option. The
782 // to-be-maintained width is specified.
784 void generic_parser_base::printOptionInfo(const Option &O,
785 unsigned GlobalWidth) const {
787 unsigned L = std::strlen(O.ArgStr);
788 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
789 << " - " << O.HelpStr << "\n";
791 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
792 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
793 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
794 << " - " << getDescription(i) << "\n";
798 std::cerr << " " << O.HelpStr << "\n";
799 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
800 unsigned L = std::strlen(getOption(i));
801 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
802 << " - " << getDescription(i) << "\n";
808 //===----------------------------------------------------------------------===//
809 // --help and --help-hidden option implementation
815 const Option *EmptyArg;
816 const bool ShowHidden;
818 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
819 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
820 return OptPair.second->getOptionHiddenFlag() >= Hidden;
822 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
823 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
827 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
831 void operator=(bool Value) {
832 if (Value == false) return;
834 // Copy Options into a vector so we can sort them as we like...
835 std::vector<std::pair<std::string, Option*> > Options;
836 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
838 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
839 Options.erase(std::remove_if(Options.begin(), Options.end(),
840 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
843 // Eliminate duplicate entries in table (from enum flags options, f.e.)
844 { // Give OptionSet a scope
845 std::set<Option*> OptionSet;
846 for (unsigned i = 0; i != Options.size(); ++i)
847 if (OptionSet.count(Options[i].second) == 0)
848 OptionSet.insert(Options[i].second); // Add new entry to set
850 Options.erase(Options.begin()+i--); // Erase duplicate
854 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
856 std::cerr << "USAGE: " << ProgramName << " [options]";
858 // Print out the positional options...
859 std::vector<Option*> &PosOpts = getPositionalOpts();
860 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
861 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
864 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
865 if (PosOpts[i]->ArgStr[0])
866 std::cerr << " --" << PosOpts[i]->ArgStr;
867 std::cerr << " " << PosOpts[i]->HelpStr;
870 // Print the consume after option info if it exists...
871 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
875 // Compute the maximum argument length...
877 for (unsigned i = 0, e = Options.size(); i != e; ++i)
878 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
880 std::cerr << "OPTIONS:\n";
881 for (unsigned i = 0, e = Options.size(); i != e; ++i)
882 Options[i].second->printOptionInfo(MaxArgLen);
884 // Halt the program if help information is printed
891 // Define the two HelpPrinter instances that are used to print out help, or
894 HelpPrinter NormalPrinter(false);
895 HelpPrinter HiddenPrinter(true);
897 cl::opt<HelpPrinter, true, parser<bool> >
898 HOp("help", cl::desc("display available options (--help-hidden for more)"),
899 cl::location(NormalPrinter), cl::ValueDisallowed);
901 cl::opt<HelpPrinter, true, parser<bool> >
902 HHOp("help-hidden", cl::desc("display all available options"),
903 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
905 } // End anonymous namespace