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/System/Path.h"
33 //===----------------------------------------------------------------------===//
34 // Template instantiations and anchors.
36 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
37 TEMPLATE_INSTANTIATION(class basic_parser<int>);
38 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
39 TEMPLATE_INSTANTIATION(class basic_parser<double>);
40 TEMPLATE_INSTANTIATION(class basic_parser<float>);
41 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
43 TEMPLATE_INSTANTIATION(class opt<unsigned>);
44 TEMPLATE_INSTANTIATION(class opt<int>);
45 TEMPLATE_INSTANTIATION(class opt<std::string>);
46 TEMPLATE_INSTANTIATION(class opt<bool>);
48 void Option::anchor() {}
49 void basic_parser_impl::anchor() {}
50 void parser<bool>::anchor() {}
51 void parser<int>::anchor() {}
52 void parser<unsigned>::anchor() {}
53 void parser<double>::anchor() {}
54 void parser<float>::anchor() {}
55 void parser<std::string>::anchor() {}
57 //===----------------------------------------------------------------------===//
59 // Globals for name and overview of program
60 static std::string ProgramName = "<premain>";
61 static const char *ProgramOverview = 0;
63 // This collects additional help to be printed.
64 static std::vector<const char*> &MoreHelp() {
65 static 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 // Return the global command line option vector. Making it a function scoped
79 // static ensures that it will be initialized correctly before its first use.
81 static std::map<std::string, Option*> &getOpts() {
82 static std::map<std::string, Option*> CommandLineOptions;
83 return CommandLineOptions;
86 static Option *getOption(const std::string &Str) {
87 std::map<std::string,Option*>::iterator I = getOpts().find(Str);
88 return I != getOpts().end() ? I->second : 0;
91 static std::vector<Option*> &getPositionalOpts() {
92 static std::vector<Option*> Positional;
96 static void AddArgument(const char *ArgName, Option *Opt) {
97 if (getOption(ArgName)) {
98 std::cerr << ProgramName << ": CommandLine Error: Argument '"
99 << ArgName << "' defined more than once!\n";
101 // Add argument to the argument map!
102 getOpts()[ArgName] = Opt;
106 // RemoveArgument - It's possible that the argument is no longer in the map if
107 // options have already been processed and the map has been deleted!
109 static void RemoveArgument(const char *ArgName, Option *Opt) {
110 if(getOpts().empty()) return;
113 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
114 // If we pass ArgName directly into getOption here.
115 std::string Tmp = ArgName;
116 assert(getOption(Tmp) == Opt && "Arg not in map!");
118 getOpts().erase(ArgName);
121 static inline bool ProvideOption(Option *Handler, const char *ArgName,
122 const char *Value, int argc, char **argv,
124 // Enforce value requirements
125 switch (Handler->getValueExpectedFlag()) {
127 if (Value == 0) { // No value specified?
128 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
131 return Handler->error(" requires a value!");
135 case ValueDisallowed:
137 return Handler->error(" does not allow a value! '" +
138 std::string(Value) + "' specified.");
143 std::cerr << ProgramName
144 << ": Bad ValueMask flag! CommandLine usage error:"
145 << Handler->getValueExpectedFlag() << "\n";
150 // Run the handler now!
151 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
154 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
157 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
161 // Option predicates...
162 static inline bool isGrouping(const Option *O) {
163 return O->getFormattingFlag() == cl::Grouping;
165 static inline bool isPrefixedOrGrouping(const Option *O) {
166 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
169 // getOptionPred - Check to see if there are any options that satisfy the
170 // specified predicate with names that are the prefixes in Name. This is
171 // checked by progressively stripping characters off of the name, checking to
172 // see if there options that satisfy the predicate. If we find one, return it,
173 // otherwise return null.
175 static Option *getOptionPred(std::string Name, unsigned &Length,
176 bool (*Pred)(const Option*)) {
178 Option *Op = getOption(Name);
179 if (Op && Pred(Op)) {
180 Length = Name.length();
184 if (Name.size() == 1) return 0;
186 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
187 Op = getOption(Name);
189 // Loop while we haven't found an option and Name still has at least two
190 // characters in it (so that the next iteration will not be the empty
192 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
194 if (Op && Pred(Op)) {
195 Length = Name.length();
196 return Op; // Found one!
198 return 0; // No option found!
201 static bool RequiresValue(const Option *O) {
202 return O->getNumOccurrencesFlag() == cl::Required ||
203 O->getNumOccurrencesFlag() == cl::OneOrMore;
206 static bool EatsUnboundedNumberOfValues(const Option *O) {
207 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
208 O->getNumOccurrencesFlag() == cl::OneOrMore;
211 /// ParseCStringVector - Break INPUT up wherever one or more
212 /// whitespace characters are found, and store the resulting tokens in
213 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
214 /// using strdup (), so it is the caller's responsibility to free ()
217 static void ParseCStringVector (std::vector<char *> &output,
219 // Characters which will be treated as token separators:
220 static const char *delims = " \v\f\t\r\n";
222 std::string work (input);
223 // Skip past any delims at head of input string.
224 size_t pos = work.find_first_not_of (delims);
225 // If the string consists entirely of delims, then exit early.
226 if (pos == std::string::npos) return;
227 // Otherwise, jump forward to beginning of first word.
228 work = work.substr (pos);
229 // Find position of first delimiter.
230 pos = work.find_first_of (delims);
232 while (!work.empty() && pos != std::string::npos) {
233 // Everything from 0 to POS is the next word to copy.
234 output.push_back (strdup (work.substr (0,pos).c_str ()));
235 // Is there another word in the string?
236 size_t nextpos = work.find_first_not_of (delims, pos + 1);
237 if (nextpos != std::string::npos) {
238 // Yes? Then remove delims from beginning ...
239 work = work.substr (work.find_first_not_of (delims, pos + 1));
240 // and find the end of the word.
241 pos = work.find_first_of (delims);
243 // No? (Remainder of string is delims.) End the loop.
245 pos = std::string::npos;
249 // If `input' ended with non-delim char, then we'll get here with
250 // the last word of `input' in `work'; copy it now.
251 if (!work.empty ()) {
252 output.push_back (strdup (work.c_str ()));
256 /// ParseEnvironmentOptions - An alternative entry point to the
257 /// CommandLine library, which allows you to read the program's name
258 /// from the caller (as PROGNAME) and its command-line arguments from
259 /// an environment variable (whose name is given in ENVVAR).
261 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
262 const char *Overview) {
264 assert(progName && "Program name not specified");
265 assert(envVar && "Environment variable name missing");
267 // Get the environment variable they want us to parse options out of.
268 const char *envValue = getenv (envVar);
272 // Get program's "name", which we wouldn't know without the caller
274 std::vector<char *> newArgv;
275 newArgv.push_back (strdup (progName));
277 // Parse the value of the environment variable into a "command line"
278 // and hand it off to ParseCommandLineOptions().
279 ParseCStringVector (newArgv, envValue);
280 int newArgc = newArgv.size ();
281 ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
283 // Free all the strdup()ed strings.
284 for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
290 /// LookupOption - Lookup the option specified by the specified option on the
291 /// command line. If there is a value specified (after an equal sign) return
293 static Option *LookupOption(const char *&Arg, const char *&Value) {
294 while (*Arg == '-') ++Arg; // Eat leading dashes
296 const char *ArgEnd = Arg;
297 while (*ArgEnd && *ArgEnd != '=')
298 ++ArgEnd; // Scan till end of argument name.
300 if (*ArgEnd == '=') // If we have an equals sign...
301 Value = ArgEnd+1; // Get the value, not the equals
304 if (*Arg == 0) return 0;
306 // Look up the option.
307 std::map<std::string, Option*> &Opts = getOpts();
308 std::map<std::string, Option*>::iterator I =
309 Opts.find(std::string(Arg, ArgEnd));
310 return (I != Opts.end()) ? I->second : 0;
313 void cl::ParseCommandLineOptions(int &argc, char **argv,
314 const char *Overview) {
315 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
316 "No options specified, or ParseCommandLineOptions called more"
318 sys::Path progname(argv[0]);
319 ProgramName = sys::Path(argv[0]).getLast();
320 ProgramOverview = Overview;
321 bool ErrorParsing = false;
323 std::map<std::string, Option*> &Opts = getOpts();
324 std::vector<Option*> &PositionalOpts = getPositionalOpts();
326 // Check out the positional arguments to collect information about them.
327 unsigned NumPositionalRequired = 0;
329 // Determine whether or not there are an unlimited number of positionals
330 bool HasUnlimitedPositionals = false;
332 Option *ConsumeAfterOpt = 0;
333 if (!PositionalOpts.empty()) {
334 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
335 assert(PositionalOpts.size() > 1 &&
336 "Cannot specify cl::ConsumeAfter without a positional argument!");
337 ConsumeAfterOpt = PositionalOpts[0];
340 // Calculate how many positional values are _required_.
341 bool UnboundedFound = false;
342 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
344 Option *Opt = PositionalOpts[i];
345 if (RequiresValue(Opt))
346 ++NumPositionalRequired;
347 else if (ConsumeAfterOpt) {
348 // ConsumeAfter cannot be combined with "optional" positional options
349 // unless there is only one positional argument...
350 if (PositionalOpts.size() > 2)
352 Opt->error(" error - this positional option will never be matched, "
353 "because it does not Require a value, and a "
354 "cl::ConsumeAfter option is active!");
355 } else if (UnboundedFound && !Opt->ArgStr[0]) {
356 // This option does not "require" a value... Make sure this option is
357 // not specified after an option that eats all extra arguments, or this
358 // one will never get any!
360 ErrorParsing |= Opt->error(" error - option can never match, because "
361 "another positional argument will match an "
362 "unbounded number of values, and this option"
363 " does not require a value!");
365 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
367 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
370 // PositionalVals - A vector of "positional" arguments we accumulate into
371 // the process at the end...
373 std::vector<std::pair<std::string,unsigned> > PositionalVals;
375 // If the program has named positional arguments, and the name has been run
376 // across, keep track of which positional argument was named. Otherwise put
377 // the positional args into the PositionalVals list...
378 Option *ActivePositionalArg = 0;
380 // Loop over all of the arguments... processing them.
381 bool DashDashFound = false; // Have we read '--'?
382 for (int i = 1; i < argc; ++i) {
384 const char *Value = 0;
385 const char *ArgName = "";
387 // Check to see if this is a positional argument. This argument is
388 // considered to be positional if it doesn't start with '-', if it is "-"
389 // itself, or if we have seen "--" already.
391 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
392 // Positional argument!
393 if (ActivePositionalArg) {
394 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
395 continue; // We are done!
396 } else if (!PositionalOpts.empty()) {
397 PositionalVals.push_back(std::make_pair(argv[i],i));
399 // All of the positional arguments have been fulfulled, give the rest to
400 // the consume after option... if it's specified...
402 if (PositionalVals.size() >= NumPositionalRequired &&
403 ConsumeAfterOpt != 0) {
404 for (++i; i < argc; ++i)
405 PositionalVals.push_back(std::make_pair(argv[i],i));
406 break; // Handle outside of the argument processing loop...
409 // Delay processing positional arguments until the end...
412 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
414 DashDashFound = true; // This is the mythical "--"?
415 continue; // Don't try to process it as an argument itself.
416 } else if (ActivePositionalArg &&
417 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
418 // If there is a positional argument eating options, check to see if this
419 // option is another positional argument. If so, treat it as an argument,
420 // otherwise feed it to the eating positional.
422 Handler = LookupOption(ArgName, Value);
423 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
424 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
425 continue; // We are done!
428 } else { // We start with a '-', must be an argument...
430 Handler = LookupOption(ArgName, Value);
432 // Check to see if this "option" is really a prefixed or grouped argument.
434 std::string RealName(ArgName);
435 if (RealName.size() > 1) {
437 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
439 // If the option is a prefixed option, then the value is simply the
440 // rest of the name... so fall through to later processing, by
441 // setting up the argument name flags and value fields.
443 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
444 Value = ArgName+Length;
445 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
446 Opts.find(std::string(ArgName, Value))->second == PGOpt);
449 // This must be a grouped option... handle them now.
450 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
453 // Move current arg name out of RealName into RealArgName...
454 std::string RealArgName(RealName.begin(),
455 RealName.begin() + Length);
456 RealName.erase(RealName.begin(), RealName.begin() + Length);
458 // Because ValueRequired is an invalid flag for grouped arguments,
459 // we don't need to pass argc/argv in...
461 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
462 "Option can not be cl::Grouping AND cl::ValueRequired!");
464 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
467 // Get the next grouping option...
468 PGOpt = getOptionPred(RealName, Length, isGrouping);
469 } while (PGOpt && Length != RealName.size());
471 Handler = PGOpt; // Ate all of the options.
478 std::cerr << ProgramName << ": Unknown command line argument '"
479 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
484 // Check to see if this option accepts a comma separated list of values. If
485 // it does, we have to split up the value into multiple values...
486 if (Value && Handler->getMiscFlags() & CommaSeparated) {
487 std::string Val(Value);
488 std::string::size_type Pos = Val.find(',');
490 while (Pos != std::string::npos) {
491 // Process the portion before the comma...
492 ErrorParsing |= ProvideOption(Handler, ArgName,
493 std::string(Val.begin(),
494 Val.begin()+Pos).c_str(),
496 // Erase the portion before the comma, AND the comma...
497 Val.erase(Val.begin(), Val.begin()+Pos+1);
498 Value += Pos+1; // Increment the original value pointer as well...
500 // Check for another comma...
505 // If this is a named positional argument, just remember that it is the
507 if (Handler->getFormattingFlag() == cl::Positional)
508 ActivePositionalArg = Handler;
510 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
513 // Check and handle positional arguments now...
514 if (NumPositionalRequired > PositionalVals.size()) {
515 std::cerr << ProgramName
516 << ": Not enough positional command line arguments specified!\n"
517 << "Must specify at least " << NumPositionalRequired
518 << " positional arguments: See: " << argv[0] << " --help\n";
521 } else if (!HasUnlimitedPositionals
522 && PositionalVals.size() > PositionalOpts.size()) {
523 std::cerr << ProgramName
524 << ": Too many positional arguments specified!\n"
525 << "Can specify at most " << PositionalOpts.size()
526 << " positional arguments: See: " << argv[0] << " --help\n";
529 } else if (ConsumeAfterOpt == 0) {
530 // Positional args have already been handled if ConsumeAfter is specified...
531 unsigned ValNo = 0, NumVals = PositionalVals.size();
532 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
533 if (RequiresValue(PositionalOpts[i])) {
534 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
535 PositionalVals[ValNo].second);
537 --NumPositionalRequired; // We fulfilled our duty...
540 // If we _can_ give this option more arguments, do so now, as long as we
541 // do not give it values that others need. 'Done' controls whether the
542 // option even _WANTS_ any more.
544 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
545 while (NumVals-ValNo > NumPositionalRequired && !Done) {
546 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
548 Done = true; // Optional arguments want _at most_ one value
550 case cl::ZeroOrMore: // Zero or more will take all they can get...
551 case cl::OneOrMore: // One or more will take all they can get...
552 ProvidePositionalOption(PositionalOpts[i],
553 PositionalVals[ValNo].first,
554 PositionalVals[ValNo].second);
558 assert(0 && "Internal error, unexpected NumOccurrences flag in "
559 "positional argument processing!");
564 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
566 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
567 if (RequiresValue(PositionalOpts[j])) {
568 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
569 PositionalVals[ValNo].first,
570 PositionalVals[ValNo].second);
574 // Handle the case where there is just one positional option, and it's
575 // optional. In this case, we want to give JUST THE FIRST option to the
576 // positional option and keep the rest for the consume after. The above
577 // loop would have assigned no values to positional options in this case.
579 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
580 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
581 PositionalVals[ValNo].first,
582 PositionalVals[ValNo].second);
586 // Handle over all of the rest of the arguments to the
587 // cl::ConsumeAfter command line option...
588 for (; ValNo != PositionalVals.size(); ++ValNo)
589 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
590 PositionalVals[ValNo].first,
591 PositionalVals[ValNo].second);
594 // Loop over args and make sure all required args are specified!
595 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
596 E = Opts.end(); I != E; ++I) {
597 switch (I->second->getNumOccurrencesFlag()) {
600 if (I->second->getNumOccurrences() == 0) {
601 I->second->error(" must be specified at least once!");
610 // Free all of the memory allocated to the map. Command line options may only
611 // be processed once!
613 PositionalOpts.clear();
616 // If we had an error processing our arguments, don't let the program execute
617 if (ErrorParsing) exit(1);
620 //===----------------------------------------------------------------------===//
621 // Option Base class implementation
624 bool Option::error(std::string Message, const char *ArgName) {
625 if (ArgName == 0) ArgName = ArgStr;
627 std::cerr << HelpStr; // Be nice for positional arguments
629 std::cerr << ProgramName << ": for the -" << ArgName;
631 std::cerr << " option: " << Message << "\n";
635 bool Option::addOccurrence(unsigned pos, const char *ArgName,
636 const std::string &Value) {
637 NumOccurrences++; // Increment the number of times we have been seen
639 switch (getNumOccurrencesFlag()) {
641 if (NumOccurrences > 1)
642 return error(": may only occur zero or one times!", ArgName);
645 if (NumOccurrences > 1)
646 return error(": must occur exactly one time!", ArgName);
650 case ConsumeAfter: break;
651 default: return error(": bad num occurrences flag value!");
654 return handleOccurrence(pos, ArgName, Value);
657 // addArgument - Tell the system that this Option subclass will handle all
658 // occurrences of -ArgStr on the command line.
660 void Option::addArgument(const char *ArgStr) {
662 AddArgument(ArgStr, this);
664 if (getFormattingFlag() == Positional)
665 getPositionalOpts().push_back(this);
666 else if (getNumOccurrencesFlag() == ConsumeAfter) {
667 if (!getPositionalOpts().empty() &&
668 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
669 error("Cannot specify more than one option with cl::ConsumeAfter!");
670 getPositionalOpts().insert(getPositionalOpts().begin(), this);
674 void Option::removeArgument(const char *ArgStr) {
676 RemoveArgument(ArgStr, this);
678 if (getFormattingFlag() == Positional) {
679 std::vector<Option*>::iterator I =
680 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
681 assert(I != getPositionalOpts().end() && "Arg not registered!");
682 getPositionalOpts().erase(I);
683 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
684 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
685 "Arg not registered correctly!");
686 getPositionalOpts().erase(getPositionalOpts().begin());
691 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
692 // has been specified yet.
694 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
695 if (O.ValueStr[0] == 0) return DefaultMsg;
699 //===----------------------------------------------------------------------===//
700 // cl::alias class implementation
703 // Return the width of the option tag for printing...
704 unsigned alias::getOptionWidth() const {
705 return std::strlen(ArgStr)+6;
708 // Print out the option for the alias.
709 void alias::printOptionInfo(unsigned GlobalWidth) const {
710 unsigned L = std::strlen(ArgStr);
711 std::cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
717 //===----------------------------------------------------------------------===//
718 // Parser Implementation code...
721 // basic_parser implementation
724 // Return the width of the option tag for printing...
725 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
726 unsigned Len = std::strlen(O.ArgStr);
727 if (const char *ValName = getValueName())
728 Len += std::strlen(getValueStr(O, ValName))+3;
733 // printOptionInfo - Print out information about this option. The
734 // to-be-maintained width is specified.
736 void basic_parser_impl::printOptionInfo(const Option &O,
737 unsigned GlobalWidth) const {
738 std::cout << " -" << O.ArgStr;
740 if (const char *ValName = getValueName())
741 std::cout << "=<" << getValueStr(O, ValName) << ">";
743 std::cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
744 << O.HelpStr << "\n";
750 // parser<bool> implementation
752 bool parser<bool>::parse(Option &O, const char *ArgName,
753 const std::string &Arg, bool &Value) {
754 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
757 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
760 return O.error(": '" + Arg +
761 "' is invalid value for boolean argument! Try 0 or 1");
766 // parser<int> implementation
768 bool parser<int>::parse(Option &O, const char *ArgName,
769 const std::string &Arg, int &Value) {
771 Value = (int)strtol(Arg.c_str(), &End, 0);
773 return O.error(": '" + Arg + "' value invalid for integer argument!");
777 // parser<unsigned> implementation
779 bool parser<unsigned>::parse(Option &O, const char *ArgName,
780 const std::string &Arg, unsigned &Value) {
783 unsigned long V = strtoul(Arg.c_str(), &End, 0);
785 if (((V == ULONG_MAX) && (errno == ERANGE))
788 return O.error(": '" + Arg + "' value invalid for uint argument!");
792 // parser<double>/parser<float> implementation
794 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
795 const char *ArgStart = Arg.c_str();
797 Value = strtod(ArgStart, &End);
799 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
803 bool parser<double>::parse(Option &O, const char *AN,
804 const std::string &Arg, double &Val) {
805 return parseDouble(O, Arg, Val);
808 bool parser<float>::parse(Option &O, const char *AN,
809 const std::string &Arg, float &Val) {
811 if (parseDouble(O, Arg, dVal))
819 // generic_parser_base implementation
822 // findOption - Return the option number corresponding to the specified
823 // argument string. If the option is not found, getNumOptions() is returned.
825 unsigned generic_parser_base::findOption(const char *Name) {
826 unsigned i = 0, e = getNumOptions();
830 if (getOption(i) == N)
838 // Return the width of the option tag for printing...
839 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
841 unsigned Size = std::strlen(O.ArgStr)+6;
842 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
843 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
846 unsigned BaseSize = 0;
847 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
848 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
853 // printOptionInfo - Print out information about this option. The
854 // to-be-maintained width is specified.
856 void generic_parser_base::printOptionInfo(const Option &O,
857 unsigned GlobalWidth) const {
859 unsigned L = std::strlen(O.ArgStr);
860 std::cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
861 << " - " << O.HelpStr << "\n";
863 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
864 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
865 std::cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
866 << " - " << getDescription(i) << "\n";
870 std::cout << " " << O.HelpStr << "\n";
871 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
872 unsigned L = std::strlen(getOption(i));
873 std::cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
874 << " - " << getDescription(i) << "\n";
880 //===----------------------------------------------------------------------===//
881 // --help and --help-hidden option implementation
888 const Option *EmptyArg;
889 const bool ShowHidden;
891 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
892 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
893 return OptPair.second->getOptionHiddenFlag() >= Hidden;
895 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
896 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
900 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
904 void operator=(bool Value) {
905 if (Value == false) return;
907 // Copy Options into a vector so we can sort them as we like...
908 std::vector<std::pair<std::string, Option*> > Options;
909 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
911 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
912 Options.erase(std::remove_if(Options.begin(), Options.end(),
913 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
916 // Eliminate duplicate entries in table (from enum flags options, f.e.)
917 { // Give OptionSet a scope
918 std::set<Option*> OptionSet;
919 for (unsigned i = 0; i != Options.size(); ++i)
920 if (OptionSet.count(Options[i].second) == 0)
921 OptionSet.insert(Options[i].second); // Add new entry to set
923 Options.erase(Options.begin()+i--); // Erase duplicate
927 std::cout << "OVERVIEW:" << ProgramOverview << "\n";
929 std::cout << "USAGE: " << ProgramName << " [options]";
931 // Print out the positional options...
932 std::vector<Option*> &PosOpts = getPositionalOpts();
933 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
934 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
937 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
938 if (PosOpts[i]->ArgStr[0])
939 std::cout << " --" << PosOpts[i]->ArgStr;
940 std::cout << " " << PosOpts[i]->HelpStr;
943 // Print the consume after option info if it exists...
944 if (CAOpt) std::cout << " " << CAOpt->HelpStr;
948 // Compute the maximum argument length...
950 for (unsigned i = 0, e = Options.size(); i != e; ++i)
951 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
953 std::cout << "OPTIONS:\n";
954 for (unsigned i = 0, e = Options.size(); i != e; ++i)
955 Options[i].second->printOptionInfo(MaxArgLen);
957 // Print any extra help the user has declared.
958 for (std::vector<const char *>::iterator I = MoreHelp().begin(),
959 E = MoreHelp().end(); I != E; ++I)
963 // Halt the program since help information was printed
964 getOpts().clear(); // Don't bother making option dtors remove from map.
969 // Define the two HelpPrinter instances that are used to print out help, or
972 HelpPrinter NormalPrinter(false);
973 HelpPrinter HiddenPrinter(true);
975 cl::opt<HelpPrinter, true, parser<bool> >
976 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
977 cl::location(NormalPrinter), cl::ValueDisallowed);
979 cl::opt<HelpPrinter, true, parser<bool> >
980 HHOp("help-hidden", cl::desc("Display all available options"),
981 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
983 void (*OverrideVersionPrinter)() = 0;
985 class VersionPrinter {
987 void operator=(bool OptionWasSpecified) {
988 if (OptionWasSpecified) {
989 if (OverrideVersionPrinter == 0) {
990 std::cout << "Low Level Virtual Machine (http://llvm.org/):\n";
991 std::cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
992 #ifdef LLVM_VERSION_INFO
993 std::cout << LLVM_VERSION_INFO;
997 std::cout << "DEBUG build";
999 std::cout << "Optimized build";
1002 std::cout << " with assertions";
1005 getOpts().clear(); // Don't bother making option dtors remove from map.
1008 (*OverrideVersionPrinter)();
1016 // Define the --version option that prints out the LLVM version for the tool
1017 VersionPrinter VersionPrinterInstance;
1018 cl::opt<VersionPrinter, true, parser<bool> >
1019 VersOp("version", cl::desc("Display the version of this program"),
1020 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1023 } // End anonymous namespace
1025 // Utility function for printing the help message.
1026 void cl::PrintHelpMessage() {
1027 // This looks weird, but it actually prints the help message. The
1028 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1029 // its operator= is invoked. That's because the "normal" usages of the
1030 // help printer is to be assigned true/false depending on whether the
1031 // --help option was given or not. Since we're circumventing that we have
1032 // to make it look like --help was given, so we assign true.
1033 NormalPrinter = true;
1036 void cl::SetVersionPrinter(void (*func)()) {
1037 OverrideVersionPrinter = func;