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*> *CommandLineOptions = 0;
33 static map<string, Option*> &getOpts() {
34 if (CommandLineOptions == 0) CommandLineOptions = new map<string,Option*>();
35 return *CommandLineOptions;
38 static Option *getOption(const string &Str) {
39 if (CommandLineOptions == 0) return 0;
40 map<string,Option*>::iterator I = CommandLineOptions->find(Str);
41 return I != CommandLineOptions->end() ? I->second : 0;
44 static vector<Option*> &getPositionalOpts() {
45 static vector<Option*> Positional;
49 static void AddArgument(const char *ArgName, Option *Opt) {
50 if (getOption(ArgName)) {
51 cerr << "CommandLine Error: Argument '" << ArgName
52 << "' defined more than once!\n";
54 // Add argument to the argument map!
55 getOpts()[ArgName] = Opt;
59 // RemoveArgument - It's possible that the argument is no longer in the map if
60 // options have already been processed and the map has been deleted!
62 static void RemoveArgument(const char *ArgName, Option *Opt) {
63 if (CommandLineOptions == 0) return;
64 assert(getOption(ArgName) == Opt && "Arg not in map!");
65 CommandLineOptions->erase(ArgName);
66 if (CommandLineOptions->empty()) {
67 delete CommandLineOptions;
68 CommandLineOptions = 0;
72 static const char *ProgramName = 0;
73 static const char *ProgramOverview = 0;
75 static inline bool ProvideOption(Option *Handler, const char *ArgName,
76 const char *Value, int argc, char **argv,
78 // Enforce value requirements
79 switch (Handler->getValueExpectedFlag()) {
81 if (Value == 0 || *Value == 0) { // No value specified?
82 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
85 return Handler->error(" requires a value!");
91 return Handler->error(" does not allow a value! '" +
92 string(Value) + "' specified.");
94 case ValueOptional: break;
95 default: cerr << "Bad ValueMask flag! CommandLine usage error:"
96 << Handler->getValueExpectedFlag() << "\n"; abort();
99 // Run the handler now!
100 return Handler->addOccurance(ArgName, Value);
103 static bool ProvidePositionalOption(Option *Handler, string &Arg) {
105 return ProvideOption(Handler, "", Arg.c_str(), 0, 0, Dummy);
109 // Option predicates...
110 static inline bool isGrouping(const Option *O) {
111 return O->getFormattingFlag() == cl::Grouping;
113 static inline bool isPrefixedOrGrouping(const Option *O) {
114 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
117 // getOptionPred - Check to see if there are any options that satisfy the
118 // specified predicate with names that are the prefixes in Name. This is
119 // checked by progressively stripping characters off of the name, checking to
120 // see if there options that satisfy the predicate. If we find one, return it,
121 // otherwise return null.
123 static Option *getOptionPred(std::string Name, unsigned &Length,
124 bool (*Pred)(const Option*)) {
126 Option *Op = getOption(Name);
127 if (Op && Pred(Op)) {
128 Length = Name.length();
132 if (Name.size() == 1) return 0;
134 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
135 Op = getOption(Name);
137 // Loop while we haven't found an option and Name still has at least two
138 // characters in it (so that the next iteration will not be the empty
140 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
142 if (Op && Pred(Op)) {
143 Length = Name.length();
144 return Op; // Found one!
146 return 0; // No option found!
149 static bool RequiresValue(const Option *O) {
150 return O->getNumOccurancesFlag() == cl::Required ||
151 O->getNumOccurancesFlag() == cl::OneOrMore;
154 static bool EatsUnboundedNumberOfValues(const Option *O) {
155 return O->getNumOccurancesFlag() == cl::ZeroOrMore ||
156 O->getNumOccurancesFlag() == cl::OneOrMore;
159 void cl::ParseCommandLineOptions(int &argc, char **argv,
160 const char *Overview) {
161 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
162 "No options specified, or ParseCommandLineOptions called more"
164 ProgramName = argv[0]; // Save this away safe and snug
165 ProgramOverview = Overview;
166 bool ErrorParsing = false;
168 map<string, Option*> &Opts = getOpts();
169 vector<Option*> &PositionalOpts = getPositionalOpts();
171 // Check out the positional arguments to collect information about them.
172 unsigned NumPositionalRequired = 0;
173 Option *ConsumeAfterOpt = 0;
174 if (!PositionalOpts.empty()) {
175 if (PositionalOpts[0]->getNumOccurancesFlag() == cl::ConsumeAfter) {
176 assert(PositionalOpts.size() > 1 &&
177 "Cannot specify cl::ConsumeAfter without a positional argument!");
178 ConsumeAfterOpt = PositionalOpts[0];
181 // Calculate how many positional values are _required_.
182 bool UnboundedFound = false;
183 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
185 Option *Opt = PositionalOpts[i];
186 if (RequiresValue(Opt))
187 ++NumPositionalRequired;
188 else if (ConsumeAfterOpt) {
189 // ConsumeAfter cannot be combined with "optional" positional options
190 // unless there is only one positional argument...
191 if (PositionalOpts.size() > 2)
193 Opt->error(" error - this positional option will never be matched, "
194 "because it does not Require a value, and a "
195 "cl::ConsumeAfter option is active!");
196 } else if (UnboundedFound) { // This option does not "require" a value...
197 // Make sure this option is not specified after an option that eats all
198 // extra arguments, or this one will never get any!
200 ErrorParsing |= Opt->error(" error - option can never match, because "
201 "another positional argument will match an "
202 "unbounded number of values, and this option"
203 " does not require a value!");
205 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
209 // PositionalVals - A vector of "positional" arguments we accumulate into to
210 // processes at the end...
212 vector<string> PositionalVals;
214 // Loop over all of the arguments... processing them.
215 bool DashDashFound = false; // Have we read '--'?
216 for (int i = 1; i < argc; ++i) {
218 const char *Value = "";
219 const char *ArgName = "";
221 // Check to see if this is a positional argument. This argument is
222 // considered to be positional if it doesn't start with '-', if it is "-"
223 // itself, or if we have see "--" already.
225 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
226 // Positional argument!
227 if (!PositionalOpts.empty()) {
228 PositionalVals.push_back(argv[i]);
230 // All of the positional arguments have been fulfulled, give the rest to
231 // the consume after option... if it's specified...
233 if (PositionalVals.size() >= NumPositionalRequired &&
234 ConsumeAfterOpt != 0) {
235 for (++i; i < argc; ++i)
236 PositionalVals.push_back(argv[i]);
237 break; // Handle outside of the argument processing loop...
240 // Delay processing positional arguments until the end...
243 } else { // We start with a '-', must be an argument...
245 while (*ArgName == '-') ++ArgName; // Eat leading dashes
247 if (*ArgName == 0 && !DashDashFound) { // Is this the mythical "--"?
248 DashDashFound = true; // Yup, take note of that fact...
249 continue; // Don't try to process it as an argument iself.
252 const char *ArgNameEnd = ArgName;
253 while (*ArgNameEnd && *ArgNameEnd != '=')
254 ++ArgNameEnd; // Scan till end of argument name...
257 if (*Value) // If we have an equals sign...
258 ++Value; // Advance to value...
261 string RealName(ArgName, ArgNameEnd);
262 // Extract arg name part
263 map<string, Option*>::iterator I = Opts.find(RealName);
265 if (I == Opts.end() && !*Value && RealName.size() > 1) {
266 // Check to see if this "option" is really a prefixed or grouped
270 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
272 // If the option is a prefixed option, then the value is simply the
273 // rest of the name... so fall through to later processing, by
274 // setting up the argument name flags and value fields.
276 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
277 ArgNameEnd = ArgName+Length;
279 I = Opts.find(string(ArgName, ArgNameEnd));
280 assert(I->second == PGOpt);
282 // This must be a grouped option... handle all of them now...
283 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
286 // Move current arg name out of RealName into RealArgName...
287 string RealArgName(RealName.begin(), RealName.begin()+Length);
288 RealName.erase(RealName.begin(), RealName.begin()+Length);
290 // Because ValueRequired is an invalid flag for grouped arguments,
291 // we don't need to pass argc/argv in...
293 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
294 "Option can not be cl::Grouping AND cl::ValueRequired!");
296 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(), "",
299 // Get the next grouping option...
300 if (!RealName.empty())
301 PGOpt = getOptionPred(RealName, Length, isGrouping);
302 } while (!RealName.empty() && PGOpt);
304 if (RealName.empty()) // Processed all of the options, move on
305 continue; // to the next argv[] value...
307 // If RealName is not empty, that means we did not match one of the
308 // options! This is an error.
314 Handler = I != Opts.end() ? I->second : 0;
319 cerr << "Unknown command line argument '" << argv[i] << "'. Try: "
320 << argv[0] << " --help'\n";
325 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
328 // Check and handle positional arguments now...
329 if (NumPositionalRequired > PositionalVals.size()) {
330 cerr << "Not enough positional command line arguments specified!\n";
331 cerr << "Must specify at least " << NumPositionalRequired
332 << " positional arguments: See: " << argv[0] << " --help\n";
336 } else if (ConsumeAfterOpt == 0) {
337 // Positional args have already been handled if ConsumeAfter is specified...
338 unsigned ValNo = 0, NumVals = PositionalVals.size();
339 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
340 if (RequiresValue(PositionalOpts[i])) {
341 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
342 --NumPositionalRequired; // We fulfilled our duty...
345 // If we _can_ give this option more arguments, do so now, as long as we
346 // do not give it values that others need. 'Done' controls whether the
347 // option even _WANTS_ any more.
349 bool Done = PositionalOpts[i]->getNumOccurancesFlag() == cl::Required;
350 while (NumVals-ValNo > NumPositionalRequired && !Done) {
351 switch (PositionalOpts[i]->getNumOccurancesFlag()) {
353 Done = true; // Optional arguments want _at most_ one value
355 case cl::ZeroOrMore: // Zero or more will take all they can get...
356 case cl::OneOrMore: // One or more will take all they can get...
357 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
360 assert(0 && "Internal error, unexpected NumOccurances flag in "
361 "positional argument processing!");
366 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
368 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
369 if (RequiresValue(PositionalOpts[j]))
370 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
371 PositionalVals[ValNo++]);
373 // Handle the case where there is just one positional option, and it's
374 // optional. In this case, we want to give JUST THE FIRST option to the
375 // positional option and keep the rest for the consume after. The above
376 // loop would have assigned no values to positional options in this case.
378 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty())
379 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
380 PositionalVals[ValNo++]);
382 // Handle over all of the rest of the arguments to the
383 // cl::ConsumeAfter command line option...
384 for (; ValNo != PositionalVals.size(); ++ValNo)
385 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
386 PositionalVals[ValNo]);
389 // Loop over args and make sure all required args are specified!
390 for (map<string, Option*>::iterator I = Opts.begin(),
391 E = Opts.end(); I != E; ++I) {
392 switch (I->second->getNumOccurancesFlag()) {
395 if (I->second->getNumOccurances() == 0) {
396 I->second->error(" must be specified at least once!");
405 // Free all of the memory allocated to the map. Command line options may only
406 // be processed once!
407 delete CommandLineOptions;
408 CommandLineOptions = 0;
409 PositionalOpts.clear();
411 // If we had an error processing our arguments, don't let the program execute
412 if (ErrorParsing) exit(1);
415 //===----------------------------------------------------------------------===//
416 // Option Base class implementation
419 bool Option::error(string Message, const char *ArgName) {
420 if (ArgName == 0) ArgName = ArgStr;
422 cerr << HelpStr; // Be nice for positional arguments
424 cerr << "-" << ArgName;
425 cerr << " option" << Message << "\n";
429 bool Option::addOccurance(const char *ArgName, const string &Value) {
430 NumOccurances++; // Increment the number of times we have been seen
432 switch (getNumOccurancesFlag()) {
434 if (NumOccurances > 1)
435 return error(": may only occur zero or one times!", ArgName);
438 if (NumOccurances > 1)
439 return error(": must occur exactly one time!", ArgName);
443 case ConsumeAfter: break;
444 default: return error(": bad num occurances flag value!");
447 return handleOccurance(ArgName, Value);
450 // addArgument - Tell the system that this Option subclass will handle all
451 // occurances of -ArgStr on the command line.
453 void Option::addArgument(const char *ArgStr) {
455 AddArgument(ArgStr, this);
456 else if (getFormattingFlag() == Positional)
457 getPositionalOpts().push_back(this);
458 else if (getNumOccurancesFlag() == ConsumeAfter) {
459 assert((getPositionalOpts().empty() ||
460 getPositionalOpts().front()->getNumOccurancesFlag() != ConsumeAfter)
461 && "Cannot specify more than one option with cl::ConsumeAfter "
463 getPositionalOpts().insert(getPositionalOpts().begin(), this);
467 void Option::removeArgument(const char *ArgStr) {
469 RemoveArgument(ArgStr, this);
470 } else if (getFormattingFlag() == Positional) {
471 vector<Option*>::iterator I =
472 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
473 assert(I != getPositionalOpts().end() && "Arg not registered!");
474 getPositionalOpts().erase(I);
475 } else if (getNumOccurancesFlag() == ConsumeAfter) {
476 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
477 "Arg not registered correctly!");
478 getPositionalOpts().erase(getPositionalOpts().begin());
483 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
484 // has been specified yet.
486 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
487 if (O.ValueStr[0] == 0) return DefaultMsg;
491 //===----------------------------------------------------------------------===//
492 // cl::alias class implementation
495 // Return the width of the option tag for printing...
496 unsigned alias::getOptionWidth() const {
497 return std::strlen(ArgStr)+6;
500 // Print out the option for the alias...
501 void alias::printOptionInfo(unsigned GlobalWidth) const {
502 unsigned L = std::strlen(ArgStr);
503 cerr << " -" << ArgStr << string(GlobalWidth-L-6, ' ') << " - "
509 //===----------------------------------------------------------------------===//
510 // Parser Implementation code...
513 // basic_parser implementation
516 // Return the width of the option tag for printing...
517 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
518 unsigned Len = std::strlen(O.ArgStr);
519 if (const char *ValName = getValueName())
520 Len += std::strlen(getValueStr(O, ValName))+3;
525 // printOptionInfo - Print out information about this option. The
526 // to-be-maintained width is specified.
528 void basic_parser_impl::printOptionInfo(const Option &O,
529 unsigned GlobalWidth) const {
530 cerr << " -" << O.ArgStr;
532 if (const char *ValName = getValueName())
533 cerr << "=<" << getValueStr(O, ValName) << ">";
535 cerr << string(GlobalWidth-getOptionWidth(O), ' ') << " - "
536 << O.HelpStr << "\n";
542 // parser<bool> implementation
544 bool parser<bool>::parse(Option &O, const char *ArgName,
545 const string &Arg, bool &Value) {
546 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
549 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
552 return O.error(": '" + Arg +
553 "' is invalid value for boolean argument! Try 0 or 1");
558 // parser<int> implementation
560 bool parser<int>::parse(Option &O, const char *ArgName,
561 const string &Arg, int &Value) {
562 const char *ArgStart = Arg.c_str();
564 Value = (int)strtol(ArgStart, &End, 0);
566 return O.error(": '" + Arg + "' value invalid for integer argument!");
570 // parser<double>/parser<float> implementation
572 static bool parseDouble(Option &O, const string &Arg, double &Value) {
573 const char *ArgStart = Arg.c_str();
575 Value = strtod(ArgStart, &End);
577 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
581 bool parser<double>::parse(Option &O, const char *AN,
582 const std::string &Arg, double &Val) {
583 return parseDouble(O, Arg, Val);
586 bool parser<float>::parse(Option &O, const char *AN,
587 const std::string &Arg, float &Val) {
589 if (parseDouble(O, Arg, dVal))
597 // generic_parser_base implementation
600 // findOption - Return the option number corresponding to the specified
601 // argument string. If the option is not found, getNumOptions() is returned.
603 unsigned generic_parser_base::findOption(const char *Name) {
604 unsigned i = 0, e = getNumOptions();
608 if (getOption(i) == N)
616 // Return the width of the option tag for printing...
617 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
619 unsigned Size = std::strlen(O.ArgStr)+6;
620 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
621 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
624 unsigned BaseSize = 0;
625 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
626 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
631 // printOptionInfo - Print out information about this option. The
632 // to-be-maintained width is specified.
634 void generic_parser_base::printOptionInfo(const Option &O,
635 unsigned GlobalWidth) const {
637 unsigned L = std::strlen(O.ArgStr);
638 cerr << " -" << O.ArgStr << string(GlobalWidth-L-6, ' ')
639 << " - " << O.HelpStr << "\n";
641 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
642 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
643 cerr << " =" << getOption(i) << string(NumSpaces, ' ') << " - "
644 << getDescription(i) << "\n";
648 cerr << " " << O.HelpStr << "\n";
649 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
650 unsigned L = std::strlen(getOption(i));
651 cerr << " -" << getOption(i) << string(GlobalWidth-L-8, ' ') << " - "
652 << getDescription(i) << "\n";
658 //===----------------------------------------------------------------------===//
659 // --help and --help-hidden option implementation
665 const Option *EmptyArg;
666 const bool ShowHidden;
668 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
669 inline static bool isHidden(pair<string, Option *> &OptPair) {
670 return OptPair.second->getOptionHiddenFlag() >= Hidden;
672 inline static bool isReallyHidden(pair<string, Option *> &OptPair) {
673 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
677 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
681 void operator=(bool Value) {
682 if (Value == false) return;
684 // Copy Options into a vector so we can sort them as we like...
685 vector<pair<string, Option*> > Options;
686 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
688 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
689 Options.erase(std::remove_if(Options.begin(), Options.end(),
690 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
693 // Eliminate duplicate entries in table (from enum flags options, f.e.)
694 { // Give OptionSet a scope
695 std::set<Option*> OptionSet;
696 for (unsigned i = 0; i != Options.size(); ++i)
697 if (OptionSet.count(Options[i].second) == 0)
698 OptionSet.insert(Options[i].second); // Add new entry to set
700 Options.erase(Options.begin()+i--); // Erase duplicate
704 cerr << "OVERVIEW:" << ProgramOverview << "\n";
706 cerr << "USAGE: " << ProgramName << " [options]";
708 // Print out the positional options...
709 vector<Option*> &PosOpts = getPositionalOpts();
710 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
711 if (!PosOpts.empty() && PosOpts[0]->getNumOccurancesFlag() == ConsumeAfter)
714 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i)
715 cerr << " " << PosOpts[i]->HelpStr;
717 // Print the consume after option info if it exists...
718 if (CAOpt) cerr << " " << CAOpt->HelpStr;
722 // Compute the maximum argument length...
724 for (unsigned i = 0, e = Options.size(); i != e; ++i)
725 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
727 cerr << "OPTIONS:\n";
728 for (unsigned i = 0, e = Options.size(); i != e; ++i)
729 Options[i].second->printOptionInfo(MaxArgLen);
731 // Halt the program if help information is printed
738 // Define the two HelpPrinter instances that are used to print out help, or
741 HelpPrinter NormalPrinter(false);
742 HelpPrinter HiddenPrinter(true);
744 cl::opt<HelpPrinter, true, parser<bool> >
745 HOp("help", cl::desc("display available options (--help-hidden for more)"),
746 cl::location(NormalPrinter), cl::ValueDisallowed);
748 cl::opt<HelpPrinter, true, parser<bool> >
749 HHOp("help-hidden", cl::desc("display all available options"),
750 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
752 } // End anonymous namespace