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"
20 //===----------------------------------------------------------------------===//
21 // Basic, shared command line option processing machinery...
24 // Return the global command line option vector. Making it a function scoped
25 // static ensures that it will be initialized correctly before its first use.
27 static std::map<std::string, Option*> *CommandLineOptions = 0;
28 static std::map<std::string, Option*> &getOpts() {
29 if (CommandLineOptions == 0)
30 CommandLineOptions = new std::map<std::string,Option*>();
31 return *CommandLineOptions;
34 static Option *getOption(const std::string &Str) {
35 if (CommandLineOptions == 0) return 0;
36 std::map<std::string,Option*>::iterator I = CommandLineOptions->find(Str);
37 return I != CommandLineOptions->end() ? I->second : 0;
40 static std::vector<Option*> &getPositionalOpts() {
41 static std::vector<Option*> Positional;
45 static void AddArgument(const char *ArgName, Option *Opt) {
46 if (getOption(ArgName)) {
47 std::cerr << "CommandLine Error: Argument '" << ArgName
48 << "' defined more than once!\n";
50 // Add argument to the argument map!
51 getOpts()[ArgName] = Opt;
55 // RemoveArgument - It's possible that the argument is no longer in the map if
56 // options have already been processed and the map has been deleted!
58 static void RemoveArgument(const char *ArgName, Option *Opt) {
59 if (CommandLineOptions == 0) return;
60 assert(getOption(ArgName) == Opt && "Arg not in map!");
61 CommandLineOptions->erase(ArgName);
62 if (CommandLineOptions->empty()) {
63 delete CommandLineOptions;
64 CommandLineOptions = 0;
68 static const char *ProgramName = 0;
69 static const char *ProgramOverview = 0;
71 static inline bool ProvideOption(Option *Handler, const char *ArgName,
72 const char *Value, int argc, char **argv,
74 // Enforce value requirements
75 switch (Handler->getValueExpectedFlag()) {
77 if (Value == 0 || *Value == 0) { // No value specified?
78 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
81 return Handler->error(" requires a value!");
87 return Handler->error(" does not allow a value! '" +
88 std::string(Value) + "' specified.");
90 case ValueOptional: break;
91 default: std::cerr << "Bad ValueMask flag! CommandLine usage error:"
92 << Handler->getValueExpectedFlag() << "\n"; abort();
95 // Run the handler now!
96 return Handler->addOccurance(ArgName, Value);
99 static bool ProvidePositionalOption(Option *Handler, std::string &Arg) {
101 return ProvideOption(Handler, "", Arg.c_str(), 0, 0, Dummy);
105 // Option predicates...
106 static inline bool isGrouping(const Option *O) {
107 return O->getFormattingFlag() == cl::Grouping;
109 static inline bool isPrefixedOrGrouping(const Option *O) {
110 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
113 // getOptionPred - Check to see if there are any options that satisfy the
114 // specified predicate with names that are the prefixes in Name. This is
115 // checked by progressively stripping characters off of the name, checking to
116 // see if there options that satisfy the predicate. If we find one, return it,
117 // otherwise return null.
119 static Option *getOptionPred(std::string Name, unsigned &Length,
120 bool (*Pred)(const Option*)) {
122 Option *Op = getOption(Name);
123 if (Op && Pred(Op)) {
124 Length = Name.length();
128 if (Name.size() == 1) return 0;
130 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
131 Op = getOption(Name);
133 // Loop while we haven't found an option and Name still has at least two
134 // characters in it (so that the next iteration will not be the empty
136 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
138 if (Op && Pred(Op)) {
139 Length = Name.length();
140 return Op; // Found one!
142 return 0; // No option found!
145 static bool RequiresValue(const Option *O) {
146 return O->getNumOccurancesFlag() == cl::Required ||
147 O->getNumOccurancesFlag() == cl::OneOrMore;
150 static bool EatsUnboundedNumberOfValues(const Option *O) {
151 return O->getNumOccurancesFlag() == cl::ZeroOrMore ||
152 O->getNumOccurancesFlag() == cl::OneOrMore;
155 void cl::ParseCommandLineOptions(int &argc, char **argv,
156 const char *Overview) {
157 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
158 "No options specified, or ParseCommandLineOptions called more"
160 ProgramName = argv[0]; // Save this away safe and snug
161 ProgramOverview = Overview;
162 bool ErrorParsing = false;
164 std::map<std::string, Option*> &Opts = getOpts();
165 std::vector<Option*> &PositionalOpts = getPositionalOpts();
167 // Check out the positional arguments to collect information about them.
168 unsigned NumPositionalRequired = 0;
169 Option *ConsumeAfterOpt = 0;
170 if (!PositionalOpts.empty()) {
171 if (PositionalOpts[0]->getNumOccurancesFlag() == cl::ConsumeAfter) {
172 assert(PositionalOpts.size() > 1 &&
173 "Cannot specify cl::ConsumeAfter without a positional argument!");
174 ConsumeAfterOpt = PositionalOpts[0];
177 // Calculate how many positional values are _required_.
178 bool UnboundedFound = false;
179 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
181 Option *Opt = PositionalOpts[i];
182 if (RequiresValue(Opt))
183 ++NumPositionalRequired;
184 else if (ConsumeAfterOpt) {
185 // ConsumeAfter cannot be combined with "optional" positional options
186 // unless there is only one positional argument...
187 if (PositionalOpts.size() > 2)
189 Opt->error(" error - this positional option will never be matched, "
190 "because it does not Require a value, and a "
191 "cl::ConsumeAfter option is active!");
192 } else if (UnboundedFound) { // This option does not "require" a value...
193 // Make sure this option is not specified after an option that eats all
194 // extra arguments, or this one will never get any!
196 ErrorParsing |= Opt->error(" error - option can never match, because "
197 "another positional argument will match an "
198 "unbounded number of values, and this option"
199 " does not require a value!");
201 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
205 // PositionalVals - A vector of "positional" arguments we accumulate into to
206 // processes at the end...
208 std::vector<std::string> PositionalVals;
210 // Loop over all of the arguments... processing them.
211 bool DashDashFound = false; // Have we read '--'?
212 for (int i = 1; i < argc; ++i) {
214 const char *Value = "";
215 const char *ArgName = "";
217 // Check to see if this is a positional argument. This argument is
218 // considered to be positional if it doesn't start with '-', if it is "-"
219 // itself, or if we have see "--" already.
221 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
222 // Positional argument!
223 if (!PositionalOpts.empty()) {
224 PositionalVals.push_back(argv[i]);
226 // All of the positional arguments have been fulfulled, give the rest to
227 // the consume after option... if it's specified...
229 if (PositionalVals.size() >= NumPositionalRequired &&
230 ConsumeAfterOpt != 0) {
231 for (++i; i < argc; ++i)
232 PositionalVals.push_back(argv[i]);
233 break; // Handle outside of the argument processing loop...
236 // Delay processing positional arguments until the end...
239 } else { // We start with a '-', must be an argument...
241 while (*ArgName == '-') ++ArgName; // Eat leading dashes
243 if (*ArgName == 0 && !DashDashFound) { // Is this the mythical "--"?
244 DashDashFound = true; // Yup, take note of that fact...
245 continue; // Don't try to process it as an argument iself.
248 const char *ArgNameEnd = ArgName;
249 while (*ArgNameEnd && *ArgNameEnd != '=')
250 ++ArgNameEnd; // Scan till end of argument name...
253 if (*Value) // If we have an equals sign...
254 ++Value; // Advance to value...
257 std::string RealName(ArgName, ArgNameEnd);
258 // Extract arg name part
259 std::map<std::string, Option*>::iterator I = Opts.find(RealName);
261 if (I == Opts.end() && !*Value && RealName.size() > 1) {
262 // Check to see if this "option" is really a prefixed or grouped
266 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
268 // If the option is a prefixed option, then the value is simply the
269 // rest of the name... so fall through to later processing, by
270 // setting up the argument name flags and value fields.
272 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
273 ArgNameEnd = ArgName+Length;
275 I = Opts.find(std::string(ArgName, ArgNameEnd));
276 assert(I->second == PGOpt);
278 // This must be a grouped option... handle all of them now...
279 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
282 // Move current arg name out of RealName into RealArgName...
283 std::string RealArgName(RealName.begin(),RealName.begin()+Length);
284 RealName.erase(RealName.begin(), RealName.begin()+Length);
286 // Because ValueRequired is an invalid flag for grouped arguments,
287 // we don't need to pass argc/argv in...
289 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
290 "Option can not be cl::Grouping AND cl::ValueRequired!");
292 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(), "",
295 // Get the next grouping option...
296 if (!RealName.empty())
297 PGOpt = getOptionPred(RealName, Length, isGrouping);
298 } while (!RealName.empty() && PGOpt);
300 if (RealName.empty()) // Processed all of the options, move on
301 continue; // to the next argv[] value...
303 // If RealName is not empty, that means we did not match one of the
304 // options! This is an error.
310 Handler = I != Opts.end() ? I->second : 0;
315 std::cerr << "Unknown command line argument '" << argv[i] << "'. Try: "
316 << argv[0] << " --help'\n";
321 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
324 // Check and handle positional arguments now...
325 if (NumPositionalRequired > PositionalVals.size()) {
326 std::cerr << "Not enough positional command line arguments specified!\n"
327 << "Must specify at least " << NumPositionalRequired
328 << " positional arguments: See: " << argv[0] << " --help\n";
332 } else if (ConsumeAfterOpt == 0) {
333 // Positional args have already been handled if ConsumeAfter is specified...
334 unsigned ValNo = 0, NumVals = PositionalVals.size();
335 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
336 if (RequiresValue(PositionalOpts[i])) {
337 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
338 --NumPositionalRequired; // We fulfilled our duty...
341 // If we _can_ give this option more arguments, do so now, as long as we
342 // do not give it values that others need. 'Done' controls whether the
343 // option even _WANTS_ any more.
345 bool Done = PositionalOpts[i]->getNumOccurancesFlag() == cl::Required;
346 while (NumVals-ValNo > NumPositionalRequired && !Done) {
347 switch (PositionalOpts[i]->getNumOccurancesFlag()) {
349 Done = true; // Optional arguments want _at most_ one value
351 case cl::ZeroOrMore: // Zero or more will take all they can get...
352 case cl::OneOrMore: // One or more will take all they can get...
353 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
356 assert(0 && "Internal error, unexpected NumOccurances flag in "
357 "positional argument processing!");
362 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
364 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
365 if (RequiresValue(PositionalOpts[j]))
366 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
367 PositionalVals[ValNo++]);
369 // Handle the case where there is just one positional option, and it's
370 // optional. In this case, we want to give JUST THE FIRST option to the
371 // positional option and keep the rest for the consume after. The above
372 // loop would have assigned no values to positional options in this case.
374 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty())
375 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
376 PositionalVals[ValNo++]);
378 // Handle over all of the rest of the arguments to the
379 // cl::ConsumeAfter command line option...
380 for (; ValNo != PositionalVals.size(); ++ValNo)
381 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
382 PositionalVals[ValNo]);
385 // Loop over args and make sure all required args are specified!
386 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
387 E = Opts.end(); I != E; ++I) {
388 switch (I->second->getNumOccurancesFlag()) {
391 if (I->second->getNumOccurances() == 0) {
392 I->second->error(" must be specified at least once!");
401 // Free all of the memory allocated to the map. Command line options may only
402 // be processed once!
403 delete CommandLineOptions;
404 CommandLineOptions = 0;
405 PositionalOpts.clear();
407 // If we had an error processing our arguments, don't let the program execute
408 if (ErrorParsing) exit(1);
411 //===----------------------------------------------------------------------===//
412 // Option Base class implementation
415 bool Option::error(std::string Message, const char *ArgName) {
416 if (ArgName == 0) ArgName = ArgStr;
418 std::cerr << HelpStr; // Be nice for positional arguments
420 std::cerr << "-" << ArgName;
421 std::cerr << " option" << Message << "\n";
425 bool Option::addOccurance(const char *ArgName, const std::string &Value) {
426 NumOccurances++; // Increment the number of times we have been seen
428 switch (getNumOccurancesFlag()) {
430 if (NumOccurances > 1)
431 return error(": may only occur zero or one times!", ArgName);
434 if (NumOccurances > 1)
435 return error(": must occur exactly one time!", ArgName);
439 case ConsumeAfter: break;
440 default: return error(": bad num occurances flag value!");
443 return handleOccurance(ArgName, Value);
446 // addArgument - Tell the system that this Option subclass will handle all
447 // occurances of -ArgStr on the command line.
449 void Option::addArgument(const char *ArgStr) {
451 AddArgument(ArgStr, this);
452 else if (getFormattingFlag() == Positional)
453 getPositionalOpts().push_back(this);
454 else if (getNumOccurancesFlag() == ConsumeAfter) {
455 assert((getPositionalOpts().empty() ||
456 getPositionalOpts().front()->getNumOccurancesFlag() != ConsumeAfter)
457 && "Cannot specify more than one option with cl::ConsumeAfter "
459 getPositionalOpts().insert(getPositionalOpts().begin(), this);
463 void Option::removeArgument(const char *ArgStr) {
465 RemoveArgument(ArgStr, this);
466 } else if (getFormattingFlag() == Positional) {
467 std::vector<Option*>::iterator I =
468 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
469 assert(I != getPositionalOpts().end() && "Arg not registered!");
470 getPositionalOpts().erase(I);
471 } else if (getNumOccurancesFlag() == ConsumeAfter) {
472 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
473 "Arg not registered correctly!");
474 getPositionalOpts().erase(getPositionalOpts().begin());
479 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
480 // has been specified yet.
482 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
483 if (O.ValueStr[0] == 0) return DefaultMsg;
487 //===----------------------------------------------------------------------===//
488 // cl::alias class implementation
491 // Return the width of the option tag for printing...
492 unsigned alias::getOptionWidth() const {
493 return std::strlen(ArgStr)+6;
496 // Print out the option for the alias...
497 void alias::printOptionInfo(unsigned GlobalWidth) const {
498 unsigned L = std::strlen(ArgStr);
499 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
505 //===----------------------------------------------------------------------===//
506 // Parser Implementation code...
509 // basic_parser implementation
512 // Return the width of the option tag for printing...
513 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
514 unsigned Len = std::strlen(O.ArgStr);
515 if (const char *ValName = getValueName())
516 Len += std::strlen(getValueStr(O, ValName))+3;
521 // printOptionInfo - Print out information about this option. The
522 // to-be-maintained width is specified.
524 void basic_parser_impl::printOptionInfo(const Option &O,
525 unsigned GlobalWidth) const {
526 std::cerr << " -" << O.ArgStr;
528 if (const char *ValName = getValueName())
529 std::cerr << "=<" << getValueStr(O, ValName) << ">";
531 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
532 << O.HelpStr << "\n";
538 // parser<bool> implementation
540 bool parser<bool>::parse(Option &O, const char *ArgName,
541 const std::string &Arg, bool &Value) {
542 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
545 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
548 return O.error(": '" + Arg +
549 "' is invalid value for boolean argument! Try 0 or 1");
554 // parser<int> implementation
556 bool parser<int>::parse(Option &O, const char *ArgName,
557 const std::string &Arg, int &Value) {
558 const char *ArgStart = Arg.c_str();
560 Value = (int)strtol(ArgStart, &End, 0);
562 return O.error(": '" + Arg + "' value invalid for integer argument!");
566 // parser<double>/parser<float> implementation
568 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
569 const char *ArgStart = Arg.c_str();
571 Value = strtod(ArgStart, &End);
573 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
577 bool parser<double>::parse(Option &O, const char *AN,
578 const std::string &Arg, double &Val) {
579 return parseDouble(O, Arg, Val);
582 bool parser<float>::parse(Option &O, const char *AN,
583 const std::string &Arg, float &Val) {
585 if (parseDouble(O, Arg, dVal))
593 // generic_parser_base implementation
596 // findOption - Return the option number corresponding to the specified
597 // argument string. If the option is not found, getNumOptions() is returned.
599 unsigned generic_parser_base::findOption(const char *Name) {
600 unsigned i = 0, e = getNumOptions();
604 if (getOption(i) == N)
612 // Return the width of the option tag for printing...
613 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
615 unsigned Size = std::strlen(O.ArgStr)+6;
616 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
617 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
620 unsigned BaseSize = 0;
621 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
622 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
627 // printOptionInfo - Print out information about this option. The
628 // to-be-maintained width is specified.
630 void generic_parser_base::printOptionInfo(const Option &O,
631 unsigned GlobalWidth) const {
633 unsigned L = std::strlen(O.ArgStr);
634 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
635 << " - " << O.HelpStr << "\n";
637 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
638 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
639 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ')
640 << " - " << getDescription(i) << "\n";
644 std::cerr << " " << O.HelpStr << "\n";
645 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
646 unsigned L = std::strlen(getOption(i));
647 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
648 << " - " << getDescription(i) << "\n";
654 //===----------------------------------------------------------------------===//
655 // --help and --help-hidden option implementation
661 const Option *EmptyArg;
662 const bool ShowHidden;
664 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
665 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
666 return OptPair.second->getOptionHiddenFlag() >= Hidden;
668 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
669 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
673 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
677 void operator=(bool Value) {
678 if (Value == false) return;
680 // Copy Options into a vector so we can sort them as we like...
681 std::vector<std::pair<std::string, Option*> > Options;
682 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
684 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
685 Options.erase(std::remove_if(Options.begin(), Options.end(),
686 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
689 // Eliminate duplicate entries in table (from enum flags options, f.e.)
690 { // Give OptionSet a scope
691 std::set<Option*> OptionSet;
692 for (unsigned i = 0; i != Options.size(); ++i)
693 if (OptionSet.count(Options[i].second) == 0)
694 OptionSet.insert(Options[i].second); // Add new entry to set
696 Options.erase(Options.begin()+i--); // Erase duplicate
700 std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
702 std::cerr << "USAGE: " << ProgramName << " [options]";
704 // Print out the positional options...
705 std::vector<Option*> &PosOpts = getPositionalOpts();
706 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
707 if (!PosOpts.empty() && PosOpts[0]->getNumOccurancesFlag() == ConsumeAfter)
710 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i)
711 std::cerr << " " << PosOpts[i]->HelpStr;
713 // Print the consume after option info if it exists...
714 if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
718 // Compute the maximum argument length...
720 for (unsigned i = 0, e = Options.size(); i != e; ++i)
721 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
723 std::cerr << "OPTIONS:\n";
724 for (unsigned i = 0, e = Options.size(); i != e; ++i)
725 Options[i].second->printOptionInfo(MaxArgLen);
727 // Halt the program if help information is printed
734 // Define the two HelpPrinter instances that are used to print out help, or
737 HelpPrinter NormalPrinter(false);
738 HelpPrinter HiddenPrinter(true);
740 cl::opt<HelpPrinter, true, parser<bool> >
741 HOp("help", cl::desc("display available options (--help-hidden for more)"),
742 cl::location(NormalPrinter), cl::ValueDisallowed);
744 cl::opt<HelpPrinter, true, parser<bool> >
745 HHOp("help-hidden", cl::desc("display all available options"),
746 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
748 } // End anonymous namespace