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 //===----------------------------------------------------------------------===//
75 // Basic, shared command line option processing machinery.
78 static ManagedStatic<std::map<std::string, Option*> > Options;
79 static ManagedStatic<std::vector<Option*> > PositionalOptions;
81 static Option *getOption(const std::string &Str) {
82 std::map<std::string,Option*>::iterator I = Options->find(Str);
83 return I != Options->end() ? I->second : 0;
86 static void AddArgument(const char *ArgName, Option *Opt) {
87 if (getOption(ArgName)) {
88 cerr << ProgramName << ": CommandLine Error: Argument '"
89 << ArgName << "' defined more than once!\n";
91 // Add argument to the argument map!
92 (*Options)[ArgName] = Opt;
96 // RemoveArgument - It's possible that the argument is no longer in the map if
97 // options have already been processed and the map has been deleted!
99 static void RemoveArgument(const char *ArgName, Option *Opt) {
100 if (Options->empty()) return;
103 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
104 // If we pass ArgName directly into getOption here.
105 std::string Tmp = ArgName;
106 assert(getOption(Tmp) == Opt && "Arg not in map!");
108 Options->erase(ArgName);
111 static inline bool ProvideOption(Option *Handler, const char *ArgName,
112 const char *Value, int argc, char **argv,
114 // Enforce value requirements
115 switch (Handler->getValueExpectedFlag()) {
117 if (Value == 0) { // No value specified?
118 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
121 return Handler->error(" requires a value!");
125 case ValueDisallowed:
127 return Handler->error(" does not allow a value! '" +
128 std::string(Value) + "' specified.");
134 << ": Bad ValueMask flag! CommandLine usage error:"
135 << Handler->getValueExpectedFlag() << "\n";
140 // Run the handler now!
141 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
144 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
147 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
151 // Option predicates...
152 static inline bool isGrouping(const Option *O) {
153 return O->getFormattingFlag() == cl::Grouping;
155 static inline bool isPrefixedOrGrouping(const Option *O) {
156 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
159 // getOptionPred - Check to see if there are any options that satisfy the
160 // specified predicate with names that are the prefixes in Name. This is
161 // checked by progressively stripping characters off of the name, checking to
162 // see if there options that satisfy the predicate. If we find one, return it,
163 // otherwise return null.
165 static Option *getOptionPred(std::string Name, unsigned &Length,
166 bool (*Pred)(const Option*)) {
168 Option *Op = getOption(Name);
169 if (Op && Pred(Op)) {
170 Length = Name.length();
174 if (Name.size() == 1) return 0;
176 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
177 Op = getOption(Name);
179 // Loop while we haven't found an option and Name still has at least two
180 // characters in it (so that the next iteration will not be the empty
182 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
184 if (Op && Pred(Op)) {
185 Length = Name.length();
186 return Op; // Found one!
188 return 0; // No option found!
191 static bool RequiresValue(const Option *O) {
192 return O->getNumOccurrencesFlag() == cl::Required ||
193 O->getNumOccurrencesFlag() == cl::OneOrMore;
196 static bool EatsUnboundedNumberOfValues(const Option *O) {
197 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
198 O->getNumOccurrencesFlag() == cl::OneOrMore;
201 /// ParseCStringVector - Break INPUT up wherever one or more
202 /// whitespace characters are found, and store the resulting tokens in
203 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
204 /// using strdup (), so it is the caller's responsibility to free ()
207 static void ParseCStringVector(std::vector<char *> &output,
209 // Characters which will be treated as token separators:
210 static const char *delims = " \v\f\t\r\n";
212 std::string work (input);
213 // Skip past any delims at head of input string.
214 size_t pos = work.find_first_not_of (delims);
215 // If the string consists entirely of delims, then exit early.
216 if (pos == std::string::npos) return;
217 // Otherwise, jump forward to beginning of first word.
218 work = work.substr (pos);
219 // Find position of first delimiter.
220 pos = work.find_first_of (delims);
222 while (!work.empty() && pos != std::string::npos) {
223 // Everything from 0 to POS is the next word to copy.
224 output.push_back (strdup (work.substr (0,pos).c_str ()));
225 // Is there another word in the string?
226 size_t nextpos = work.find_first_not_of (delims, pos + 1);
227 if (nextpos != std::string::npos) {
228 // Yes? Then remove delims from beginning ...
229 work = work.substr (work.find_first_not_of (delims, pos + 1));
230 // and find the end of the word.
231 pos = work.find_first_of (delims);
233 // No? (Remainder of string is delims.) End the loop.
235 pos = std::string::npos;
239 // If `input' ended with non-delim char, then we'll get here with
240 // the last word of `input' in `work'; copy it now.
241 if (!work.empty ()) {
242 output.push_back (strdup (work.c_str ()));
246 /// ParseEnvironmentOptions - An alternative entry point to the
247 /// CommandLine library, which allows you to read the program's name
248 /// from the caller (as PROGNAME) and its command-line arguments from
249 /// an environment variable (whose name is given in ENVVAR).
251 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
252 const char *Overview) {
254 assert(progName && "Program name not specified");
255 assert(envVar && "Environment variable name missing");
257 // Get the environment variable they want us to parse options out of.
258 const char *envValue = getenv(envVar);
262 // Get program's "name", which we wouldn't know without the caller
264 std::vector<char*> newArgv;
265 newArgv.push_back(strdup(progName));
267 // Parse the value of the environment variable into a "command line"
268 // and hand it off to ParseCommandLineOptions().
269 ParseCStringVector(newArgv, envValue);
270 int newArgc = newArgv.size();
271 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
273 // Free all the strdup()ed strings.
274 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
279 /// LookupOption - Lookup the option specified by the specified option on the
280 /// command line. If there is a value specified (after an equal sign) return
282 static Option *LookupOption(const char *&Arg, const char *&Value) {
283 while (*Arg == '-') ++Arg; // Eat leading dashes
285 const char *ArgEnd = Arg;
286 while (*ArgEnd && *ArgEnd != '=')
287 ++ArgEnd; // Scan till end of argument name.
289 if (*ArgEnd == '=') // If we have an equals sign...
290 Value = ArgEnd+1; // Get the value, not the equals
293 if (*Arg == 0) return 0;
295 // Look up the option.
296 std::map<std::string, Option*> &Opts = *Options;
297 std::map<std::string, Option*>::iterator I =
298 Opts.find(std::string(Arg, ArgEnd));
299 return (I != Opts.end()) ? I->second : 0;
302 void cl::ParseCommandLineOptions(int &argc, char **argv,
303 const char *Overview) {
304 assert((!Options->empty() || !PositionalOptions->empty()) &&
305 "No options specified, or ParseCommandLineOptions called more"
307 sys::Path progname(argv[0]);
309 // Copy the program name into ProgName, making sure not to overflow it.
310 std::string ProgName = sys::Path(argv[0]).getLast();
311 if (ProgName.size() > 79) ProgName.resize(79);
312 strcpy(ProgramName, ProgName.c_str());
314 ProgramOverview = Overview;
315 bool ErrorParsing = false;
317 std::map<std::string, Option*> &Opts = *Options;
318 std::vector<Option*> &PositionalOpts = *PositionalOptions;
320 // Check out the positional arguments to collect information about them.
321 unsigned NumPositionalRequired = 0;
323 // Determine whether or not there are an unlimited number of positionals
324 bool HasUnlimitedPositionals = false;
326 Option *ConsumeAfterOpt = 0;
327 if (!PositionalOpts.empty()) {
328 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
329 assert(PositionalOpts.size() > 1 &&
330 "Cannot specify cl::ConsumeAfter without a positional argument!");
331 ConsumeAfterOpt = PositionalOpts[0];
334 // Calculate how many positional values are _required_.
335 bool UnboundedFound = false;
336 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
338 Option *Opt = PositionalOpts[i];
339 if (RequiresValue(Opt))
340 ++NumPositionalRequired;
341 else if (ConsumeAfterOpt) {
342 // ConsumeAfter cannot be combined with "optional" positional options
343 // unless there is only one positional argument...
344 if (PositionalOpts.size() > 2)
346 Opt->error(" error - this positional option will never be matched, "
347 "because it does not Require a value, and a "
348 "cl::ConsumeAfter option is active!");
349 } else if (UnboundedFound && !Opt->ArgStr[0]) {
350 // This option does not "require" a value... Make sure this option is
351 // not specified after an option that eats all extra arguments, or this
352 // one will never get any!
354 ErrorParsing |= Opt->error(" error - option can never match, because "
355 "another positional argument will match an "
356 "unbounded number of values, and this option"
357 " does not require a value!");
359 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
361 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
364 // PositionalVals - A vector of "positional" arguments we accumulate into
365 // the process at the end...
367 std::vector<std::pair<std::string,unsigned> > PositionalVals;
369 // If the program has named positional arguments, and the name has been run
370 // across, keep track of which positional argument was named. Otherwise put
371 // the positional args into the PositionalVals list...
372 Option *ActivePositionalArg = 0;
374 // Loop over all of the arguments... processing them.
375 bool DashDashFound = false; // Have we read '--'?
376 for (int i = 1; i < argc; ++i) {
378 const char *Value = 0;
379 const char *ArgName = "";
381 // Check to see if this is a positional argument. This argument is
382 // considered to be positional if it doesn't start with '-', if it is "-"
383 // itself, or if we have seen "--" already.
385 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
386 // Positional argument!
387 if (ActivePositionalArg) {
388 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
389 continue; // We are done!
390 } else if (!PositionalOpts.empty()) {
391 PositionalVals.push_back(std::make_pair(argv[i],i));
393 // All of the positional arguments have been fulfulled, give the rest to
394 // the consume after option... if it's specified...
396 if (PositionalVals.size() >= NumPositionalRequired &&
397 ConsumeAfterOpt != 0) {
398 for (++i; i < argc; ++i)
399 PositionalVals.push_back(std::make_pair(argv[i],i));
400 break; // Handle outside of the argument processing loop...
403 // Delay processing positional arguments until the end...
406 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
408 DashDashFound = true; // This is the mythical "--"?
409 continue; // Don't try to process it as an argument itself.
410 } else if (ActivePositionalArg &&
411 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
412 // If there is a positional argument eating options, check to see if this
413 // option is another positional argument. If so, treat it as an argument,
414 // otherwise feed it to the eating positional.
416 Handler = LookupOption(ArgName, Value);
417 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
418 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
419 continue; // We are done!
422 } else { // We start with a '-', must be an argument...
424 Handler = LookupOption(ArgName, Value);
426 // Check to see if this "option" is really a prefixed or grouped argument.
428 std::string RealName(ArgName);
429 if (RealName.size() > 1) {
431 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
433 // If the option is a prefixed option, then the value is simply the
434 // rest of the name... so fall through to later processing, by
435 // setting up the argument name flags and value fields.
437 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
438 Value = ArgName+Length;
439 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
440 Opts.find(std::string(ArgName, Value))->second == PGOpt);
443 // This must be a grouped option... handle them now.
444 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
447 // Move current arg name out of RealName into RealArgName...
448 std::string RealArgName(RealName.begin(),
449 RealName.begin() + Length);
450 RealName.erase(RealName.begin(), RealName.begin() + Length);
452 // Because ValueRequired is an invalid flag for grouped arguments,
453 // we don't need to pass argc/argv in...
455 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
456 "Option can not be cl::Grouping AND cl::ValueRequired!");
458 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
461 // Get the next grouping option...
462 PGOpt = getOptionPred(RealName, Length, isGrouping);
463 } while (PGOpt && Length != RealName.size());
465 Handler = PGOpt; // Ate all of the options.
472 cerr << ProgramName << ": Unknown command line argument '"
473 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
478 // Check to see if this option accepts a comma separated list of values. If
479 // it does, we have to split up the value into multiple values...
480 if (Value && Handler->getMiscFlags() & CommaSeparated) {
481 std::string Val(Value);
482 std::string::size_type Pos = Val.find(',');
484 while (Pos != std::string::npos) {
485 // Process the portion before the comma...
486 ErrorParsing |= ProvideOption(Handler, ArgName,
487 std::string(Val.begin(),
488 Val.begin()+Pos).c_str(),
490 // Erase the portion before the comma, AND the comma...
491 Val.erase(Val.begin(), Val.begin()+Pos+1);
492 Value += Pos+1; // Increment the original value pointer as well...
494 // Check for another comma...
499 // If this is a named positional argument, just remember that it is the
501 if (Handler->getFormattingFlag() == cl::Positional)
502 ActivePositionalArg = Handler;
504 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
507 // Check and handle positional arguments now...
508 if (NumPositionalRequired > PositionalVals.size()) {
510 << ": Not enough positional command line arguments specified!\n"
511 << "Must specify at least " << NumPositionalRequired
512 << " positional arguments: See: " << argv[0] << " --help\n";
515 } else if (!HasUnlimitedPositionals
516 && PositionalVals.size() > PositionalOpts.size()) {
518 << ": Too many positional arguments specified!\n"
519 << "Can specify at most " << PositionalOpts.size()
520 << " positional arguments: See: " << argv[0] << " --help\n";
523 } else if (ConsumeAfterOpt == 0) {
524 // Positional args have already been handled if ConsumeAfter is specified...
525 unsigned ValNo = 0, NumVals = PositionalVals.size();
526 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
527 if (RequiresValue(PositionalOpts[i])) {
528 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
529 PositionalVals[ValNo].second);
531 --NumPositionalRequired; // We fulfilled our duty...
534 // If we _can_ give this option more arguments, do so now, as long as we
535 // do not give it values that others need. 'Done' controls whether the
536 // option even _WANTS_ any more.
538 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
539 while (NumVals-ValNo > NumPositionalRequired && !Done) {
540 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
542 Done = true; // Optional arguments want _at most_ one value
544 case cl::ZeroOrMore: // Zero or more will take all they can get...
545 case cl::OneOrMore: // One or more will take all they can get...
546 ProvidePositionalOption(PositionalOpts[i],
547 PositionalVals[ValNo].first,
548 PositionalVals[ValNo].second);
552 assert(0 && "Internal error, unexpected NumOccurrences flag in "
553 "positional argument processing!");
558 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
560 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
561 if (RequiresValue(PositionalOpts[j])) {
562 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
563 PositionalVals[ValNo].first,
564 PositionalVals[ValNo].second);
568 // Handle the case where there is just one positional option, and it's
569 // optional. In this case, we want to give JUST THE FIRST option to the
570 // positional option and keep the rest for the consume after. The above
571 // loop would have assigned no values to positional options in this case.
573 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
574 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
575 PositionalVals[ValNo].first,
576 PositionalVals[ValNo].second);
580 // Handle over all of the rest of the arguments to the
581 // cl::ConsumeAfter command line option...
582 for (; ValNo != PositionalVals.size(); ++ValNo)
583 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
584 PositionalVals[ValNo].first,
585 PositionalVals[ValNo].second);
588 // Loop over args and make sure all required args are specified!
589 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
590 E = Opts.end(); I != E; ++I) {
591 switch (I->second->getNumOccurrencesFlag()) {
594 if (I->second->getNumOccurrences() == 0) {
595 I->second->error(" must be specified at least once!");
604 // Free all of the memory allocated to the map. Command line options may only
605 // be processed once!
607 PositionalOpts.clear();
610 // If we had an error processing our arguments, don't let the program execute
611 if (ErrorParsing) exit(1);
614 //===----------------------------------------------------------------------===//
615 // Option Base class implementation
618 bool Option::error(std::string Message, const char *ArgName) {
619 if (ArgName == 0) ArgName = ArgStr;
621 cerr << HelpStr; // Be nice for positional arguments
623 cerr << ProgramName << ": for the -" << ArgName;
625 cerr << " option: " << Message << "\n";
629 bool Option::addOccurrence(unsigned pos, const char *ArgName,
630 const std::string &Value) {
631 NumOccurrences++; // Increment the number of times we have been seen
633 switch (getNumOccurrencesFlag()) {
635 if (NumOccurrences > 1)
636 return error(": may only occur zero or one times!", ArgName);
639 if (NumOccurrences > 1)
640 return error(": must occur exactly one time!", ArgName);
644 case ConsumeAfter: break;
645 default: return error(": bad num occurrences flag value!");
648 return handleOccurrence(pos, ArgName, Value);
651 // addArgument - Tell the system that this Option subclass will handle all
652 // occurrences of -ArgStr on the command line.
654 void Option::addArgument(const char *ArgStr) {
656 AddArgument(ArgStr, this);
658 if (getFormattingFlag() == Positional)
659 PositionalOptions->push_back(this);
660 else if (getNumOccurrencesFlag() == ConsumeAfter) {
661 if (!PositionalOptions->empty() &&
662 PositionalOptions->front()->getNumOccurrencesFlag() == ConsumeAfter)
663 error("Cannot specify more than one option with cl::ConsumeAfter!");
664 PositionalOptions->insert(PositionalOptions->begin(), this);
668 void Option::removeArgument(const char *ArgStr) {
670 RemoveArgument(ArgStr, this);
672 if (getFormattingFlag() == Positional) {
673 std::vector<Option*>::iterator I =
674 std::find(PositionalOptions->begin(), PositionalOptions->end(), this);
675 assert(I != PositionalOptions->end() && "Arg not registered!");
676 PositionalOptions->erase(I);
677 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
678 assert(!PositionalOptions->empty() && (*PositionalOptions)[0] == this &&
679 "Arg not registered correctly!");
680 PositionalOptions->erase(PositionalOptions->begin());
685 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
686 // has been specified yet.
688 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
689 if (O.ValueStr[0] == 0) return DefaultMsg;
693 //===----------------------------------------------------------------------===//
694 // cl::alias class implementation
697 // Return the width of the option tag for printing...
698 unsigned alias::getOptionWidth() const {
699 return std::strlen(ArgStr)+6;
702 // Print out the option for the alias.
703 void alias::printOptionInfo(unsigned GlobalWidth) const {
704 unsigned L = std::strlen(ArgStr);
705 cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
711 //===----------------------------------------------------------------------===//
712 // Parser Implementation code...
715 // basic_parser implementation
718 // Return the width of the option tag for printing...
719 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
720 unsigned Len = std::strlen(O.ArgStr);
721 if (const char *ValName = getValueName())
722 Len += std::strlen(getValueStr(O, ValName))+3;
727 // printOptionInfo - Print out information about this option. The
728 // to-be-maintained width is specified.
730 void basic_parser_impl::printOptionInfo(const Option &O,
731 unsigned GlobalWidth) const {
732 cout << " -" << O.ArgStr;
734 if (const char *ValName = getValueName())
735 cout << "=<" << getValueStr(O, ValName) << ">";
737 cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
738 << O.HelpStr << "\n";
744 // parser<bool> implementation
746 bool parser<bool>::parse(Option &O, const char *ArgName,
747 const std::string &Arg, bool &Value) {
748 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
751 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
754 return O.error(": '" + Arg +
755 "' is invalid value for boolean argument! Try 0 or 1");
760 // parser<int> implementation
762 bool parser<int>::parse(Option &O, const char *ArgName,
763 const std::string &Arg, int &Value) {
765 Value = (int)strtol(Arg.c_str(), &End, 0);
767 return O.error(": '" + Arg + "' value invalid for integer argument!");
771 // parser<unsigned> implementation
773 bool parser<unsigned>::parse(Option &O, const char *ArgName,
774 const std::string &Arg, unsigned &Value) {
777 unsigned long V = strtoul(Arg.c_str(), &End, 0);
779 if (((V == ULONG_MAX) && (errno == ERANGE))
782 return O.error(": '" + Arg + "' value invalid for uint argument!");
786 // parser<double>/parser<float> implementation
788 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
789 const char *ArgStart = Arg.c_str();
791 Value = strtod(ArgStart, &End);
793 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
797 bool parser<double>::parse(Option &O, const char *AN,
798 const std::string &Arg, double &Val) {
799 return parseDouble(O, Arg, Val);
802 bool parser<float>::parse(Option &O, const char *AN,
803 const std::string &Arg, float &Val) {
805 if (parseDouble(O, Arg, dVal))
813 // generic_parser_base implementation
816 // findOption - Return the option number corresponding to the specified
817 // argument string. If the option is not found, getNumOptions() is returned.
819 unsigned generic_parser_base::findOption(const char *Name) {
820 unsigned i = 0, e = getNumOptions();
824 if (getOption(i) == N)
832 // Return the width of the option tag for printing...
833 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
835 unsigned Size = std::strlen(O.ArgStr)+6;
836 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
837 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
840 unsigned BaseSize = 0;
841 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
842 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
847 // printOptionInfo - Print out information about this option. The
848 // to-be-maintained width is specified.
850 void generic_parser_base::printOptionInfo(const Option &O,
851 unsigned GlobalWidth) const {
853 unsigned L = std::strlen(O.ArgStr);
854 cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
855 << " - " << O.HelpStr << "\n";
857 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
858 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
859 cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
860 << " - " << getDescription(i) << "\n";
864 cout << " " << O.HelpStr << "\n";
865 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
866 unsigned L = std::strlen(getOption(i));
867 cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
868 << " - " << getDescription(i) << "\n";
874 //===----------------------------------------------------------------------===//
875 // --help and --help-hidden option implementation
882 const Option *EmptyArg;
883 const bool ShowHidden;
885 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
886 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
887 return OptPair.second->getOptionHiddenFlag() >= Hidden;
889 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
890 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
894 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
898 void operator=(bool Value) {
899 if (Value == false) return;
901 // Copy Options into a vector so we can sort them as we like...
902 std::vector<std::pair<std::string, Option*> > Opts;
903 copy(Options->begin(), Options->end(), std::back_inserter(Opts));
905 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
906 Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
907 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
910 // Eliminate duplicate entries in table (from enum flags options, f.e.)
911 { // Give OptionSet a scope
912 std::set<Option*> OptionSet;
913 for (unsigned i = 0; i != Opts.size(); ++i)
914 if (OptionSet.count(Opts[i].second) == 0)
915 OptionSet.insert(Opts[i].second); // Add new entry to set
917 Opts.erase(Opts.begin()+i--); // Erase duplicate
921 cout << "OVERVIEW:" << ProgramOverview << "\n";
923 cout << "USAGE: " << ProgramName << " [options]";
925 // Print out the positional options.
926 std::vector<Option*> &PosOpts = *PositionalOptions;
927 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
928 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
931 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
932 if (PosOpts[i]->ArgStr[0])
933 cout << " --" << PosOpts[i]->ArgStr;
934 cout << " " << PosOpts[i]->HelpStr;
937 // Print the consume after option info if it exists...
938 if (CAOpt) cout << " " << CAOpt->HelpStr;
942 // Compute the maximum argument length...
944 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
945 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
947 cout << "OPTIONS:\n";
948 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
949 Opts[i].second->printOptionInfo(MaxArgLen);
951 // Print any extra help the user has declared.
952 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
953 E = MoreHelp->end(); I != E; ++I)
957 // Halt the program since help information was printed
958 Options->clear(); // Don't bother making option dtors remove from map.
962 } // End anonymous namespace
964 // Define the two HelpPrinter instances that are used to print out help, or
967 static HelpPrinter NormalPrinter(false);
968 static HelpPrinter HiddenPrinter(true);
970 static cl::opt<HelpPrinter, true, parser<bool> >
971 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
972 cl::location(NormalPrinter), cl::ValueDisallowed);
974 static cl::opt<HelpPrinter, true, parser<bool> >
975 HHOp("help-hidden", cl::desc("Display all available options"),
976 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
978 static void (*OverrideVersionPrinter)() = 0;
981 class VersionPrinter {
983 void operator=(bool OptionWasSpecified) {
984 if (OptionWasSpecified) {
985 if (OverrideVersionPrinter == 0) {
986 cout << "Low Level Virtual Machine (http://llvm.org/):\n";
987 cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
988 #ifdef LLVM_VERSION_INFO
989 cout << LLVM_VERSION_INFO;
993 cout << "DEBUG build";
995 cout << "Optimized build";
998 cout << " with assertions";
1001 Options->clear(); // Don't bother making option dtors remove from map.
1004 (*OverrideVersionPrinter)();
1010 } // End anonymous namespace
1013 // Define the --version option that prints out the LLVM version for the tool
1014 static VersionPrinter VersionPrinterInstance;
1016 static cl::opt<VersionPrinter, true, parser<bool> >
1017 VersOp("version", cl::desc("Display the version of this program"),
1018 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1020 // Utility function for printing the help message.
1021 void cl::PrintHelpMessage() {
1022 // This looks weird, but it actually prints the help message. The
1023 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1024 // its operator= is invoked. That's because the "normal" usages of the
1025 // help printer is to be assigned true/false depending on whether the
1026 // --help option was given or not. Since we're circumventing that we have
1027 // to make it look like --help was given, so we assign true.
1028 NormalPrinter = true;
1031 void cl::SetVersionPrinter(void (*func)()) {
1032 OverrideVersionPrinter = func;