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 static bool OptionListChanged = false;
76 // MarkOptionsChanged - Internal helper function.
77 void cl::MarkOptionsChanged() {
78 OptionListChanged = true;
81 /// RegisteredOptionList - This is the list of the command line options that
82 /// have statically constructed themselves.
83 static Option *RegisteredOptionList = 0;
85 void Option::addArgument() {
86 assert(NextRegistered == 0 && "argument multiply registered!");
88 NextRegistered = RegisteredOptionList;
89 RegisteredOptionList = this;
94 //===----------------------------------------------------------------------===//
95 // Basic, shared command line option processing machinery.
98 /// GetOptionInfo - Scan the list of registered options, turning them into data
99 /// structures that are easier to handle.
100 static void GetOptionInfo(std::vector<Option*> &PositionalOpts,
101 std::map<std::string, Option*> &OptionsMap) {
102 std::vector<const char*> OptionNames;
103 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
104 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
105 // If this option wants to handle multiple option names, get the full set.
106 // This handles enum options like "-O1 -O2" etc.
107 O->getExtraOptionNames(OptionNames);
109 OptionNames.push_back(O->ArgStr);
111 // Handle named options.
112 for (unsigned i = 0, e = OptionNames.size(); i != e; ++i) {
113 // Add argument to the argument map!
114 if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i],
116 cerr << ProgramName << ": CommandLine Error: Argument '"
117 << OptionNames[0] << "' defined more than once!\n";
123 // Remember information about positional options.
124 if (O->getFormattingFlag() == cl::Positional)
125 PositionalOpts.push_back(O);
126 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
128 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
134 PositionalOpts.push_back(CAOpt);
136 // Make sure that they are in order of registration not backwards.
137 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
141 /// LookupOption - Lookup the option specified by the specified option on the
142 /// command line. If there is a value specified (after an equal sign) return
144 static Option *LookupOption(const char *&Arg, const char *&Value,
145 std::map<std::string, Option*> &OptionsMap) {
146 while (*Arg == '-') ++Arg; // Eat leading dashes
148 const char *ArgEnd = Arg;
149 while (*ArgEnd && *ArgEnd != '=')
150 ++ArgEnd; // Scan till end of argument name.
152 if (*ArgEnd == '=') // If we have an equals sign...
153 Value = ArgEnd+1; // Get the value, not the equals
156 if (*Arg == 0) return 0;
158 // Look up the option.
159 std::map<std::string, Option*>::iterator I =
160 OptionsMap.find(std::string(Arg, ArgEnd));
161 return I != OptionsMap.end() ? I->second : 0;
164 static inline bool ProvideOption(Option *Handler, const char *ArgName,
165 const char *Value, int argc, char **argv,
167 // Enforce value requirements
168 switch (Handler->getValueExpectedFlag()) {
170 if (Value == 0) { // No value specified?
171 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
174 return Handler->error(" requires a value!");
178 case ValueDisallowed:
180 return Handler->error(" does not allow a value! '" +
181 std::string(Value) + "' specified.");
187 << ": Bad ValueMask flag! CommandLine usage error:"
188 << Handler->getValueExpectedFlag() << "\n";
193 // Run the handler now!
194 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
197 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
200 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
204 // Option predicates...
205 static inline bool isGrouping(const Option *O) {
206 return O->getFormattingFlag() == cl::Grouping;
208 static inline bool isPrefixedOrGrouping(const Option *O) {
209 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
212 // getOptionPred - Check to see if there are any options that satisfy the
213 // specified predicate with names that are the prefixes in Name. This is
214 // checked by progressively stripping characters off of the name, checking to
215 // see if there options that satisfy the predicate. If we find one, return it,
216 // otherwise return null.
218 static Option *getOptionPred(std::string Name, unsigned &Length,
219 bool (*Pred)(const Option*),
220 std::map<std::string, Option*> &OptionsMap) {
222 std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name);
223 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
224 Length = Name.length();
228 if (Name.size() == 1) return 0;
230 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
231 OMI = OptionsMap.find(Name);
233 // Loop while we haven't found an option and Name still has at least two
234 // characters in it (so that the next iteration will not be the empty
236 } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1);
238 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
239 Length = Name.length();
240 return OMI->second; // Found one!
242 return 0; // No option found!
245 static bool RequiresValue(const Option *O) {
246 return O->getNumOccurrencesFlag() == cl::Required ||
247 O->getNumOccurrencesFlag() == cl::OneOrMore;
250 static bool EatsUnboundedNumberOfValues(const Option *O) {
251 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
252 O->getNumOccurrencesFlag() == cl::OneOrMore;
255 /// ParseCStringVector - Break INPUT up wherever one or more
256 /// whitespace characters are found, and store the resulting tokens in
257 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
258 /// using strdup (), so it is the caller's responsibility to free ()
261 static void ParseCStringVector(std::vector<char *> &output,
263 // Characters which will be treated as token separators:
264 static const char *delims = " \v\f\t\r\n";
266 std::string work (input);
267 // Skip past any delims at head of input string.
268 size_t pos = work.find_first_not_of (delims);
269 // If the string consists entirely of delims, then exit early.
270 if (pos == std::string::npos) return;
271 // Otherwise, jump forward to beginning of first word.
272 work = work.substr (pos);
273 // Find position of first delimiter.
274 pos = work.find_first_of (delims);
276 while (!work.empty() && pos != std::string::npos) {
277 // Everything from 0 to POS is the next word to copy.
278 output.push_back (strdup (work.substr (0,pos).c_str ()));
279 // Is there another word in the string?
280 size_t nextpos = work.find_first_not_of (delims, pos + 1);
281 if (nextpos != std::string::npos) {
282 // Yes? Then remove delims from beginning ...
283 work = work.substr (work.find_first_not_of (delims, pos + 1));
284 // and find the end of the word.
285 pos = work.find_first_of (delims);
287 // No? (Remainder of string is delims.) End the loop.
289 pos = std::string::npos;
293 // If `input' ended with non-delim char, then we'll get here with
294 // the last word of `input' in `work'; copy it now.
295 if (!work.empty ()) {
296 output.push_back (strdup (work.c_str ()));
300 /// ParseEnvironmentOptions - An alternative entry point to the
301 /// CommandLine library, which allows you to read the program's name
302 /// from the caller (as PROGNAME) and its command-line arguments from
303 /// an environment variable (whose name is given in ENVVAR).
305 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
306 const char *Overview) {
308 assert(progName && "Program name not specified");
309 assert(envVar && "Environment variable name missing");
311 // Get the environment variable they want us to parse options out of.
312 const char *envValue = getenv(envVar);
316 // Get program's "name", which we wouldn't know without the caller
318 std::vector<char*> newArgv;
319 newArgv.push_back(strdup(progName));
321 // Parse the value of the environment variable into a "command line"
322 // and hand it off to ParseCommandLineOptions().
323 ParseCStringVector(newArgv, envValue);
324 int newArgc = newArgv.size();
325 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
327 // Free all the strdup()ed strings.
328 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
333 void cl::ParseCommandLineOptions(int &argc, char **argv,
334 const char *Overview) {
335 // Process all registered options.
336 std::vector<Option*> PositionalOpts;
337 std::map<std::string, Option*> Opts;
338 GetOptionInfo(PositionalOpts, Opts);
340 assert((!Opts.empty() || !PositionalOpts.empty()) &&
341 "No options specified!");
342 sys::Path progname(argv[0]);
344 // Copy the program name into ProgName, making sure not to overflow it.
345 std::string ProgName = sys::Path(argv[0]).getLast();
346 if (ProgName.size() > 79) ProgName.resize(79);
347 strcpy(ProgramName, ProgName.c_str());
349 ProgramOverview = Overview;
350 bool ErrorParsing = false;
352 // Check out the positional arguments to collect information about them.
353 unsigned NumPositionalRequired = 0;
355 // Determine whether or not there are an unlimited number of positionals
356 bool HasUnlimitedPositionals = false;
358 Option *ConsumeAfterOpt = 0;
359 if (!PositionalOpts.empty()) {
360 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
361 assert(PositionalOpts.size() > 1 &&
362 "Cannot specify cl::ConsumeAfter without a positional argument!");
363 ConsumeAfterOpt = PositionalOpts[0];
366 // Calculate how many positional values are _required_.
367 bool UnboundedFound = false;
368 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
370 Option *Opt = PositionalOpts[i];
371 if (RequiresValue(Opt))
372 ++NumPositionalRequired;
373 else if (ConsumeAfterOpt) {
374 // ConsumeAfter cannot be combined with "optional" positional options
375 // unless there is only one positional argument...
376 if (PositionalOpts.size() > 2)
378 Opt->error(" error - this positional option will never be matched, "
379 "because it does not Require a value, and a "
380 "cl::ConsumeAfter option is active!");
381 } else if (UnboundedFound && !Opt->ArgStr[0]) {
382 // This option does not "require" a value... Make sure this option is
383 // not specified after an option that eats all extra arguments, or this
384 // one will never get any!
386 ErrorParsing |= Opt->error(" error - option can never match, because "
387 "another positional argument will match an "
388 "unbounded number of values, and this option"
389 " does not require a value!");
391 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
393 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
396 // PositionalVals - A vector of "positional" arguments we accumulate into
397 // the process at the end...
399 std::vector<std::pair<std::string,unsigned> > PositionalVals;
401 // If the program has named positional arguments, and the name has been run
402 // across, keep track of which positional argument was named. Otherwise put
403 // the positional args into the PositionalVals list...
404 Option *ActivePositionalArg = 0;
406 // Loop over all of the arguments... processing them.
407 bool DashDashFound = false; // Have we read '--'?
408 for (int i = 1; i < argc; ++i) {
410 const char *Value = 0;
411 const char *ArgName = "";
413 // If the option list changed, this means that some command line
414 // option has just been registered or deregistered. This can occur in
415 // response to things like -load, etc. If this happens, rescan the options.
416 if (OptionListChanged) {
417 PositionalOpts.clear();
419 GetOptionInfo(PositionalOpts, Opts);
420 OptionListChanged = false;
423 // Check to see if this is a positional argument. This argument is
424 // considered to be positional if it doesn't start with '-', if it is "-"
425 // itself, or if we have seen "--" already.
427 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
428 // Positional argument!
429 if (ActivePositionalArg) {
430 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
431 continue; // We are done!
432 } else if (!PositionalOpts.empty()) {
433 PositionalVals.push_back(std::make_pair(argv[i],i));
435 // All of the positional arguments have been fulfulled, give the rest to
436 // the consume after option... if it's specified...
438 if (PositionalVals.size() >= NumPositionalRequired &&
439 ConsumeAfterOpt != 0) {
440 for (++i; i < argc; ++i)
441 PositionalVals.push_back(std::make_pair(argv[i],i));
442 break; // Handle outside of the argument processing loop...
445 // Delay processing positional arguments until the end...
448 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
450 DashDashFound = true; // This is the mythical "--"?
451 continue; // Don't try to process it as an argument itself.
452 } else if (ActivePositionalArg &&
453 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
454 // If there is a positional argument eating options, check to see if this
455 // option is another positional argument. If so, treat it as an argument,
456 // otherwise feed it to the eating positional.
458 Handler = LookupOption(ArgName, Value, Opts);
459 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
460 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
461 continue; // We are done!
464 } else { // We start with a '-', must be an argument...
466 Handler = LookupOption(ArgName, Value, Opts);
468 // Check to see if this "option" is really a prefixed or grouped argument.
470 std::string RealName(ArgName);
471 if (RealName.size() > 1) {
473 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping,
476 // If the option is a prefixed option, then the value is simply the
477 // rest of the name... so fall through to later processing, by
478 // setting up the argument name flags and value fields.
480 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
481 Value = ArgName+Length;
482 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
483 Opts.find(std::string(ArgName, Value))->second == PGOpt);
486 // This must be a grouped option... handle them now.
487 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
490 // Move current arg name out of RealName into RealArgName...
491 std::string RealArgName(RealName.begin(),
492 RealName.begin() + Length);
493 RealName.erase(RealName.begin(), RealName.begin() + Length);
495 // Because ValueRequired is an invalid flag for grouped arguments,
496 // we don't need to pass argc/argv in...
498 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
499 "Option can not be cl::Grouping AND cl::ValueRequired!");
501 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
504 // Get the next grouping option...
505 PGOpt = getOptionPred(RealName, Length, isGrouping, Opts);
506 } while (PGOpt && Length != RealName.size());
508 Handler = PGOpt; // Ate all of the options.
515 cerr << ProgramName << ": Unknown command line argument '"
516 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
521 // Check to see if this option accepts a comma separated list of values. If
522 // it does, we have to split up the value into multiple values...
523 if (Value && Handler->getMiscFlags() & CommaSeparated) {
524 std::string Val(Value);
525 std::string::size_type Pos = Val.find(',');
527 while (Pos != std::string::npos) {
528 // Process the portion before the comma...
529 ErrorParsing |= ProvideOption(Handler, ArgName,
530 std::string(Val.begin(),
531 Val.begin()+Pos).c_str(),
533 // Erase the portion before the comma, AND the comma...
534 Val.erase(Val.begin(), Val.begin()+Pos+1);
535 Value += Pos+1; // Increment the original value pointer as well...
537 // Check for another comma...
542 // If this is a named positional argument, just remember that it is the
544 if (Handler->getFormattingFlag() == cl::Positional)
545 ActivePositionalArg = Handler;
547 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
550 // Check and handle positional arguments now...
551 if (NumPositionalRequired > PositionalVals.size()) {
553 << ": Not enough positional command line arguments specified!\n"
554 << "Must specify at least " << NumPositionalRequired
555 << " positional arguments: See: " << argv[0] << " --help\n";
558 } else if (!HasUnlimitedPositionals
559 && PositionalVals.size() > PositionalOpts.size()) {
561 << ": Too many positional arguments specified!\n"
562 << "Can specify at most " << PositionalOpts.size()
563 << " positional arguments: See: " << argv[0] << " --help\n";
566 } else if (ConsumeAfterOpt == 0) {
567 // Positional args have already been handled if ConsumeAfter is specified...
568 unsigned ValNo = 0, NumVals = PositionalVals.size();
569 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
570 if (RequiresValue(PositionalOpts[i])) {
571 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
572 PositionalVals[ValNo].second);
574 --NumPositionalRequired; // We fulfilled our duty...
577 // If we _can_ give this option more arguments, do so now, as long as we
578 // do not give it values that others need. 'Done' controls whether the
579 // option even _WANTS_ any more.
581 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
582 while (NumVals-ValNo > NumPositionalRequired && !Done) {
583 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
585 Done = true; // Optional arguments want _at most_ one value
587 case cl::ZeroOrMore: // Zero or more will take all they can get...
588 case cl::OneOrMore: // One or more will take all they can get...
589 ProvidePositionalOption(PositionalOpts[i],
590 PositionalVals[ValNo].first,
591 PositionalVals[ValNo].second);
595 assert(0 && "Internal error, unexpected NumOccurrences flag in "
596 "positional argument processing!");
601 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
603 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
604 if (RequiresValue(PositionalOpts[j])) {
605 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
606 PositionalVals[ValNo].first,
607 PositionalVals[ValNo].second);
611 // Handle the case where there is just one positional option, and it's
612 // optional. In this case, we want to give JUST THE FIRST option to the
613 // positional option and keep the rest for the consume after. The above
614 // loop would have assigned no values to positional options in this case.
616 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
617 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
618 PositionalVals[ValNo].first,
619 PositionalVals[ValNo].second);
623 // Handle over all of the rest of the arguments to the
624 // cl::ConsumeAfter command line option...
625 for (; ValNo != PositionalVals.size(); ++ValNo)
626 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
627 PositionalVals[ValNo].first,
628 PositionalVals[ValNo].second);
631 // Loop over args and make sure all required args are specified!
632 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
633 E = Opts.end(); I != E; ++I) {
634 switch (I->second->getNumOccurrencesFlag()) {
637 if (I->second->getNumOccurrences() == 0) {
638 I->second->error(" must be specified at least once!");
647 // Free all of the memory allocated to the map. Command line options may only
648 // be processed once!
650 PositionalOpts.clear();
653 // If we had an error processing our arguments, don't let the program execute
654 if (ErrorParsing) exit(1);
657 //===----------------------------------------------------------------------===//
658 // Option Base class implementation
661 bool Option::error(std::string Message, const char *ArgName) {
662 if (ArgName == 0) ArgName = ArgStr;
664 cerr << HelpStr; // Be nice for positional arguments
666 cerr << ProgramName << ": for the -" << ArgName;
668 cerr << " option: " << Message << "\n";
672 bool Option::addOccurrence(unsigned pos, const char *ArgName,
673 const std::string &Value) {
674 NumOccurrences++; // Increment the number of times we have been seen
676 switch (getNumOccurrencesFlag()) {
678 if (NumOccurrences > 1)
679 return error(": may only occur zero or one times!", ArgName);
682 if (NumOccurrences > 1)
683 return error(": must occur exactly one time!", ArgName);
687 case ConsumeAfter: break;
688 default: return error(": bad num occurrences flag value!");
691 return handleOccurrence(pos, ArgName, Value);
695 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
696 // has been specified yet.
698 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
699 if (O.ValueStr[0] == 0) return DefaultMsg;
703 //===----------------------------------------------------------------------===//
704 // cl::alias class implementation
707 // Return the width of the option tag for printing...
708 unsigned alias::getOptionWidth() const {
709 return std::strlen(ArgStr)+6;
712 // Print out the option for the alias.
713 void alias::printOptionInfo(unsigned GlobalWidth) const {
714 unsigned L = std::strlen(ArgStr);
715 cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
721 //===----------------------------------------------------------------------===//
722 // Parser Implementation code...
725 // basic_parser implementation
728 // Return the width of the option tag for printing...
729 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
730 unsigned Len = std::strlen(O.ArgStr);
731 if (const char *ValName = getValueName())
732 Len += std::strlen(getValueStr(O, ValName))+3;
737 // printOptionInfo - Print out information about this option. The
738 // to-be-maintained width is specified.
740 void basic_parser_impl::printOptionInfo(const Option &O,
741 unsigned GlobalWidth) const {
742 cout << " -" << O.ArgStr;
744 if (const char *ValName = getValueName())
745 cout << "=<" << getValueStr(O, ValName) << ">";
747 cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
748 << O.HelpStr << "\n";
754 // parser<bool> implementation
756 bool parser<bool>::parse(Option &O, const char *ArgName,
757 const std::string &Arg, bool &Value) {
758 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
761 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
764 return O.error(": '" + Arg +
765 "' is invalid value for boolean argument! Try 0 or 1");
770 // parser<int> implementation
772 bool parser<int>::parse(Option &O, const char *ArgName,
773 const std::string &Arg, int &Value) {
775 Value = (int)strtol(Arg.c_str(), &End, 0);
777 return O.error(": '" + Arg + "' value invalid for integer argument!");
781 // parser<unsigned> implementation
783 bool parser<unsigned>::parse(Option &O, const char *ArgName,
784 const std::string &Arg, unsigned &Value) {
787 unsigned long V = strtoul(Arg.c_str(), &End, 0);
789 if (((V == ULONG_MAX) && (errno == ERANGE))
792 return O.error(": '" + Arg + "' value invalid for uint argument!");
796 // parser<double>/parser<float> implementation
798 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
799 const char *ArgStart = Arg.c_str();
801 Value = strtod(ArgStart, &End);
803 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
807 bool parser<double>::parse(Option &O, const char *AN,
808 const std::string &Arg, double &Val) {
809 return parseDouble(O, Arg, Val);
812 bool parser<float>::parse(Option &O, const char *AN,
813 const std::string &Arg, float &Val) {
815 if (parseDouble(O, Arg, dVal))
823 // generic_parser_base implementation
826 // findOption - Return the option number corresponding to the specified
827 // argument string. If the option is not found, getNumOptions() is returned.
829 unsigned generic_parser_base::findOption(const char *Name) {
830 unsigned i = 0, e = getNumOptions();
834 if (getOption(i) == N)
842 // Return the width of the option tag for printing...
843 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
845 unsigned Size = std::strlen(O.ArgStr)+6;
846 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
847 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
850 unsigned BaseSize = 0;
851 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
852 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
857 // printOptionInfo - Print out information about this option. The
858 // to-be-maintained width is specified.
860 void generic_parser_base::printOptionInfo(const Option &O,
861 unsigned GlobalWidth) const {
863 unsigned L = std::strlen(O.ArgStr);
864 cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
865 << " - " << O.HelpStr << "\n";
867 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
868 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
869 cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
870 << " - " << getDescription(i) << "\n";
874 cout << " " << O.HelpStr << "\n";
875 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
876 unsigned L = std::strlen(getOption(i));
877 cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
878 << " - " << getDescription(i) << "\n";
884 //===----------------------------------------------------------------------===//
885 // --help and --help-hidden option implementation
892 const Option *EmptyArg;
893 const bool ShowHidden;
895 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
896 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
897 return OptPair.second->getOptionHiddenFlag() >= Hidden;
899 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
900 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
904 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
908 void operator=(bool Value) {
909 if (Value == false) return;
911 // Get all the options.
912 std::vector<Option*> PositionalOpts;
913 std::map<std::string, Option*> OptMap;
914 GetOptionInfo(PositionalOpts, OptMap);
916 // Copy Options into a vector so we can sort them as we like...
917 std::vector<std::pair<std::string, Option*> > Opts;
918 copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts));
920 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
921 Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
922 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
925 // Eliminate duplicate entries in table (from enum flags options, f.e.)
926 { // Give OptionSet a scope
927 std::set<Option*> OptionSet;
928 for (unsigned i = 0; i != Opts.size(); ++i)
929 if (OptionSet.count(Opts[i].second) == 0)
930 OptionSet.insert(Opts[i].second); // Add new entry to set
932 Opts.erase(Opts.begin()+i--); // Erase duplicate
936 cout << "OVERVIEW:" << ProgramOverview << "\n";
938 cout << "USAGE: " << ProgramName << " [options]";
940 // Print out the positional options.
941 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
942 if (!PositionalOpts.empty() &&
943 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
944 CAOpt = PositionalOpts[0];
946 for (unsigned i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
947 if (PositionalOpts[i]->ArgStr[0])
948 cout << " --" << PositionalOpts[i]->ArgStr;
949 cout << " " << PositionalOpts[i]->HelpStr;
952 // Print the consume after option info if it exists...
953 if (CAOpt) cout << " " << CAOpt->HelpStr;
957 // Compute the maximum argument length...
959 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
960 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
962 cout << "OPTIONS:\n";
963 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
964 Opts[i].second->printOptionInfo(MaxArgLen);
966 // Print any extra help the user has declared.
967 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
968 E = MoreHelp->end(); I != E; ++I)
972 // Halt the program since help information was printed
976 } // End anonymous namespace
978 // Define the two HelpPrinter instances that are used to print out help, or
981 static HelpPrinter NormalPrinter(false);
982 static HelpPrinter HiddenPrinter(true);
984 static cl::opt<HelpPrinter, true, parser<bool> >
985 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
986 cl::location(NormalPrinter), cl::ValueDisallowed);
988 static cl::opt<HelpPrinter, true, parser<bool> >
989 HHOp("help-hidden", cl::desc("Display all available options"),
990 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
992 static void (*OverrideVersionPrinter)() = 0;
995 class VersionPrinter {
998 cout << "Low Level Virtual Machine (http://llvm.org/):\n";
999 cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1000 #ifdef LLVM_VERSION_INFO
1001 cout << LLVM_VERSION_INFO;
1004 #ifndef __OPTIMIZE__
1005 cout << "DEBUG build";
1007 cout << "Optimized build";
1010 cout << " with assertions";
1014 void operator=(bool OptionWasSpecified) {
1015 if (OptionWasSpecified) {
1016 if (OverrideVersionPrinter == 0) {
1020 (*OverrideVersionPrinter)();
1026 } // End anonymous namespace
1029 // Define the --version option that prints out the LLVM version for the tool
1030 static VersionPrinter VersionPrinterInstance;
1032 static cl::opt<VersionPrinter, true, parser<bool> >
1033 VersOp("version", cl::desc("Display the version of this program"),
1034 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1036 // Utility function for printing the help message.
1037 void cl::PrintHelpMessage() {
1038 // This looks weird, but it actually prints the help message. The
1039 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1040 // its operator= is invoked. That's because the "normal" usages of the
1041 // help printer is to be assigned true/false depending on whether the
1042 // --help option was given or not. Since we're circumventing that we have
1043 // to make it look like --help was given, so we assign true.
1044 NormalPrinter = true;
1047 /// Utility function for printing version number.
1048 void cl::PrintVersionMessage() {
1049 VersionPrinterInstance.print();
1052 void cl::SetVersionPrinter(void (*func)()) {
1053 OverrideVersionPrinter = func;