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;
73 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
74 // If we pass ArgName directly into getOption here.
75 std::string Tmp = ArgName;
76 assert(getOption(Tmp) == Opt && "Arg not in map!");
78 CommandLineOptions->erase(ArgName);
79 if (CommandLineOptions->empty()) {
80 delete CommandLineOptions;
81 CommandLineOptions = 0;
85 static const char *ProgramName = 0;
86 static const char *ProgramOverview = 0;
88 static inline bool ProvideOption(Option *Handler, const char *ArgName,
89 const char *Value, int argc, char **argv,
91 // Enforce value requirements
92 switch (Handler->getValueExpectedFlag()) {
94 if (Value == 0 || *Value == 0) { // No value specified?
95 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
98 return Handler->error(" requires a value!");
102 case ValueDisallowed:
104 return Handler->error(" does not allow a value! '" +
105 std::string(Value) + "' specified.");
107 case ValueOptional: break;
108 default: std::cerr << "Bad ValueMask flag! CommandLine usage error:"
109 << Handler->getValueExpectedFlag() << "\n"; abort();
112 // Run the handler now!
113 return Handler->addOccurrence(ArgName, Value);
116 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg) {
118 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
122 // Option predicates...
123 static inline bool isGrouping(const Option *O) {
124 return O->getFormattingFlag() == cl::Grouping;
126 static inline bool isPrefixedOrGrouping(const Option *O) {
127 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
130 // getOptionPred - Check to see if there are any options that satisfy the
131 // specified predicate with names that are the prefixes in Name. This is
132 // checked by progressively stripping characters off of the name, checking to
133 // see if there options that satisfy the predicate. If we find one, return it,
134 // otherwise return null.
136 static Option *getOptionPred(std::string Name, unsigned &Length,
137 bool (*Pred)(const Option*)) {
139 Option *Op = getOption(Name);
140 if (Op && Pred(Op)) {
141 Length = Name.length();
145 if (Name.size() == 1) return 0;
147 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
148 Op = getOption(Name);
150 // Loop while we haven't found an option and Name still has at least two
151 // characters in it (so that the next iteration will not be the empty
153 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
155 if (Op && Pred(Op)) {
156 Length = Name.length();
157 return Op; // Found one!
159 return 0; // No option found!
162 static bool RequiresValue(const Option *O) {
163 return O->getNumOccurrencesFlag() == cl::Required ||
164 O->getNumOccurrencesFlag() == cl::OneOrMore;
167 static bool EatsUnboundedNumberOfValues(const Option *O) {
168 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
169 O->getNumOccurrencesFlag() == cl::OneOrMore;
172 /// ParseCStringVector - Break INPUT up wherever one or more
173 /// whitespace characters are found, and store the resulting tokens in
174 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
175 /// using strdup (), so it is the caller's responsibility to free ()
178 static void ParseCStringVector (std::vector<char *> &output,
180 // Characters which will be treated as token separators:
181 static const char *delims = " \v\f\t\r\n";
183 std::string work (input);
184 // Skip past any delims at head of input string.
185 size_t pos = work.find_first_not_of (delims);
186 // If the string consists entirely of delims, then exit early.
187 if (pos == std::string::npos) return;
188 // Otherwise, jump forward to beginning of first word.
189 work = work.substr (pos);
190 // Find position of first delimiter.
191 pos = work.find_first_of (delims);
193 while (!work.empty() && pos != std::string::npos) {
194 // Everything from 0 to POS is the next word to copy.
195 output.push_back (strdup (work.substr (0,pos).c_str ()));
196 // Is there another word in the string?
197 size_t nextpos = work.find_first_not_of (delims, pos + 1);
198 if (nextpos != std::string::npos) {
199 // Yes? Then remove delims from beginning ...
200 work = work.substr (work.find_first_not_of (delims, pos + 1));
201 // and find the end of the word.
202 pos = work.find_first_of (delims);
204 // No? (Remainder of string is delims.) End the loop.
206 pos = std::string::npos;
210 // If `input' ended with non-delim char, then we'll get here with
211 // the last word of `input' in `work'; copy it now.
212 if (!work.empty ()) {
213 output.push_back (strdup (work.c_str ()));
217 /// ParseEnvironmentOptions - An alternative entry point to the
218 /// CommandLine library, which allows you to read the program's name
219 /// from the caller (as PROGNAME) and its command-line arguments from
220 /// an environment variable (whose name is given in ENVVAR).
222 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
223 const char *Overview) {
225 assert(progName && "Program name not specified");
226 assert(envVar && "Environment variable name missing");
228 // Get the environment variable they want us to parse options out of.
229 const char *envValue = getenv (envVar);
233 // Get program's "name", which we wouldn't know without the caller
235 std::vector<char *> newArgv;
236 newArgv.push_back (strdup (progName));
238 // Parse the value of the environment variable into a "command line"
239 // and hand it off to ParseCommandLineOptions().
240 ParseCStringVector (newArgv, envValue);
241 int newArgc = newArgv.size ();
242 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
244 // Free all the strdup()ed strings.
245 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
251 /// LookupOption - Lookup the option specified by the specified option on the
252 /// command line. If there is a value specified (after an equal sign) return
254 static Option *LookupOption(const char *&Arg, const char *&Value) {
255 while (*Arg == '-') ++Arg; // Eat leading dashes
257 const char *ArgEnd = Arg;
258 while (*ArgEnd && *ArgEnd != '=')
259 ++ArgEnd; // Scan till end of argument name...
262 if (*Value) // If we have an equals sign...
263 ++Value; // Advance to value...
265 if (*Arg == 0) return 0;
267 // Look up the option.
268 std::map<std::string, Option*> &Opts = getOpts();
269 std::map<std::string, Option*>::iterator I =
270 Opts.find(std::string(Arg, ArgEnd));
271 return (I != Opts.end()) ? I->second : 0;
274 void cl::ParseCommandLineOptions(int &argc, char **argv,
275 const char *Overview) {
276 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
277 "No options specified, or ParseCommandLineOptions called more"
279 ProgramName = argv[0]; // Save this away safe and snug
280 ProgramOverview = Overview;
281 bool ErrorParsing = false;
283 std::map<std::string, Option*> &Opts = getOpts();
284 std::vector<Option*> &PositionalOpts = getPositionalOpts();
286 // Check out the positional arguments to collect information about them.
287 unsigned NumPositionalRequired = 0;
288 Option *ConsumeAfterOpt = 0;
289 if (!PositionalOpts.empty()) {
290 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
291 assert(PositionalOpts.size() > 1 &&
292 "Cannot specify cl::ConsumeAfter without a positional argument!");
293 ConsumeAfterOpt = PositionalOpts[0];
296 // Calculate how many positional values are _required_.
297 bool UnboundedFound = false;
298 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
300 Option *Opt = PositionalOpts[i];
301 if (RequiresValue(Opt))
302 ++NumPositionalRequired;
303 else if (ConsumeAfterOpt) {
304 // ConsumeAfter cannot be combined with "optional" positional options
305 // unless there is only one positional argument...
306 if (PositionalOpts.size() > 2)
308 Opt->error(" error - this positional option will never be matched, "
309 "because it does not Require a value, and a "
310 "cl::ConsumeAfter option is active!");
311 } else if (UnboundedFound && !Opt->ArgStr[0]) {
312 // This option does not "require" a value... Make sure this option is
313 // not specified after an option that eats all extra arguments, or this
314 // one will never get any!
316 ErrorParsing |= Opt->error(" error - option can never match, because "
317 "another positional argument will match an "
318 "unbounded number of values, and this option"
319 " does not require a value!");
321 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
325 // PositionalVals - A vector of "positional" arguments we accumulate into to
326 // processes at the end...
328 std::vector<std::string> PositionalVals;
330 // If the program has named positional arguments, and the name has been run
331 // across, keep track of which positional argument was named. Otherwise put
332 // the positional args into the PositionalVals list...
333 Option *ActivePositionalArg = 0;
335 // Loop over all of the arguments... processing them.
336 bool DashDashFound = false; // Have we read '--'?
337 for (int i = 1; i < argc; ++i) {
339 const char *Value = "";
340 const char *ArgName = "";
342 // Check to see if this is a positional argument. This argument is
343 // considered to be positional if it doesn't start with '-', if it is "-"
344 // itself, or if we have seen "--" already.
346 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
347 // Positional argument!
348 if (ActivePositionalArg) {
349 ProvidePositionalOption(ActivePositionalArg, argv[i]);
350 continue; // We are done!
351 } else if (!PositionalOpts.empty()) {
352 PositionalVals.push_back(argv[i]);
354 // All of the positional arguments have been fulfulled, give the rest to
355 // the consume after option... if it's specified...
357 if (PositionalVals.size() >= NumPositionalRequired &&
358 ConsumeAfterOpt != 0) {
359 for (++i; i < argc; ++i)
360 PositionalVals.push_back(argv[i]);
361 break; // Handle outside of the argument processing loop...
364 // Delay processing positional arguments until the end...
367 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
369 DashDashFound = true; // This is the mythical "--"?
370 continue; // Don't try to process it as an argument itself.
371 } else if (ActivePositionalArg &&
372 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
373 // If there is a positional argument eating options, check to see if this
374 // option is another positional argument. If so, treat it as an argument,
375 // otherwise feed it to the eating positional.
377 Handler = LookupOption(ArgName, Value);
378 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
379 ProvidePositionalOption(ActivePositionalArg, argv[i]);
380 continue; // We are done!
383 } else { // We start with a '-', must be an argument...
385 Handler = LookupOption(ArgName, Value);
387 // Check to see if this "option" is really a prefixed or grouped argument.
388 if (Handler == 0 && *Value == 0) {
389 std::string RealName(ArgName);
390 if (RealName.size() > 1) {
392 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
394 // If the option is a prefixed option, then the value is simply the
395 // rest of the name... so fall through to later processing, by
396 // setting up the argument name flags and value fields.
398 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
399 Value = ArgName+Length;
400 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
401 Opts.find(std::string(ArgName, Value))->second == PGOpt);
404 // This must be a grouped option... handle them now.
405 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
408 // Move current arg name out of RealName into RealArgName...
409 std::string RealArgName(RealName.begin(),
410 RealName.begin() + Length);
411 RealName.erase(RealName.begin(), RealName.begin() + Length);
413 // Because ValueRequired is an invalid flag for grouped arguments,
414 // we don't need to pass argc/argv in...
416 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
417 "Option can not be cl::Grouping AND cl::ValueRequired!");
419 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
422 // Get the next grouping option...
423 PGOpt = getOptionPred(RealName, Length, isGrouping);
424 } while (PGOpt && Length != RealName.size());
426 Handler = PGOpt; // Ate all of the options.
433 std::cerr << "Unknown command line argument '" << argv[i] << "'. Try: '"
434 << argv[0] << " --help'\n";
439 // Check to see if this option accepts a comma separated list of values. If
440 // it does, we have to split up the value into multiple values...
441 if (Handler->getMiscFlags() & CommaSeparated) {
442 std::string Val(Value);
443 std::string::size_type Pos = Val.find(',');
445 while (Pos != std::string::npos) {
446 // Process the portion before the comma...
447 ErrorParsing |= ProvideOption(Handler, ArgName,
448 std::string(Val.begin(),
449 Val.begin()+Pos).c_str(),
451 // Erase the portion before the comma, AND the comma...
452 Val.erase(Val.begin(), Val.begin()+Pos+1);
453 Value += Pos+1; // Increment the original value pointer as well...
455 // Check for another comma...
460 // If this is a named positional argument, just remember that it is the
462 if (Handler->getFormattingFlag() == cl::Positional)
463 ActivePositionalArg = Handler;
465 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
468 // Check and handle positional arguments now...
469 if (NumPositionalRequired > PositionalVals.size()) {
470 std::cerr << "Not enough positional command line arguments specified!\n"
471 << "Must specify at least " << NumPositionalRequired
472 << " positional arguments: See: " << argv[0] << " --help\n";
476 } else if (ConsumeAfterOpt == 0) {
477 // Positional args have already been handled if ConsumeAfter is specified...
478 unsigned ValNo = 0, NumVals = PositionalVals.size();
479 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
480 if (RequiresValue(PositionalOpts[i])) {
481 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
482 --NumPositionalRequired; // We fulfilled our duty...
485 // If we _can_ give this option more arguments, do so now, as long as we
486 // do not give it values that others need. 'Done' controls whether the
487 // option even _WANTS_ any more.
489 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
490 while (NumVals-ValNo > NumPositionalRequired && !Done) {
491 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
493 Done = true; // Optional arguments want _at most_ one value
495 case cl::ZeroOrMore: // Zero or more will take all they can get...
496 case cl::OneOrMore: // One or more will take all they can get...
497 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
500 assert(0 && "Internal error, unexpected NumOccurrences flag in "
501 "positional argument processing!");
506 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
508 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
509 if (RequiresValue(PositionalOpts[j]))
510 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
511 PositionalVals[ValNo++]);
513 // Handle the case where there is just one positional option, and it's
514 // optional. In this case, we want to give JUST THE FIRST option to the
515 // positional option and keep the rest for the consume after. The above
516 // loop would have assigned no values to positional options in this case.
518 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty())
519 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
520 PositionalVals[ValNo++]);
522 // Handle over all of the rest of the arguments to the
523 // cl::ConsumeAfter command line option...
524 for (; ValNo != PositionalVals.size(); ++ValNo)
525 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
526 PositionalVals[ValNo]);
529 // Loop over args and make sure all required args are specified!
530 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
531 E = Opts.end(); I != E; ++I) {
532 switch (I->second->getNumOccurrencesFlag()) {
535 if (I->second->getNumOccurrences() == 0) {
536 I->second->error(" must be specified at least once!");
545 // Free all of the memory allocated to the map. Command line options may only
546 // be processed once!
547 delete CommandLineOptions;
548 CommandLineOptions = 0;
549 PositionalOpts.clear();
551 // If we had an error processing our arguments, don't let the program execute
552 if (ErrorParsing) exit(1);
555 //===----------------------------------------------------------------------===//
556 // Option Base class implementation
559 bool Option::error(std::string Message, const char *ArgName) {
560 if (ArgName == 0) ArgName = ArgStr;
562 std::cerr << HelpStr; // Be nice for positional arguments
564 std::cerr << "-" << ArgName;
565 std::cerr << " option" << Message << "\n";
569 bool Option::addOccurrence(const char *ArgName, const std::string &Value) {
570 NumOccurrences++; // Increment the number of times we have been seen
572 switch (getNumOccurrencesFlag()) {
574 if (NumOccurrences > 1)
575 return error(": may only occur zero or one times!", ArgName);
578 if (NumOccurrences > 1)
579 return error(": must occur exactly one time!", ArgName);
583 case ConsumeAfter: break;
584 default: return error(": bad num occurrences flag value!");
587 return handleOccurrence(ArgName, Value);
590 // addArgument - Tell the system that this Option subclass will handle all
591 // occurrences of -ArgStr on the command line.
593 void Option::addArgument(const char *ArgStr) {
595 AddArgument(ArgStr, this);
597 if (getFormattingFlag() == Positional)
598 getPositionalOpts().push_back(this);
599 else if (getNumOccurrencesFlag() == ConsumeAfter) {
600 if (!getPositionalOpts().empty() &&
601 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
602 error("Cannot specify more than one option with cl::ConsumeAfter!");
603 getPositionalOpts().insert(getPositionalOpts().begin(), this);
607 void Option::removeArgument(const char *ArgStr) {
609 RemoveArgument(ArgStr, this);
611 if (getFormattingFlag() == Positional) {
612 std::vector<Option*>::iterator I =
613 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
614 assert(I != getPositionalOpts().end() && "Arg not registered!");
615 getPositionalOpts().erase(I);
616 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
617 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
618 "Arg not registered correctly!");
619 getPositionalOpts().erase(getPositionalOpts().begin());
624 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
625 // has been specified yet.
627 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
628 if (O.ValueStr[0] == 0) return DefaultMsg;
632 //===----------------------------------------------------------------------===//
633 // cl::alias class implementation
636 // Return the width of the option tag for printing...
637 unsigned alias::getOptionWidth() const {
638 return std::strlen(ArgStr)+6;
641 // Print out the option for the alias...
642 void alias::printOptionInfo(unsigned GlobalWidth) const {
643 unsigned L = std::strlen(ArgStr);
644 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
650 //===----------------------------------------------------------------------===//
651 // Parser Implementation code...
654 // basic_parser implementation
657 // Return the width of the option tag for printing...
658 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
659 unsigned Len = std::strlen(O.ArgStr);
660 if (const char *ValName = getValueName())
661 Len += std::strlen(getValueStr(O, ValName))+3;
666 // printOptionInfo - Print out information about this option. The
667 // to-be-maintained width is specified.
669 void basic_parser_impl::printOptionInfo(const Option &O,
670 unsigned GlobalWidth) const {
671 std::cerr << " -" << O.ArgStr;
673 if (const char *ValName = getValueName())
674 std::cerr << "=<" << getValueStr(O, ValName) << ">";
676 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
677 << O.HelpStr << "\n";
683 // parser<bool> implementation
685 bool parser<bool>::parse(Option &O, const char *ArgName,
686 const std::string &Arg, bool &Value) {
687 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
690 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
693 return O.error(": '" + Arg +
694 "' is invalid value for boolean argument! Try 0 or 1");
699 // parser<int> implementation
701 bool parser<int>::parse(Option &O, const char *ArgName,
702 const std::string &Arg, int &Value) {
704 Value = (int)strtol(Arg.c_str(), &End, 0);
706 return O.error(": '" + Arg + "' value invalid for integer argument!");
710 // parser<unsigned> implementation
712 bool parser<unsigned>::parse(Option &O, const char *ArgName,
713 const std::string &Arg, unsigned &Value) {
716 unsigned long V = strtoul(Arg.c_str(), &End, 0);
718 if (((V == ULONG_MAX) && (errno == ERANGE))
721 return O.error(": '" + Arg + "' value invalid for uint argument!");
725 // parser<double>/parser<float> implementation
727 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
728 const char *ArgStart = Arg.c_str();
730 Value = strtod(ArgStart, &End);
732 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
736 bool parser<double>::parse(Option &O, const char *AN,
737 const std::string &Arg, double &Val) {
738 return parseDouble(O, Arg, Val);
741 bool parser<float>::parse(Option &O, const char *AN,
742 const std::string &Arg, float &Val) {
744 if (parseDouble(O, Arg, dVal))
752 // generic_parser_base implementation
755 // findOption - Return the option number corresponding to the specified
756 // argument string. If the option is not found, getNumOptions() is returned.
758 unsigned generic_parser_base::findOption(const char *Name) {
759 unsigned i = 0, e = getNumOptions();
763 if (getOption(i) == N)
771 // Return the width of the option tag for printing...
772 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
774 unsigned Size = std::strlen(O.ArgStr)+6;
775 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
776 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
779 unsigned BaseSize = 0;
780 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
781 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
786 // printOptionInfo - Print out information about this option. The
787 // to-be-maintained width is specified.
789 void generic_parser_base::printOptionInfo(const Option &O,
790 unsigned GlobalWidth) const {
792 unsigned L = std::strlen(O.ArgStr);
793 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
794 << " - " << O.HelpStr << "\n";
796 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
797 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
798 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
799 << " - " << getDescription(i) << "\n";
803 std::cerr << " " << O.HelpStr << "\n";
804 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
805 unsigned L = std::strlen(getOption(i));
806 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
807 << " - " << getDescription(i) << "\n";
813 //===----------------------------------------------------------------------===//
814 // --help and --help-hidden option implementation
820 const Option *EmptyArg;
821 const bool ShowHidden;
823 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
824 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
825 return OptPair.second->getOptionHiddenFlag() >= Hidden;
827 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
828 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
832 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
836 void operator=(bool Value) {
837 if (Value == false) return;
839 // Copy Options into a vector so we can sort them as we like...
840 std::vector<std::pair<std::string, Option*> > Options;
841 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
843 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
844 Options.erase(std::remove_if(Options.begin(), Options.end(),
845 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
848 // Eliminate duplicate entries in table (from enum flags options, f.e.)
849 { // Give OptionSet a scope
850 std::set<Option*> OptionSet;
851 for (unsigned i = 0; i != Options.size(); ++i)
852 if (OptionSet.count(Options[i].second) == 0)
853 OptionSet.insert(Options[i].second); // Add new entry to set
855 Options.erase(Options.begin()+i--); // Erase duplicate
859 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
861 std::cerr << "USAGE: " << ProgramName << " [options]";
863 // Print out the positional options...
864 std::vector<Option*> &PosOpts = getPositionalOpts();
865 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
866 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
869 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
870 if (PosOpts[i]->ArgStr[0])
871 std::cerr << " --" << PosOpts[i]->ArgStr;
872 std::cerr << " " << PosOpts[i]->HelpStr;
875 // Print the consume after option info if it exists...
876 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
880 // Compute the maximum argument length...
882 for (unsigned i = 0, e = Options.size(); i != e; ++i)
883 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
885 std::cerr << "OPTIONS:\n";
886 for (unsigned i = 0, e = Options.size(); i != e; ++i)
887 Options[i].second->printOptionInfo(MaxArgLen);
889 // Halt the program if help information is printed
896 // Define the two HelpPrinter instances that are used to print out help, or
899 HelpPrinter NormalPrinter(false);
900 HelpPrinter HiddenPrinter(true);
902 cl::opt<HelpPrinter, true, parser<bool> >
903 HOp("help", cl::desc("display available options (--help-hidden for more)"),
904 cl::location(NormalPrinter), cl::ValueDisallowed);
906 cl::opt<HelpPrinter, true, parser<bool> >
907 HHOp("help-hidden", cl::desc("display all available options"),
908 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
910 } // End anonymous namespace