1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
3 // This class implements a command line argument processor that is useful when
4 // creating a tool. It provides a simple, minimalistic interface that is easily
5 // extensible and supports nonlocal (library) command line options.
7 // Note that rather than trying to figure out what this code does, you could try
8 // reading the library documentation located in docs/CommandLine.html
10 //===----------------------------------------------------------------------===//
12 #include "Support/CommandLine.h"
20 //===----------------------------------------------------------------------===//
21 // Basic, shared command line option processing machinery...
24 // Return the global command line option vector. Making it a function scoped
25 // static ensures that it will be initialized correctly before its first use.
27 static std::map<std::string, Option*> *CommandLineOptions = 0;
28 static std::map<std::string, Option*> &getOpts() {
29 if (CommandLineOptions == 0)
30 CommandLineOptions = new std::map<std::string,Option*>();
31 return *CommandLineOptions;
34 static Option *getOption(const std::string &Str) {
35 if (CommandLineOptions == 0) return 0;
36 std::map<std::string,Option*>::iterator I = CommandLineOptions->find(Str);
37 return I != CommandLineOptions->end() ? I->second : 0;
40 static std::vector<Option*> &getPositionalOpts() {
41 static std::vector<Option*> Positional;
45 static void AddArgument(const char *ArgName, Option *Opt) {
46 if (getOption(ArgName)) {
47 std::cerr << "CommandLine Error: Argument '" << ArgName
48 << "' defined more than once!\n";
50 // Add argument to the argument map!
51 getOpts()[ArgName] = Opt;
55 // RemoveArgument - It's possible that the argument is no longer in the map if
56 // options have already been processed and the map has been deleted!
58 static void RemoveArgument(const char *ArgName, Option *Opt) {
59 if (CommandLineOptions == 0) return;
60 assert(getOption(ArgName) == Opt && "Arg not in map!");
61 CommandLineOptions->erase(ArgName);
62 if (CommandLineOptions->empty()) {
63 delete CommandLineOptions;
64 CommandLineOptions = 0;
68 static const char *ProgramName = 0;
69 static const char *ProgramOverview = 0;
71 static inline bool ProvideOption(Option *Handler, const char *ArgName,
72 const char *Value, int argc, char **argv,
74 // Enforce value requirements
75 switch (Handler->getValueExpectedFlag()) {
77 if (Value == 0 || *Value == 0) { // No value specified?
78 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
81 return Handler->error(" requires a value!");
87 return Handler->error(" does not allow a value! '" +
88 std::string(Value) + "' specified.");
90 case ValueOptional: break;
91 default: std::cerr << "Bad ValueMask flag! CommandLine usage error:"
92 << Handler->getValueExpectedFlag() << "\n"; abort();
95 // Run the handler now!
96 return Handler->addOccurrence(ArgName, Value);
99 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg) {
101 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
105 // Option predicates...
106 static inline bool isGrouping(const Option *O) {
107 return O->getFormattingFlag() == cl::Grouping;
109 static inline bool isPrefixedOrGrouping(const Option *O) {
110 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
113 // getOptionPred - Check to see if there are any options that satisfy the
114 // specified predicate with names that are the prefixes in Name. This is
115 // checked by progressively stripping characters off of the name, checking to
116 // see if there options that satisfy the predicate. If we find one, return it,
117 // otherwise return null.
119 static Option *getOptionPred(std::string Name, unsigned &Length,
120 bool (*Pred)(const Option*)) {
122 Option *Op = getOption(Name);
123 if (Op && Pred(Op)) {
124 Length = Name.length();
128 if (Name.size() == 1) return 0;
130 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
131 Op = getOption(Name);
133 // Loop while we haven't found an option and Name still has at least two
134 // characters in it (so that the next iteration will not be the empty
136 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
138 if (Op && Pred(Op)) {
139 Length = Name.length();
140 return Op; // Found one!
142 return 0; // No option found!
145 static bool RequiresValue(const Option *O) {
146 return O->getNumOccurrencesFlag() == cl::Required ||
147 O->getNumOccurrencesFlag() == cl::OneOrMore;
150 static bool EatsUnboundedNumberOfValues(const Option *O) {
151 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
152 O->getNumOccurrencesFlag() == cl::OneOrMore;
155 /// ParseStringVector - Break INPUT up wherever one or more characters
156 /// from DELIMS are found, and store the resulting tokens in OUTPUT.
158 static void ParseStringVector (std::vector<std::string> &output,
159 std::string &input, const char *delims) {
160 std::string work (input);
161 int pos = work.find_first_not_of (delims);
162 if (pos == -1) return;
163 work = work.substr (pos);
164 pos = work.find_first_of (delims);
165 while (!work.empty() && pos != -1) {
166 if (pos == -1) break;
167 output.push_back (work.substr (0,pos));
168 int nextpos = work.find_first_not_of (delims, pos + 1);
170 work = work.substr (work.find_first_not_of (delims, pos + 1));
171 pos = work.find_first_of (delims);
177 if (!work.empty ()) {
178 output.push_back (work);
182 /// ParseCStringVector - Same effect as ParseStringVector, but the
183 /// resulting output vector contains dynamically-allocated pointers to
184 /// char, instead of standard C++ strings.
186 static void ParseCStringVector (std::vector<char *> &output,
187 std::string &input, const char *delims) {
188 std::vector<std::string> work;
189 ParseStringVector (work, input, delims);
190 for (std::vector<std::string>::iterator i = work.begin(), e = work.end();
192 output.push_back (strdup (i->c_str ()));
196 /// ParseEnvironmentOptions - An alternative entry point to the
197 /// CommandLine library, which allows you to read the program's name
198 /// from the caller (as PROGNAME) and its command-line arguments from
199 /// an environment variable (whose name is given in ENVVAR).
201 void cl::ParseEnvironmentOptions (char *progName, char *envvar,
202 const char *Overview) {
203 // Get program's "name", which we wouldn't know without the caller
205 assert (progName && "Program name not specified");
206 static std::vector<char *> newargv; // Maybe making it "static" is a hack.
208 newargv.push_back (progName);
210 // Get the environment variable they want us to parse options out of.
211 assert (envvar && "Environment variable name missing");
212 char *envvalue = getenv (envvar);
213 if (envvalue == NULL) {
214 // Env var not set --> act like there are no more command line
216 newargc = newargv.size ();
217 ParseCommandLineOptions (newargc, &newargv[0], Overview);
220 std::string envvaluestr (envvalue);
222 // Parse the value of the environment variable into a "command line"
223 // and hand it off to ParseCommandLineOptions().
224 ParseCStringVector (newargv, envvaluestr, " \v\f\t\r\n");
225 newargc = newargv.size ();
226 ParseCommandLineOptions (newargc, &newargv[0], Overview);
229 void cl::ParseCommandLineOptions(int &argc, char **argv,
230 const char *Overview) {
231 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
232 "No options specified, or ParseCommandLineOptions called more"
234 ProgramName = argv[0]; // Save this away safe and snug
235 ProgramOverview = Overview;
236 bool ErrorParsing = false;
238 std::map<std::string, Option*> &Opts = getOpts();
239 std::vector<Option*> &PositionalOpts = getPositionalOpts();
241 // Check out the positional arguments to collect information about them.
242 unsigned NumPositionalRequired = 0;
243 Option *ConsumeAfterOpt = 0;
244 if (!PositionalOpts.empty()) {
245 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
246 assert(PositionalOpts.size() > 1 &&
247 "Cannot specify cl::ConsumeAfter without a positional argument!");
248 ConsumeAfterOpt = PositionalOpts[0];
251 // Calculate how many positional values are _required_.
252 bool UnboundedFound = false;
253 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
255 Option *Opt = PositionalOpts[i];
256 if (RequiresValue(Opt))
257 ++NumPositionalRequired;
258 else if (ConsumeAfterOpt) {
259 // ConsumeAfter cannot be combined with "optional" positional options
260 // unless there is only one positional argument...
261 if (PositionalOpts.size() > 2)
263 Opt->error(" error - this positional option will never be matched, "
264 "because it does not Require a value, and a "
265 "cl::ConsumeAfter option is active!");
266 } else if (UnboundedFound && !Opt->ArgStr[0]) {
267 // This option does not "require" a value... Make sure this option is
268 // not specified after an option that eats all extra arguments, or this
269 // one will never get any!
271 ErrorParsing |= Opt->error(" error - option can never match, because "
272 "another positional argument will match an "
273 "unbounded number of values, and this option"
274 " does not require a value!");
276 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
280 // PositionalVals - A vector of "positional" arguments we accumulate into to
281 // processes at the end...
283 std::vector<std::string> PositionalVals;
285 // If the program has named positional arguments, and the name has been run
286 // across, keep track of which positional argument was named. Otherwise put
287 // the positional args into the PositionalVals list...
288 Option *ActivePositionalArg = 0;
290 // Loop over all of the arguments... processing them.
291 bool DashDashFound = false; // Have we read '--'?
292 for (int i = 1; i < argc; ++i) {
294 const char *Value = "";
295 const char *ArgName = "";
297 // Check to see if this is a positional argument. This argument is
298 // considered to be positional if it doesn't start with '-', if it is "-"
299 // itself, or if we have seen "--" already.
301 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
302 // Positional argument!
303 if (ActivePositionalArg) {
304 ProvidePositionalOption(ActivePositionalArg, argv[i]);
305 continue; // We are done!
306 } else if (!PositionalOpts.empty()) {
307 PositionalVals.push_back(argv[i]);
309 // All of the positional arguments have been fulfulled, give the rest to
310 // the consume after option... if it's specified...
312 if (PositionalVals.size() >= NumPositionalRequired &&
313 ConsumeAfterOpt != 0) {
314 for (++i; i < argc; ++i)
315 PositionalVals.push_back(argv[i]);
316 break; // Handle outside of the argument processing loop...
319 // Delay processing positional arguments until the end...
322 } else { // We start with a '-', must be an argument...
324 while (*ArgName == '-') ++ArgName; // Eat leading dashes
326 if (*ArgName == 0 && !DashDashFound) { // Is this the mythical "--"?
327 DashDashFound = true; // Yup, take note of that fact...
328 continue; // Don't try to process it as an argument iself.
331 const char *ArgNameEnd = ArgName;
332 while (*ArgNameEnd && *ArgNameEnd != '=')
333 ++ArgNameEnd; // Scan till end of argument name...
336 if (*Value) // If we have an equals sign...
337 ++Value; // Advance to value...
340 std::string RealName(ArgName, ArgNameEnd);
341 // Extract arg name part
342 std::map<std::string, Option*>::iterator I = Opts.find(RealName);
344 if (I == Opts.end() && !*Value && RealName.size() > 1) {
345 // Check to see if this "option" is really a prefixed or grouped
349 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
351 // If the option is a prefixed option, then the value is simply the
352 // rest of the name... so fall through to later processing, by
353 // setting up the argument name flags and value fields.
355 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
356 ArgNameEnd = ArgName+Length;
358 I = Opts.find(std::string(ArgName, ArgNameEnd));
359 assert(I->second == PGOpt);
361 // This must be a grouped option... handle all of them now...
362 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
365 // Move current arg name out of RealName into RealArgName...
366 std::string RealArgName(RealName.begin(),RealName.begin()+Length);
367 RealName.erase(RealName.begin(), RealName.begin()+Length);
369 // Because ValueRequired is an invalid flag for grouped arguments,
370 // we don't need to pass argc/argv in...
372 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
373 "Option can not be cl::Grouping AND cl::ValueRequired!");
375 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(), "",
378 // Get the next grouping option...
379 if (!RealName.empty())
380 PGOpt = getOptionPred(RealName, Length, isGrouping);
381 } while (!RealName.empty() && PGOpt);
383 if (RealName.empty()) // Processed all of the options, move on
384 continue; // to the next argv[] value...
386 // If RealName is not empty, that means we did not match one of the
387 // options! This is an error.
393 Handler = I != Opts.end() ? I->second : 0;
398 std::cerr << "Unknown command line argument '" << argv[i] << "'. Try: "
399 << argv[0] << " --help'\n";
404 // Check to see if this option accepts a comma separated list of values. If
405 // it does, we have to split up the value into multiple values...
406 if (Handler->getMiscFlags() & CommaSeparated) {
407 std::string Val(Value);
408 std::string::size_type Pos = Val.find(',');
410 while (Pos != std::string::npos) {
411 // Process the portion before the comma...
412 ErrorParsing |= ProvideOption(Handler, ArgName,
413 std::string(Val.begin(),
414 Val.begin()+Pos).c_str(),
416 // Erase the portion before the comma, AND the comma...
417 Val.erase(Val.begin(), Val.begin()+Pos+1);
418 Value += Pos+1; // Increment the original value pointer as well...
420 // Check for another comma...
425 // If this is a named positional argument, just remember that it is the
427 if (Handler->getFormattingFlag() == cl::Positional)
428 ActivePositionalArg = Handler;
430 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
433 // Check and handle positional arguments now...
434 if (NumPositionalRequired > PositionalVals.size()) {
435 std::cerr << "Not enough positional command line arguments specified!\n"
436 << "Must specify at least " << NumPositionalRequired
437 << " positional arguments: See: " << argv[0] << " --help\n";
441 } else if (ConsumeAfterOpt == 0) {
442 // Positional args have already been handled if ConsumeAfter is specified...
443 unsigned ValNo = 0, NumVals = PositionalVals.size();
444 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
445 if (RequiresValue(PositionalOpts[i])) {
446 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
447 --NumPositionalRequired; // We fulfilled our duty...
450 // If we _can_ give this option more arguments, do so now, as long as we
451 // do not give it values that others need. 'Done' controls whether the
452 // option even _WANTS_ any more.
454 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
455 while (NumVals-ValNo > NumPositionalRequired && !Done) {
456 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
458 Done = true; // Optional arguments want _at most_ one value
460 case cl::ZeroOrMore: // Zero or more will take all they can get...
461 case cl::OneOrMore: // One or more will take all they can get...
462 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
465 assert(0 && "Internal error, unexpected NumOccurrences flag in "
466 "positional argument processing!");
471 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
473 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
474 if (RequiresValue(PositionalOpts[j]))
475 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
476 PositionalVals[ValNo++]);
478 // Handle the case where there is just one positional option, and it's
479 // optional. In this case, we want to give JUST THE FIRST option to the
480 // positional option and keep the rest for the consume after. The above
481 // loop would have assigned no values to positional options in this case.
483 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty())
484 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
485 PositionalVals[ValNo++]);
487 // Handle over all of the rest of the arguments to the
488 // cl::ConsumeAfter command line option...
489 for (; ValNo != PositionalVals.size(); ++ValNo)
490 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
491 PositionalVals[ValNo]);
494 // Loop over args and make sure all required args are specified!
495 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
496 E = Opts.end(); I != E; ++I) {
497 switch (I->second->getNumOccurrencesFlag()) {
500 if (I->second->getNumOccurrences() == 0) {
501 I->second->error(" must be specified at least once!");
510 // Free all of the memory allocated to the map. Command line options may only
511 // be processed once!
512 delete CommandLineOptions;
513 CommandLineOptions = 0;
514 PositionalOpts.clear();
516 // If we had an error processing our arguments, don't let the program execute
517 if (ErrorParsing) exit(1);
520 //===----------------------------------------------------------------------===//
521 // Option Base class implementation
524 bool Option::error(std::string Message, const char *ArgName) {
525 if (ArgName == 0) ArgName = ArgStr;
527 std::cerr << HelpStr; // Be nice for positional arguments
529 std::cerr << "-" << ArgName;
530 std::cerr << " option" << Message << "\n";
534 bool Option::addOccurrence(const char *ArgName, const std::string &Value) {
535 NumOccurrences++; // Increment the number of times we have been seen
537 switch (getNumOccurrencesFlag()) {
539 if (NumOccurrences > 1)
540 return error(": may only occur zero or one times!", ArgName);
543 if (NumOccurrences > 1)
544 return error(": must occur exactly one time!", ArgName);
548 case ConsumeAfter: break;
549 default: return error(": bad num occurrences flag value!");
552 return handleOccurrence(ArgName, Value);
555 // addArgument - Tell the system that this Option subclass will handle all
556 // occurrences of -ArgStr on the command line.
558 void Option::addArgument(const char *ArgStr) {
560 AddArgument(ArgStr, this);
562 if (getFormattingFlag() == Positional)
563 getPositionalOpts().push_back(this);
564 else if (getNumOccurrencesFlag() == ConsumeAfter) {
565 if (!getPositionalOpts().empty() &&
566 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
567 error("Cannot specify more than one option with cl::ConsumeAfter!");
568 getPositionalOpts().insert(getPositionalOpts().begin(), this);
572 void Option::removeArgument(const char *ArgStr) {
574 RemoveArgument(ArgStr, this);
576 if (getFormattingFlag() == Positional) {
577 std::vector<Option*>::iterator I =
578 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
579 assert(I != getPositionalOpts().end() && "Arg not registered!");
580 getPositionalOpts().erase(I);
581 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
582 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
583 "Arg not registered correctly!");
584 getPositionalOpts().erase(getPositionalOpts().begin());
589 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
590 // has been specified yet.
592 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
593 if (O.ValueStr[0] == 0) return DefaultMsg;
597 //===----------------------------------------------------------------------===//
598 // cl::alias class implementation
601 // Return the width of the option tag for printing...
602 unsigned alias::getOptionWidth() const {
603 return std::strlen(ArgStr)+6;
606 // Print out the option for the alias...
607 void alias::printOptionInfo(unsigned GlobalWidth) const {
608 unsigned L = std::strlen(ArgStr);
609 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
615 //===----------------------------------------------------------------------===//
616 // Parser Implementation code...
619 // basic_parser implementation
622 // Return the width of the option tag for printing...
623 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
624 unsigned Len = std::strlen(O.ArgStr);
625 if (const char *ValName = getValueName())
626 Len += std::strlen(getValueStr(O, ValName))+3;
631 // printOptionInfo - Print out information about this option. The
632 // to-be-maintained width is specified.
634 void basic_parser_impl::printOptionInfo(const Option &O,
635 unsigned GlobalWidth) const {
636 std::cerr << " -" << O.ArgStr;
638 if (const char *ValName = getValueName())
639 std::cerr << "=<" << getValueStr(O, ValName) << ">";
641 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
642 << O.HelpStr << "\n";
648 // parser<bool> implementation
650 bool parser<bool>::parse(Option &O, const char *ArgName,
651 const std::string &Arg, bool &Value) {
652 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
655 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
658 return O.error(": '" + Arg +
659 "' is invalid value for boolean argument! Try 0 or 1");
664 // parser<int> implementation
666 bool parser<int>::parse(Option &O, const char *ArgName,
667 const std::string &Arg, int &Value) {
669 Value = (int)strtol(Arg.c_str(), &End, 0);
671 return O.error(": '" + Arg + "' value invalid for integer argument!");
675 // parser<unsigned> implementation
677 bool parser<unsigned>::parse(Option &O, const char *ArgName,
678 const std::string &Arg, unsigned &Value) {
680 long long int V = strtoll(Arg.c_str(), &End, 0);
682 if (*End != 0 || V < 0 || Value != V)
683 return O.error(": '" + Arg + "' value invalid for uint argument!");
687 // parser<double>/parser<float> implementation
689 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
690 const char *ArgStart = Arg.c_str();
692 Value = strtod(ArgStart, &End);
694 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
698 bool parser<double>::parse(Option &O, const char *AN,
699 const std::string &Arg, double &Val) {
700 return parseDouble(O, Arg, Val);
703 bool parser<float>::parse(Option &O, const char *AN,
704 const std::string &Arg, float &Val) {
706 if (parseDouble(O, Arg, dVal))
714 // generic_parser_base implementation
717 // findOption - Return the option number corresponding to the specified
718 // argument string. If the option is not found, getNumOptions() is returned.
720 unsigned generic_parser_base::findOption(const char *Name) {
721 unsigned i = 0, e = getNumOptions();
725 if (getOption(i) == N)
733 // Return the width of the option tag for printing...
734 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
736 unsigned Size = std::strlen(O.ArgStr)+6;
737 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
738 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
741 unsigned BaseSize = 0;
742 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
743 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
748 // printOptionInfo - Print out information about this option. The
749 // to-be-maintained width is specified.
751 void generic_parser_base::printOptionInfo(const Option &O,
752 unsigned GlobalWidth) const {
754 unsigned L = std::strlen(O.ArgStr);
755 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
756 << " - " << O.HelpStr << "\n";
758 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
759 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
760 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
761 << " - " << getDescription(i) << "\n";
765 std::cerr << " " << O.HelpStr << "\n";
766 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
767 unsigned L = std::strlen(getOption(i));
768 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
769 << " - " << getDescription(i) << "\n";
775 //===----------------------------------------------------------------------===//
776 // --help and --help-hidden option implementation
782 const Option *EmptyArg;
783 const bool ShowHidden;
785 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
786 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
787 return OptPair.second->getOptionHiddenFlag() >= Hidden;
789 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
790 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
794 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
798 void operator=(bool Value) {
799 if (Value == false) return;
801 // Copy Options into a vector so we can sort them as we like...
802 std::vector<std::pair<std::string, Option*> > Options;
803 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
805 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
806 Options.erase(std::remove_if(Options.begin(), Options.end(),
807 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
810 // Eliminate duplicate entries in table (from enum flags options, f.e.)
811 { // Give OptionSet a scope
812 std::set<Option*> OptionSet;
813 for (unsigned i = 0; i != Options.size(); ++i)
814 if (OptionSet.count(Options[i].second) == 0)
815 OptionSet.insert(Options[i].second); // Add new entry to set
817 Options.erase(Options.begin()+i--); // Erase duplicate
821 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
823 std::cerr << "USAGE: " << ProgramName << " [options]";
825 // Print out the positional options...
826 std::vector<Option*> &PosOpts = getPositionalOpts();
827 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
828 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
831 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
832 if (PosOpts[i]->ArgStr[0])
833 std::cerr << " --" << PosOpts[i]->ArgStr;
834 std::cerr << " " << PosOpts[i]->HelpStr;
837 // Print the consume after option info if it exists...
838 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
842 // Compute the maximum argument length...
844 for (unsigned i = 0, e = Options.size(); i != e; ++i)
845 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
847 std::cerr << "OPTIONS:\n";
848 for (unsigned i = 0, e = Options.size(); i != e; ++i)
849 Options[i].second->printOptionInfo(MaxArgLen);
851 // Halt the program if help information is printed
858 // Define the two HelpPrinter instances that are used to print out help, or
861 HelpPrinter NormalPrinter(false);
862 HelpPrinter HiddenPrinter(true);
864 cl::opt<HelpPrinter, true, parser<bool> >
865 HOp("help", cl::desc("display available options (--help-hidden for more)"),
866 cl::location(NormalPrinter), cl::ValueDisallowed);
868 cl::opt<HelpPrinter, true, parser<bool> >
869 HHOp("help-hidden", cl::desc("display all available options"),
870 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
872 } // End anonymous namespace