1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements a command line argument processor that is useful when
11 // creating a tool. It provides a simple, minimalistic interface that is easily
12 // extensible and supports nonlocal (library) command line options.
14 // Note that rather than trying to figure out what this code does, you could try
15 // reading the library documentation located in docs/CommandLine.html
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Config/config.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/Streams.h"
23 #include "llvm/System/Path.h"
35 //===----------------------------------------------------------------------===//
36 // Template instantiations and anchors.
38 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
39 TEMPLATE_INSTANTIATION(class basic_parser<int>);
40 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
41 TEMPLATE_INSTANTIATION(class basic_parser<double>);
42 TEMPLATE_INSTANTIATION(class basic_parser<float>);
43 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
45 TEMPLATE_INSTANTIATION(class opt<unsigned>);
46 TEMPLATE_INSTANTIATION(class opt<int>);
47 TEMPLATE_INSTANTIATION(class opt<std::string>);
48 TEMPLATE_INSTANTIATION(class opt<bool>);
50 void Option::anchor() {}
51 void basic_parser_impl::anchor() {}
52 void parser<bool>::anchor() {}
53 void parser<int>::anchor() {}
54 void parser<unsigned>::anchor() {}
55 void parser<double>::anchor() {}
56 void parser<float>::anchor() {}
57 void parser<std::string>::anchor() {}
59 //===----------------------------------------------------------------------===//
61 // Globals for name and overview of program. Program name is not a string to
62 // avoid static ctor/dtor issues.
63 static char ProgramName[80] = "<premain>";
64 static const char *ProgramOverview = 0;
66 // This collects additional help to be printed.
67 static ManagedStatic<std::vector<const char*> > MoreHelp;
69 extrahelp::extrahelp(const char *Help)
71 MoreHelp->push_back(Help);
74 /// RegisteredOptionList - This is the list of the command line options that
75 /// have statically constructed themselves.
76 static Option *RegisteredOptionList = 0;
78 void Option::addArgument() {
79 assert(NextRegistered == 0 && "argument multiply registered!");
81 NextRegistered = RegisteredOptionList;
82 RegisteredOptionList = this;
85 //===----------------------------------------------------------------------===//
86 // Basic, shared command line option processing machinery.
89 /// GetOptionInfo - Scan the list of registered options, turning them into data
90 /// structures that are easier to handle.
91 static void GetOptionInfo(std::vector<Option*> &PositionalOpts,
92 std::map<std::string, Option*> &OptionsMap) {
93 std::vector<const char*> OptionNames;
94 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
95 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
96 // If this option wants to handle multiple option names, get the full set.
97 // This handles enum options like "-O1 -O2" etc.
98 O->getExtraOptionNames(OptionNames);
100 OptionNames.push_back(O->ArgStr);
102 // Handle named options.
103 for (unsigned i = 0, e = OptionNames.size(); i != e; ++i) {
104 // Add argument to the argument map!
105 if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i],
107 cerr << ProgramName << ": CommandLine Error: Argument '"
108 << OptionNames[0] << "' defined more than once!\n";
114 // Remember information about positional options.
115 if (O->getFormattingFlag() == cl::Positional)
116 PositionalOpts.push_back(O);
117 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
119 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
125 PositionalOpts.push_back(CAOpt);
127 // Make sure that they are in order of registration not backwards.
128 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
132 /// LookupOption - Lookup the option specified by the specified option on the
133 /// command line. If there is a value specified (after an equal sign) return
135 static Option *LookupOption(const char *&Arg, const char *&Value,
136 std::map<std::string, Option*> &OptionsMap) {
137 while (*Arg == '-') ++Arg; // Eat leading dashes
139 const char *ArgEnd = Arg;
140 while (*ArgEnd && *ArgEnd != '=')
141 ++ArgEnd; // Scan till end of argument name.
143 if (*ArgEnd == '=') // If we have an equals sign...
144 Value = ArgEnd+1; // Get the value, not the equals
147 if (*Arg == 0) return 0;
149 // Look up the option.
150 std::map<std::string, Option*>::iterator I =
151 OptionsMap.find(std::string(Arg, ArgEnd));
152 return I != OptionsMap.end() ? I->second : 0;
155 static inline bool ProvideOption(Option *Handler, const char *ArgName,
156 const char *Value, int argc, char **argv,
158 // Enforce value requirements
159 switch (Handler->getValueExpectedFlag()) {
161 if (Value == 0) { // No value specified?
162 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
165 return Handler->error(" requires a value!");
169 case ValueDisallowed:
171 return Handler->error(" does not allow a value! '" +
172 std::string(Value) + "' specified.");
178 << ": Bad ValueMask flag! CommandLine usage error:"
179 << Handler->getValueExpectedFlag() << "\n";
184 // Run the handler now!
185 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
188 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
191 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
195 // Option predicates...
196 static inline bool isGrouping(const Option *O) {
197 return O->getFormattingFlag() == cl::Grouping;
199 static inline bool isPrefixedOrGrouping(const Option *O) {
200 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
203 // getOptionPred - Check to see if there are any options that satisfy the
204 // specified predicate with names that are the prefixes in Name. This is
205 // checked by progressively stripping characters off of the name, checking to
206 // see if there options that satisfy the predicate. If we find one, return it,
207 // otherwise return null.
209 static Option *getOptionPred(std::string Name, unsigned &Length,
210 bool (*Pred)(const Option*),
211 std::map<std::string, Option*> &OptionsMap) {
213 std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name);
214 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
215 Length = Name.length();
219 if (Name.size() == 1) return 0;
221 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
222 OMI = OptionsMap.find(Name);
224 // Loop while we haven't found an option and Name still has at least two
225 // characters in it (so that the next iteration will not be the empty
227 } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1);
229 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
230 Length = Name.length();
231 return OMI->second; // Found one!
233 return 0; // No option found!
236 static bool RequiresValue(const Option *O) {
237 return O->getNumOccurrencesFlag() == cl::Required ||
238 O->getNumOccurrencesFlag() == cl::OneOrMore;
241 static bool EatsUnboundedNumberOfValues(const Option *O) {
242 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
243 O->getNumOccurrencesFlag() == cl::OneOrMore;
246 /// ParseCStringVector - Break INPUT up wherever one or more
247 /// whitespace characters are found, and store the resulting tokens in
248 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
249 /// using strdup (), so it is the caller's responsibility to free ()
252 static void ParseCStringVector(std::vector<char *> &output,
254 // Characters which will be treated as token separators:
255 static const char *delims = " \v\f\t\r\n";
257 std::string work (input);
258 // Skip past any delims at head of input string.
259 size_t pos = work.find_first_not_of (delims);
260 // If the string consists entirely of delims, then exit early.
261 if (pos == std::string::npos) return;
262 // Otherwise, jump forward to beginning of first word.
263 work = work.substr (pos);
264 // Find position of first delimiter.
265 pos = work.find_first_of (delims);
267 while (!work.empty() && pos != std::string::npos) {
268 // Everything from 0 to POS is the next word to copy.
269 output.push_back (strdup (work.substr (0,pos).c_str ()));
270 // Is there another word in the string?
271 size_t nextpos = work.find_first_not_of (delims, pos + 1);
272 if (nextpos != std::string::npos) {
273 // Yes? Then remove delims from beginning ...
274 work = work.substr (work.find_first_not_of (delims, pos + 1));
275 // and find the end of the word.
276 pos = work.find_first_of (delims);
278 // No? (Remainder of string is delims.) End the loop.
280 pos = std::string::npos;
284 // If `input' ended with non-delim char, then we'll get here with
285 // the last word of `input' in `work'; copy it now.
286 if (!work.empty ()) {
287 output.push_back (strdup (work.c_str ()));
291 /// ParseEnvironmentOptions - An alternative entry point to the
292 /// CommandLine library, which allows you to read the program's name
293 /// from the caller (as PROGNAME) and its command-line arguments from
294 /// an environment variable (whose name is given in ENVVAR).
296 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
297 const char *Overview) {
299 assert(progName && "Program name not specified");
300 assert(envVar && "Environment variable name missing");
302 // Get the environment variable they want us to parse options out of.
303 const char *envValue = getenv(envVar);
307 // Get program's "name", which we wouldn't know without the caller
309 std::vector<char*> newArgv;
310 newArgv.push_back(strdup(progName));
312 // Parse the value of the environment variable into a "command line"
313 // and hand it off to ParseCommandLineOptions().
314 ParseCStringVector(newArgv, envValue);
315 int newArgc = newArgv.size();
316 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
318 // Free all the strdup()ed strings.
319 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
324 void cl::ParseCommandLineOptions(int &argc, char **argv,
325 const char *Overview) {
326 // Process all registered options.
327 std::vector<Option*> PositionalOpts;
328 std::map<std::string, Option*> Opts;
329 GetOptionInfo(PositionalOpts, Opts);
331 assert((!Opts.empty() || !PositionalOpts.empty()) &&
332 "No options specified!");
333 sys::Path progname(argv[0]);
335 // Copy the program name into ProgName, making sure not to overflow it.
336 std::string ProgName = sys::Path(argv[0]).getLast();
337 if (ProgName.size() > 79) ProgName.resize(79);
338 strcpy(ProgramName, ProgName.c_str());
340 ProgramOverview = Overview;
341 bool ErrorParsing = false;
343 // Check out the positional arguments to collect information about them.
344 unsigned NumPositionalRequired = 0;
346 // Determine whether or not there are an unlimited number of positionals
347 bool HasUnlimitedPositionals = false;
349 Option *ConsumeAfterOpt = 0;
350 if (!PositionalOpts.empty()) {
351 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
352 assert(PositionalOpts.size() > 1 &&
353 "Cannot specify cl::ConsumeAfter without a positional argument!");
354 ConsumeAfterOpt = PositionalOpts[0];
357 // Calculate how many positional values are _required_.
358 bool UnboundedFound = false;
359 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
361 Option *Opt = PositionalOpts[i];
362 if (RequiresValue(Opt))
363 ++NumPositionalRequired;
364 else if (ConsumeAfterOpt) {
365 // ConsumeAfter cannot be combined with "optional" positional options
366 // unless there is only one positional argument...
367 if (PositionalOpts.size() > 2)
369 Opt->error(" error - this positional option will never be matched, "
370 "because it does not Require a value, and a "
371 "cl::ConsumeAfter option is active!");
372 } else if (UnboundedFound && !Opt->ArgStr[0]) {
373 // This option does not "require" a value... Make sure this option is
374 // not specified after an option that eats all extra arguments, or this
375 // one will never get any!
377 ErrorParsing |= Opt->error(" error - option can never match, because "
378 "another positional argument will match an "
379 "unbounded number of values, and this option"
380 " does not require a value!");
382 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
384 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
387 // PositionalVals - A vector of "positional" arguments we accumulate into
388 // the process at the end...
390 std::vector<std::pair<std::string,unsigned> > PositionalVals;
392 // If the program has named positional arguments, and the name has been run
393 // across, keep track of which positional argument was named. Otherwise put
394 // the positional args into the PositionalVals list...
395 Option *ActivePositionalArg = 0;
397 // Loop over all of the arguments... processing them.
398 bool DashDashFound = false; // Have we read '--'?
399 for (int i = 1; i < argc; ++i) {
401 const char *Value = 0;
402 const char *ArgName = "";
404 // Check to see if this is a positional argument. This argument is
405 // considered to be positional if it doesn't start with '-', if it is "-"
406 // itself, or if we have seen "--" already.
408 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
409 // Positional argument!
410 if (ActivePositionalArg) {
411 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
412 continue; // We are done!
413 } else if (!PositionalOpts.empty()) {
414 PositionalVals.push_back(std::make_pair(argv[i],i));
416 // All of the positional arguments have been fulfulled, give the rest to
417 // the consume after option... if it's specified...
419 if (PositionalVals.size() >= NumPositionalRequired &&
420 ConsumeAfterOpt != 0) {
421 for (++i; i < argc; ++i)
422 PositionalVals.push_back(std::make_pair(argv[i],i));
423 break; // Handle outside of the argument processing loop...
426 // Delay processing positional arguments until the end...
429 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
431 DashDashFound = true; // This is the mythical "--"?
432 continue; // Don't try to process it as an argument itself.
433 } else if (ActivePositionalArg &&
434 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
435 // If there is a positional argument eating options, check to see if this
436 // option is another positional argument. If so, treat it as an argument,
437 // otherwise feed it to the eating positional.
439 Handler = LookupOption(ArgName, Value, Opts);
440 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
441 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
442 continue; // We are done!
445 } else { // We start with a '-', must be an argument...
447 Handler = LookupOption(ArgName, Value, Opts);
449 // Check to see if this "option" is really a prefixed or grouped argument.
451 std::string RealName(ArgName);
452 if (RealName.size() > 1) {
454 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping,
457 // If the option is a prefixed option, then the value is simply the
458 // rest of the name... so fall through to later processing, by
459 // setting up the argument name flags and value fields.
461 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
462 Value = ArgName+Length;
463 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
464 Opts.find(std::string(ArgName, Value))->second == PGOpt);
467 // This must be a grouped option... handle them now.
468 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
471 // Move current arg name out of RealName into RealArgName...
472 std::string RealArgName(RealName.begin(),
473 RealName.begin() + Length);
474 RealName.erase(RealName.begin(), RealName.begin() + Length);
476 // Because ValueRequired is an invalid flag for grouped arguments,
477 // we don't need to pass argc/argv in...
479 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
480 "Option can not be cl::Grouping AND cl::ValueRequired!");
482 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
485 // Get the next grouping option...
486 PGOpt = getOptionPred(RealName, Length, isGrouping, Opts);
487 } while (PGOpt && Length != RealName.size());
489 Handler = PGOpt; // Ate all of the options.
496 cerr << ProgramName << ": Unknown command line argument '"
497 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
502 // Check to see if this option accepts a comma separated list of values. If
503 // it does, we have to split up the value into multiple values...
504 if (Value && Handler->getMiscFlags() & CommaSeparated) {
505 std::string Val(Value);
506 std::string::size_type Pos = Val.find(',');
508 while (Pos != std::string::npos) {
509 // Process the portion before the comma...
510 ErrorParsing |= ProvideOption(Handler, ArgName,
511 std::string(Val.begin(),
512 Val.begin()+Pos).c_str(),
514 // Erase the portion before the comma, AND the comma...
515 Val.erase(Val.begin(), Val.begin()+Pos+1);
516 Value += Pos+1; // Increment the original value pointer as well...
518 // Check for another comma...
523 // If this is a named positional argument, just remember that it is the
525 if (Handler->getFormattingFlag() == cl::Positional)
526 ActivePositionalArg = Handler;
528 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
531 // Check and handle positional arguments now...
532 if (NumPositionalRequired > PositionalVals.size()) {
534 << ": Not enough positional command line arguments specified!\n"
535 << "Must specify at least " << NumPositionalRequired
536 << " positional arguments: See: " << argv[0] << " --help\n";
539 } else if (!HasUnlimitedPositionals
540 && PositionalVals.size() > PositionalOpts.size()) {
542 << ": Too many positional arguments specified!\n"
543 << "Can specify at most " << PositionalOpts.size()
544 << " positional arguments: See: " << argv[0] << " --help\n";
547 } else if (ConsumeAfterOpt == 0) {
548 // Positional args have already been handled if ConsumeAfter is specified...
549 unsigned ValNo = 0, NumVals = PositionalVals.size();
550 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
551 if (RequiresValue(PositionalOpts[i])) {
552 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
553 PositionalVals[ValNo].second);
555 --NumPositionalRequired; // We fulfilled our duty...
558 // If we _can_ give this option more arguments, do so now, as long as we
559 // do not give it values that others need. 'Done' controls whether the
560 // option even _WANTS_ any more.
562 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
563 while (NumVals-ValNo > NumPositionalRequired && !Done) {
564 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
566 Done = true; // Optional arguments want _at most_ one value
568 case cl::ZeroOrMore: // Zero or more will take all they can get...
569 case cl::OneOrMore: // One or more will take all they can get...
570 ProvidePositionalOption(PositionalOpts[i],
571 PositionalVals[ValNo].first,
572 PositionalVals[ValNo].second);
576 assert(0 && "Internal error, unexpected NumOccurrences flag in "
577 "positional argument processing!");
582 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
584 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
585 if (RequiresValue(PositionalOpts[j])) {
586 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
587 PositionalVals[ValNo].first,
588 PositionalVals[ValNo].second);
592 // Handle the case where there is just one positional option, and it's
593 // optional. In this case, we want to give JUST THE FIRST option to the
594 // positional option and keep the rest for the consume after. The above
595 // loop would have assigned no values to positional options in this case.
597 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
598 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
599 PositionalVals[ValNo].first,
600 PositionalVals[ValNo].second);
604 // Handle over all of the rest of the arguments to the
605 // cl::ConsumeAfter command line option...
606 for (; ValNo != PositionalVals.size(); ++ValNo)
607 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
608 PositionalVals[ValNo].first,
609 PositionalVals[ValNo].second);
612 // Loop over args and make sure all required args are specified!
613 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
614 E = Opts.end(); I != E; ++I) {
615 switch (I->second->getNumOccurrencesFlag()) {
618 if (I->second->getNumOccurrences() == 0) {
619 I->second->error(" must be specified at least once!");
628 // Free all of the memory allocated to the map. Command line options may only
629 // be processed once!
631 PositionalOpts.clear();
634 // If we had an error processing our arguments, don't let the program execute
635 if (ErrorParsing) exit(1);
638 //===----------------------------------------------------------------------===//
639 // Option Base class implementation
642 bool Option::error(std::string Message, const char *ArgName) {
643 if (ArgName == 0) ArgName = ArgStr;
645 cerr << HelpStr; // Be nice for positional arguments
647 cerr << ProgramName << ": for the -" << ArgName;
649 cerr << " option: " << Message << "\n";
653 bool Option::addOccurrence(unsigned pos, const char *ArgName,
654 const std::string &Value) {
655 NumOccurrences++; // Increment the number of times we have been seen
657 switch (getNumOccurrencesFlag()) {
659 if (NumOccurrences > 1)
660 return error(": may only occur zero or one times!", ArgName);
663 if (NumOccurrences > 1)
664 return error(": must occur exactly one time!", ArgName);
668 case ConsumeAfter: break;
669 default: return error(": bad num occurrences flag value!");
672 return handleOccurrence(pos, ArgName, Value);
676 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
677 // has been specified yet.
679 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
680 if (O.ValueStr[0] == 0) return DefaultMsg;
684 //===----------------------------------------------------------------------===//
685 // cl::alias class implementation
688 // Return the width of the option tag for printing...
689 unsigned alias::getOptionWidth() const {
690 return std::strlen(ArgStr)+6;
693 // Print out the option for the alias.
694 void alias::printOptionInfo(unsigned GlobalWidth) const {
695 unsigned L = std::strlen(ArgStr);
696 cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
702 //===----------------------------------------------------------------------===//
703 // Parser Implementation code...
706 // basic_parser implementation
709 // Return the width of the option tag for printing...
710 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
711 unsigned Len = std::strlen(O.ArgStr);
712 if (const char *ValName = getValueName())
713 Len += std::strlen(getValueStr(O, ValName))+3;
718 // printOptionInfo - Print out information about this option. The
719 // to-be-maintained width is specified.
721 void basic_parser_impl::printOptionInfo(const Option &O,
722 unsigned GlobalWidth) const {
723 cout << " -" << O.ArgStr;
725 if (const char *ValName = getValueName())
726 cout << "=<" << getValueStr(O, ValName) << ">";
728 cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
729 << O.HelpStr << "\n";
735 // parser<bool> implementation
737 bool parser<bool>::parse(Option &O, const char *ArgName,
738 const std::string &Arg, bool &Value) {
739 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
742 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
745 return O.error(": '" + Arg +
746 "' is invalid value for boolean argument! Try 0 or 1");
751 // parser<int> implementation
753 bool parser<int>::parse(Option &O, const char *ArgName,
754 const std::string &Arg, int &Value) {
756 Value = (int)strtol(Arg.c_str(), &End, 0);
758 return O.error(": '" + Arg + "' value invalid for integer argument!");
762 // parser<unsigned> implementation
764 bool parser<unsigned>::parse(Option &O, const char *ArgName,
765 const std::string &Arg, unsigned &Value) {
768 unsigned long V = strtoul(Arg.c_str(), &End, 0);
770 if (((V == ULONG_MAX) && (errno == ERANGE))
773 return O.error(": '" + Arg + "' value invalid for uint argument!");
777 // parser<double>/parser<float> implementation
779 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
780 const char *ArgStart = Arg.c_str();
782 Value = strtod(ArgStart, &End);
784 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
788 bool parser<double>::parse(Option &O, const char *AN,
789 const std::string &Arg, double &Val) {
790 return parseDouble(O, Arg, Val);
793 bool parser<float>::parse(Option &O, const char *AN,
794 const std::string &Arg, float &Val) {
796 if (parseDouble(O, Arg, dVal))
804 // generic_parser_base implementation
807 // findOption - Return the option number corresponding to the specified
808 // argument string. If the option is not found, getNumOptions() is returned.
810 unsigned generic_parser_base::findOption(const char *Name) {
811 unsigned i = 0, e = getNumOptions();
815 if (getOption(i) == N)
823 // Return the width of the option tag for printing...
824 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
826 unsigned Size = std::strlen(O.ArgStr)+6;
827 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
828 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
831 unsigned BaseSize = 0;
832 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
833 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
838 // printOptionInfo - Print out information about this option. The
839 // to-be-maintained width is specified.
841 void generic_parser_base::printOptionInfo(const Option &O,
842 unsigned GlobalWidth) const {
844 unsigned L = std::strlen(O.ArgStr);
845 cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
846 << " - " << O.HelpStr << "\n";
848 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
849 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
850 cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
851 << " - " << getDescription(i) << "\n";
855 cout << " " << O.HelpStr << "\n";
856 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
857 unsigned L = std::strlen(getOption(i));
858 cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
859 << " - " << getDescription(i) << "\n";
865 //===----------------------------------------------------------------------===//
866 // --help and --help-hidden option implementation
873 const Option *EmptyArg;
874 const bool ShowHidden;
876 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
877 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
878 return OptPair.second->getOptionHiddenFlag() >= Hidden;
880 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
881 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
885 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
889 void operator=(bool Value) {
890 if (Value == false) return;
892 // Get all the options.
893 std::vector<Option*> PositionalOpts;
894 std::map<std::string, Option*> OptMap;
895 GetOptionInfo(PositionalOpts, OptMap);
897 // Copy Options into a vector so we can sort them as we like...
898 std::vector<std::pair<std::string, Option*> > Opts;
899 copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts));
901 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
902 Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
903 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
906 // Eliminate duplicate entries in table (from enum flags options, f.e.)
907 { // Give OptionSet a scope
908 std::set<Option*> OptionSet;
909 for (unsigned i = 0; i != Opts.size(); ++i)
910 if (OptionSet.count(Opts[i].second) == 0)
911 OptionSet.insert(Opts[i].second); // Add new entry to set
913 Opts.erase(Opts.begin()+i--); // Erase duplicate
917 cout << "OVERVIEW:" << ProgramOverview << "\n";
919 cout << "USAGE: " << ProgramName << " [options]";
921 // Print out the positional options.
922 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
923 if (!PositionalOpts.empty() &&
924 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
925 CAOpt = PositionalOpts[0];
927 for (unsigned i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
928 if (PositionalOpts[i]->ArgStr[0])
929 cout << " --" << PositionalOpts[i]->ArgStr;
930 cout << " " << PositionalOpts[i]->HelpStr;
933 // Print the consume after option info if it exists...
934 if (CAOpt) cout << " " << CAOpt->HelpStr;
938 // Compute the maximum argument length...
940 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
941 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
943 cout << "OPTIONS:\n";
944 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
945 Opts[i].second->printOptionInfo(MaxArgLen);
947 // Print any extra help the user has declared.
948 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
949 E = MoreHelp->end(); I != E; ++I)
953 // Halt the program since help information was printed
957 } // End anonymous namespace
959 // Define the two HelpPrinter instances that are used to print out help, or
962 static HelpPrinter NormalPrinter(false);
963 static HelpPrinter HiddenPrinter(true);
965 static cl::opt<HelpPrinter, true, parser<bool> >
966 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
967 cl::location(NormalPrinter), cl::ValueDisallowed);
969 static cl::opt<HelpPrinter, true, parser<bool> >
970 HHOp("help-hidden", cl::desc("Display all available options"),
971 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
973 static void (*OverrideVersionPrinter)() = 0;
976 class VersionPrinter {
979 cout << "Low Level Virtual Machine (http://llvm.org/):\n";
980 cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
981 #ifdef LLVM_VERSION_INFO
982 cout << LLVM_VERSION_INFO;
986 cout << "DEBUG build";
988 cout << "Optimized build";
991 cout << " with assertions";
995 void operator=(bool OptionWasSpecified) {
996 if (OptionWasSpecified) {
997 if (OverrideVersionPrinter == 0) {
1001 (*OverrideVersionPrinter)();
1007 } // End anonymous namespace
1010 // Define the --version option that prints out the LLVM version for the tool
1011 static VersionPrinter VersionPrinterInstance;
1013 static cl::opt<VersionPrinter, true, parser<bool> >
1014 VersOp("version", cl::desc("Display the version of this program"),
1015 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1017 // Utility function for printing the help message.
1018 void cl::PrintHelpMessage() {
1019 // This looks weird, but it actually prints the help message. The
1020 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1021 // its operator= is invoked. That's because the "normal" usages of the
1022 // help printer is to be assigned true/false depending on whether the
1023 // --help option was given or not. Since we're circumventing that we have
1024 // to make it look like --help was given, so we assign true.
1025 NormalPrinter = true;
1028 /// Utility function for printing version number.
1029 void cl::PrintVersionMessage() {
1030 VersionPrinterInstance.print();
1033 void cl::SetVersionPrinter(void (*func)()) {
1034 OverrideVersionPrinter = func;