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"
30 //===----------------------------------------------------------------------===//
31 // Basic, shared command line option processing machinery...
34 // Return the global command line option vector. Making it a function scoped
35 // static ensures that it will be initialized correctly before its first use.
37 static std::map<std::string, Option*> *CommandLineOptions = 0;
38 static std::map<std::string, Option*> &getOpts() {
39 if (CommandLineOptions == 0)
40 CommandLineOptions = new std::map<std::string,Option*>();
41 return *CommandLineOptions;
44 static Option *getOption(const std::string &Str) {
45 if (CommandLineOptions == 0) return 0;
46 std::map<std::string,Option*>::iterator I = CommandLineOptions->find(Str);
47 return I != CommandLineOptions->end() ? I->second : 0;
50 static std::vector<Option*> &getPositionalOpts() {
51 static std::vector<Option*> Positional;
55 static void AddArgument(const char *ArgName, Option *Opt) {
56 if (getOption(ArgName)) {
57 std::cerr << "CommandLine Error: Argument '" << ArgName
58 << "' defined more than once!\n";
60 // Add argument to the argument map!
61 getOpts()[ArgName] = Opt;
65 // RemoveArgument - It's possible that the argument is no longer in the map if
66 // options have already been processed and the map has been deleted!
68 static void RemoveArgument(const char *ArgName, Option *Opt) {
69 if (CommandLineOptions == 0) return;
70 assert(getOption(ArgName) == Opt && "Arg not in map!");
71 CommandLineOptions->erase(ArgName);
72 if (CommandLineOptions->empty()) {
73 delete CommandLineOptions;
74 CommandLineOptions = 0;
78 static const char *ProgramName = 0;
79 static const char *ProgramOverview = 0;
81 static inline bool ProvideOption(Option *Handler, const char *ArgName,
82 const char *Value, int argc, char **argv,
84 // Enforce value requirements
85 switch (Handler->getValueExpectedFlag()) {
87 if (Value == 0 || *Value == 0) { // No value specified?
88 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
91 return Handler->error(" requires a value!");
97 return Handler->error(" does not allow a value! '" +
98 std::string(Value) + "' specified.");
100 case ValueOptional: break;
101 default: std::cerr << "Bad ValueMask flag! CommandLine usage error:"
102 << Handler->getValueExpectedFlag() << "\n"; abort();
105 // Run the handler now!
106 return Handler->addOccurrence(ArgName, Value);
109 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg) {
111 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
115 // Option predicates...
116 static inline bool isGrouping(const Option *O) {
117 return O->getFormattingFlag() == cl::Grouping;
119 static inline bool isPrefixedOrGrouping(const Option *O) {
120 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
123 // getOptionPred - Check to see if there are any options that satisfy the
124 // specified predicate with names that are the prefixes in Name. This is
125 // checked by progressively stripping characters off of the name, checking to
126 // see if there options that satisfy the predicate. If we find one, return it,
127 // otherwise return null.
129 static Option *getOptionPred(std::string Name, unsigned &Length,
130 bool (*Pred)(const Option*)) {
132 Option *Op = getOption(Name);
133 if (Op && Pred(Op)) {
134 Length = Name.length();
138 if (Name.size() == 1) return 0;
140 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
141 Op = getOption(Name);
143 // Loop while we haven't found an option and Name still has at least two
144 // characters in it (so that the next iteration will not be the empty
146 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
148 if (Op && Pred(Op)) {
149 Length = Name.length();
150 return Op; // Found one!
152 return 0; // No option found!
155 static bool RequiresValue(const Option *O) {
156 return O->getNumOccurrencesFlag() == cl::Required ||
157 O->getNumOccurrencesFlag() == cl::OneOrMore;
160 static bool EatsUnboundedNumberOfValues(const Option *O) {
161 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
162 O->getNumOccurrencesFlag() == cl::OneOrMore;
165 /// ParseCStringVector - Break INPUT up wherever one or more
166 /// whitespace characters are found, and store the resulting tokens in
167 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
168 /// using strdup (), so it is the caller's responsibility to free ()
171 static void ParseCStringVector (std::vector<char *> &output,
173 // Characters which will be treated as token separators:
174 static const char *delims = " \v\f\t\r\n";
176 std::string work (input);
177 // Skip past any delims at head of input string.
178 size_t pos = work.find_first_not_of (delims);
179 // If the string consists entirely of delims, then exit early.
180 if (pos == std::string::npos) return;
181 // Otherwise, jump forward to beginning of first word.
182 work = work.substr (pos);
183 // Find position of first delimiter.
184 pos = work.find_first_of (delims);
186 while (!work.empty() && pos != std::string::npos) {
187 // Everything from 0 to POS is the next word to copy.
188 output.push_back (strdup (work.substr (0,pos).c_str ()));
189 // Is there another word in the string?
190 size_t nextpos = work.find_first_not_of (delims, pos + 1);
191 if (nextpos != std::string::npos) {
192 // Yes? Then remove delims from beginning ...
193 work = work.substr (work.find_first_not_of (delims, pos + 1));
194 // and find the end of the word.
195 pos = work.find_first_of (delims);
197 // No? (Remainder of string is delims.) End the loop.
199 pos = std::string::npos;
203 // If `input' ended with non-delim char, then we'll get here with
204 // the last word of `input' in `work'; copy it now.
205 if (!work.empty ()) {
206 output.push_back (strdup (work.c_str ()));
210 /// ParseEnvironmentOptions - An alternative entry point to the
211 /// CommandLine library, which allows you to read the program's name
212 /// from the caller (as PROGNAME) and its command-line arguments from
213 /// an environment variable (whose name is given in ENVVAR).
215 void cl::ParseEnvironmentOptions (const char *progName, const char *envVar,
216 const char *Overview) {
218 assert (progName && "Program name not specified");
219 assert (envVar && "Environment variable name missing");
221 // Get the environment variable they want us to parse options out of.
222 const char *envValue = getenv (envVar);
226 // Get program's "name", which we wouldn't know without the caller
228 std::vector<char *> newArgv;
229 newArgv.push_back (strdup (progName));
231 // Parse the value of the environment variable into a "command line"
232 // and hand it off to ParseCommandLineOptions().
233 ParseCStringVector (newArgv, envValue);
234 int newArgc = newArgv.size ();
235 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
237 // Free all the strdup()ed strings.
238 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
244 void cl::ParseCommandLineOptions(int &argc, char **argv,
245 const char *Overview) {
246 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
247 "No options specified, or ParseCommandLineOptions called more"
249 ProgramName = argv[0]; // Save this away safe and snug
250 ProgramOverview = Overview;
251 bool ErrorParsing = false;
253 std::map<std::string, Option*> &Opts = getOpts();
254 std::vector<Option*> &PositionalOpts = getPositionalOpts();
256 // Check out the positional arguments to collect information about them.
257 unsigned NumPositionalRequired = 0;
258 Option *ConsumeAfterOpt = 0;
259 if (!PositionalOpts.empty()) {
260 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
261 assert(PositionalOpts.size() > 1 &&
262 "Cannot specify cl::ConsumeAfter without a positional argument!");
263 ConsumeAfterOpt = PositionalOpts[0];
266 // Calculate how many positional values are _required_.
267 bool UnboundedFound = false;
268 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
270 Option *Opt = PositionalOpts[i];
271 if (RequiresValue(Opt))
272 ++NumPositionalRequired;
273 else if (ConsumeAfterOpt) {
274 // ConsumeAfter cannot be combined with "optional" positional options
275 // unless there is only one positional argument...
276 if (PositionalOpts.size() > 2)
278 Opt->error(" error - this positional option will never be matched, "
279 "because it does not Require a value, and a "
280 "cl::ConsumeAfter option is active!");
281 } else if (UnboundedFound && !Opt->ArgStr[0]) {
282 // This option does not "require" a value... Make sure this option is
283 // not specified after an option that eats all extra arguments, or this
284 // one will never get any!
286 ErrorParsing |= Opt->error(" error - option can never match, because "
287 "another positional argument will match an "
288 "unbounded number of values, and this option"
289 " does not require a value!");
291 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
295 // PositionalVals - A vector of "positional" arguments we accumulate into to
296 // processes at the end...
298 std::vector<std::string> PositionalVals;
300 // If the program has named positional arguments, and the name has been run
301 // across, keep track of which positional argument was named. Otherwise put
302 // the positional args into the PositionalVals list...
303 Option *ActivePositionalArg = 0;
305 // Loop over all of the arguments... processing them.
306 bool DashDashFound = false; // Have we read '--'?
307 for (int i = 1; i < argc; ++i) {
309 const char *Value = "";
310 const char *ArgName = "";
312 // Check to see if this is a positional argument. This argument is
313 // considered to be positional if it doesn't start with '-', if it is "-"
314 // itself, or if we have seen "--" already.
316 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
317 // Positional argument!
318 if (ActivePositionalArg) {
319 ProvidePositionalOption(ActivePositionalArg, argv[i]);
320 continue; // We are done!
321 } else if (!PositionalOpts.empty()) {
322 PositionalVals.push_back(argv[i]);
324 // All of the positional arguments have been fulfulled, give the rest to
325 // the consume after option... if it's specified...
327 if (PositionalVals.size() >= NumPositionalRequired &&
328 ConsumeAfterOpt != 0) {
329 for (++i; i < argc; ++i)
330 PositionalVals.push_back(argv[i]);
331 break; // Handle outside of the argument processing loop...
334 // Delay processing positional arguments until the end...
337 } else { // We start with a '-', must be an argument...
339 while (*ArgName == '-') ++ArgName; // Eat leading dashes
341 if (*ArgName == 0 && !DashDashFound) { // Is this the mythical "--"?
342 DashDashFound = true; // Yup, take note of that fact...
343 continue; // Don't try to process it as an argument itself.
346 const char *ArgNameEnd = ArgName;
347 while (*ArgNameEnd && *ArgNameEnd != '=')
348 ++ArgNameEnd; // Scan till end of argument name...
351 if (*Value) // If we have an equals sign...
352 ++Value; // Advance to value...
355 std::string RealName(ArgName, ArgNameEnd);
356 // Extract arg name part
357 std::map<std::string, Option*>::iterator I = Opts.find(RealName);
359 if (I == Opts.end() && !*Value && RealName.size() > 1) {
360 // Check to see if this "option" is really a prefixed or grouped
364 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
366 // If the option is a prefixed option, then the value is simply the
367 // rest of the name... so fall through to later processing, by
368 // setting up the argument name flags and value fields.
370 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
371 ArgNameEnd = ArgName+Length;
373 I = Opts.find(std::string(ArgName, ArgNameEnd));
374 assert(I->second == PGOpt);
376 // This must be a grouped option... handle all of them now...
377 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
380 // Move current arg name out of RealName into RealArgName...
381 std::string RealArgName(RealName.begin(),RealName.begin()+Length);
382 RealName.erase(RealName.begin(), RealName.begin()+Length);
384 // Because ValueRequired is an invalid flag for grouped arguments,
385 // we don't need to pass argc/argv in...
387 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
388 "Option can not be cl::Grouping AND cl::ValueRequired!");
390 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(), "",
393 // Get the next grouping option...
394 if (!RealName.empty())
395 PGOpt = getOptionPred(RealName, Length, isGrouping);
396 } while (!RealName.empty() && PGOpt);
398 if (RealName.empty()) // Processed all of the options, move on
399 continue; // to the next argv[] value...
401 // If RealName is not empty, that means we did not match one of the
402 // options! This is an error.
408 Handler = I != Opts.end() ? I->second : 0;
413 std::cerr << "Unknown command line argument '" << argv[i] << "'. Try: '"
414 << argv[0] << " --help'\n";
419 // Check to see if this option accepts a comma separated list of values. If
420 // it does, we have to split up the value into multiple values...
421 if (Handler->getMiscFlags() & CommaSeparated) {
422 std::string Val(Value);
423 std::string::size_type Pos = Val.find(',');
425 while (Pos != std::string::npos) {
426 // Process the portion before the comma...
427 ErrorParsing |= ProvideOption(Handler, ArgName,
428 std::string(Val.begin(),
429 Val.begin()+Pos).c_str(),
431 // Erase the portion before the comma, AND the comma...
432 Val.erase(Val.begin(), Val.begin()+Pos+1);
433 Value += Pos+1; // Increment the original value pointer as well...
435 // Check for another comma...
440 // If this is a named positional argument, just remember that it is the
442 if (Handler->getFormattingFlag() == cl::Positional)
443 ActivePositionalArg = Handler;
445 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
448 // Check and handle positional arguments now...
449 if (NumPositionalRequired > PositionalVals.size()) {
450 std::cerr << "Not enough positional command line arguments specified!\n"
451 << "Must specify at least " << NumPositionalRequired
452 << " positional arguments: See: " << argv[0] << " --help\n";
456 } else if (ConsumeAfterOpt == 0) {
457 // Positional args have already been handled if ConsumeAfter is specified...
458 unsigned ValNo = 0, NumVals = PositionalVals.size();
459 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
460 if (RequiresValue(PositionalOpts[i])) {
461 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
462 --NumPositionalRequired; // We fulfilled our duty...
465 // If we _can_ give this option more arguments, do so now, as long as we
466 // do not give it values that others need. 'Done' controls whether the
467 // option even _WANTS_ any more.
469 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
470 while (NumVals-ValNo > NumPositionalRequired && !Done) {
471 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
473 Done = true; // Optional arguments want _at most_ one value
475 case cl::ZeroOrMore: // Zero or more will take all they can get...
476 case cl::OneOrMore: // One or more will take all they can get...
477 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
480 assert(0 && "Internal error, unexpected NumOccurrences flag in "
481 "positional argument processing!");
486 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
488 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
489 if (RequiresValue(PositionalOpts[j]))
490 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
491 PositionalVals[ValNo++]);
493 // Handle the case where there is just one positional option, and it's
494 // optional. In this case, we want to give JUST THE FIRST option to the
495 // positional option and keep the rest for the consume after. The above
496 // loop would have assigned no values to positional options in this case.
498 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty())
499 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
500 PositionalVals[ValNo++]);
502 // Handle over all of the rest of the arguments to the
503 // cl::ConsumeAfter command line option...
504 for (; ValNo != PositionalVals.size(); ++ValNo)
505 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
506 PositionalVals[ValNo]);
509 // Loop over args and make sure all required args are specified!
510 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
511 E = Opts.end(); I != E; ++I) {
512 switch (I->second->getNumOccurrencesFlag()) {
515 if (I->second->getNumOccurrences() == 0) {
516 I->second->error(" must be specified at least once!");
525 // Free all of the memory allocated to the map. Command line options may only
526 // be processed once!
527 delete CommandLineOptions;
528 CommandLineOptions = 0;
529 PositionalOpts.clear();
531 // If we had an error processing our arguments, don't let the program execute
532 if (ErrorParsing) exit(1);
535 //===----------------------------------------------------------------------===//
536 // Option Base class implementation
539 bool Option::error(std::string Message, const char *ArgName) {
540 if (ArgName == 0) ArgName = ArgStr;
542 std::cerr << HelpStr; // Be nice for positional arguments
544 std::cerr << "-" << ArgName;
545 std::cerr << " option" << Message << "\n";
549 bool Option::addOccurrence(const char *ArgName, const std::string &Value) {
550 NumOccurrences++; // Increment the number of times we have been seen
552 switch (getNumOccurrencesFlag()) {
554 if (NumOccurrences > 1)
555 return error(": may only occur zero or one times!", ArgName);
558 if (NumOccurrences > 1)
559 return error(": must occur exactly one time!", ArgName);
563 case ConsumeAfter: break;
564 default: return error(": bad num occurrences flag value!");
567 return handleOccurrence(ArgName, Value);
570 // addArgument - Tell the system that this Option subclass will handle all
571 // occurrences of -ArgStr on the command line.
573 void Option::addArgument(const char *ArgStr) {
575 AddArgument(ArgStr, this);
577 if (getFormattingFlag() == Positional)
578 getPositionalOpts().push_back(this);
579 else if (getNumOccurrencesFlag() == ConsumeAfter) {
580 if (!getPositionalOpts().empty() &&
581 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
582 error("Cannot specify more than one option with cl::ConsumeAfter!");
583 getPositionalOpts().insert(getPositionalOpts().begin(), this);
587 void Option::removeArgument(const char *ArgStr) {
589 RemoveArgument(ArgStr, this);
591 if (getFormattingFlag() == Positional) {
592 std::vector<Option*>::iterator I =
593 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
594 assert(I != getPositionalOpts().end() && "Arg not registered!");
595 getPositionalOpts().erase(I);
596 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
597 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
598 "Arg not registered correctly!");
599 getPositionalOpts().erase(getPositionalOpts().begin());
604 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
605 // has been specified yet.
607 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
608 if (O.ValueStr[0] == 0) return DefaultMsg;
612 //===----------------------------------------------------------------------===//
613 // cl::alias class implementation
616 // Return the width of the option tag for printing...
617 unsigned alias::getOptionWidth() const {
618 return std::strlen(ArgStr)+6;
621 // Print out the option for the alias...
622 void alias::printOptionInfo(unsigned GlobalWidth) const {
623 unsigned L = std::strlen(ArgStr);
624 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
630 //===----------------------------------------------------------------------===//
631 // Parser Implementation code...
634 // basic_parser implementation
637 // Return the width of the option tag for printing...
638 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
639 unsigned Len = std::strlen(O.ArgStr);
640 if (const char *ValName = getValueName())
641 Len += std::strlen(getValueStr(O, ValName))+3;
646 // printOptionInfo - Print out information about this option. The
647 // to-be-maintained width is specified.
649 void basic_parser_impl::printOptionInfo(const Option &O,
650 unsigned GlobalWidth) const {
651 std::cerr << " -" << O.ArgStr;
653 if (const char *ValName = getValueName())
654 std::cerr << "=<" << getValueStr(O, ValName) << ">";
656 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
657 << O.HelpStr << "\n";
663 // parser<bool> implementation
665 bool parser<bool>::parse(Option &O, const char *ArgName,
666 const std::string &Arg, bool &Value) {
667 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
670 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
673 return O.error(": '" + Arg +
674 "' is invalid value for boolean argument! Try 0 or 1");
679 // parser<int> implementation
681 bool parser<int>::parse(Option &O, const char *ArgName,
682 const std::string &Arg, int &Value) {
684 Value = (int)strtol(Arg.c_str(), &End, 0);
686 return O.error(": '" + Arg + "' value invalid for integer argument!");
690 // parser<unsigned> implementation
692 bool parser<unsigned>::parse(Option &O, const char *ArgName,
693 const std::string &Arg, unsigned &Value) {
696 unsigned long V = strtoul(Arg.c_str(), &End, 0);
698 if (((V == ULONG_MAX) && (errno == ERANGE))
701 return O.error(": '" + Arg + "' value invalid for uint argument!");
705 // parser<double>/parser<float> implementation
707 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
708 const char *ArgStart = Arg.c_str();
710 Value = strtod(ArgStart, &End);
712 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
716 bool parser<double>::parse(Option &O, const char *AN,
717 const std::string &Arg, double &Val) {
718 return parseDouble(O, Arg, Val);
721 bool parser<float>::parse(Option &O, const char *AN,
722 const std::string &Arg, float &Val) {
724 if (parseDouble(O, Arg, dVal))
732 // generic_parser_base implementation
735 // findOption - Return the option number corresponding to the specified
736 // argument string. If the option is not found, getNumOptions() is returned.
738 unsigned generic_parser_base::findOption(const char *Name) {
739 unsigned i = 0, e = getNumOptions();
743 if (getOption(i) == N)
751 // Return the width of the option tag for printing...
752 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
754 unsigned Size = std::strlen(O.ArgStr)+6;
755 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
756 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
759 unsigned BaseSize = 0;
760 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
761 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
766 // printOptionInfo - Print out information about this option. The
767 // to-be-maintained width is specified.
769 void generic_parser_base::printOptionInfo(const Option &O,
770 unsigned GlobalWidth) const {
772 unsigned L = std::strlen(O.ArgStr);
773 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
774 << " - " << O.HelpStr << "\n";
776 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
777 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
778 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
779 << " - " << getDescription(i) << "\n";
783 std::cerr << " " << O.HelpStr << "\n";
784 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
785 unsigned L = std::strlen(getOption(i));
786 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
787 << " - " << getDescription(i) << "\n";
793 //===----------------------------------------------------------------------===//
794 // --help and --help-hidden option implementation
800 const Option *EmptyArg;
801 const bool ShowHidden;
803 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
804 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
805 return OptPair.second->getOptionHiddenFlag() >= Hidden;
807 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
808 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
812 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
816 void operator=(bool Value) {
817 if (Value == false) return;
819 // Copy Options into a vector so we can sort them as we like...
820 std::vector<std::pair<std::string, Option*> > Options;
821 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
823 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
824 Options.erase(std::remove_if(Options.begin(), Options.end(),
825 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
828 // Eliminate duplicate entries in table (from enum flags options, f.e.)
829 { // Give OptionSet a scope
830 std::set<Option*> OptionSet;
831 for (unsigned i = 0; i != Options.size(); ++i)
832 if (OptionSet.count(Options[i].second) == 0)
833 OptionSet.insert(Options[i].second); // Add new entry to set
835 Options.erase(Options.begin()+i--); // Erase duplicate
839 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
841 std::cerr << "USAGE: " << ProgramName << " [options]";
843 // Print out the positional options...
844 std::vector<Option*> &PosOpts = getPositionalOpts();
845 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
846 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
849 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
850 if (PosOpts[i]->ArgStr[0])
851 std::cerr << " --" << PosOpts[i]->ArgStr;
852 std::cerr << " " << PosOpts[i]->HelpStr;
855 // Print the consume after option info if it exists...
856 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
860 // Compute the maximum argument length...
862 for (unsigned i = 0, e = Options.size(); i != e; ++i)
863 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
865 std::cerr << "OPTIONS:\n";
866 for (unsigned i = 0, e = Options.size(); i != e; ++i)
867 Options[i].second->printOptionInfo(MaxArgLen);
869 // Halt the program if help information is printed
876 // Define the two HelpPrinter instances that are used to print out help, or
879 HelpPrinter NormalPrinter(false);
880 HelpPrinter HiddenPrinter(true);
882 cl::opt<HelpPrinter, true, parser<bool> >
883 HOp("help", cl::desc("display available options (--help-hidden for more)"),
884 cl::location(NormalPrinter), cl::ValueDisallowed);
886 cl::opt<HelpPrinter, true, parser<bool> >
887 HHOp("help-hidden", cl::desc("display all available options"),
888 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
890 } // End anonymous namespace