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"
25 //===----------------------------------------------------------------------===//
26 // Basic, shared command line option processing machinery...
29 // Return the global command line option vector. Making it a function scoped
30 // static ensures that it will be initialized correctly before its first use.
32 static map<string, Option*> &getOpts() {
33 static map<string,Option*> CommandLineOptions;
34 return CommandLineOptions;
37 static vector<Option*> &getPositionalOpts() {
38 static vector<Option*> Positional;
42 static void AddArgument(const string &ArgName, Option *Opt) {
43 if (getOpts().find(ArgName) != getOpts().end()) {
44 cerr << "CommandLine Error: Argument '" << ArgName
45 << "' defined more than once!\n";
47 // Add argument to the argument map!
48 getOpts().insert(std::make_pair(ArgName, Opt));
52 static const char *ProgramName = 0;
53 static const char *ProgramOverview = 0;
55 static inline bool ProvideOption(Option *Handler, const char *ArgName,
56 const char *Value, int argc, char **argv,
58 // Enforce value requirements
59 switch (Handler->getValueExpectedFlag()) {
61 if (Value == 0 || *Value == 0) { // No value specified?
62 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
65 return Handler->error(" requires a value!");
71 return Handler->error(" does not allow a value! '" +
72 string(Value) + "' specified.");
74 case ValueOptional: break;
75 default: cerr << "Bad ValueMask flag! CommandLine usage error:"
76 << Handler->getValueExpectedFlag() << "\n"; abort();
79 // Run the handler now!
80 return Handler->addOccurance(ArgName, Value);
83 static bool ProvidePositionalOption(Option *Handler, string &Arg) {
85 return ProvideOption(Handler, "", Arg.c_str(), 0, 0, Dummy);
89 // Option predicates...
90 static inline bool isGrouping(const Option *O) {
91 return O->getFormattingFlag() == cl::Grouping;
93 static inline bool isPrefixedOrGrouping(const Option *O) {
94 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
97 // getOptionPred - Check to see if there are any options that satisfy the
98 // specified predicate with names that are the prefixes in Name. This is
99 // checked by progressively stripping characters off of the name, checking to
100 // see if there options that satisfy the predicate. If we find one, return it,
101 // otherwise return null.
103 static Option *getOptionPred(std::string Name, unsigned &Length,
104 bool (*Pred)(const Option*)) {
106 map<string, Option*>::iterator I = getOpts().find(Name);
107 if (I != getOpts().end() && Pred(I->second)) {
108 Length = Name.length();
112 if (Name.size() == 1) return 0;
114 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
115 I = getOpts().find(Name);
117 // Loop while we haven't found an option and Name still has at least two
118 // characters in it (so that the next iteration will not be the empty
120 } while ((I == getOpts().end() || !Pred(I->second)) && Name.size() > 1);
122 if (I != getOpts().end() && Pred(I->second)) {
123 Length = Name.length();
124 return I->second; // Found one!
126 return 0; // No option found!
129 static bool RequiresValue(const Option *O) {
130 return O->getNumOccurancesFlag() == cl::Required ||
131 O->getNumOccurancesFlag() == cl::OneOrMore;
134 static bool EatsUnboundedNumberOfValues(const Option *O) {
135 return O->getNumOccurancesFlag() == cl::ZeroOrMore ||
136 O->getNumOccurancesFlag() == cl::OneOrMore;
139 void cl::ParseCommandLineOptions(int &argc, char **argv,
140 const char *Overview) {
141 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
142 "No options specified, or ParseCommandLineOptions called more"
144 ProgramName = argv[0]; // Save this away safe and snug
145 ProgramOverview = Overview;
146 bool ErrorParsing = false;
148 map<string, Option*> &Opts = getOpts();
149 vector<Option*> &PositionalOpts = getPositionalOpts();
151 // Check out the positional arguments to collect information about them.
152 unsigned NumPositionalRequired = 0;
153 Option *ConsumeAfterOpt = 0;
154 if (!PositionalOpts.empty()) {
155 if (PositionalOpts[0]->getNumOccurancesFlag() == cl::ConsumeAfter) {
156 assert(PositionalOpts.size() > 1 &&
157 "Cannot specify cl::ConsumeAfter without a positional argument!");
158 ConsumeAfterOpt = PositionalOpts[0];
161 // Calculate how many positional values are _required_.
162 bool UnboundedFound = false;
163 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
165 Option *Opt = PositionalOpts[i];
166 if (RequiresValue(Opt))
167 ++NumPositionalRequired;
168 else if (ConsumeAfterOpt) {
169 // ConsumeAfter cannot be combined with "optional" positional options
170 // unless there is only one positional argument...
171 if (PositionalOpts.size() > 2)
173 Opt->error(" error - this positional option will never be matched, "
174 "because it does not Require a value, and a "
175 "cl::ConsumeAfter option is active!");
176 } else if (UnboundedFound) { // This option does not "require" a value...
177 // Make sure this option is not specified after an option that eats all
178 // extra arguments, or this one will never get any!
180 ErrorParsing |= Opt->error(" error - option can never match, because "
181 "another positional argument will match an "
182 "unbounded number of values, and this option"
183 " does not require a value!");
185 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
189 // PositionalVals - A vector of "positional" arguments we accumulate into to
190 // processes at the end...
192 vector<string> PositionalVals;
194 // Loop over all of the arguments... processing them.
195 bool DashDashFound = false; // Have we read '--'?
196 for (int i = 1; i < argc; ++i) {
198 const char *Value = "";
199 const char *ArgName = "";
201 // Check to see if this is a positional argument. This argument is
202 // considered to be positional if it doesn't start with '-', if it is "-"
203 // itself, or if we have see "--" already.
205 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
206 // Positional argument!
207 if (!PositionalOpts.empty()) {
208 PositionalVals.push_back(argv[i]);
210 // All of the positional arguments have been fulfulled, give the rest to
211 // the consume after option... if it's specified...
213 if (PositionalVals.size() == NumPositionalRequired &&
214 ConsumeAfterOpt != 0) {
215 for (++i; i < argc; ++i)
216 PositionalVals.push_back(argv[i]);
217 break; // Handle outside of the argument processing loop...
220 // Delay processing positional arguments until the end...
223 } else { // We start with a '-', must be an argument...
225 while (*ArgName == '-') ++ArgName; // Eat leading dashes
227 if (*ArgName == 0 && !DashDashFound) { // Is this the mythical "--"?
228 DashDashFound = true; // Yup, take note of that fact...
229 continue; // Don't try to process it as an argument iself.
232 const char *ArgNameEnd = ArgName;
233 while (*ArgNameEnd && *ArgNameEnd != '=')
234 ++ArgNameEnd; // Scan till end of argument name...
237 if (*Value) // If we have an equals sign...
238 ++Value; // Advance to value...
241 string RealName(ArgName, ArgNameEnd);
242 // Extract arg name part
243 map<string, Option*>::iterator I = Opts.find(RealName);
245 if (I == Opts.end() && !*Value && RealName.size() > 1) {
246 // Check to see if this "option" is really a prefixed or grouped
250 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
252 // If the option is a prefixed option, then the value is simply the
253 // rest of the name... so fall through to later processing, by
254 // setting up the argument name flags and value fields.
256 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
257 ArgNameEnd = ArgName+Length;
259 I = Opts.find(string(ArgName, ArgNameEnd));
260 assert(I->second == PGOpt);
262 // This must be a grouped option... handle all of them now...
263 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
266 // Move current arg name out of RealName into RealArgName...
267 string RealArgName(RealName.begin(), RealName.begin()+Length);
268 RealName.erase(RealName.begin(), RealName.begin()+Length);
270 // Because ValueRequired is an invalid flag for grouped arguments,
271 // we don't need to pass argc/argv in...
273 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
274 "Option can not be cl::Grouping AND cl::ValueRequired!");
276 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(), "",
279 // Get the next grouping option...
280 if (!RealName.empty())
281 PGOpt = getOptionPred(RealName, Length, isGrouping);
282 } while (!RealName.empty() && PGOpt);
284 if (RealName.empty()) // Processed all of the options, move on
285 continue; // to the next argv[] value...
287 // If RealName is not empty, that means we did not match one of the
288 // options! This is an error.
294 Handler = I != Opts.end() ? I->second : 0;
299 cerr << "Unknown command line argument '" << argv[i] << "'. Try: "
300 << argv[0] << " --help'\n";
305 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
308 // Check and handle positional arguments now...
309 if (NumPositionalRequired > PositionalVals.size()) {
310 cerr << "Not enough positional command line arguments specified!\n";
311 cerr << "Must specify at least " << NumPositionalRequired
312 << " positional arguments: See: " << argv[0] << " --help\n";
316 } else if (ConsumeAfterOpt == 0) {
317 // Positional args have already been handled if ConsumeAfter is specified...
318 unsigned ValNo = 0, NumVals = PositionalVals.size();
319 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
320 if (RequiresValue(PositionalOpts[i])) {
321 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
322 --NumPositionalRequired; // We fulfilled our duty...
325 // If we _can_ give this option more arguments, do so now, as long as we
326 // do not give it values that others need. 'Done' controls whether the
327 // option even _WANTS_ any more.
329 bool Done = PositionalOpts[i]->getNumOccurancesFlag() == cl::Required;
330 while (NumVals-ValNo > NumPositionalRequired && !Done) {
331 switch (PositionalOpts[i]->getNumOccurancesFlag()) {
333 Done = true; // Optional arguments want _at most_ one value
335 case cl::ZeroOrMore: // Zero or more will take all they can get...
336 case cl::OneOrMore: // One or more will take all they can get...
337 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
340 assert(0 && "Internal error, unexpected NumOccurances flag in "
341 "positional argument processing!");
346 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
348 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
349 if (RequiresValue(PositionalOpts[j]))
350 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
351 PositionalVals[ValNo++]);
353 // Handle the case where there is just one positional option, and it's
354 // optional. In this case, we want to give JUST THE FIRST option to the
355 // positional option and keep the rest for the consume after. The above
356 // loop would have assigned no values to positional options in this case.
358 if (PositionalOpts.size() == 2 && ValNo == 0)
359 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
360 PositionalVals[ValNo++]);
362 // Handle over all of the rest of the arguments to the
363 // cl::ConsumeAfter command line option...
364 for (; ValNo != PositionalVals.size(); ++ValNo)
365 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
366 PositionalVals[ValNo]);
369 // Loop over args and make sure all required args are specified!
370 for (map<string, Option*>::iterator I = Opts.begin(),
371 E = Opts.end(); I != E; ++I) {
372 switch (I->second->getNumOccurancesFlag()) {
375 if (I->second->getNumOccurances() == 0) {
376 I->second->error(" must be specified at least once!");
385 // Free all of the memory allocated to the map. Command line options may only
386 // be processed once!
388 PositionalOpts.clear();
390 // If we had an error processing our arguments, don't let the program execute
391 if (ErrorParsing) exit(1);
394 //===----------------------------------------------------------------------===//
395 // Option Base class implementation
398 bool Option::error(string Message, const char *ArgName) {
399 if (ArgName == 0) ArgName = ArgStr;
401 cerr << HelpStr; // Be nice for positional arguments
403 cerr << "-" << ArgName;
404 cerr << " option" << Message << "\n";
408 bool Option::addOccurance(const char *ArgName, const string &Value) {
409 NumOccurances++; // Increment the number of times we have been seen
411 switch (getNumOccurancesFlag()) {
413 if (NumOccurances > 1)
414 return error(": may only occur zero or one times!", ArgName);
417 if (NumOccurances > 1)
418 return error(": must occur exactly one time!", ArgName);
422 case ConsumeAfter: break;
423 default: return error(": bad num occurances flag value!");
426 return handleOccurance(ArgName, Value);
429 // addArgument - Tell the system that this Option subclass will handle all
430 // occurances of -ArgStr on the command line.
432 void Option::addArgument(const char *ArgStr) {
434 AddArgument(ArgStr, this);
435 else if (getFormattingFlag() == Positional)
436 getPositionalOpts().push_back(this);
437 else if (getNumOccurancesFlag() == ConsumeAfter) {
438 assert((getPositionalOpts().empty() ||
439 getPositionalOpts().front()->getNumOccurancesFlag() != ConsumeAfter)
440 && "Cannot specify more than one option with cl::ConsumeAfter "
442 getPositionalOpts().insert(getPositionalOpts().begin(), this);
446 void Option::removeArgument(const char *ArgStr) {
448 assert(getOpts()[ArgStr] == this && "Arg not in map!");
449 getOpts().erase(ArgStr);
450 } else if (getFormattingFlag() == Positional) {
451 vector<Option*>::iterator I =
452 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
453 assert(I != getPositionalOpts().end() && "Arg not registered!");
454 getPositionalOpts().erase(I);
455 } else if (getNumOccurancesFlag() == ConsumeAfter) {
456 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
457 "Arg not registered correctly!");
458 getPositionalOpts().erase(getPositionalOpts().begin());
463 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
464 // has been specified yet.
466 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
467 if (O.ValueStr[0] == 0) return DefaultMsg;
471 //===----------------------------------------------------------------------===//
472 // cl::alias class implementation
475 // Return the width of the option tag for printing...
476 unsigned alias::getOptionWidth() const {
477 return std::strlen(ArgStr)+6;
480 // Print out the option for the alias...
481 void alias::printOptionInfo(unsigned GlobalWidth) const {
482 unsigned L = std::strlen(ArgStr);
483 cerr << " -" << ArgStr << string(GlobalWidth-L-6, ' ') << " - "
489 //===----------------------------------------------------------------------===//
490 // Parser Implementation code...
493 // parser<bool> implementation
495 bool parser<bool>::parseImpl(Option &O, const string &Arg, bool &Value) {
496 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
499 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
502 return O.error(": '" + Arg +
503 "' is invalid value for boolean argument! Try 0 or 1");
508 // Return the width of the option tag for printing...
509 unsigned parser<bool>::getOptionWidth(const Option &O) const {
510 return std::strlen(O.ArgStr)+6;
513 // printOptionInfo - Print out information about this option. The
514 // to-be-maintained width is specified.
516 void parser<bool>::printOptionInfo(const Option &O, unsigned GlobalWidth) const{
517 unsigned L = std::strlen(O.ArgStr);
518 cerr << " -" << O.ArgStr << string(GlobalWidth-L-6, ' ') << " - "
519 << O.HelpStr << "\n";
524 // parser<int> implementation
526 bool parser<int>::parseImpl(Option &O, const string &Arg, int &Value) {
527 const char *ArgStart = Arg.c_str();
529 Value = (int)strtol(ArgStart, &End, 0);
531 return O.error(": '" + Arg + "' value invalid for integer argument!");
535 // Return the width of the option tag for printing...
536 unsigned parser<int>::getOptionWidth(const Option &O) const {
537 return std::strlen(O.ArgStr)+std::strlen(getValueStr(O, "int"))+9;
540 // printOptionInfo - Print out information about this option. The
541 // to-be-maintained width is specified.
543 void parser<int>::printOptionInfo(const Option &O, unsigned GlobalWidth) const{
544 cerr << " -" << O.ArgStr << "=<" << getValueStr(O, "int") << ">"
545 << string(GlobalWidth-getOptionWidth(O), ' ') << " - "
546 << O.HelpStr << "\n";
550 // parser<double> implementation
552 bool parser<double>::parseImpl(Option &O, const string &Arg, double &Value) {
553 const char *ArgStart = Arg.c_str();
555 Value = strtod(ArgStart, &End);
557 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
561 // Return the width of the option tag for printing...
562 unsigned parser<double>::getOptionWidth(const Option &O) const {
563 return std::strlen(O.ArgStr)+std::strlen(getValueStr(O, "number"))+9;
566 // printOptionInfo - Print out information about this option. The
567 // to-be-maintained width is specified.
569 void parser<double>::printOptionInfo(const Option &O,
570 unsigned GlobalWidth) const{
571 cerr << " -" << O.ArgStr << "=<" << getValueStr(O, "number") << ">"
572 << string(GlobalWidth-getOptionWidth(O), ' ')
573 << " - " << O.HelpStr << "\n";
577 // parser<string> implementation
580 // Return the width of the option tag for printing...
581 unsigned parser<string>::getOptionWidth(const Option &O) const {
582 return std::strlen(O.ArgStr)+std::strlen(getValueStr(O, "string"))+9;
585 // printOptionInfo - Print out information about this option. The
586 // to-be-maintained width is specified.
588 void parser<string>::printOptionInfo(const Option &O,
589 unsigned GlobalWidth) const{
590 cerr << " -" << O.ArgStr << " <" << getValueStr(O, "string") << ">"
591 << string(GlobalWidth-getOptionWidth(O), ' ')
592 << " - " << O.HelpStr << "\n";
595 // generic_parser_base implementation
598 // findOption - Return the option number corresponding to the specified
599 // argument string. If the option is not found, getNumOptions() is returned.
601 unsigned generic_parser_base::findOption(const char *Name) {
602 unsigned i = 0, e = getNumOptions();
606 if (getOption(i) == N)
614 // Return the width of the option tag for printing...
615 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
617 unsigned Size = std::strlen(O.ArgStr)+6;
618 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
619 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
622 unsigned BaseSize = 0;
623 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
624 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
629 // printOptionInfo - Print out information about this option. The
630 // to-be-maintained width is specified.
632 void generic_parser_base::printOptionInfo(const Option &O,
633 unsigned GlobalWidth) const {
635 unsigned L = std::strlen(O.ArgStr);
636 cerr << " -" << O.ArgStr << string(GlobalWidth-L-6, ' ')
637 << " - " << O.HelpStr << "\n";
639 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
640 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
641 cerr << " =" << getOption(i) << string(NumSpaces, ' ') << " - "
642 << getDescription(i) << "\n";
646 cerr << " " << O.HelpStr << "\n";
647 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
648 unsigned L = std::strlen(getOption(i));
649 cerr << " -" << getOption(i) << string(GlobalWidth-L-8, ' ') << " - "
650 << getDescription(i) << "\n";
656 //===----------------------------------------------------------------------===//
657 // --help and --help-hidden option implementation
663 const Option *EmptyArg;
664 const bool ShowHidden;
666 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
667 inline static bool isHidden(pair<string, Option *> &OptPair) {
668 return OptPair.second->getOptionHiddenFlag() >= Hidden;
670 inline static bool isReallyHidden(pair<string, Option *> &OptPair) {
671 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
675 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
679 void operator=(bool Value) {
680 if (Value == false) return;
682 // Copy Options into a vector so we can sort them as we like...
683 vector<pair<string, Option*> > Options;
684 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
686 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
687 Options.erase(std::remove_if(Options.begin(), Options.end(),
688 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
691 // Eliminate duplicate entries in table (from enum flags options, f.e.)
692 { // Give OptionSet a scope
693 std::set<Option*> OptionSet;
694 for (unsigned i = 0; i != Options.size(); ++i)
695 if (OptionSet.count(Options[i].second) == 0)
696 OptionSet.insert(Options[i].second); // Add new entry to set
698 Options.erase(Options.begin()+i--); // Erase duplicate
702 cerr << "OVERVIEW:" << ProgramOverview << "\n";
704 cerr << "USAGE: " << ProgramName << " [options]";
706 // Print out the positional options...
707 vector<Option*> &PosOpts = getPositionalOpts();
708 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
709 if (!PosOpts.empty() && PosOpts[0]->getNumOccurancesFlag() == ConsumeAfter)
712 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
713 cerr << " " << PosOpts[i]->HelpStr;
714 switch (PosOpts[i]->getNumOccurancesFlag()) {
715 case Optional: cerr << "?"; break;
716 case ZeroOrMore: cerr << "*"; break;
717 case Required: break;
718 case OneOrMore: cerr << "+"; break;
721 assert(0 && "Unknown NumOccurances Flag Value!");
725 // Print the consume after option info if it exists...
726 if (CAOpt) cerr << " " << CAOpt->HelpStr;
730 // Compute the maximum argument length...
732 for (unsigned i = 0, e = Options.size(); i != e; ++i)
733 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
735 cerr << "OPTIONS:\n";
736 for (unsigned i = 0, e = Options.size(); i != e; ++i)
737 Options[i].second->printOptionInfo(MaxArgLen);
739 // Halt the program if help information is printed
746 // Define the two HelpPrinter instances that are used to print out help, or
749 HelpPrinter NormalPrinter(false);
750 HelpPrinter HiddenPrinter(true);
752 cl::opt<HelpPrinter, true, parser<bool> >
753 HOp("help", cl::desc("display available options (--help-hidden for more)"),
754 cl::location(NormalPrinter));
756 cl::opt<HelpPrinter, true, parser<bool> >
757 HHOp("help-hidden", cl::desc("display all available options"),
758 cl::location(HiddenPrinter), cl::Hidden);
760 } // End anonymous namespace