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/System/Path.h"
34 //===----------------------------------------------------------------------===//
35 // Template instantiations and anchors.
37 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
38 TEMPLATE_INSTANTIATION(class basic_parser<int>);
39 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
40 TEMPLATE_INSTANTIATION(class basic_parser<double>);
41 TEMPLATE_INSTANTIATION(class basic_parser<float>);
42 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
44 TEMPLATE_INSTANTIATION(class opt<unsigned>);
45 TEMPLATE_INSTANTIATION(class opt<int>);
46 TEMPLATE_INSTANTIATION(class opt<std::string>);
47 TEMPLATE_INSTANTIATION(class opt<bool>);
49 void Option::anchor() {}
50 void basic_parser_impl::anchor() {}
51 void parser<bool>::anchor() {}
52 void parser<int>::anchor() {}
53 void parser<unsigned>::anchor() {}
54 void parser<double>::anchor() {}
55 void parser<float>::anchor() {}
56 void parser<std::string>::anchor() {}
58 //===----------------------------------------------------------------------===//
60 // Globals for name and overview of program
61 static std::string ProgramName = "<premain>";
62 static const char *ProgramOverview = 0;
64 // This collects additional help to be printed.
65 static ManagedStatic<std::vector<const char*> > MoreHelp;
67 extrahelp::extrahelp(const char *Help)
69 MoreHelp->push_back(Help);
72 //===----------------------------------------------------------------------===//
73 // Basic, shared command line option processing machinery.
76 static ManagedStatic<std::map<std::string, Option*> > Options;
77 static ManagedStatic<std::vector<Option*> > PositionalOptions;
79 static Option *getOption(const std::string &Str) {
80 std::map<std::string,Option*>::iterator I = Options->find(Str);
81 return I != Options->end() ? I->second : 0;
84 static void AddArgument(const char *ArgName, Option *Opt) {
85 if (getOption(ArgName)) {
86 std::cerr << ProgramName << ": CommandLine Error: Argument '"
87 << ArgName << "' defined more than once!\n";
89 // Add argument to the argument map!
90 (*Options)[ArgName] = Opt;
94 // RemoveArgument - It's possible that the argument is no longer in the map if
95 // options have already been processed and the map has been deleted!
97 static void RemoveArgument(const char *ArgName, Option *Opt) {
98 if (Options->empty()) return;
101 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
102 // If we pass ArgName directly into getOption here.
103 std::string Tmp = ArgName;
104 assert(getOption(Tmp) == Opt && "Arg not in map!");
106 Options->erase(ArgName);
109 static inline bool ProvideOption(Option *Handler, const char *ArgName,
110 const char *Value, int argc, char **argv,
112 // Enforce value requirements
113 switch (Handler->getValueExpectedFlag()) {
115 if (Value == 0) { // No value specified?
116 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
119 return Handler->error(" requires a value!");
123 case ValueDisallowed:
125 return Handler->error(" does not allow a value! '" +
126 std::string(Value) + "' specified.");
131 std::cerr << ProgramName
132 << ": Bad ValueMask flag! CommandLine usage error:"
133 << Handler->getValueExpectedFlag() << "\n";
138 // Run the handler now!
139 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
142 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
145 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
149 // Option predicates...
150 static inline bool isGrouping(const Option *O) {
151 return O->getFormattingFlag() == cl::Grouping;
153 static inline bool isPrefixedOrGrouping(const Option *O) {
154 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
157 // getOptionPred - Check to see if there are any options that satisfy the
158 // specified predicate with names that are the prefixes in Name. This is
159 // checked by progressively stripping characters off of the name, checking to
160 // see if there options that satisfy the predicate. If we find one, return it,
161 // otherwise return null.
163 static Option *getOptionPred(std::string Name, unsigned &Length,
164 bool (*Pred)(const Option*)) {
166 Option *Op = getOption(Name);
167 if (Op && Pred(Op)) {
168 Length = Name.length();
172 if (Name.size() == 1) return 0;
174 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
175 Op = getOption(Name);
177 // Loop while we haven't found an option and Name still has at least two
178 // characters in it (so that the next iteration will not be the empty
180 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
182 if (Op && Pred(Op)) {
183 Length = Name.length();
184 return Op; // Found one!
186 return 0; // No option found!
189 static bool RequiresValue(const Option *O) {
190 return O->getNumOccurrencesFlag() == cl::Required ||
191 O->getNumOccurrencesFlag() == cl::OneOrMore;
194 static bool EatsUnboundedNumberOfValues(const Option *O) {
195 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
196 O->getNumOccurrencesFlag() == cl::OneOrMore;
199 /// ParseCStringVector - Break INPUT up wherever one or more
200 /// whitespace characters are found, and store the resulting tokens in
201 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
202 /// using strdup (), so it is the caller's responsibility to free ()
205 static void ParseCStringVector(std::vector<char *> &output,
207 // Characters which will be treated as token separators:
208 static const char *delims = " \v\f\t\r\n";
210 std::string work (input);
211 // Skip past any delims at head of input string.
212 size_t pos = work.find_first_not_of (delims);
213 // If the string consists entirely of delims, then exit early.
214 if (pos == std::string::npos) return;
215 // Otherwise, jump forward to beginning of first word.
216 work = work.substr (pos);
217 // Find position of first delimiter.
218 pos = work.find_first_of (delims);
220 while (!work.empty() && pos != std::string::npos) {
221 // Everything from 0 to POS is the next word to copy.
222 output.push_back (strdup (work.substr (0,pos).c_str ()));
223 // Is there another word in the string?
224 size_t nextpos = work.find_first_not_of (delims, pos + 1);
225 if (nextpos != std::string::npos) {
226 // Yes? Then remove delims from beginning ...
227 work = work.substr (work.find_first_not_of (delims, pos + 1));
228 // and find the end of the word.
229 pos = work.find_first_of (delims);
231 // No? (Remainder of string is delims.) End the loop.
233 pos = std::string::npos;
237 // If `input' ended with non-delim char, then we'll get here with
238 // the last word of `input' in `work'; copy it now.
239 if (!work.empty ()) {
240 output.push_back (strdup (work.c_str ()));
244 /// ParseEnvironmentOptions - An alternative entry point to the
245 /// CommandLine library, which allows you to read the program's name
246 /// from the caller (as PROGNAME) and its command-line arguments from
247 /// an environment variable (whose name is given in ENVVAR).
249 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
250 const char *Overview) {
252 assert(progName && "Program name not specified");
253 assert(envVar && "Environment variable name missing");
255 // Get the environment variable they want us to parse options out of.
256 const char *envValue = getenv(envVar);
260 // Get program's "name", which we wouldn't know without the caller
262 std::vector<char*> newArgv;
263 newArgv.push_back(strdup(progName));
265 // Parse the value of the environment variable into a "command line"
266 // and hand it off to ParseCommandLineOptions().
267 ParseCStringVector(newArgv, envValue);
268 int newArgc = newArgv.size();
269 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
271 // Free all the strdup()ed strings.
272 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
277 /// LookupOption - Lookup the option specified by the specified option on the
278 /// command line. If there is a value specified (after an equal sign) return
280 static Option *LookupOption(const char *&Arg, const char *&Value) {
281 while (*Arg == '-') ++Arg; // Eat leading dashes
283 const char *ArgEnd = Arg;
284 while (*ArgEnd && *ArgEnd != '=')
285 ++ArgEnd; // Scan till end of argument name.
287 if (*ArgEnd == '=') // If we have an equals sign...
288 Value = ArgEnd+1; // Get the value, not the equals
291 if (*Arg == 0) return 0;
293 // Look up the option.
294 std::map<std::string, Option*> &Opts = *Options;
295 std::map<std::string, Option*>::iterator I =
296 Opts.find(std::string(Arg, ArgEnd));
297 return (I != Opts.end()) ? I->second : 0;
300 void cl::ParseCommandLineOptions(int &argc, char **argv,
301 const char *Overview) {
302 assert((!Options->empty() || !PositionalOptions->empty()) &&
303 "No options specified, or ParseCommandLineOptions called more"
305 sys::Path progname(argv[0]);
306 ProgramName = sys::Path(argv[0]).getLast();
307 ProgramOverview = Overview;
308 bool ErrorParsing = false;
310 std::map<std::string, Option*> &Opts = *Options;
311 std::vector<Option*> &PositionalOpts = *PositionalOptions;
313 // Check out the positional arguments to collect information about them.
314 unsigned NumPositionalRequired = 0;
316 // Determine whether or not there are an unlimited number of positionals
317 bool HasUnlimitedPositionals = false;
319 Option *ConsumeAfterOpt = 0;
320 if (!PositionalOpts.empty()) {
321 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
322 assert(PositionalOpts.size() > 1 &&
323 "Cannot specify cl::ConsumeAfter without a positional argument!");
324 ConsumeAfterOpt = PositionalOpts[0];
327 // Calculate how many positional values are _required_.
328 bool UnboundedFound = false;
329 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
331 Option *Opt = PositionalOpts[i];
332 if (RequiresValue(Opt))
333 ++NumPositionalRequired;
334 else if (ConsumeAfterOpt) {
335 // ConsumeAfter cannot be combined with "optional" positional options
336 // unless there is only one positional argument...
337 if (PositionalOpts.size() > 2)
339 Opt->error(" error - this positional option will never be matched, "
340 "because it does not Require a value, and a "
341 "cl::ConsumeAfter option is active!");
342 } else if (UnboundedFound && !Opt->ArgStr[0]) {
343 // This option does not "require" a value... Make sure this option is
344 // not specified after an option that eats all extra arguments, or this
345 // one will never get any!
347 ErrorParsing |= Opt->error(" error - option can never match, because "
348 "another positional argument will match an "
349 "unbounded number of values, and this option"
350 " does not require a value!");
352 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
354 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
357 // PositionalVals - A vector of "positional" arguments we accumulate into
358 // the process at the end...
360 std::vector<std::pair<std::string,unsigned> > PositionalVals;
362 // If the program has named positional arguments, and the name has been run
363 // across, keep track of which positional argument was named. Otherwise put
364 // the positional args into the PositionalVals list...
365 Option *ActivePositionalArg = 0;
367 // Loop over all of the arguments... processing them.
368 bool DashDashFound = false; // Have we read '--'?
369 for (int i = 1; i < argc; ++i) {
371 const char *Value = 0;
372 const char *ArgName = "";
374 // Check to see if this is a positional argument. This argument is
375 // considered to be positional if it doesn't start with '-', if it is "-"
376 // itself, or if we have seen "--" already.
378 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
379 // Positional argument!
380 if (ActivePositionalArg) {
381 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
382 continue; // We are done!
383 } else if (!PositionalOpts.empty()) {
384 PositionalVals.push_back(std::make_pair(argv[i],i));
386 // All of the positional arguments have been fulfulled, give the rest to
387 // the consume after option... if it's specified...
389 if (PositionalVals.size() >= NumPositionalRequired &&
390 ConsumeAfterOpt != 0) {
391 for (++i; i < argc; ++i)
392 PositionalVals.push_back(std::make_pair(argv[i],i));
393 break; // Handle outside of the argument processing loop...
396 // Delay processing positional arguments until the end...
399 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
401 DashDashFound = true; // This is the mythical "--"?
402 continue; // Don't try to process it as an argument itself.
403 } else if (ActivePositionalArg &&
404 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
405 // If there is a positional argument eating options, check to see if this
406 // option is another positional argument. If so, treat it as an argument,
407 // otherwise feed it to the eating positional.
409 Handler = LookupOption(ArgName, Value);
410 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
411 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
412 continue; // We are done!
415 } else { // We start with a '-', must be an argument...
417 Handler = LookupOption(ArgName, Value);
419 // Check to see if this "option" is really a prefixed or grouped argument.
421 std::string RealName(ArgName);
422 if (RealName.size() > 1) {
424 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
426 // If the option is a prefixed option, then the value is simply the
427 // rest of the name... so fall through to later processing, by
428 // setting up the argument name flags and value fields.
430 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
431 Value = ArgName+Length;
432 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
433 Opts.find(std::string(ArgName, Value))->second == PGOpt);
436 // This must be a grouped option... handle them now.
437 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
440 // Move current arg name out of RealName into RealArgName...
441 std::string RealArgName(RealName.begin(),
442 RealName.begin() + Length);
443 RealName.erase(RealName.begin(), RealName.begin() + Length);
445 // Because ValueRequired is an invalid flag for grouped arguments,
446 // we don't need to pass argc/argv in...
448 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
449 "Option can not be cl::Grouping AND cl::ValueRequired!");
451 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
454 // Get the next grouping option...
455 PGOpt = getOptionPred(RealName, Length, isGrouping);
456 } while (PGOpt && Length != RealName.size());
458 Handler = PGOpt; // Ate all of the options.
465 std::cerr << ProgramName << ": Unknown command line argument '"
466 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
471 // Check to see if this option accepts a comma separated list of values. If
472 // it does, we have to split up the value into multiple values...
473 if (Value && Handler->getMiscFlags() & CommaSeparated) {
474 std::string Val(Value);
475 std::string::size_type Pos = Val.find(',');
477 while (Pos != std::string::npos) {
478 // Process the portion before the comma...
479 ErrorParsing |= ProvideOption(Handler, ArgName,
480 std::string(Val.begin(),
481 Val.begin()+Pos).c_str(),
483 // Erase the portion before the comma, AND the comma...
484 Val.erase(Val.begin(), Val.begin()+Pos+1);
485 Value += Pos+1; // Increment the original value pointer as well...
487 // Check for another comma...
492 // If this is a named positional argument, just remember that it is the
494 if (Handler->getFormattingFlag() == cl::Positional)
495 ActivePositionalArg = Handler;
497 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
500 // Check and handle positional arguments now...
501 if (NumPositionalRequired > PositionalVals.size()) {
502 std::cerr << ProgramName
503 << ": Not enough positional command line arguments specified!\n"
504 << "Must specify at least " << NumPositionalRequired
505 << " positional arguments: See: " << argv[0] << " --help\n";
508 } else if (!HasUnlimitedPositionals
509 && PositionalVals.size() > PositionalOpts.size()) {
510 std::cerr << ProgramName
511 << ": Too many positional arguments specified!\n"
512 << "Can specify at most " << PositionalOpts.size()
513 << " positional arguments: See: " << argv[0] << " --help\n";
516 } else if (ConsumeAfterOpt == 0) {
517 // Positional args have already been handled if ConsumeAfter is specified...
518 unsigned ValNo = 0, NumVals = PositionalVals.size();
519 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
520 if (RequiresValue(PositionalOpts[i])) {
521 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
522 PositionalVals[ValNo].second);
524 --NumPositionalRequired; // We fulfilled our duty...
527 // If we _can_ give this option more arguments, do so now, as long as we
528 // do not give it values that others need. 'Done' controls whether the
529 // option even _WANTS_ any more.
531 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
532 while (NumVals-ValNo > NumPositionalRequired && !Done) {
533 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
535 Done = true; // Optional arguments want _at most_ one value
537 case cl::ZeroOrMore: // Zero or more will take all they can get...
538 case cl::OneOrMore: // One or more will take all they can get...
539 ProvidePositionalOption(PositionalOpts[i],
540 PositionalVals[ValNo].first,
541 PositionalVals[ValNo].second);
545 assert(0 && "Internal error, unexpected NumOccurrences flag in "
546 "positional argument processing!");
551 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
553 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
554 if (RequiresValue(PositionalOpts[j])) {
555 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
556 PositionalVals[ValNo].first,
557 PositionalVals[ValNo].second);
561 // Handle the case where there is just one positional option, and it's
562 // optional. In this case, we want to give JUST THE FIRST option to the
563 // positional option and keep the rest for the consume after. The above
564 // loop would have assigned no values to positional options in this case.
566 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
567 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
568 PositionalVals[ValNo].first,
569 PositionalVals[ValNo].second);
573 // Handle over all of the rest of the arguments to the
574 // cl::ConsumeAfter command line option...
575 for (; ValNo != PositionalVals.size(); ++ValNo)
576 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
577 PositionalVals[ValNo].first,
578 PositionalVals[ValNo].second);
581 // Loop over args and make sure all required args are specified!
582 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
583 E = Opts.end(); I != E; ++I) {
584 switch (I->second->getNumOccurrencesFlag()) {
587 if (I->second->getNumOccurrences() == 0) {
588 I->second->error(" must be specified at least once!");
597 // Free all of the memory allocated to the map. Command line options may only
598 // be processed once!
600 PositionalOpts.clear();
603 // If we had an error processing our arguments, don't let the program execute
604 if (ErrorParsing) exit(1);
607 //===----------------------------------------------------------------------===//
608 // Option Base class implementation
611 bool Option::error(std::string Message, const char *ArgName) {
612 if (ArgName == 0) ArgName = ArgStr;
614 std::cerr << HelpStr; // Be nice for positional arguments
616 std::cerr << ProgramName << ": for the -" << ArgName;
618 std::cerr << " option: " << Message << "\n";
622 bool Option::addOccurrence(unsigned pos, const char *ArgName,
623 const std::string &Value) {
624 NumOccurrences++; // Increment the number of times we have been seen
626 switch (getNumOccurrencesFlag()) {
628 if (NumOccurrences > 1)
629 return error(": may only occur zero or one times!", ArgName);
632 if (NumOccurrences > 1)
633 return error(": must occur exactly one time!", ArgName);
637 case ConsumeAfter: break;
638 default: return error(": bad num occurrences flag value!");
641 return handleOccurrence(pos, ArgName, Value);
644 // addArgument - Tell the system that this Option subclass will handle all
645 // occurrences of -ArgStr on the command line.
647 void Option::addArgument(const char *ArgStr) {
649 AddArgument(ArgStr, this);
651 if (getFormattingFlag() == Positional)
652 PositionalOptions->push_back(this);
653 else if (getNumOccurrencesFlag() == ConsumeAfter) {
654 if (!PositionalOptions->empty() &&
655 PositionalOptions->front()->getNumOccurrencesFlag() == ConsumeAfter)
656 error("Cannot specify more than one option with cl::ConsumeAfter!");
657 PositionalOptions->insert(PositionalOptions->begin(), this);
661 void Option::removeArgument(const char *ArgStr) {
663 RemoveArgument(ArgStr, this);
665 if (getFormattingFlag() == Positional) {
666 std::vector<Option*>::iterator I =
667 std::find(PositionalOptions->begin(), PositionalOptions->end(), this);
668 assert(I != PositionalOptions->end() && "Arg not registered!");
669 PositionalOptions->erase(I);
670 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
671 assert(!PositionalOptions->empty() && (*PositionalOptions)[0] == this &&
672 "Arg not registered correctly!");
673 PositionalOptions->erase(PositionalOptions->begin());
678 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
679 // has been specified yet.
681 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
682 if (O.ValueStr[0] == 0) return DefaultMsg;
686 //===----------------------------------------------------------------------===//
687 // cl::alias class implementation
690 // Return the width of the option tag for printing...
691 unsigned alias::getOptionWidth() const {
692 return std::strlen(ArgStr)+6;
695 // Print out the option for the alias.
696 void alias::printOptionInfo(unsigned GlobalWidth) const {
697 unsigned L = std::strlen(ArgStr);
698 std::cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
704 //===----------------------------------------------------------------------===//
705 // Parser Implementation code...
708 // basic_parser implementation
711 // Return the width of the option tag for printing...
712 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
713 unsigned Len = std::strlen(O.ArgStr);
714 if (const char *ValName = getValueName())
715 Len += std::strlen(getValueStr(O, ValName))+3;
720 // printOptionInfo - Print out information about this option. The
721 // to-be-maintained width is specified.
723 void basic_parser_impl::printOptionInfo(const Option &O,
724 unsigned GlobalWidth) const {
725 std::cout << " -" << O.ArgStr;
727 if (const char *ValName = getValueName())
728 std::cout << "=<" << getValueStr(O, ValName) << ">";
730 std::cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
731 << O.HelpStr << "\n";
737 // parser<bool> implementation
739 bool parser<bool>::parse(Option &O, const char *ArgName,
740 const std::string &Arg, bool &Value) {
741 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
744 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
747 return O.error(": '" + Arg +
748 "' is invalid value for boolean argument! Try 0 or 1");
753 // parser<int> implementation
755 bool parser<int>::parse(Option &O, const char *ArgName,
756 const std::string &Arg, int &Value) {
758 Value = (int)strtol(Arg.c_str(), &End, 0);
760 return O.error(": '" + Arg + "' value invalid for integer argument!");
764 // parser<unsigned> implementation
766 bool parser<unsigned>::parse(Option &O, const char *ArgName,
767 const std::string &Arg, unsigned &Value) {
770 unsigned long V = strtoul(Arg.c_str(), &End, 0);
772 if (((V == ULONG_MAX) && (errno == ERANGE))
775 return O.error(": '" + Arg + "' value invalid for uint argument!");
779 // parser<double>/parser<float> implementation
781 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
782 const char *ArgStart = Arg.c_str();
784 Value = strtod(ArgStart, &End);
786 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
790 bool parser<double>::parse(Option &O, const char *AN,
791 const std::string &Arg, double &Val) {
792 return parseDouble(O, Arg, Val);
795 bool parser<float>::parse(Option &O, const char *AN,
796 const std::string &Arg, float &Val) {
798 if (parseDouble(O, Arg, dVal))
806 // generic_parser_base implementation
809 // findOption - Return the option number corresponding to the specified
810 // argument string. If the option is not found, getNumOptions() is returned.
812 unsigned generic_parser_base::findOption(const char *Name) {
813 unsigned i = 0, e = getNumOptions();
817 if (getOption(i) == N)
825 // Return the width of the option tag for printing...
826 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
828 unsigned Size = std::strlen(O.ArgStr)+6;
829 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
830 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
833 unsigned BaseSize = 0;
834 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
835 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
840 // printOptionInfo - Print out information about this option. The
841 // to-be-maintained width is specified.
843 void generic_parser_base::printOptionInfo(const Option &O,
844 unsigned GlobalWidth) const {
846 unsigned L = std::strlen(O.ArgStr);
847 std::cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
848 << " - " << O.HelpStr << "\n";
850 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
851 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
852 std::cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
853 << " - " << getDescription(i) << "\n";
857 std::cout << " " << O.HelpStr << "\n";
858 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
859 unsigned L = std::strlen(getOption(i));
860 std::cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
861 << " - " << getDescription(i) << "\n";
867 //===----------------------------------------------------------------------===//
868 // --help and --help-hidden option implementation
875 const Option *EmptyArg;
876 const bool ShowHidden;
878 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
879 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
880 return OptPair.second->getOptionHiddenFlag() >= Hidden;
882 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
883 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
887 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
891 void operator=(bool Value) {
892 if (Value == false) return;
894 // Copy Options into a vector so we can sort them as we like...
895 std::vector<std::pair<std::string, Option*> > Opts;
896 copy(Options->begin(), Options->end(), std::back_inserter(Opts));
898 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
899 Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
900 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
903 // Eliminate duplicate entries in table (from enum flags options, f.e.)
904 { // Give OptionSet a scope
905 std::set<Option*> OptionSet;
906 for (unsigned i = 0; i != Opts.size(); ++i)
907 if (OptionSet.count(Opts[i].second) == 0)
908 OptionSet.insert(Opts[i].second); // Add new entry to set
910 Opts.erase(Opts.begin()+i--); // Erase duplicate
914 std::cout << "OVERVIEW:" << ProgramOverview << "\n";
916 std::cout << "USAGE: " << ProgramName << " [options]";
918 // Print out the positional options.
919 std::vector<Option*> &PosOpts = *PositionalOptions;
920 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
921 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
924 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
925 if (PosOpts[i]->ArgStr[0])
926 std::cout << " --" << PosOpts[i]->ArgStr;
927 std::cout << " " << PosOpts[i]->HelpStr;
930 // Print the consume after option info if it exists...
931 if (CAOpt) std::cout << " " << CAOpt->HelpStr;
935 // Compute the maximum argument length...
937 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
938 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
940 std::cout << "OPTIONS:\n";
941 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
942 Opts[i].second->printOptionInfo(MaxArgLen);
944 // Print any extra help the user has declared.
945 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
946 E = MoreHelp->end(); I != E; ++I)
950 // Halt the program since help information was printed
951 Options->clear(); // Don't bother making option dtors remove from map.
955 } // End anonymous namespace
957 // Define the two HelpPrinter instances that are used to print out help, or
960 static HelpPrinter NormalPrinter(false);
961 static HelpPrinter HiddenPrinter(true);
963 static cl::opt<HelpPrinter, true, parser<bool> >
964 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
965 cl::location(NormalPrinter), cl::ValueDisallowed);
967 static cl::opt<HelpPrinter, true, parser<bool> >
968 HHOp("help-hidden", cl::desc("Display all available options"),
969 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
971 static void (*OverrideVersionPrinter)() = 0;
974 class VersionPrinter {
976 void operator=(bool OptionWasSpecified) {
977 if (OptionWasSpecified) {
978 if (OverrideVersionPrinter == 0) {
979 std::cout << "Low Level Virtual Machine (http://llvm.org/):\n";
980 std::cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
981 #ifdef LLVM_VERSION_INFO
982 std::cout << LLVM_VERSION_INFO;
986 std::cout << "DEBUG build";
988 std::cout << "Optimized build";
991 std::cout << " with assertions";
994 Options->clear(); // Don't bother making option dtors remove from map.
997 (*OverrideVersionPrinter)();
1003 } // End anonymous namespace
1006 // Define the --version option that prints out the LLVM version for the tool
1007 static VersionPrinter VersionPrinterInstance;
1009 static cl::opt<VersionPrinter, true, parser<bool> >
1010 VersOp("version", cl::desc("Display the version of this program"),
1011 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1013 // Utility function for printing the help message.
1014 void cl::PrintHelpMessage() {
1015 // This looks weird, but it actually prints the help message. The
1016 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1017 // its operator= is invoked. That's because the "normal" usages of the
1018 // help printer is to be assigned true/false depending on whether the
1019 // --help option was given or not. Since we're circumventing that we have
1020 // to make it look like --help was given, so we assign true.
1021 NormalPrinter = true;
1024 void cl::SetVersionPrinter(void (*func)()) {
1025 OverrideVersionPrinter = func;