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"
29 //===----------------------------------------------------------------------===//
30 // Basic, shared command line option processing machinery...
33 // Return the global command line option vector. Making it a function scoped
34 // static ensures that it will be initialized correctly before its first use.
36 static std::map<std::string, Option*> *CommandLineOptions = 0;
37 static std::map<std::string, Option*> &getOpts() {
38 if (CommandLineOptions == 0)
39 CommandLineOptions = new std::map<std::string,Option*>();
40 return *CommandLineOptions;
43 static Option *getOption(const std::string &Str) {
44 if (CommandLineOptions == 0) return 0;
45 std::map<std::string,Option*>::iterator I = CommandLineOptions->find(Str);
46 return I != CommandLineOptions->end() ? I->second : 0;
49 static std::vector<Option*> &getPositionalOpts() {
50 static std::vector<Option*> Positional;
54 static void AddArgument(const char *ArgName, Option *Opt) {
55 if (getOption(ArgName)) {
56 std::cerr << "CommandLine Error: Argument '" << ArgName
57 << "' defined more than once!\n";
59 // Add argument to the argument map!
60 getOpts()[ArgName] = Opt;
64 // RemoveArgument - It's possible that the argument is no longer in the map if
65 // options have already been processed and the map has been deleted!
67 static void RemoveArgument(const char *ArgName, Option *Opt) {
68 if (CommandLineOptions == 0) return;
69 assert(getOption(ArgName) == Opt && "Arg not in map!");
70 CommandLineOptions->erase(ArgName);
71 if (CommandLineOptions->empty()) {
72 delete CommandLineOptions;
73 CommandLineOptions = 0;
77 static const char *ProgramName = 0;
78 static const char *ProgramOverview = 0;
80 static inline bool ProvideOption(Option *Handler, const char *ArgName,
81 const char *Value, int argc, char **argv,
83 // Enforce value requirements
84 switch (Handler->getValueExpectedFlag()) {
86 if (Value == 0 || *Value == 0) { // No value specified?
87 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
90 return Handler->error(" requires a value!");
96 return Handler->error(" does not allow a value! '" +
97 std::string(Value) + "' specified.");
99 case ValueOptional: break;
100 default: std::cerr << "Bad ValueMask flag! CommandLine usage error:"
101 << Handler->getValueExpectedFlag() << "\n"; abort();
104 // Run the handler now!
105 return Handler->addOccurrence(ArgName, Value);
108 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg) {
110 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
114 // Option predicates...
115 static inline bool isGrouping(const Option *O) {
116 return O->getFormattingFlag() == cl::Grouping;
118 static inline bool isPrefixedOrGrouping(const Option *O) {
119 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
122 // getOptionPred - Check to see if there are any options that satisfy the
123 // specified predicate with names that are the prefixes in Name. This is
124 // checked by progressively stripping characters off of the name, checking to
125 // see if there options that satisfy the predicate. If we find one, return it,
126 // otherwise return null.
128 static Option *getOptionPred(std::string Name, unsigned &Length,
129 bool (*Pred)(const Option*)) {
131 Option *Op = getOption(Name);
132 if (Op && Pred(Op)) {
133 Length = Name.length();
137 if (Name.size() == 1) return 0;
139 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
140 Op = getOption(Name);
142 // Loop while we haven't found an option and Name still has at least two
143 // characters in it (so that the next iteration will not be the empty
145 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
147 if (Op && Pred(Op)) {
148 Length = Name.length();
149 return Op; // Found one!
151 return 0; // No option found!
154 static bool RequiresValue(const Option *O) {
155 return O->getNumOccurrencesFlag() == cl::Required ||
156 O->getNumOccurrencesFlag() == cl::OneOrMore;
159 static bool EatsUnboundedNumberOfValues(const Option *O) {
160 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
161 O->getNumOccurrencesFlag() == cl::OneOrMore;
164 /// ParseCStringVector - Break INPUT up wherever one or more
165 /// whitespace characters are found, and store the resulting tokens in
166 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
167 /// using strdup (), so it is the caller's responsibility to free ()
170 static void ParseCStringVector (std::vector<char *> &output,
172 // Characters which will be treated as token separators:
173 static const char *delims = " \v\f\t\r\n";
175 std::string work (input);
176 // Skip past any delims at head of input string.
177 size_t pos = work.find_first_not_of (delims);
178 // If the string consists entirely of delims, then exit early.
179 if (pos == std::string::npos) return;
180 // Otherwise, jump forward to beginning of first word.
181 work = work.substr (pos);
182 // Find position of first delimiter.
183 pos = work.find_first_of (delims);
185 while (!work.empty() && pos != std::string::npos) {
186 // Everything from 0 to POS is the next word to copy.
187 output.push_back (strdup (work.substr (0,pos).c_str ()));
188 // Is there another word in the string?
189 size_t nextpos = work.find_first_not_of (delims, pos + 1);
190 if (nextpos != std::string::npos) {
191 // Yes? Then remove delims from beginning ...
192 work = work.substr (work.find_first_not_of (delims, pos + 1));
193 // and find the end of the word.
194 pos = work.find_first_of (delims);
196 // No? (Remainder of string is delims.) End the loop.
198 pos = std::string::npos;
202 // If `input' ended with non-delim char, then we'll get here with
203 // the last word of `input' in `work'; copy it now.
204 if (!work.empty ()) {
205 output.push_back (strdup (work.c_str ()));
209 /// ParseEnvironmentOptions - An alternative entry point to the
210 /// CommandLine library, which allows you to read the program's name
211 /// from the caller (as PROGNAME) and its command-line arguments from
212 /// an environment variable (whose name is given in ENVVAR).
214 void cl::ParseEnvironmentOptions (const char *progName, const char *envVar,
215 const char *Overview) {
217 assert (progName && "Program name not specified");
218 assert (envVar && "Environment variable name missing");
220 // Get the environment variable they want us to parse options out of.
221 const char *envValue = getenv (envVar);
225 // Get program's "name", which we wouldn't know without the caller
227 std::vector<char *> newArgv;
228 newArgv.push_back (strdup (progName));
230 // Parse the value of the environment variable into a "command line"
231 // and hand it off to ParseCommandLineOptions().
232 ParseCStringVector (newArgv, envValue);
233 int newArgc = newArgv.size ();
234 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
236 // Free all the strdup()ed strings.
237 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
243 void cl::ParseCommandLineOptions(int &argc, char **argv,
244 const char *Overview) {
245 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
246 "No options specified, or ParseCommandLineOptions called more"
248 ProgramName = argv[0]; // Save this away safe and snug
249 ProgramOverview = Overview;
250 bool ErrorParsing = false;
252 std::map<std::string, Option*> &Opts = getOpts();
253 std::vector<Option*> &PositionalOpts = getPositionalOpts();
255 // Check out the positional arguments to collect information about them.
256 unsigned NumPositionalRequired = 0;
257 Option *ConsumeAfterOpt = 0;
258 if (!PositionalOpts.empty()) {
259 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
260 assert(PositionalOpts.size() > 1 &&
261 "Cannot specify cl::ConsumeAfter without a positional argument!");
262 ConsumeAfterOpt = PositionalOpts[0];
265 // Calculate how many positional values are _required_.
266 bool UnboundedFound = false;
267 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
269 Option *Opt = PositionalOpts[i];
270 if (RequiresValue(Opt))
271 ++NumPositionalRequired;
272 else if (ConsumeAfterOpt) {
273 // ConsumeAfter cannot be combined with "optional" positional options
274 // unless there is only one positional argument...
275 if (PositionalOpts.size() > 2)
277 Opt->error(" error - this positional option will never be matched, "
278 "because it does not Require a value, and a "
279 "cl::ConsumeAfter option is active!");
280 } else if (UnboundedFound && !Opt->ArgStr[0]) {
281 // This option does not "require" a value... Make sure this option is
282 // not specified after an option that eats all extra arguments, or this
283 // one will never get any!
285 ErrorParsing |= Opt->error(" error - option can never match, because "
286 "another positional argument will match an "
287 "unbounded number of values, and this option"
288 " does not require a value!");
290 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
294 // PositionalVals - A vector of "positional" arguments we accumulate into to
295 // processes at the end...
297 std::vector<std::string> PositionalVals;
299 // If the program has named positional arguments, and the name has been run
300 // across, keep track of which positional argument was named. Otherwise put
301 // the positional args into the PositionalVals list...
302 Option *ActivePositionalArg = 0;
304 // Loop over all of the arguments... processing them.
305 bool DashDashFound = false; // Have we read '--'?
306 for (int i = 1; i < argc; ++i) {
308 const char *Value = "";
309 const char *ArgName = "";
311 // Check to see if this is a positional argument. This argument is
312 // considered to be positional if it doesn't start with '-', if it is "-"
313 // itself, or if we have seen "--" already.
315 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
316 // Positional argument!
317 if (ActivePositionalArg) {
318 ProvidePositionalOption(ActivePositionalArg, argv[i]);
319 continue; // We are done!
320 } else if (!PositionalOpts.empty()) {
321 PositionalVals.push_back(argv[i]);
323 // All of the positional arguments have been fulfulled, give the rest to
324 // the consume after option... if it's specified...
326 if (PositionalVals.size() >= NumPositionalRequired &&
327 ConsumeAfterOpt != 0) {
328 for (++i; i < argc; ++i)
329 PositionalVals.push_back(argv[i]);
330 break; // Handle outside of the argument processing loop...
333 // Delay processing positional arguments until the end...
336 } else { // We start with a '-', must be an argument...
338 while (*ArgName == '-') ++ArgName; // Eat leading dashes
340 if (*ArgName == 0 && !DashDashFound) { // Is this the mythical "--"?
341 DashDashFound = true; // Yup, take note of that fact...
342 continue; // Don't try to process it as an argument itself.
345 const char *ArgNameEnd = ArgName;
346 while (*ArgNameEnd && *ArgNameEnd != '=')
347 ++ArgNameEnd; // Scan till end of argument name...
350 if (*Value) // If we have an equals sign...
351 ++Value; // Advance to value...
354 std::string RealName(ArgName, ArgNameEnd);
355 // Extract arg name part
356 std::map<std::string, Option*>::iterator I = Opts.find(RealName);
358 if (I == Opts.end() && !*Value && RealName.size() > 1) {
359 // Check to see if this "option" is really a prefixed or grouped
363 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
365 // If the option is a prefixed option, then the value is simply the
366 // rest of the name... so fall through to later processing, by
367 // setting up the argument name flags and value fields.
369 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
370 ArgNameEnd = ArgName+Length;
372 I = Opts.find(std::string(ArgName, ArgNameEnd));
373 assert(I->second == PGOpt);
375 // This must be a grouped option... handle all of them now...
376 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
379 // Move current arg name out of RealName into RealArgName...
380 std::string RealArgName(RealName.begin(),RealName.begin()+Length);
381 RealName.erase(RealName.begin(), RealName.begin()+Length);
383 // Because ValueRequired is an invalid flag for grouped arguments,
384 // we don't need to pass argc/argv in...
386 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
387 "Option can not be cl::Grouping AND cl::ValueRequired!");
389 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(), "",
392 // Get the next grouping option...
393 if (!RealName.empty())
394 PGOpt = getOptionPred(RealName, Length, isGrouping);
395 } while (!RealName.empty() && PGOpt);
397 if (RealName.empty()) // Processed all of the options, move on
398 continue; // to the next argv[] value...
400 // If RealName is not empty, that means we did not match one of the
401 // options! This is an error.
407 Handler = I != Opts.end() ? I->second : 0;
412 std::cerr << "Unknown command line argument '" << argv[i] << "'. Try: '"
413 << argv[0] << " --help'\n";
418 // Check to see if this option accepts a comma separated list of values. If
419 // it does, we have to split up the value into multiple values...
420 if (Handler->getMiscFlags() & CommaSeparated) {
421 std::string Val(Value);
422 std::string::size_type Pos = Val.find(',');
424 while (Pos != std::string::npos) {
425 // Process the portion before the comma...
426 ErrorParsing |= ProvideOption(Handler, ArgName,
427 std::string(Val.begin(),
428 Val.begin()+Pos).c_str(),
430 // Erase the portion before the comma, AND the comma...
431 Val.erase(Val.begin(), Val.begin()+Pos+1);
432 Value += Pos+1; // Increment the original value pointer as well...
434 // Check for another comma...
439 // If this is a named positional argument, just remember that it is the
441 if (Handler->getFormattingFlag() == cl::Positional)
442 ActivePositionalArg = Handler;
444 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
447 // Check and handle positional arguments now...
448 if (NumPositionalRequired > PositionalVals.size()) {
449 std::cerr << "Not enough positional command line arguments specified!\n"
450 << "Must specify at least " << NumPositionalRequired
451 << " positional arguments: See: " << argv[0] << " --help\n";
455 } else if (ConsumeAfterOpt == 0) {
456 // Positional args have already been handled if ConsumeAfter is specified...
457 unsigned ValNo = 0, NumVals = PositionalVals.size();
458 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
459 if (RequiresValue(PositionalOpts[i])) {
460 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
461 --NumPositionalRequired; // We fulfilled our duty...
464 // If we _can_ give this option more arguments, do so now, as long as we
465 // do not give it values that others need. 'Done' controls whether the
466 // option even _WANTS_ any more.
468 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
469 while (NumVals-ValNo > NumPositionalRequired && !Done) {
470 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
472 Done = true; // Optional arguments want _at most_ one value
474 case cl::ZeroOrMore: // Zero or more will take all they can get...
475 case cl::OneOrMore: // One or more will take all they can get...
476 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
479 assert(0 && "Internal error, unexpected NumOccurrences flag in "
480 "positional argument processing!");
485 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
487 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
488 if (RequiresValue(PositionalOpts[j]))
489 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
490 PositionalVals[ValNo++]);
492 // Handle the case where there is just one positional option, and it's
493 // optional. In this case, we want to give JUST THE FIRST option to the
494 // positional option and keep the rest for the consume after. The above
495 // loop would have assigned no values to positional options in this case.
497 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty())
498 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
499 PositionalVals[ValNo++]);
501 // Handle over all of the rest of the arguments to the
502 // cl::ConsumeAfter command line option...
503 for (; ValNo != PositionalVals.size(); ++ValNo)
504 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
505 PositionalVals[ValNo]);
508 // Loop over args and make sure all required args are specified!
509 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
510 E = Opts.end(); I != E; ++I) {
511 switch (I->second->getNumOccurrencesFlag()) {
514 if (I->second->getNumOccurrences() == 0) {
515 I->second->error(" must be specified at least once!");
524 // Free all of the memory allocated to the map. Command line options may only
525 // be processed once!
526 delete CommandLineOptions;
527 CommandLineOptions = 0;
528 PositionalOpts.clear();
530 // If we had an error processing our arguments, don't let the program execute
531 if (ErrorParsing) exit(1);
534 //===----------------------------------------------------------------------===//
535 // Option Base class implementation
538 bool Option::error(std::string Message, const char *ArgName) {
539 if (ArgName == 0) ArgName = ArgStr;
541 std::cerr << HelpStr; // Be nice for positional arguments
543 std::cerr << "-" << ArgName;
544 std::cerr << " option" << Message << "\n";
548 bool Option::addOccurrence(const char *ArgName, const std::string &Value) {
549 NumOccurrences++; // Increment the number of times we have been seen
551 switch (getNumOccurrencesFlag()) {
553 if (NumOccurrences > 1)
554 return error(": may only occur zero or one times!", ArgName);
557 if (NumOccurrences > 1)
558 return error(": must occur exactly one time!", ArgName);
562 case ConsumeAfter: break;
563 default: return error(": bad num occurrences flag value!");
566 return handleOccurrence(ArgName, Value);
569 // addArgument - Tell the system that this Option subclass will handle all
570 // occurrences of -ArgStr on the command line.
572 void Option::addArgument(const char *ArgStr) {
574 AddArgument(ArgStr, this);
576 if (getFormattingFlag() == Positional)
577 getPositionalOpts().push_back(this);
578 else if (getNumOccurrencesFlag() == ConsumeAfter) {
579 if (!getPositionalOpts().empty() &&
580 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
581 error("Cannot specify more than one option with cl::ConsumeAfter!");
582 getPositionalOpts().insert(getPositionalOpts().begin(), this);
586 void Option::removeArgument(const char *ArgStr) {
588 RemoveArgument(ArgStr, this);
590 if (getFormattingFlag() == Positional) {
591 std::vector<Option*>::iterator I =
592 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
593 assert(I != getPositionalOpts().end() && "Arg not registered!");
594 getPositionalOpts().erase(I);
595 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
596 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
597 "Arg not registered correctly!");
598 getPositionalOpts().erase(getPositionalOpts().begin());
603 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
604 // has been specified yet.
606 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
607 if (O.ValueStr[0] == 0) return DefaultMsg;
611 //===----------------------------------------------------------------------===//
612 // cl::alias class implementation
615 // Return the width of the option tag for printing...
616 unsigned alias::getOptionWidth() const {
617 return std::strlen(ArgStr)+6;
620 // Print out the option for the alias...
621 void alias::printOptionInfo(unsigned GlobalWidth) const {
622 unsigned L = std::strlen(ArgStr);
623 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
629 //===----------------------------------------------------------------------===//
630 // Parser Implementation code...
633 // basic_parser implementation
636 // Return the width of the option tag for printing...
637 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
638 unsigned Len = std::strlen(O.ArgStr);
639 if (const char *ValName = getValueName())
640 Len += std::strlen(getValueStr(O, ValName))+3;
645 // printOptionInfo - Print out information about this option. The
646 // to-be-maintained width is specified.
648 void basic_parser_impl::printOptionInfo(const Option &O,
649 unsigned GlobalWidth) const {
650 std::cerr << " -" << O.ArgStr;
652 if (const char *ValName = getValueName())
653 std::cerr << "=<" << getValueStr(O, ValName) << ">";
655 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
656 << O.HelpStr << "\n";
662 // parser<bool> implementation
664 bool parser<bool>::parse(Option &O, const char *ArgName,
665 const std::string &Arg, bool &Value) {
666 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
669 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
672 return O.error(": '" + Arg +
673 "' is invalid value for boolean argument! Try 0 or 1");
678 // parser<int> implementation
680 bool parser<int>::parse(Option &O, const char *ArgName,
681 const std::string &Arg, int &Value) {
683 Value = (int)strtol(Arg.c_str(), &End, 0);
685 return O.error(": '" + Arg + "' value invalid for integer argument!");
689 // parser<unsigned> implementation
691 bool parser<unsigned>::parse(Option &O, const char *ArgName,
692 const std::string &Arg, unsigned &Value) {
695 unsigned long V = strtoul(Arg.c_str(), &End, 0);
697 if (((V == ULONG_MAX) && (errno == ERANGE))
700 return O.error(": '" + Arg + "' value invalid for uint argument!");
704 // parser<double>/parser<float> implementation
706 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
707 const char *ArgStart = Arg.c_str();
709 Value = strtod(ArgStart, &End);
711 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
715 bool parser<double>::parse(Option &O, const char *AN,
716 const std::string &Arg, double &Val) {
717 return parseDouble(O, Arg, Val);
720 bool parser<float>::parse(Option &O, const char *AN,
721 const std::string &Arg, float &Val) {
723 if (parseDouble(O, Arg, dVal))
731 // generic_parser_base implementation
734 // findOption - Return the option number corresponding to the specified
735 // argument string. If the option is not found, getNumOptions() is returned.
737 unsigned generic_parser_base::findOption(const char *Name) {
738 unsigned i = 0, e = getNumOptions();
742 if (getOption(i) == N)
750 // Return the width of the option tag for printing...
751 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
753 unsigned Size = std::strlen(O.ArgStr)+6;
754 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
755 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
758 unsigned BaseSize = 0;
759 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
760 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
765 // printOptionInfo - Print out information about this option. The
766 // to-be-maintained width is specified.
768 void generic_parser_base::printOptionInfo(const Option &O,
769 unsigned GlobalWidth) const {
771 unsigned L = std::strlen(O.ArgStr);
772 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
773 << " - " << O.HelpStr << "\n";
775 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
776 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
777 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
778 << " - " << getDescription(i) << "\n";
782 std::cerr << " " << O.HelpStr << "\n";
783 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
784 unsigned L = std::strlen(getOption(i));
785 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
786 << " - " << getDescription(i) << "\n";
792 //===----------------------------------------------------------------------===//
793 // --help and --help-hidden option implementation
799 const Option *EmptyArg;
800 const bool ShowHidden;
802 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
803 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
804 return OptPair.second->getOptionHiddenFlag() >= Hidden;
806 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
807 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
811 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
815 void operator=(bool Value) {
816 if (Value == false) return;
818 // Copy Options into a vector so we can sort them as we like...
819 std::vector<std::pair<std::string, Option*> > Options;
820 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
822 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
823 Options.erase(std::remove_if(Options.begin(), Options.end(),
824 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
827 // Eliminate duplicate entries in table (from enum flags options, f.e.)
828 { // Give OptionSet a scope
829 std::set<Option*> OptionSet;
830 for (unsigned i = 0; i != Options.size(); ++i)
831 if (OptionSet.count(Options[i].second) == 0)
832 OptionSet.insert(Options[i].second); // Add new entry to set
834 Options.erase(Options.begin()+i--); // Erase duplicate
838 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
840 std::cerr << "USAGE: " << ProgramName << " [options]";
842 // Print out the positional options...
843 std::vector<Option*> &PosOpts = getPositionalOpts();
844 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
845 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
848 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
849 if (PosOpts[i]->ArgStr[0])
850 std::cerr << " --" << PosOpts[i]->ArgStr;
851 std::cerr << " " << PosOpts[i]->HelpStr;
854 // Print the consume after option info if it exists...
855 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
859 // Compute the maximum argument length...
861 for (unsigned i = 0, e = Options.size(); i != e; ++i)
862 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
864 std::cerr << "OPTIONS:\n";
865 for (unsigned i = 0, e = Options.size(); i != e; ++i)
866 Options[i].second->printOptionInfo(MaxArgLen);
868 // Halt the program if help information is printed
875 // Define the two HelpPrinter instances that are used to print out help, or
878 HelpPrinter NormalPrinter(false);
879 HelpPrinter HiddenPrinter(true);
881 cl::opt<HelpPrinter, true, parser<bool> >
882 HOp("help", cl::desc("display available options (--help-hidden for more)"),
883 cl::location(NormalPrinter), cl::ValueDisallowed);
885 cl::opt<HelpPrinter, true, parser<bool> >
886 HHOp("help-hidden", cl::desc("display all available options"),
887 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
889 } // End anonymous namespace