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"
22 //===----------------------------------------------------------------------===//
23 // Basic, shared command line option processing machinery...
26 // Return the global command line option vector. Making it a function scoped
27 // static ensures that it will be initialized correctly before its first use.
29 static std::map<std::string, Option*> *CommandLineOptions = 0;
30 static std::map<std::string, Option*> &getOpts() {
31 if (CommandLineOptions == 0)
32 CommandLineOptions = new std::map<std::string,Option*>();
33 return *CommandLineOptions;
36 static Option *getOption(const std::string &Str) {
37 if (CommandLineOptions == 0) return 0;
38 std::map<std::string,Option*>::iterator I = CommandLineOptions->find(Str);
39 return I != CommandLineOptions->end() ? I->second : 0;
42 static std::vector<Option*> &getPositionalOpts() {
43 static std::vector<Option*> Positional;
47 static void AddArgument(const char *ArgName, Option *Opt) {
48 if (getOption(ArgName)) {
49 std::cerr << "CommandLine Error: Argument '" << ArgName
50 << "' defined more than once!\n";
52 // Add argument to the argument map!
53 getOpts()[ArgName] = Opt;
57 // RemoveArgument - It's possible that the argument is no longer in the map if
58 // options have already been processed and the map has been deleted!
60 static void RemoveArgument(const char *ArgName, Option *Opt) {
61 if (CommandLineOptions == 0) return;
62 assert(getOption(ArgName) == Opt && "Arg not in map!");
63 CommandLineOptions->erase(ArgName);
64 if (CommandLineOptions->empty()) {
65 delete CommandLineOptions;
66 CommandLineOptions = 0;
70 static const char *ProgramName = 0;
71 static const char *ProgramOverview = 0;
73 static inline bool ProvideOption(Option *Handler, const char *ArgName,
74 const char *Value, int argc, char **argv,
76 // Enforce value requirements
77 switch (Handler->getValueExpectedFlag()) {
79 if (Value == 0 || *Value == 0) { // No value specified?
80 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
83 return Handler->error(" requires a value!");
89 return Handler->error(" does not allow a value! '" +
90 std::string(Value) + "' specified.");
92 case ValueOptional: break;
93 default: std::cerr << "Bad ValueMask flag! CommandLine usage error:"
94 << Handler->getValueExpectedFlag() << "\n"; abort();
97 // Run the handler now!
98 return Handler->addOccurrence(ArgName, Value);
101 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg) {
103 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
107 // Option predicates...
108 static inline bool isGrouping(const Option *O) {
109 return O->getFormattingFlag() == cl::Grouping;
111 static inline bool isPrefixedOrGrouping(const Option *O) {
112 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
115 // getOptionPred - Check to see if there are any options that satisfy the
116 // specified predicate with names that are the prefixes in Name. This is
117 // checked by progressively stripping characters off of the name, checking to
118 // see if there options that satisfy the predicate. If we find one, return it,
119 // otherwise return null.
121 static Option *getOptionPred(std::string Name, unsigned &Length,
122 bool (*Pred)(const Option*)) {
124 Option *Op = getOption(Name);
125 if (Op && Pred(Op)) {
126 Length = Name.length();
130 if (Name.size() == 1) return 0;
132 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
133 Op = getOption(Name);
135 // Loop while we haven't found an option and Name still has at least two
136 // characters in it (so that the next iteration will not be the empty
138 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
140 if (Op && Pred(Op)) {
141 Length = Name.length();
142 return Op; // Found one!
144 return 0; // No option found!
147 static bool RequiresValue(const Option *O) {
148 return O->getNumOccurrencesFlag() == cl::Required ||
149 O->getNumOccurrencesFlag() == cl::OneOrMore;
152 static bool EatsUnboundedNumberOfValues(const Option *O) {
153 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
154 O->getNumOccurrencesFlag() == cl::OneOrMore;
157 /// ParseCStringVector - Break INPUT up wherever one or more
158 /// whitespace characters are found, and store the resulting tokens in
159 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
160 /// using strdup (), so it is the caller's responsibility to free ()
163 static void ParseCStringVector (std::vector<char *> &output,
165 // Characters which will be treated as token separators:
166 static const char *delims = " \v\f\t\r\n";
168 std::string work (input);
169 // Skip past any delims at head of input string.
170 size_t pos = work.find_first_not_of (delims);
171 // If the string consists entirely of delims, then exit early.
172 if (pos == std::string::npos) return;
173 // Otherwise, jump forward to beginning of first word.
174 work = work.substr (pos);
175 // Find position of first delimiter.
176 pos = work.find_first_of (delims);
178 while (!work.empty() && pos != std::string::npos) {
179 // Everything from 0 to POS is the next word to copy.
180 output.push_back (strdup (work.substr (0,pos).c_str ()));
181 // Is there another word in the string?
182 size_t nextpos = work.find_first_not_of (delims, pos + 1);
183 if (nextpos != std::string::npos) {
184 // Yes? Then remove delims from beginning ...
185 work = work.substr (work.find_first_not_of (delims, pos + 1));
186 // and find the end of the word.
187 pos = work.find_first_of (delims);
189 // No? (Remainder of string is delims.) End the loop.
191 pos = std::string::npos;
195 // If `input' ended with non-delim char, then we'll get here with
196 // the last word of `input' in `work'; copy it now.
197 if (!work.empty ()) {
198 output.push_back (strdup (work.c_str ()));
202 /// ParseEnvironmentOptions - An alternative entry point to the
203 /// CommandLine library, which allows you to read the program's name
204 /// from the caller (as PROGNAME) and its command-line arguments from
205 /// an environment variable (whose name is given in ENVVAR).
207 void cl::ParseEnvironmentOptions (const char *progName, const char *envVar,
208 const char *Overview) {
210 assert (progName && "Program name not specified");
211 assert (envVar && "Environment variable name missing");
213 // Get the environment variable they want us to parse options out of.
214 const char *envValue = getenv (envVar);
218 // Get program's "name", which we wouldn't know without the caller
220 std::vector<char *> newArgv;
221 newArgv.push_back (strdup (progName));
223 // Parse the value of the environment variable into a "command line"
224 // and hand it off to ParseCommandLineOptions().
225 ParseCStringVector (newArgv, envValue);
226 int newArgc = newArgv.size ();
227 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
229 // Free all the strdup()ed strings.
230 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
236 void cl::ParseCommandLineOptions(int &argc, char **argv,
237 const char *Overview) {
238 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
239 "No options specified, or ParseCommandLineOptions called more"
241 ProgramName = argv[0]; // Save this away safe and snug
242 ProgramOverview = Overview;
243 bool ErrorParsing = false;
245 std::map<std::string, Option*> &Opts = getOpts();
246 std::vector<Option*> &PositionalOpts = getPositionalOpts();
248 // Check out the positional arguments to collect information about them.
249 unsigned NumPositionalRequired = 0;
250 Option *ConsumeAfterOpt = 0;
251 if (!PositionalOpts.empty()) {
252 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
253 assert(PositionalOpts.size() > 1 &&
254 "Cannot specify cl::ConsumeAfter without a positional argument!");
255 ConsumeAfterOpt = PositionalOpts[0];
258 // Calculate how many positional values are _required_.
259 bool UnboundedFound = false;
260 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
262 Option *Opt = PositionalOpts[i];
263 if (RequiresValue(Opt))
264 ++NumPositionalRequired;
265 else if (ConsumeAfterOpt) {
266 // ConsumeAfter cannot be combined with "optional" positional options
267 // unless there is only one positional argument...
268 if (PositionalOpts.size() > 2)
270 Opt->error(" error - this positional option will never be matched, "
271 "because it does not Require a value, and a "
272 "cl::ConsumeAfter option is active!");
273 } else if (UnboundedFound && !Opt->ArgStr[0]) {
274 // This option does not "require" a value... Make sure this option is
275 // not specified after an option that eats all extra arguments, or this
276 // one will never get any!
278 ErrorParsing |= Opt->error(" error - option can never match, because "
279 "another positional argument will match an "
280 "unbounded number of values, and this option"
281 " does not require a value!");
283 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
287 // PositionalVals - A vector of "positional" arguments we accumulate into to
288 // processes at the end...
290 std::vector<std::string> PositionalVals;
292 // If the program has named positional arguments, and the name has been run
293 // across, keep track of which positional argument was named. Otherwise put
294 // the positional args into the PositionalVals list...
295 Option *ActivePositionalArg = 0;
297 // Loop over all of the arguments... processing them.
298 bool DashDashFound = false; // Have we read '--'?
299 for (int i = 1; i < argc; ++i) {
301 const char *Value = "";
302 const char *ArgName = "";
304 // Check to see if this is a positional argument. This argument is
305 // considered to be positional if it doesn't start with '-', if it is "-"
306 // itself, or if we have seen "--" already.
308 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
309 // Positional argument!
310 if (ActivePositionalArg) {
311 ProvidePositionalOption(ActivePositionalArg, argv[i]);
312 continue; // We are done!
313 } else if (!PositionalOpts.empty()) {
314 PositionalVals.push_back(argv[i]);
316 // All of the positional arguments have been fulfulled, give the rest to
317 // the consume after option... if it's specified...
319 if (PositionalVals.size() >= NumPositionalRequired &&
320 ConsumeAfterOpt != 0) {
321 for (++i; i < argc; ++i)
322 PositionalVals.push_back(argv[i]);
323 break; // Handle outside of the argument processing loop...
326 // Delay processing positional arguments until the end...
329 } else { // We start with a '-', must be an argument...
331 while (*ArgName == '-') ++ArgName; // Eat leading dashes
333 if (*ArgName == 0 && !DashDashFound) { // Is this the mythical "--"?
334 DashDashFound = true; // Yup, take note of that fact...
335 continue; // Don't try to process it as an argument itself.
338 const char *ArgNameEnd = ArgName;
339 while (*ArgNameEnd && *ArgNameEnd != '=')
340 ++ArgNameEnd; // Scan till end of argument name...
343 if (*Value) // If we have an equals sign...
344 ++Value; // Advance to value...
347 std::string RealName(ArgName, ArgNameEnd);
348 // Extract arg name part
349 std::map<std::string, Option*>::iterator I = Opts.find(RealName);
351 if (I == Opts.end() && !*Value && RealName.size() > 1) {
352 // Check to see if this "option" is really a prefixed or grouped
356 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
358 // If the option is a prefixed option, then the value is simply the
359 // rest of the name... so fall through to later processing, by
360 // setting up the argument name flags and value fields.
362 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
363 ArgNameEnd = ArgName+Length;
365 I = Opts.find(std::string(ArgName, ArgNameEnd));
366 assert(I->second == PGOpt);
368 // This must be a grouped option... handle all of them now...
369 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
372 // Move current arg name out of RealName into RealArgName...
373 std::string RealArgName(RealName.begin(),RealName.begin()+Length);
374 RealName.erase(RealName.begin(), RealName.begin()+Length);
376 // Because ValueRequired is an invalid flag for grouped arguments,
377 // we don't need to pass argc/argv in...
379 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
380 "Option can not be cl::Grouping AND cl::ValueRequired!");
382 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(), "",
385 // Get the next grouping option...
386 if (!RealName.empty())
387 PGOpt = getOptionPred(RealName, Length, isGrouping);
388 } while (!RealName.empty() && PGOpt);
390 if (RealName.empty()) // Processed all of the options, move on
391 continue; // to the next argv[] value...
393 // If RealName is not empty, that means we did not match one of the
394 // options! This is an error.
400 Handler = I != Opts.end() ? I->second : 0;
405 std::cerr << "Unknown command line argument '" << argv[i] << "'. Try: '"
406 << argv[0] << " --help'\n";
411 // Check to see if this option accepts a comma separated list of values. If
412 // it does, we have to split up the value into multiple values...
413 if (Handler->getMiscFlags() & CommaSeparated) {
414 std::string Val(Value);
415 std::string::size_type Pos = Val.find(',');
417 while (Pos != std::string::npos) {
418 // Process the portion before the comma...
419 ErrorParsing |= ProvideOption(Handler, ArgName,
420 std::string(Val.begin(),
421 Val.begin()+Pos).c_str(),
423 // Erase the portion before the comma, AND the comma...
424 Val.erase(Val.begin(), Val.begin()+Pos+1);
425 Value += Pos+1; // Increment the original value pointer as well...
427 // Check for another comma...
432 // If this is a named positional argument, just remember that it is the
434 if (Handler->getFormattingFlag() == cl::Positional)
435 ActivePositionalArg = Handler;
437 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
440 // Check and handle positional arguments now...
441 if (NumPositionalRequired > PositionalVals.size()) {
442 std::cerr << "Not enough positional command line arguments specified!\n"
443 << "Must specify at least " << NumPositionalRequired
444 << " positional arguments: See: " << argv[0] << " --help\n";
448 } else if (ConsumeAfterOpt == 0) {
449 // Positional args have already been handled if ConsumeAfter is specified...
450 unsigned ValNo = 0, NumVals = PositionalVals.size();
451 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
452 if (RequiresValue(PositionalOpts[i])) {
453 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
454 --NumPositionalRequired; // We fulfilled our duty...
457 // If we _can_ give this option more arguments, do so now, as long as we
458 // do not give it values that others need. 'Done' controls whether the
459 // option even _WANTS_ any more.
461 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
462 while (NumVals-ValNo > NumPositionalRequired && !Done) {
463 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
465 Done = true; // Optional arguments want _at most_ one value
467 case cl::ZeroOrMore: // Zero or more will take all they can get...
468 case cl::OneOrMore: // One or more will take all they can get...
469 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
472 assert(0 && "Internal error, unexpected NumOccurrences flag in "
473 "positional argument processing!");
478 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
480 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
481 if (RequiresValue(PositionalOpts[j]))
482 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
483 PositionalVals[ValNo++]);
485 // Handle the case where there is just one positional option, and it's
486 // optional. In this case, we want to give JUST THE FIRST option to the
487 // positional option and keep the rest for the consume after. The above
488 // loop would have assigned no values to positional options in this case.
490 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty())
491 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
492 PositionalVals[ValNo++]);
494 // Handle over all of the rest of the arguments to the
495 // cl::ConsumeAfter command line option...
496 for (; ValNo != PositionalVals.size(); ++ValNo)
497 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
498 PositionalVals[ValNo]);
501 // Loop over args and make sure all required args are specified!
502 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
503 E = Opts.end(); I != E; ++I) {
504 switch (I->second->getNumOccurrencesFlag()) {
507 if (I->second->getNumOccurrences() == 0) {
508 I->second->error(" must be specified at least once!");
517 // Free all of the memory allocated to the map. Command line options may only
518 // be processed once!
519 delete CommandLineOptions;
520 CommandLineOptions = 0;
521 PositionalOpts.clear();
523 // If we had an error processing our arguments, don't let the program execute
524 if (ErrorParsing) exit(1);
527 //===----------------------------------------------------------------------===//
528 // Option Base class implementation
531 bool Option::error(std::string Message, const char *ArgName) {
532 if (ArgName == 0) ArgName = ArgStr;
534 std::cerr << HelpStr; // Be nice for positional arguments
536 std::cerr << "-" << ArgName;
537 std::cerr << " option" << Message << "\n";
541 bool Option::addOccurrence(const char *ArgName, const std::string &Value) {
542 NumOccurrences++; // Increment the number of times we have been seen
544 switch (getNumOccurrencesFlag()) {
546 if (NumOccurrences > 1)
547 return error(": may only occur zero or one times!", ArgName);
550 if (NumOccurrences > 1)
551 return error(": must occur exactly one time!", ArgName);
555 case ConsumeAfter: break;
556 default: return error(": bad num occurrences flag value!");
559 return handleOccurrence(ArgName, Value);
562 // addArgument - Tell the system that this Option subclass will handle all
563 // occurrences of -ArgStr on the command line.
565 void Option::addArgument(const char *ArgStr) {
567 AddArgument(ArgStr, this);
569 if (getFormattingFlag() == Positional)
570 getPositionalOpts().push_back(this);
571 else if (getNumOccurrencesFlag() == ConsumeAfter) {
572 if (!getPositionalOpts().empty() &&
573 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
574 error("Cannot specify more than one option with cl::ConsumeAfter!");
575 getPositionalOpts().insert(getPositionalOpts().begin(), this);
579 void Option::removeArgument(const char *ArgStr) {
581 RemoveArgument(ArgStr, this);
583 if (getFormattingFlag() == Positional) {
584 std::vector<Option*>::iterator I =
585 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
586 assert(I != getPositionalOpts().end() && "Arg not registered!");
587 getPositionalOpts().erase(I);
588 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
589 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
590 "Arg not registered correctly!");
591 getPositionalOpts().erase(getPositionalOpts().begin());
596 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
597 // has been specified yet.
599 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
600 if (O.ValueStr[0] == 0) return DefaultMsg;
604 //===----------------------------------------------------------------------===//
605 // cl::alias class implementation
608 // Return the width of the option tag for printing...
609 unsigned alias::getOptionWidth() const {
610 return std::strlen(ArgStr)+6;
613 // Print out the option for the alias...
614 void alias::printOptionInfo(unsigned GlobalWidth) const {
615 unsigned L = std::strlen(ArgStr);
616 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
622 //===----------------------------------------------------------------------===//
623 // Parser Implementation code...
626 // basic_parser implementation
629 // Return the width of the option tag for printing...
630 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
631 unsigned Len = std::strlen(O.ArgStr);
632 if (const char *ValName = getValueName())
633 Len += std::strlen(getValueStr(O, ValName))+3;
638 // printOptionInfo - Print out information about this option. The
639 // to-be-maintained width is specified.
641 void basic_parser_impl::printOptionInfo(const Option &O,
642 unsigned GlobalWidth) const {
643 std::cerr << " -" << O.ArgStr;
645 if (const char *ValName = getValueName())
646 std::cerr << "=<" << getValueStr(O, ValName) << ">";
648 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
649 << O.HelpStr << "\n";
655 // parser<bool> implementation
657 bool parser<bool>::parse(Option &O, const char *ArgName,
658 const std::string &Arg, bool &Value) {
659 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
662 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
665 return O.error(": '" + Arg +
666 "' is invalid value for boolean argument! Try 0 or 1");
671 // parser<int> implementation
673 bool parser<int>::parse(Option &O, const char *ArgName,
674 const std::string &Arg, int &Value) {
676 Value = (int)strtol(Arg.c_str(), &End, 0);
678 return O.error(": '" + Arg + "' value invalid for integer argument!");
682 // parser<unsigned> implementation
684 bool parser<unsigned>::parse(Option &O, const char *ArgName,
685 const std::string &Arg, unsigned &Value) {
688 unsigned long V = strtoul(Arg.c_str(), &End, 0);
690 if (((V == ULONG_MAX) && (errno == ERANGE))
693 return O.error(": '" + Arg + "' value invalid for uint argument!");
697 // parser<double>/parser<float> implementation
699 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
700 const char *ArgStart = Arg.c_str();
702 Value = strtod(ArgStart, &End);
704 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
708 bool parser<double>::parse(Option &O, const char *AN,
709 const std::string &Arg, double &Val) {
710 return parseDouble(O, Arg, Val);
713 bool parser<float>::parse(Option &O, const char *AN,
714 const std::string &Arg, float &Val) {
716 if (parseDouble(O, Arg, dVal))
724 // generic_parser_base implementation
727 // findOption - Return the option number corresponding to the specified
728 // argument string. If the option is not found, getNumOptions() is returned.
730 unsigned generic_parser_base::findOption(const char *Name) {
731 unsigned i = 0, e = getNumOptions();
735 if (getOption(i) == N)
743 // Return the width of the option tag for printing...
744 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
746 unsigned Size = std::strlen(O.ArgStr)+6;
747 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
748 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
751 unsigned BaseSize = 0;
752 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
753 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
758 // printOptionInfo - Print out information about this option. The
759 // to-be-maintained width is specified.
761 void generic_parser_base::printOptionInfo(const Option &O,
762 unsigned GlobalWidth) const {
764 unsigned L = std::strlen(O.ArgStr);
765 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
766 << " - " << O.HelpStr << "\n";
768 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
769 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
770 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
771 << " - " << getDescription(i) << "\n";
775 std::cerr << " " << O.HelpStr << "\n";
776 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
777 unsigned L = std::strlen(getOption(i));
778 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
779 << " - " << getDescription(i) << "\n";
785 //===----------------------------------------------------------------------===//
786 // --help and --help-hidden option implementation
792 const Option *EmptyArg;
793 const bool ShowHidden;
795 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
796 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
797 return OptPair.second->getOptionHiddenFlag() >= Hidden;
799 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
800 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
804 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
808 void operator=(bool Value) {
809 if (Value == false) return;
811 // Copy Options into a vector so we can sort them as we like...
812 std::vector<std::pair<std::string, Option*> > Options;
813 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
815 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
816 Options.erase(std::remove_if(Options.begin(), Options.end(),
817 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
820 // Eliminate duplicate entries in table (from enum flags options, f.e.)
821 { // Give OptionSet a scope
822 std::set<Option*> OptionSet;
823 for (unsigned i = 0; i != Options.size(); ++i)
824 if (OptionSet.count(Options[i].second) == 0)
825 OptionSet.insert(Options[i].second); // Add new entry to set
827 Options.erase(Options.begin()+i--); // Erase duplicate
831 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
833 std::cerr << "USAGE: " << ProgramName << " [options]";
835 // Print out the positional options...
836 std::vector<Option*> &PosOpts = getPositionalOpts();
837 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
838 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
841 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
842 if (PosOpts[i]->ArgStr[0])
843 std::cerr << " --" << PosOpts[i]->ArgStr;
844 std::cerr << " " << PosOpts[i]->HelpStr;
847 // Print the consume after option info if it exists...
848 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
852 // Compute the maximum argument length...
854 for (unsigned i = 0, e = Options.size(); i != e; ++i)
855 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
857 std::cerr << "OPTIONS:\n";
858 for (unsigned i = 0, e = Options.size(); i != e; ++i)
859 Options[i].second->printOptionInfo(MaxArgLen);
861 // Halt the program if help information is printed
868 // Define the two HelpPrinter instances that are used to print out help, or
871 HelpPrinter NormalPrinter(false);
872 HelpPrinter HiddenPrinter(true);
874 cl::opt<HelpPrinter, true, parser<bool> >
875 HOp("help", cl::desc("display available options (--help-hidden for more)"),
876 cl::location(NormalPrinter), cl::ValueDisallowed);
878 cl::opt<HelpPrinter, true, parser<bool> >
879 HHOp("help-hidden", cl::desc("display all available options"),
880 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
882 } // End anonymous namespace