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();
289 /// LookupOption - Lookup the option specified by the specified option on the
290 /// command line. If there is a value specified (after an equal sign) return
292 static Option *LookupOption(const char *&Arg, const char *&Value) {
293 while (*Arg == '-') ++Arg; // Eat leading dashes
295 const char *ArgEnd = Arg;
296 while (*ArgEnd && *ArgEnd != '=')
297 ++ArgEnd; // Scan till end of argument name.
299 if (*ArgEnd == '=') // If we have an equals sign...
300 Value = ArgEnd+1; // Get the value, not the equals
303 if (*Arg == 0) return 0;
305 // Look up the option.
306 std::map<std::string, Option*> &Opts = getOpts();
307 std::map<std::string, Option*>::iterator I =
308 Opts.find(std::string(Arg, ArgEnd));
309 return (I != Opts.end()) ? I->second : 0;
312 void cl::ParseCommandLineOptions(int &argc, char **argv,
313 const char *Overview) {
314 assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
315 "No options specified, or ParseCommandLineOptions called more"
317 sys::Path progname(argv[0]);
318 ProgramName = sys::Path(argv[0]).getLast();
319 ProgramOverview = Overview;
320 bool ErrorParsing = false;
322 std::map<std::string, Option*> &Opts = getOpts();
323 std::vector<Option*> &PositionalOpts = getPositionalOpts();
325 // Check out the positional arguments to collect information about them.
326 unsigned NumPositionalRequired = 0;
328 // Determine whether or not there are an unlimited number of positionals
329 bool HasUnlimitedPositionals = false;
331 Option *ConsumeAfterOpt = 0;
332 if (!PositionalOpts.empty()) {
333 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
334 assert(PositionalOpts.size() > 1 &&
335 "Cannot specify cl::ConsumeAfter without a positional argument!");
336 ConsumeAfterOpt = PositionalOpts[0];
339 // Calculate how many positional values are _required_.
340 bool UnboundedFound = false;
341 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
343 Option *Opt = PositionalOpts[i];
344 if (RequiresValue(Opt))
345 ++NumPositionalRequired;
346 else if (ConsumeAfterOpt) {
347 // ConsumeAfter cannot be combined with "optional" positional options
348 // unless there is only one positional argument...
349 if (PositionalOpts.size() > 2)
351 Opt->error(" error - this positional option will never be matched, "
352 "because it does not Require a value, and a "
353 "cl::ConsumeAfter option is active!");
354 } else if (UnboundedFound && !Opt->ArgStr[0]) {
355 // This option does not "require" a value... Make sure this option is
356 // not specified after an option that eats all extra arguments, or this
357 // one will never get any!
359 ErrorParsing |= Opt->error(" error - option can never match, because "
360 "another positional argument will match an "
361 "unbounded number of values, and this option"
362 " does not require a value!");
364 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
366 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
369 // PositionalVals - A vector of "positional" arguments we accumulate into
370 // the process at the end...
372 std::vector<std::pair<std::string,unsigned> > PositionalVals;
374 // If the program has named positional arguments, and the name has been run
375 // across, keep track of which positional argument was named. Otherwise put
376 // the positional args into the PositionalVals list...
377 Option *ActivePositionalArg = 0;
379 // Loop over all of the arguments... processing them.
380 bool DashDashFound = false; // Have we read '--'?
381 for (int i = 1; i < argc; ++i) {
383 const char *Value = 0;
384 const char *ArgName = "";
386 // Check to see if this is a positional argument. This argument is
387 // considered to be positional if it doesn't start with '-', if it is "-"
388 // itself, or if we have seen "--" already.
390 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
391 // Positional argument!
392 if (ActivePositionalArg) {
393 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
394 continue; // We are done!
395 } else if (!PositionalOpts.empty()) {
396 PositionalVals.push_back(std::make_pair(argv[i],i));
398 // All of the positional arguments have been fulfulled, give the rest to
399 // the consume after option... if it's specified...
401 if (PositionalVals.size() >= NumPositionalRequired &&
402 ConsumeAfterOpt != 0) {
403 for (++i; i < argc; ++i)
404 PositionalVals.push_back(std::make_pair(argv[i],i));
405 break; // Handle outside of the argument processing loop...
408 // Delay processing positional arguments until the end...
411 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
413 DashDashFound = true; // This is the mythical "--"?
414 continue; // Don't try to process it as an argument itself.
415 } else if (ActivePositionalArg &&
416 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
417 // If there is a positional argument eating options, check to see if this
418 // option is another positional argument. If so, treat it as an argument,
419 // otherwise feed it to the eating positional.
421 Handler = LookupOption(ArgName, Value);
422 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
423 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
424 continue; // We are done!
427 } else { // We start with a '-', must be an argument...
429 Handler = LookupOption(ArgName, Value);
431 // Check to see if this "option" is really a prefixed or grouped argument.
433 std::string RealName(ArgName);
434 if (RealName.size() > 1) {
436 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
438 // If the option is a prefixed option, then the value is simply the
439 // rest of the name... so fall through to later processing, by
440 // setting up the argument name flags and value fields.
442 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
443 Value = ArgName+Length;
444 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
445 Opts.find(std::string(ArgName, Value))->second == PGOpt);
448 // This must be a grouped option... handle them now.
449 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
452 // Move current arg name out of RealName into RealArgName...
453 std::string RealArgName(RealName.begin(),
454 RealName.begin() + Length);
455 RealName.erase(RealName.begin(), RealName.begin() + Length);
457 // Because ValueRequired is an invalid flag for grouped arguments,
458 // we don't need to pass argc/argv in...
460 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
461 "Option can not be cl::Grouping AND cl::ValueRequired!");
463 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
466 // Get the next grouping option...
467 PGOpt = getOptionPred(RealName, Length, isGrouping);
468 } while (PGOpt && Length != RealName.size());
470 Handler = PGOpt; // Ate all of the options.
477 std::cerr << ProgramName << ": Unknown command line argument '"
478 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
483 // Check to see if this option accepts a comma separated list of values. If
484 // it does, we have to split up the value into multiple values...
485 if (Value && Handler->getMiscFlags() & CommaSeparated) {
486 std::string Val(Value);
487 std::string::size_type Pos = Val.find(',');
489 while (Pos != std::string::npos) {
490 // Process the portion before the comma...
491 ErrorParsing |= ProvideOption(Handler, ArgName,
492 std::string(Val.begin(),
493 Val.begin()+Pos).c_str(),
495 // Erase the portion before the comma, AND the comma...
496 Val.erase(Val.begin(), Val.begin()+Pos+1);
497 Value += Pos+1; // Increment the original value pointer as well...
499 // Check for another comma...
504 // If this is a named positional argument, just remember that it is the
506 if (Handler->getFormattingFlag() == cl::Positional)
507 ActivePositionalArg = Handler;
509 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
512 // Check and handle positional arguments now...
513 if (NumPositionalRequired > PositionalVals.size()) {
514 std::cerr << ProgramName
515 << ": Not enough positional command line arguments specified!\n"
516 << "Must specify at least " << NumPositionalRequired
517 << " positional arguments: See: " << argv[0] << " --help\n";
520 } else if (!HasUnlimitedPositionals
521 && PositionalVals.size() > PositionalOpts.size()) {
522 std::cerr << ProgramName
523 << ": Too many positional arguments specified!\n"
524 << "Can specify at most " << PositionalOpts.size()
525 << " positional arguments: See: " << argv[0] << " --help\n";
528 } else if (ConsumeAfterOpt == 0) {
529 // Positional args have already been handled if ConsumeAfter is specified...
530 unsigned ValNo = 0, NumVals = PositionalVals.size();
531 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
532 if (RequiresValue(PositionalOpts[i])) {
533 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
534 PositionalVals[ValNo].second);
536 --NumPositionalRequired; // We fulfilled our duty...
539 // If we _can_ give this option more arguments, do so now, as long as we
540 // do not give it values that others need. 'Done' controls whether the
541 // option even _WANTS_ any more.
543 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
544 while (NumVals-ValNo > NumPositionalRequired && !Done) {
545 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
547 Done = true; // Optional arguments want _at most_ one value
549 case cl::ZeroOrMore: // Zero or more will take all they can get...
550 case cl::OneOrMore: // One or more will take all they can get...
551 ProvidePositionalOption(PositionalOpts[i],
552 PositionalVals[ValNo].first,
553 PositionalVals[ValNo].second);
557 assert(0 && "Internal error, unexpected NumOccurrences flag in "
558 "positional argument processing!");
563 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
565 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
566 if (RequiresValue(PositionalOpts[j])) {
567 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
568 PositionalVals[ValNo].first,
569 PositionalVals[ValNo].second);
573 // Handle the case where there is just one positional option, and it's
574 // optional. In this case, we want to give JUST THE FIRST option to the
575 // positional option and keep the rest for the consume after. The above
576 // loop would have assigned no values to positional options in this case.
578 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
579 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
580 PositionalVals[ValNo].first,
581 PositionalVals[ValNo].second);
585 // Handle over all of the rest of the arguments to the
586 // cl::ConsumeAfter command line option...
587 for (; ValNo != PositionalVals.size(); ++ValNo)
588 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
589 PositionalVals[ValNo].first,
590 PositionalVals[ValNo].second);
593 // Loop over args and make sure all required args are specified!
594 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
595 E = Opts.end(); I != E; ++I) {
596 switch (I->second->getNumOccurrencesFlag()) {
599 if (I->second->getNumOccurrences() == 0) {
600 I->second->error(" must be specified at least once!");
609 // Free all of the memory allocated to the map. Command line options may only
610 // be processed once!
612 PositionalOpts.clear();
615 // If we had an error processing our arguments, don't let the program execute
616 if (ErrorParsing) exit(1);
619 //===----------------------------------------------------------------------===//
620 // Option Base class implementation
623 bool Option::error(std::string Message, const char *ArgName) {
624 if (ArgName == 0) ArgName = ArgStr;
626 std::cerr << HelpStr; // Be nice for positional arguments
628 std::cerr << ProgramName << ": for the -" << ArgName;
630 std::cerr << " option: " << Message << "\n";
634 bool Option::addOccurrence(unsigned pos, const char *ArgName,
635 const std::string &Value) {
636 NumOccurrences++; // Increment the number of times we have been seen
638 switch (getNumOccurrencesFlag()) {
640 if (NumOccurrences > 1)
641 return error(": may only occur zero or one times!", ArgName);
644 if (NumOccurrences > 1)
645 return error(": must occur exactly one time!", ArgName);
649 case ConsumeAfter: break;
650 default: return error(": bad num occurrences flag value!");
653 return handleOccurrence(pos, ArgName, Value);
656 // addArgument - Tell the system that this Option subclass will handle all
657 // occurrences of -ArgStr on the command line.
659 void Option::addArgument(const char *ArgStr) {
661 AddArgument(ArgStr, this);
663 if (getFormattingFlag() == Positional)
664 getPositionalOpts().push_back(this);
665 else if (getNumOccurrencesFlag() == ConsumeAfter) {
666 if (!getPositionalOpts().empty() &&
667 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
668 error("Cannot specify more than one option with cl::ConsumeAfter!");
669 getPositionalOpts().insert(getPositionalOpts().begin(), this);
673 void Option::removeArgument(const char *ArgStr) {
675 RemoveArgument(ArgStr, this);
677 if (getFormattingFlag() == Positional) {
678 std::vector<Option*>::iterator I =
679 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
680 assert(I != getPositionalOpts().end() && "Arg not registered!");
681 getPositionalOpts().erase(I);
682 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
683 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
684 "Arg not registered correctly!");
685 getPositionalOpts().erase(getPositionalOpts().begin());
690 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
691 // has been specified yet.
693 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
694 if (O.ValueStr[0] == 0) return DefaultMsg;
698 //===----------------------------------------------------------------------===//
699 // cl::alias class implementation
702 // Return the width of the option tag for printing...
703 unsigned alias::getOptionWidth() const {
704 return std::strlen(ArgStr)+6;
707 // Print out the option for the alias.
708 void alias::printOptionInfo(unsigned GlobalWidth) const {
709 unsigned L = std::strlen(ArgStr);
710 std::cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
716 //===----------------------------------------------------------------------===//
717 // Parser Implementation code...
720 // basic_parser implementation
723 // Return the width of the option tag for printing...
724 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
725 unsigned Len = std::strlen(O.ArgStr);
726 if (const char *ValName = getValueName())
727 Len += std::strlen(getValueStr(O, ValName))+3;
732 // printOptionInfo - Print out information about this option. The
733 // to-be-maintained width is specified.
735 void basic_parser_impl::printOptionInfo(const Option &O,
736 unsigned GlobalWidth) const {
737 std::cout << " -" << O.ArgStr;
739 if (const char *ValName = getValueName())
740 std::cout << "=<" << getValueStr(O, ValName) << ">";
742 std::cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
743 << O.HelpStr << "\n";
749 // parser<bool> implementation
751 bool parser<bool>::parse(Option &O, const char *ArgName,
752 const std::string &Arg, bool &Value) {
753 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
756 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
759 return O.error(": '" + Arg +
760 "' is invalid value for boolean argument! Try 0 or 1");
765 // parser<int> implementation
767 bool parser<int>::parse(Option &O, const char *ArgName,
768 const std::string &Arg, int &Value) {
770 Value = (int)strtol(Arg.c_str(), &End, 0);
772 return O.error(": '" + Arg + "' value invalid for integer argument!");
776 // parser<unsigned> implementation
778 bool parser<unsigned>::parse(Option &O, const char *ArgName,
779 const std::string &Arg, unsigned &Value) {
782 unsigned long V = strtoul(Arg.c_str(), &End, 0);
784 if (((V == ULONG_MAX) && (errno == ERANGE))
787 return O.error(": '" + Arg + "' value invalid for uint argument!");
791 // parser<double>/parser<float> implementation
793 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
794 const char *ArgStart = Arg.c_str();
796 Value = strtod(ArgStart, &End);
798 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
802 bool parser<double>::parse(Option &O, const char *AN,
803 const std::string &Arg, double &Val) {
804 return parseDouble(O, Arg, Val);
807 bool parser<float>::parse(Option &O, const char *AN,
808 const std::string &Arg, float &Val) {
810 if (parseDouble(O, Arg, dVal))
818 // generic_parser_base implementation
821 // findOption - Return the option number corresponding to the specified
822 // argument string. If the option is not found, getNumOptions() is returned.
824 unsigned generic_parser_base::findOption(const char *Name) {
825 unsigned i = 0, e = getNumOptions();
829 if (getOption(i) == N)
837 // Return the width of the option tag for printing...
838 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
840 unsigned Size = std::strlen(O.ArgStr)+6;
841 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
842 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
845 unsigned BaseSize = 0;
846 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
847 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
852 // printOptionInfo - Print out information about this option. The
853 // to-be-maintained width is specified.
855 void generic_parser_base::printOptionInfo(const Option &O,
856 unsigned GlobalWidth) const {
858 unsigned L = std::strlen(O.ArgStr);
859 std::cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
860 << " - " << O.HelpStr << "\n";
862 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
863 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
864 std::cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
865 << " - " << getDescription(i) << "\n";
869 std::cout << " " << O.HelpStr << "\n";
870 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
871 unsigned L = std::strlen(getOption(i));
872 std::cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
873 << " - " << getDescription(i) << "\n";
879 //===----------------------------------------------------------------------===//
880 // --help and --help-hidden option implementation
887 const Option *EmptyArg;
888 const bool ShowHidden;
890 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
891 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
892 return OptPair.second->getOptionHiddenFlag() >= Hidden;
894 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
895 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
899 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
903 void operator=(bool Value) {
904 if (Value == false) return;
906 // Copy Options into a vector so we can sort them as we like...
907 std::vector<std::pair<std::string, Option*> > Options;
908 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
910 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
911 Options.erase(std::remove_if(Options.begin(), Options.end(),
912 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
915 // Eliminate duplicate entries in table (from enum flags options, f.e.)
916 { // Give OptionSet a scope
917 std::set<Option*> OptionSet;
918 for (unsigned i = 0; i != Options.size(); ++i)
919 if (OptionSet.count(Options[i].second) == 0)
920 OptionSet.insert(Options[i].second); // Add new entry to set
922 Options.erase(Options.begin()+i--); // Erase duplicate
926 std::cout << "OVERVIEW:" << ProgramOverview << "\n";
928 std::cout << "USAGE: " << ProgramName << " [options]";
930 // Print out the positional options...
931 std::vector<Option*> &PosOpts = getPositionalOpts();
932 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
933 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
936 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
937 if (PosOpts[i]->ArgStr[0])
938 std::cout << " --" << PosOpts[i]->ArgStr;
939 std::cout << " " << PosOpts[i]->HelpStr;
942 // Print the consume after option info if it exists...
943 if (CAOpt) std::cout << " " << CAOpt->HelpStr;
947 // Compute the maximum argument length...
949 for (unsigned i = 0, e = Options.size(); i != e; ++i)
950 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
952 std::cout << "OPTIONS:\n";
953 for (unsigned i = 0, e = Options.size(); i != e; ++i)
954 Options[i].second->printOptionInfo(MaxArgLen);
956 // Print any extra help the user has declared.
957 for (std::vector<const char *>::iterator I = MoreHelp().begin(),
958 E = MoreHelp().end(); I != E; ++I)
962 // Halt the program since help information was printed
963 getOpts().clear(); // Don't bother making option dtors remove from map.
968 // Define the two HelpPrinter instances that are used to print out help, or
971 HelpPrinter NormalPrinter(false);
972 HelpPrinter HiddenPrinter(true);
974 cl::opt<HelpPrinter, true, parser<bool> >
975 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
976 cl::location(NormalPrinter), cl::ValueDisallowed);
978 cl::opt<HelpPrinter, true, parser<bool> >
979 HHOp("help-hidden", cl::desc("Display all available options"),
980 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
982 void (*OverrideVersionPrinter)() = 0;
984 class VersionPrinter {
986 void operator=(bool OptionWasSpecified) {
987 if (OptionWasSpecified) {
988 if (OverrideVersionPrinter == 0) {
989 std::cout << "Low Level Virtual Machine (http://llvm.org/):\n";
990 std::cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
991 #ifdef LLVM_VERSION_INFO
992 std::cout << LLVM_VERSION_INFO;
996 std::cout << "DEBUG build";
998 std::cout << "Optimized build";
1001 std::cout << " with assertions";
1004 getOpts().clear(); // Don't bother making option dtors remove from map.
1007 (*OverrideVersionPrinter)();
1015 // Define the --version option that prints out the LLVM version for the tool
1016 VersionPrinter VersionPrinterInstance;
1017 cl::opt<VersionPrinter, true, parser<bool> >
1018 VersOp("version", cl::desc("Display the version of this program"),
1019 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1022 } // End anonymous namespace
1024 // Utility function for printing the help message.
1025 void cl::PrintHelpMessage() {
1026 // This looks weird, but it actually prints the help message. The
1027 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1028 // its operator= is invoked. That's because the "normal" usages of the
1029 // help printer is to be assigned true/false depending on whether the
1030 // --help option was given or not. Since we're circumventing that we have
1031 // to make it look like --help was given, so we assign true.
1032 NormalPrinter = true;
1035 void cl::SetVersionPrinter(void (*func)()) {
1036 OverrideVersionPrinter = func;