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 "llvm/Config/config.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/Streams.h"
23 #include "llvm/System/Path.h"
35 //===----------------------------------------------------------------------===//
36 // Template instantiations and anchors.
38 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
39 TEMPLATE_INSTANTIATION(class basic_parser<int>);
40 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
41 TEMPLATE_INSTANTIATION(class basic_parser<double>);
42 TEMPLATE_INSTANTIATION(class basic_parser<float>);
43 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
45 TEMPLATE_INSTANTIATION(class opt<unsigned>);
46 TEMPLATE_INSTANTIATION(class opt<int>);
47 TEMPLATE_INSTANTIATION(class opt<std::string>);
48 TEMPLATE_INSTANTIATION(class opt<bool>);
50 void Option::anchor() {}
51 void basic_parser_impl::anchor() {}
52 void parser<bool>::anchor() {}
53 void parser<int>::anchor() {}
54 void parser<unsigned>::anchor() {}
55 void parser<double>::anchor() {}
56 void parser<float>::anchor() {}
57 void parser<std::string>::anchor() {}
59 //===----------------------------------------------------------------------===//
61 // Globals for name and overview of program. Program name is not a string to
62 // avoid static ctor/dtor issues.
63 static char ProgramName[80] = "<premain>";
64 static const char *ProgramOverview = 0;
66 // This collects additional help to be printed.
67 static ManagedStatic<std::vector<const char*> > MoreHelp;
69 extrahelp::extrahelp(const char *Help)
71 MoreHelp->push_back(Help);
74 /// RegisteredOptionList - This is the list of the command line options that
75 /// have statically constructed themselves.
76 static Option *RegisteredOptionList = 0;
78 void Option::addArgument() {
79 assert(NextRegistered == 0 && "argument multiply registered!");
81 NextRegistered = RegisteredOptionList;
82 RegisteredOptionList = this;
85 //===----------------------------------------------------------------------===//
86 // Basic, shared command line option processing machinery.
89 /// GetOptionInfo - Scan the list of registered options, turning them into data
90 /// structures that are easier to handle.
91 static void GetOptionInfo(std::vector<Option*> &PositionalOpts,
92 std::map<std::string, Option*> &OptionsMap) {
93 std::vector<const char*> OptionNames;
94 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
95 // If this option wants to handle multiple option names, get the full set.
96 // This handles enum options like "-O1 -O2" etc.
97 O->getExtraOptionNames(OptionNames);
99 OptionNames.push_back(O->ArgStr);
101 // Handle named options.
102 for (unsigned i = 0, e = OptionNames.size(); i != e; ++i) {
103 // Add argument to the argument map!
104 if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i],
106 cerr << ProgramName << ": CommandLine Error: Argument '"
107 << OptionNames[0] << "' defined more than once!\n";
113 // Remember information about positional options.
114 if (O->getFormattingFlag() == cl::Positional)
115 PositionalOpts.push_back(O);
116 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
117 if (!PositionalOpts.empty() &&
118 PositionalOpts.front()->getNumOccurrencesFlag() == cl::ConsumeAfter)
119 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
120 PositionalOpts.insert(PositionalOpts.begin(), O);
126 /// LookupOption - Lookup the option specified by the specified option on the
127 /// command line. If there is a value specified (after an equal sign) return
129 static Option *LookupOption(const char *&Arg, const char *&Value,
130 std::map<std::string, Option*> &OptionsMap) {
131 while (*Arg == '-') ++Arg; // Eat leading dashes
133 const char *ArgEnd = Arg;
134 while (*ArgEnd && *ArgEnd != '=')
135 ++ArgEnd; // Scan till end of argument name.
137 if (*ArgEnd == '=') // If we have an equals sign...
138 Value = ArgEnd+1; // Get the value, not the equals
141 if (*Arg == 0) return 0;
143 // Look up the option.
144 std::map<std::string, Option*>::iterator I =
145 OptionsMap.find(std::string(Arg, ArgEnd));
146 return I != OptionsMap.end() ? I->second : 0;
149 static inline bool ProvideOption(Option *Handler, const char *ArgName,
150 const char *Value, int argc, char **argv,
152 // Enforce value requirements
153 switch (Handler->getValueExpectedFlag()) {
155 if (Value == 0) { // No value specified?
156 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
159 return Handler->error(" requires a value!");
163 case ValueDisallowed:
165 return Handler->error(" does not allow a value! '" +
166 std::string(Value) + "' specified.");
172 << ": Bad ValueMask flag! CommandLine usage error:"
173 << Handler->getValueExpectedFlag() << "\n";
178 // Run the handler now!
179 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
182 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
185 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
189 // Option predicates...
190 static inline bool isGrouping(const Option *O) {
191 return O->getFormattingFlag() == cl::Grouping;
193 static inline bool isPrefixedOrGrouping(const Option *O) {
194 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
197 // getOptionPred - Check to see if there are any options that satisfy the
198 // specified predicate with names that are the prefixes in Name. This is
199 // checked by progressively stripping characters off of the name, checking to
200 // see if there options that satisfy the predicate. If we find one, return it,
201 // otherwise return null.
203 static Option *getOptionPred(std::string Name, unsigned &Length,
204 bool (*Pred)(const Option*),
205 std::map<std::string, Option*> &OptionsMap) {
207 std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name);
208 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
209 Length = Name.length();
213 if (Name.size() == 1) return 0;
215 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
216 OMI = OptionsMap.find(Name);
218 // Loop while we haven't found an option and Name still has at least two
219 // characters in it (so that the next iteration will not be the empty
221 } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1);
223 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
224 Length = Name.length();
225 return OMI->second; // Found one!
227 return 0; // No option found!
230 static bool RequiresValue(const Option *O) {
231 return O->getNumOccurrencesFlag() == cl::Required ||
232 O->getNumOccurrencesFlag() == cl::OneOrMore;
235 static bool EatsUnboundedNumberOfValues(const Option *O) {
236 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
237 O->getNumOccurrencesFlag() == cl::OneOrMore;
240 /// ParseCStringVector - Break INPUT up wherever one or more
241 /// whitespace characters are found, and store the resulting tokens in
242 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
243 /// using strdup (), so it is the caller's responsibility to free ()
246 static void ParseCStringVector(std::vector<char *> &output,
248 // Characters which will be treated as token separators:
249 static const char *delims = " \v\f\t\r\n";
251 std::string work (input);
252 // Skip past any delims at head of input string.
253 size_t pos = work.find_first_not_of (delims);
254 // If the string consists entirely of delims, then exit early.
255 if (pos == std::string::npos) return;
256 // Otherwise, jump forward to beginning of first word.
257 work = work.substr (pos);
258 // Find position of first delimiter.
259 pos = work.find_first_of (delims);
261 while (!work.empty() && pos != std::string::npos) {
262 // Everything from 0 to POS is the next word to copy.
263 output.push_back (strdup (work.substr (0,pos).c_str ()));
264 // Is there another word in the string?
265 size_t nextpos = work.find_first_not_of (delims, pos + 1);
266 if (nextpos != std::string::npos) {
267 // Yes? Then remove delims from beginning ...
268 work = work.substr (work.find_first_not_of (delims, pos + 1));
269 // and find the end of the word.
270 pos = work.find_first_of (delims);
272 // No? (Remainder of string is delims.) End the loop.
274 pos = std::string::npos;
278 // If `input' ended with non-delim char, then we'll get here with
279 // the last word of `input' in `work'; copy it now.
280 if (!work.empty ()) {
281 output.push_back (strdup (work.c_str ()));
285 /// ParseEnvironmentOptions - An alternative entry point to the
286 /// CommandLine library, which allows you to read the program's name
287 /// from the caller (as PROGNAME) and its command-line arguments from
288 /// an environment variable (whose name is given in ENVVAR).
290 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
291 const char *Overview) {
293 assert(progName && "Program name not specified");
294 assert(envVar && "Environment variable name missing");
296 // Get the environment variable they want us to parse options out of.
297 const char *envValue = getenv(envVar);
301 // Get program's "name", which we wouldn't know without the caller
303 std::vector<char*> newArgv;
304 newArgv.push_back(strdup(progName));
306 // Parse the value of the environment variable into a "command line"
307 // and hand it off to ParseCommandLineOptions().
308 ParseCStringVector(newArgv, envValue);
309 int newArgc = newArgv.size();
310 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
312 // Free all the strdup()ed strings.
313 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
318 void cl::ParseCommandLineOptions(int &argc, char **argv,
319 const char *Overview) {
320 // Process all registered options.
321 std::vector<Option*> PositionalOpts;
322 std::map<std::string, Option*> Opts;
323 GetOptionInfo(PositionalOpts, Opts);
325 assert((!Opts.empty() || !PositionalOpts.empty()) &&
326 "No options specified!");
327 sys::Path progname(argv[0]);
329 // Copy the program name into ProgName, making sure not to overflow it.
330 std::string ProgName = sys::Path(argv[0]).getLast();
331 if (ProgName.size() > 79) ProgName.resize(79);
332 strcpy(ProgramName, ProgName.c_str());
334 ProgramOverview = Overview;
335 bool ErrorParsing = false;
337 // Check out the positional arguments to collect information about them.
338 unsigned NumPositionalRequired = 0;
340 // Determine whether or not there are an unlimited number of positionals
341 bool HasUnlimitedPositionals = false;
343 Option *ConsumeAfterOpt = 0;
344 if (!PositionalOpts.empty()) {
345 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
346 assert(PositionalOpts.size() > 1 &&
347 "Cannot specify cl::ConsumeAfter without a positional argument!");
348 ConsumeAfterOpt = PositionalOpts[0];
351 // Calculate how many positional values are _required_.
352 bool UnboundedFound = false;
353 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
355 Option *Opt = PositionalOpts[i];
356 if (RequiresValue(Opt))
357 ++NumPositionalRequired;
358 else if (ConsumeAfterOpt) {
359 // ConsumeAfter cannot be combined with "optional" positional options
360 // unless there is only one positional argument...
361 if (PositionalOpts.size() > 2)
363 Opt->error(" error - this positional option will never be matched, "
364 "because it does not Require a value, and a "
365 "cl::ConsumeAfter option is active!");
366 } else if (UnboundedFound && !Opt->ArgStr[0]) {
367 // This option does not "require" a value... Make sure this option is
368 // not specified after an option that eats all extra arguments, or this
369 // one will never get any!
371 ErrorParsing |= Opt->error(" error - option can never match, because "
372 "another positional argument will match an "
373 "unbounded number of values, and this option"
374 " does not require a value!");
376 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
378 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
381 // PositionalVals - A vector of "positional" arguments we accumulate into
382 // the process at the end...
384 std::vector<std::pair<std::string,unsigned> > PositionalVals;
386 // If the program has named positional arguments, and the name has been run
387 // across, keep track of which positional argument was named. Otherwise put
388 // the positional args into the PositionalVals list...
389 Option *ActivePositionalArg = 0;
391 // Loop over all of the arguments... processing them.
392 bool DashDashFound = false; // Have we read '--'?
393 for (int i = 1; i < argc; ++i) {
395 const char *Value = 0;
396 const char *ArgName = "";
398 // Check to see if this is a positional argument. This argument is
399 // considered to be positional if it doesn't start with '-', if it is "-"
400 // itself, or if we have seen "--" already.
402 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
403 // Positional argument!
404 if (ActivePositionalArg) {
405 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
406 continue; // We are done!
407 } else if (!PositionalOpts.empty()) {
408 PositionalVals.push_back(std::make_pair(argv[i],i));
410 // All of the positional arguments have been fulfulled, give the rest to
411 // the consume after option... if it's specified...
413 if (PositionalVals.size() >= NumPositionalRequired &&
414 ConsumeAfterOpt != 0) {
415 for (++i; i < argc; ++i)
416 PositionalVals.push_back(std::make_pair(argv[i],i));
417 break; // Handle outside of the argument processing loop...
420 // Delay processing positional arguments until the end...
423 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
425 DashDashFound = true; // This is the mythical "--"?
426 continue; // Don't try to process it as an argument itself.
427 } else if (ActivePositionalArg &&
428 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
429 // If there is a positional argument eating options, check to see if this
430 // option is another positional argument. If so, treat it as an argument,
431 // otherwise feed it to the eating positional.
433 Handler = LookupOption(ArgName, Value, Opts);
434 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
435 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
436 continue; // We are done!
439 } else { // We start with a '-', must be an argument...
441 Handler = LookupOption(ArgName, Value, Opts);
443 // Check to see if this "option" is really a prefixed or grouped argument.
445 std::string RealName(ArgName);
446 if (RealName.size() > 1) {
448 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping,
451 // If the option is a prefixed option, then the value is simply the
452 // rest of the name... so fall through to later processing, by
453 // setting up the argument name flags and value fields.
455 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
456 Value = ArgName+Length;
457 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
458 Opts.find(std::string(ArgName, Value))->second == PGOpt);
461 // This must be a grouped option... handle them now.
462 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
465 // Move current arg name out of RealName into RealArgName...
466 std::string RealArgName(RealName.begin(),
467 RealName.begin() + Length);
468 RealName.erase(RealName.begin(), RealName.begin() + Length);
470 // Because ValueRequired is an invalid flag for grouped arguments,
471 // we don't need to pass argc/argv in...
473 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
474 "Option can not be cl::Grouping AND cl::ValueRequired!");
476 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
479 // Get the next grouping option...
480 PGOpt = getOptionPred(RealName, Length, isGrouping, Opts);
481 } while (PGOpt && Length != RealName.size());
483 Handler = PGOpt; // Ate all of the options.
490 cerr << ProgramName << ": Unknown command line argument '"
491 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
496 // Check to see if this option accepts a comma separated list of values. If
497 // it does, we have to split up the value into multiple values...
498 if (Value && Handler->getMiscFlags() & CommaSeparated) {
499 std::string Val(Value);
500 std::string::size_type Pos = Val.find(',');
502 while (Pos != std::string::npos) {
503 // Process the portion before the comma...
504 ErrorParsing |= ProvideOption(Handler, ArgName,
505 std::string(Val.begin(),
506 Val.begin()+Pos).c_str(),
508 // Erase the portion before the comma, AND the comma...
509 Val.erase(Val.begin(), Val.begin()+Pos+1);
510 Value += Pos+1; // Increment the original value pointer as well...
512 // Check for another comma...
517 // If this is a named positional argument, just remember that it is the
519 if (Handler->getFormattingFlag() == cl::Positional)
520 ActivePositionalArg = Handler;
522 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
525 // Check and handle positional arguments now...
526 if (NumPositionalRequired > PositionalVals.size()) {
528 << ": Not enough positional command line arguments specified!\n"
529 << "Must specify at least " << NumPositionalRequired
530 << " positional arguments: See: " << argv[0] << " --help\n";
533 } else if (!HasUnlimitedPositionals
534 && PositionalVals.size() > PositionalOpts.size()) {
536 << ": Too many positional arguments specified!\n"
537 << "Can specify at most " << PositionalOpts.size()
538 << " positional arguments: See: " << argv[0] << " --help\n";
541 } else if (ConsumeAfterOpt == 0) {
542 // Positional args have already been handled if ConsumeAfter is specified...
543 unsigned ValNo = 0, NumVals = PositionalVals.size();
544 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
545 if (RequiresValue(PositionalOpts[i])) {
546 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
547 PositionalVals[ValNo].second);
549 --NumPositionalRequired; // We fulfilled our duty...
552 // If we _can_ give this option more arguments, do so now, as long as we
553 // do not give it values that others need. 'Done' controls whether the
554 // option even _WANTS_ any more.
556 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
557 while (NumVals-ValNo > NumPositionalRequired && !Done) {
558 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
560 Done = true; // Optional arguments want _at most_ one value
562 case cl::ZeroOrMore: // Zero or more will take all they can get...
563 case cl::OneOrMore: // One or more will take all they can get...
564 ProvidePositionalOption(PositionalOpts[i],
565 PositionalVals[ValNo].first,
566 PositionalVals[ValNo].second);
570 assert(0 && "Internal error, unexpected NumOccurrences flag in "
571 "positional argument processing!");
576 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
578 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
579 if (RequiresValue(PositionalOpts[j])) {
580 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
581 PositionalVals[ValNo].first,
582 PositionalVals[ValNo].second);
586 // Handle the case where there is just one positional option, and it's
587 // optional. In this case, we want to give JUST THE FIRST option to the
588 // positional option and keep the rest for the consume after. The above
589 // loop would have assigned no values to positional options in this case.
591 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
592 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
593 PositionalVals[ValNo].first,
594 PositionalVals[ValNo].second);
598 // Handle over all of the rest of the arguments to the
599 // cl::ConsumeAfter command line option...
600 for (; ValNo != PositionalVals.size(); ++ValNo)
601 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
602 PositionalVals[ValNo].first,
603 PositionalVals[ValNo].second);
606 // Loop over args and make sure all required args are specified!
607 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
608 E = Opts.end(); I != E; ++I) {
609 switch (I->second->getNumOccurrencesFlag()) {
612 if (I->second->getNumOccurrences() == 0) {
613 I->second->error(" must be specified at least once!");
622 // Free all of the memory allocated to the map. Command line options may only
623 // be processed once!
625 PositionalOpts.clear();
628 // If we had an error processing our arguments, don't let the program execute
629 if (ErrorParsing) exit(1);
632 //===----------------------------------------------------------------------===//
633 // Option Base class implementation
636 bool Option::error(std::string Message, const char *ArgName) {
637 if (ArgName == 0) ArgName = ArgStr;
639 cerr << HelpStr; // Be nice for positional arguments
641 cerr << ProgramName << ": for the -" << ArgName;
643 cerr << " option: " << Message << "\n";
647 bool Option::addOccurrence(unsigned pos, const char *ArgName,
648 const std::string &Value) {
649 NumOccurrences++; // Increment the number of times we have been seen
651 switch (getNumOccurrencesFlag()) {
653 if (NumOccurrences > 1)
654 return error(": may only occur zero or one times!", ArgName);
657 if (NumOccurrences > 1)
658 return error(": must occur exactly one time!", ArgName);
662 case ConsumeAfter: break;
663 default: return error(": bad num occurrences flag value!");
666 return handleOccurrence(pos, ArgName, Value);
670 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
671 // has been specified yet.
673 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
674 if (O.ValueStr[0] == 0) return DefaultMsg;
678 //===----------------------------------------------------------------------===//
679 // cl::alias class implementation
682 // Return the width of the option tag for printing...
683 unsigned alias::getOptionWidth() const {
684 return std::strlen(ArgStr)+6;
687 // Print out the option for the alias.
688 void alias::printOptionInfo(unsigned GlobalWidth) const {
689 unsigned L = std::strlen(ArgStr);
690 cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
696 //===----------------------------------------------------------------------===//
697 // Parser Implementation code...
700 // basic_parser implementation
703 // Return the width of the option tag for printing...
704 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
705 unsigned Len = std::strlen(O.ArgStr);
706 if (const char *ValName = getValueName())
707 Len += std::strlen(getValueStr(O, ValName))+3;
712 // printOptionInfo - Print out information about this option. The
713 // to-be-maintained width is specified.
715 void basic_parser_impl::printOptionInfo(const Option &O,
716 unsigned GlobalWidth) const {
717 cout << " -" << O.ArgStr;
719 if (const char *ValName = getValueName())
720 cout << "=<" << getValueStr(O, ValName) << ">";
722 cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
723 << O.HelpStr << "\n";
729 // parser<bool> implementation
731 bool parser<bool>::parse(Option &O, const char *ArgName,
732 const std::string &Arg, bool &Value) {
733 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
736 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
739 return O.error(": '" + Arg +
740 "' is invalid value for boolean argument! Try 0 or 1");
745 // parser<int> implementation
747 bool parser<int>::parse(Option &O, const char *ArgName,
748 const std::string &Arg, int &Value) {
750 Value = (int)strtol(Arg.c_str(), &End, 0);
752 return O.error(": '" + Arg + "' value invalid for integer argument!");
756 // parser<unsigned> implementation
758 bool parser<unsigned>::parse(Option &O, const char *ArgName,
759 const std::string &Arg, unsigned &Value) {
762 unsigned long V = strtoul(Arg.c_str(), &End, 0);
764 if (((V == ULONG_MAX) && (errno == ERANGE))
767 return O.error(": '" + Arg + "' value invalid for uint argument!");
771 // parser<double>/parser<float> implementation
773 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
774 const char *ArgStart = Arg.c_str();
776 Value = strtod(ArgStart, &End);
778 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
782 bool parser<double>::parse(Option &O, const char *AN,
783 const std::string &Arg, double &Val) {
784 return parseDouble(O, Arg, Val);
787 bool parser<float>::parse(Option &O, const char *AN,
788 const std::string &Arg, float &Val) {
790 if (parseDouble(O, Arg, dVal))
798 // generic_parser_base implementation
801 // findOption - Return the option number corresponding to the specified
802 // argument string. If the option is not found, getNumOptions() is returned.
804 unsigned generic_parser_base::findOption(const char *Name) {
805 unsigned i = 0, e = getNumOptions();
809 if (getOption(i) == N)
817 // Return the width of the option tag for printing...
818 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
820 unsigned Size = std::strlen(O.ArgStr)+6;
821 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
822 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
825 unsigned BaseSize = 0;
826 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
827 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
832 // printOptionInfo - Print out information about this option. The
833 // to-be-maintained width is specified.
835 void generic_parser_base::printOptionInfo(const Option &O,
836 unsigned GlobalWidth) const {
838 unsigned L = std::strlen(O.ArgStr);
839 cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
840 << " - " << O.HelpStr << "\n";
842 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
843 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
844 cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
845 << " - " << getDescription(i) << "\n";
849 cout << " " << O.HelpStr << "\n";
850 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
851 unsigned L = std::strlen(getOption(i));
852 cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
853 << " - " << getDescription(i) << "\n";
859 //===----------------------------------------------------------------------===//
860 // --help and --help-hidden option implementation
867 const Option *EmptyArg;
868 const bool ShowHidden;
870 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
871 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
872 return OptPair.second->getOptionHiddenFlag() >= Hidden;
874 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
875 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
879 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
883 void operator=(bool Value) {
884 if (Value == false) return;
886 // Get all the options.
887 std::vector<Option*> PositionalOpts;
888 std::map<std::string, Option*> OptMap;
889 GetOptionInfo(PositionalOpts, OptMap);
891 // Copy Options into a vector so we can sort them as we like...
892 std::vector<std::pair<std::string, Option*> > Opts;
893 copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts));
895 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
896 Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
897 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
900 // Eliminate duplicate entries in table (from enum flags options, f.e.)
901 { // Give OptionSet a scope
902 std::set<Option*> OptionSet;
903 for (unsigned i = 0; i != Opts.size(); ++i)
904 if (OptionSet.count(Opts[i].second) == 0)
905 OptionSet.insert(Opts[i].second); // Add new entry to set
907 Opts.erase(Opts.begin()+i--); // Erase duplicate
911 cout << "OVERVIEW:" << ProgramOverview << "\n";
913 cout << "USAGE: " << ProgramName << " [options]";
915 // Print out the positional options.
916 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
917 if (!PositionalOpts.empty() &&
918 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
919 CAOpt = PositionalOpts[0];
921 for (unsigned i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
922 if (PositionalOpts[i]->ArgStr[0])
923 cout << " --" << PositionalOpts[i]->ArgStr;
924 cout << " " << PositionalOpts[i]->HelpStr;
927 // Print the consume after option info if it exists...
928 if (CAOpt) cout << " " << CAOpt->HelpStr;
932 // Compute the maximum argument length...
934 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
935 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
937 cout << "OPTIONS:\n";
938 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
939 Opts[i].second->printOptionInfo(MaxArgLen);
941 // Print any extra help the user has declared.
942 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
943 E = MoreHelp->end(); I != E; ++I)
947 // Halt the program since help information was printed
951 } // End anonymous namespace
953 // Define the two HelpPrinter instances that are used to print out help, or
956 static HelpPrinter NormalPrinter(false);
957 static HelpPrinter HiddenPrinter(true);
959 static cl::opt<HelpPrinter, true, parser<bool> >
960 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
961 cl::location(NormalPrinter), cl::ValueDisallowed);
963 static cl::opt<HelpPrinter, true, parser<bool> >
964 HHOp("help-hidden", cl::desc("Display all available options"),
965 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
967 static void (*OverrideVersionPrinter)() = 0;
970 class VersionPrinter {
973 cout << "Low Level Virtual Machine (http://llvm.org/):\n";
974 cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
975 #ifdef LLVM_VERSION_INFO
976 cout << LLVM_VERSION_INFO;
980 cout << "DEBUG build";
982 cout << "Optimized build";
985 cout << " with assertions";
989 void operator=(bool OptionWasSpecified) {
990 if (OptionWasSpecified) {
991 if (OverrideVersionPrinter == 0) {
995 (*OverrideVersionPrinter)();
1001 } // End anonymous namespace
1004 // Define the --version option that prints out the LLVM version for the tool
1005 static VersionPrinter VersionPrinterInstance;
1007 static cl::opt<VersionPrinter, true, parser<bool> >
1008 VersOp("version", cl::desc("Display the version of this program"),
1009 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1011 // Utility function for printing the help message.
1012 void cl::PrintHelpMessage() {
1013 // This looks weird, but it actually prints the help message. The
1014 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1015 // its operator= is invoked. That's because the "normal" usages of the
1016 // help printer is to be assigned true/false depending on whether the
1017 // --help option was given or not. Since we're circumventing that we have
1018 // to make it look like --help was given, so we assign true.
1019 NormalPrinter = true;
1022 /// Utility function for printing version number.
1023 void cl::PrintVersionMessage() {
1024 VersionPrinterInstance.print();
1027 void cl::SetVersionPrinter(void (*func)()) {
1028 OverrideVersionPrinter = func;