1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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"
36 //===----------------------------------------------------------------------===//
37 // Template instantiations and anchors.
39 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
40 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
41 TEMPLATE_INSTANTIATION(class basic_parser<int>);
42 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
43 TEMPLATE_INSTANTIATION(class basic_parser<double>);
44 TEMPLATE_INSTANTIATION(class basic_parser<float>);
45 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
47 TEMPLATE_INSTANTIATION(class opt<unsigned>);
48 TEMPLATE_INSTANTIATION(class opt<int>);
49 TEMPLATE_INSTANTIATION(class opt<std::string>);
50 TEMPLATE_INSTANTIATION(class opt<bool>);
52 void Option::anchor() {}
53 void basic_parser_impl::anchor() {}
54 void parser<bool>::anchor() {}
55 void parser<boolOrDefault>::anchor() {}
56 void parser<int>::anchor() {}
57 void parser<unsigned>::anchor() {}
58 void parser<double>::anchor() {}
59 void parser<float>::anchor() {}
60 void parser<std::string>::anchor() {}
62 //===----------------------------------------------------------------------===//
64 // Globals for name and overview of program. Program name is not a string to
65 // avoid static ctor/dtor issues.
66 static char ProgramName[80] = "<premain>";
67 static const char *ProgramOverview = 0;
69 // This collects additional help to be printed.
70 static ManagedStatic<std::vector<const char*> > MoreHelp;
72 extrahelp::extrahelp(const char *Help)
74 MoreHelp->push_back(Help);
77 static bool OptionListChanged = false;
79 // MarkOptionsChanged - Internal helper function.
80 void cl::MarkOptionsChanged() {
81 OptionListChanged = true;
84 /// RegisteredOptionList - This is the list of the command line options that
85 /// have statically constructed themselves.
86 static Option *RegisteredOptionList = 0;
88 void Option::addArgument() {
89 assert(NextRegistered == 0 && "argument multiply registered!");
91 NextRegistered = RegisteredOptionList;
92 RegisteredOptionList = this;
97 //===----------------------------------------------------------------------===//
98 // Basic, shared command line option processing machinery.
101 /// GetOptionInfo - Scan the list of registered options, turning them into data
102 /// structures that are easier to handle.
103 static void GetOptionInfo(std::vector<Option*> &PositionalOpts,
104 std::map<std::string, Option*> &OptionsMap) {
105 std::vector<const char*> OptionNames;
106 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
107 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
108 // If this option wants to handle multiple option names, get the full set.
109 // This handles enum options like "-O1 -O2" etc.
110 O->getExtraOptionNames(OptionNames);
112 OptionNames.push_back(O->ArgStr);
114 // Handle named options.
115 for (unsigned i = 0, e = OptionNames.size(); i != e; ++i) {
116 // Add argument to the argument map!
117 if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i],
119 cerr << ProgramName << ": CommandLine Error: Argument '"
120 << OptionNames[0] << "' defined more than once!\n";
126 // Remember information about positional options.
127 if (O->getFormattingFlag() == cl::Positional)
128 PositionalOpts.push_back(O);
129 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
131 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
137 PositionalOpts.push_back(CAOpt);
139 // Make sure that they are in order of registration not backwards.
140 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
144 /// LookupOption - Lookup the option specified by the specified option on the
145 /// command line. If there is a value specified (after an equal sign) return
147 static Option *LookupOption(const char *&Arg, const char *&Value,
148 std::map<std::string, Option*> &OptionsMap) {
149 while (*Arg == '-') ++Arg; // Eat leading dashes
151 const char *ArgEnd = Arg;
152 while (*ArgEnd && *ArgEnd != '=')
153 ++ArgEnd; // Scan till end of argument name.
155 if (*ArgEnd == '=') // If we have an equals sign...
156 Value = ArgEnd+1; // Get the value, not the equals
159 if (*Arg == 0) return 0;
161 // Look up the option.
162 std::map<std::string, Option*>::iterator I =
163 OptionsMap.find(std::string(Arg, ArgEnd));
164 return I != OptionsMap.end() ? I->second : 0;
167 static inline bool ProvideOption(Option *Handler, const char *ArgName,
168 const char *Value, int argc, char **argv,
170 // Enforce value requirements
171 switch (Handler->getValueExpectedFlag()) {
173 if (Value == 0) { // No value specified?
174 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
177 return Handler->error(" requires a value!");
181 case ValueDisallowed:
183 return Handler->error(" does not allow a value! '" +
184 std::string(Value) + "' specified.");
190 << ": Bad ValueMask flag! CommandLine usage error:"
191 << Handler->getValueExpectedFlag() << "\n";
196 // Run the handler now!
197 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
200 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
203 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
207 // Option predicates...
208 static inline bool isGrouping(const Option *O) {
209 return O->getFormattingFlag() == cl::Grouping;
211 static inline bool isPrefixedOrGrouping(const Option *O) {
212 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
215 // getOptionPred - Check to see if there are any options that satisfy the
216 // specified predicate with names that are the prefixes in Name. This is
217 // checked by progressively stripping characters off of the name, checking to
218 // see if there options that satisfy the predicate. If we find one, return it,
219 // otherwise return null.
221 static Option *getOptionPred(std::string Name, unsigned &Length,
222 bool (*Pred)(const Option*),
223 std::map<std::string, Option*> &OptionsMap) {
225 std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name);
226 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
227 Length = Name.length();
231 if (Name.size() == 1) return 0;
233 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
234 OMI = OptionsMap.find(Name);
236 // Loop while we haven't found an option and Name still has at least two
237 // characters in it (so that the next iteration will not be the empty
239 } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1);
241 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
242 Length = Name.length();
243 return OMI->second; // Found one!
245 return 0; // No option found!
248 static bool RequiresValue(const Option *O) {
249 return O->getNumOccurrencesFlag() == cl::Required ||
250 O->getNumOccurrencesFlag() == cl::OneOrMore;
253 static bool EatsUnboundedNumberOfValues(const Option *O) {
254 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
255 O->getNumOccurrencesFlag() == cl::OneOrMore;
258 /// ParseCStringVector - Break INPUT up wherever one or more
259 /// whitespace characters are found, and store the resulting tokens in
260 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
261 /// using strdup (), so it is the caller's responsibility to free ()
264 static void ParseCStringVector(std::vector<char *> &output,
266 // Characters which will be treated as token separators:
267 static const char *delims = " \v\f\t\r\n";
269 std::string work (input);
270 // Skip past any delims at head of input string.
271 size_t pos = work.find_first_not_of (delims);
272 // If the string consists entirely of delims, then exit early.
273 if (pos == std::string::npos) return;
274 // Otherwise, jump forward to beginning of first word.
275 work = work.substr (pos);
276 // Find position of first delimiter.
277 pos = work.find_first_of (delims);
279 while (!work.empty() && pos != std::string::npos) {
280 // Everything from 0 to POS is the next word to copy.
281 output.push_back (strdup (work.substr (0,pos).c_str ()));
282 // Is there another word in the string?
283 size_t nextpos = work.find_first_not_of (delims, pos + 1);
284 if (nextpos != std::string::npos) {
285 // Yes? Then remove delims from beginning ...
286 work = work.substr (work.find_first_not_of (delims, pos + 1));
287 // and find the end of the word.
288 pos = work.find_first_of (delims);
290 // No? (Remainder of string is delims.) End the loop.
292 pos = std::string::npos;
296 // If `input' ended with non-delim char, then we'll get here with
297 // the last word of `input' in `work'; copy it now.
298 if (!work.empty ()) {
299 output.push_back (strdup (work.c_str ()));
303 /// ParseEnvironmentOptions - An alternative entry point to the
304 /// CommandLine library, which allows you to read the program's name
305 /// from the caller (as PROGNAME) and its command-line arguments from
306 /// an environment variable (whose name is given in ENVVAR).
308 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
309 const char *Overview) {
311 assert(progName && "Program name not specified");
312 assert(envVar && "Environment variable name missing");
314 // Get the environment variable they want us to parse options out of.
315 const char *envValue = getenv(envVar);
319 // Get program's "name", which we wouldn't know without the caller
321 std::vector<char*> newArgv;
322 newArgv.push_back(strdup(progName));
324 // Parse the value of the environment variable into a "command line"
325 // and hand it off to ParseCommandLineOptions().
326 ParseCStringVector(newArgv, envValue);
327 int newArgc = newArgv.size();
328 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
330 // Free all the strdup()ed strings.
331 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
336 void cl::ParseCommandLineOptions(int argc, char **argv,
337 const char *Overview) {
338 // Process all registered options.
339 std::vector<Option*> PositionalOpts;
340 std::map<std::string, Option*> Opts;
341 GetOptionInfo(PositionalOpts, Opts);
343 assert((!Opts.empty() || !PositionalOpts.empty()) &&
344 "No options specified!");
345 sys::Path progname(argv[0]);
347 // Copy the program name into ProgName, making sure not to overflow it.
348 std::string ProgName = sys::Path(argv[0]).getLast();
349 if (ProgName.size() > 79) ProgName.resize(79);
350 strcpy(ProgramName, ProgName.c_str());
352 ProgramOverview = Overview;
353 bool ErrorParsing = false;
355 // Check out the positional arguments to collect information about them.
356 unsigned NumPositionalRequired = 0;
358 // Determine whether or not there are an unlimited number of positionals
359 bool HasUnlimitedPositionals = false;
361 Option *ConsumeAfterOpt = 0;
362 if (!PositionalOpts.empty()) {
363 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
364 assert(PositionalOpts.size() > 1 &&
365 "Cannot specify cl::ConsumeAfter without a positional argument!");
366 ConsumeAfterOpt = PositionalOpts[0];
369 // Calculate how many positional values are _required_.
370 bool UnboundedFound = false;
371 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
373 Option *Opt = PositionalOpts[i];
374 if (RequiresValue(Opt))
375 ++NumPositionalRequired;
376 else if (ConsumeAfterOpt) {
377 // ConsumeAfter cannot be combined with "optional" positional options
378 // unless there is only one positional argument...
379 if (PositionalOpts.size() > 2)
381 Opt->error(" error - this positional option will never be matched, "
382 "because it does not Require a value, and a "
383 "cl::ConsumeAfter option is active!");
384 } else if (UnboundedFound && !Opt->ArgStr[0]) {
385 // This option does not "require" a value... Make sure this option is
386 // not specified after an option that eats all extra arguments, or this
387 // one will never get any!
389 ErrorParsing |= Opt->error(" error - option can never match, because "
390 "another positional argument will match an "
391 "unbounded number of values, and this option"
392 " does not require a value!");
394 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
396 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
399 // PositionalVals - A vector of "positional" arguments we accumulate into
400 // the process at the end...
402 std::vector<std::pair<std::string,unsigned> > PositionalVals;
404 // If the program has named positional arguments, and the name has been run
405 // across, keep track of which positional argument was named. Otherwise put
406 // the positional args into the PositionalVals list...
407 Option *ActivePositionalArg = 0;
409 // Loop over all of the arguments... processing them.
410 bool DashDashFound = false; // Have we read '--'?
411 for (int i = 1; i < argc; ++i) {
413 const char *Value = 0;
414 const char *ArgName = "";
416 // If the option list changed, this means that some command line
417 // option has just been registered or deregistered. This can occur in
418 // response to things like -load, etc. If this happens, rescan the options.
419 if (OptionListChanged) {
420 PositionalOpts.clear();
422 GetOptionInfo(PositionalOpts, Opts);
423 OptionListChanged = false;
426 // Check to see if this is a positional argument. This argument is
427 // considered to be positional if it doesn't start with '-', if it is "-"
428 // itself, or if we have seen "--" already.
430 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
431 // Positional argument!
432 if (ActivePositionalArg) {
433 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
434 continue; // We are done!
435 } else if (!PositionalOpts.empty()) {
436 PositionalVals.push_back(std::make_pair(argv[i],i));
438 // All of the positional arguments have been fulfulled, give the rest to
439 // the consume after option... if it's specified...
441 if (PositionalVals.size() >= NumPositionalRequired &&
442 ConsumeAfterOpt != 0) {
443 for (++i; i < argc; ++i)
444 PositionalVals.push_back(std::make_pair(argv[i],i));
445 break; // Handle outside of the argument processing loop...
448 // Delay processing positional arguments until the end...
451 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
453 DashDashFound = true; // This is the mythical "--"?
454 continue; // Don't try to process it as an argument itself.
455 } else if (ActivePositionalArg &&
456 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
457 // If there is a positional argument eating options, check to see if this
458 // option is another positional argument. If so, treat it as an argument,
459 // otherwise feed it to the eating positional.
461 Handler = LookupOption(ArgName, Value, Opts);
462 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
463 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
464 continue; // We are done!
467 } else { // We start with a '-', must be an argument...
469 Handler = LookupOption(ArgName, Value, Opts);
471 // Check to see if this "option" is really a prefixed or grouped argument.
473 std::string RealName(ArgName);
474 if (RealName.size() > 1) {
476 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping,
479 // If the option is a prefixed option, then the value is simply the
480 // rest of the name... so fall through to later processing, by
481 // setting up the argument name flags and value fields.
483 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
484 Value = ArgName+Length;
485 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
486 Opts.find(std::string(ArgName, Value))->second == PGOpt);
489 // This must be a grouped option... handle them now.
490 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
493 // Move current arg name out of RealName into RealArgName...
494 std::string RealArgName(RealName.begin(),
495 RealName.begin() + Length);
496 RealName.erase(RealName.begin(), RealName.begin() + Length);
498 // Because ValueRequired is an invalid flag for grouped arguments,
499 // we don't need to pass argc/argv in...
501 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
502 "Option can not be cl::Grouping AND cl::ValueRequired!");
504 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
507 // Get the next grouping option...
508 PGOpt = getOptionPred(RealName, Length, isGrouping, Opts);
509 } while (PGOpt && Length != RealName.size());
511 Handler = PGOpt; // Ate all of the options.
518 cerr << ProgramName << ": Unknown command line argument '"
519 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
524 // Check to see if this option accepts a comma separated list of values. If
525 // it does, we have to split up the value into multiple values...
526 if (Value && Handler->getMiscFlags() & CommaSeparated) {
527 std::string Val(Value);
528 std::string::size_type Pos = Val.find(',');
530 while (Pos != std::string::npos) {
531 // Process the portion before the comma...
532 ErrorParsing |= ProvideOption(Handler, ArgName,
533 std::string(Val.begin(),
534 Val.begin()+Pos).c_str(),
536 // Erase the portion before the comma, AND the comma...
537 Val.erase(Val.begin(), Val.begin()+Pos+1);
538 Value += Pos+1; // Increment the original value pointer as well...
540 // Check for another comma...
545 // If this is a named positional argument, just remember that it is the
547 if (Handler->getFormattingFlag() == cl::Positional)
548 ActivePositionalArg = Handler;
550 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
553 // Check and handle positional arguments now...
554 if (NumPositionalRequired > PositionalVals.size()) {
556 << ": Not enough positional command line arguments specified!\n"
557 << "Must specify at least " << NumPositionalRequired
558 << " positional arguments: See: " << argv[0] << " --help\n";
561 } else if (!HasUnlimitedPositionals
562 && PositionalVals.size() > PositionalOpts.size()) {
564 << ": Too many positional arguments specified!\n"
565 << "Can specify at most " << PositionalOpts.size()
566 << " positional arguments: See: " << argv[0] << " --help\n";
569 } else if (ConsumeAfterOpt == 0) {
570 // Positional args have already been handled if ConsumeAfter is specified...
571 unsigned ValNo = 0, NumVals = PositionalVals.size();
572 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
573 if (RequiresValue(PositionalOpts[i])) {
574 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
575 PositionalVals[ValNo].second);
577 --NumPositionalRequired; // We fulfilled our duty...
580 // If we _can_ give this option more arguments, do so now, as long as we
581 // do not give it values that others need. 'Done' controls whether the
582 // option even _WANTS_ any more.
584 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
585 while (NumVals-ValNo > NumPositionalRequired && !Done) {
586 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
588 Done = true; // Optional arguments want _at most_ one value
590 case cl::ZeroOrMore: // Zero or more will take all they can get...
591 case cl::OneOrMore: // One or more will take all they can get...
592 ProvidePositionalOption(PositionalOpts[i],
593 PositionalVals[ValNo].first,
594 PositionalVals[ValNo].second);
598 assert(0 && "Internal error, unexpected NumOccurrences flag in "
599 "positional argument processing!");
604 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
606 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
607 if (RequiresValue(PositionalOpts[j])) {
608 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
609 PositionalVals[ValNo].first,
610 PositionalVals[ValNo].second);
614 // Handle the case where there is just one positional option, and it's
615 // optional. In this case, we want to give JUST THE FIRST option to the
616 // positional option and keep the rest for the consume after. The above
617 // loop would have assigned no values to positional options in this case.
619 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
620 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
621 PositionalVals[ValNo].first,
622 PositionalVals[ValNo].second);
626 // Handle over all of the rest of the arguments to the
627 // cl::ConsumeAfter command line option...
628 for (; ValNo != PositionalVals.size(); ++ValNo)
629 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
630 PositionalVals[ValNo].first,
631 PositionalVals[ValNo].second);
634 // Loop over args and make sure all required args are specified!
635 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
636 E = Opts.end(); I != E; ++I) {
637 switch (I->second->getNumOccurrencesFlag()) {
640 if (I->second->getNumOccurrences() == 0) {
641 I->second->error(" must be specified at least once!");
650 // Free all of the memory allocated to the map. Command line options may only
651 // be processed once!
653 PositionalOpts.clear();
656 // If we had an error processing our arguments, don't let the program execute
657 if (ErrorParsing) exit(1);
660 //===----------------------------------------------------------------------===//
661 // Option Base class implementation
664 bool Option::error(std::string Message, const char *ArgName) {
665 if (ArgName == 0) ArgName = ArgStr;
667 cerr << HelpStr; // Be nice for positional arguments
669 cerr << ProgramName << ": for the -" << ArgName;
671 cerr << " option: " << Message << "\n";
675 bool Option::addOccurrence(unsigned pos, const char *ArgName,
676 const std::string &Value) {
677 NumOccurrences++; // Increment the number of times we have been seen
679 switch (getNumOccurrencesFlag()) {
681 if (NumOccurrences > 1)
682 return error(": may only occur zero or one times!", ArgName);
685 if (NumOccurrences > 1)
686 return error(": must occur exactly one time!", ArgName);
690 case ConsumeAfter: break;
691 default: return error(": bad num occurrences flag value!");
694 return handleOccurrence(pos, ArgName, Value);
698 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
699 // has been specified yet.
701 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
702 if (O.ValueStr[0] == 0) return DefaultMsg;
706 //===----------------------------------------------------------------------===//
707 // cl::alias class implementation
710 // Return the width of the option tag for printing...
711 unsigned alias::getOptionWidth() const {
712 return std::strlen(ArgStr)+6;
715 // Print out the option for the alias.
716 void alias::printOptionInfo(unsigned GlobalWidth) const {
717 unsigned L = std::strlen(ArgStr);
718 cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
724 //===----------------------------------------------------------------------===//
725 // Parser Implementation code...
728 // basic_parser implementation
731 // Return the width of the option tag for printing...
732 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
733 unsigned Len = std::strlen(O.ArgStr);
734 if (const char *ValName = getValueName())
735 Len += std::strlen(getValueStr(O, ValName))+3;
740 // printOptionInfo - Print out information about this option. The
741 // to-be-maintained width is specified.
743 void basic_parser_impl::printOptionInfo(const Option &O,
744 unsigned GlobalWidth) const {
745 cout << " -" << O.ArgStr;
747 if (const char *ValName = getValueName())
748 cout << "=<" << getValueStr(O, ValName) << ">";
750 cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
751 << O.HelpStr << "\n";
757 // parser<bool> implementation
759 bool parser<bool>::parse(Option &O, const char *ArgName,
760 const std::string &Arg, bool &Value) {
761 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
764 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
767 return O.error(": '" + Arg +
768 "' is invalid value for boolean argument! Try 0 or 1");
773 // parser<boolOrDefault> implementation
775 bool parser<boolOrDefault>::parse(Option &O, const char *ArgName,
776 const std::string &Arg, boolOrDefault &Value) {
777 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
780 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
783 return O.error(": '" + Arg +
784 "' is invalid value for boolean argument! Try 0 or 1");
789 // parser<int> implementation
791 bool parser<int>::parse(Option &O, const char *ArgName,
792 const std::string &Arg, int &Value) {
794 Value = (int)strtol(Arg.c_str(), &End, 0);
796 return O.error(": '" + Arg + "' value invalid for integer argument!");
800 // parser<unsigned> implementation
802 bool parser<unsigned>::parse(Option &O, const char *ArgName,
803 const std::string &Arg, unsigned &Value) {
806 unsigned long V = strtoul(Arg.c_str(), &End, 0);
808 if (((V == ULONG_MAX) && (errno == ERANGE))
811 return O.error(": '" + Arg + "' value invalid for uint argument!");
815 // parser<double>/parser<float> implementation
817 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
818 const char *ArgStart = Arg.c_str();
820 Value = strtod(ArgStart, &End);
822 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
826 bool parser<double>::parse(Option &O, const char *AN,
827 const std::string &Arg, double &Val) {
828 return parseDouble(O, Arg, Val);
831 bool parser<float>::parse(Option &O, const char *AN,
832 const std::string &Arg, float &Val) {
834 if (parseDouble(O, Arg, dVal))
842 // generic_parser_base implementation
845 // findOption - Return the option number corresponding to the specified
846 // argument string. If the option is not found, getNumOptions() is returned.
848 unsigned generic_parser_base::findOption(const char *Name) {
849 unsigned i = 0, e = getNumOptions();
853 if (getOption(i) == N)
861 // Return the width of the option tag for printing...
862 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
864 unsigned Size = std::strlen(O.ArgStr)+6;
865 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
866 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
869 unsigned BaseSize = 0;
870 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
871 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
876 // printOptionInfo - Print out information about this option. The
877 // to-be-maintained width is specified.
879 void generic_parser_base::printOptionInfo(const Option &O,
880 unsigned GlobalWidth) const {
882 unsigned L = std::strlen(O.ArgStr);
883 cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
884 << " - " << O.HelpStr << "\n";
886 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
887 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
888 cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
889 << " - " << getDescription(i) << "\n";
893 cout << " " << O.HelpStr << "\n";
894 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
895 unsigned L = std::strlen(getOption(i));
896 cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
897 << " - " << getDescription(i) << "\n";
903 //===----------------------------------------------------------------------===//
904 // --help and --help-hidden option implementation
911 const Option *EmptyArg;
912 const bool ShowHidden;
914 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
915 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
916 return OptPair.second->getOptionHiddenFlag() >= Hidden;
918 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
919 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
923 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
927 void operator=(bool Value) {
928 if (Value == false) return;
930 // Get all the options.
931 std::vector<Option*> PositionalOpts;
932 std::map<std::string, Option*> OptMap;
933 GetOptionInfo(PositionalOpts, OptMap);
935 // Copy Options into a vector so we can sort them as we like...
936 std::vector<std::pair<std::string, Option*> > Opts;
937 copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts));
939 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
940 Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
941 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
944 // Eliminate duplicate entries in table (from enum flags options, f.e.)
945 { // Give OptionSet a scope
946 std::set<Option*> OptionSet;
947 for (unsigned i = 0; i != Opts.size(); ++i)
948 if (OptionSet.count(Opts[i].second) == 0)
949 OptionSet.insert(Opts[i].second); // Add new entry to set
951 Opts.erase(Opts.begin()+i--); // Erase duplicate
955 cout << "OVERVIEW: " << ProgramOverview << "\n";
957 cout << "USAGE: " << ProgramName << " [options]";
959 // Print out the positional options.
960 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
961 if (!PositionalOpts.empty() &&
962 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
963 CAOpt = PositionalOpts[0];
965 for (unsigned i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
966 if (PositionalOpts[i]->ArgStr[0])
967 cout << " --" << PositionalOpts[i]->ArgStr;
968 cout << " " << PositionalOpts[i]->HelpStr;
971 // Print the consume after option info if it exists...
972 if (CAOpt) cout << " " << CAOpt->HelpStr;
976 // Compute the maximum argument length...
978 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
979 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
981 cout << "OPTIONS:\n";
982 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
983 Opts[i].second->printOptionInfo(MaxArgLen);
985 // Print any extra help the user has declared.
986 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
987 E = MoreHelp->end(); I != E; ++I)
991 // Halt the program since help information was printed
995 } // End anonymous namespace
997 // Define the two HelpPrinter instances that are used to print out help, or
1000 static HelpPrinter NormalPrinter(false);
1001 static HelpPrinter HiddenPrinter(true);
1003 static cl::opt<HelpPrinter, true, parser<bool> >
1004 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
1005 cl::location(NormalPrinter), cl::ValueDisallowed);
1007 static cl::opt<HelpPrinter, true, parser<bool> >
1008 HHOp("help-hidden", cl::desc("Display all available options"),
1009 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1011 static void (*OverrideVersionPrinter)() = 0;
1014 class VersionPrinter {
1017 cout << "Low Level Virtual Machine (http://llvm.org/):\n";
1018 cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1019 #ifdef LLVM_VERSION_INFO
1020 cout << LLVM_VERSION_INFO;
1023 #ifndef __OPTIMIZE__
1024 cout << "DEBUG build";
1026 cout << "Optimized build";
1029 cout << " with assertions";
1033 void operator=(bool OptionWasSpecified) {
1034 if (OptionWasSpecified) {
1035 if (OverrideVersionPrinter == 0) {
1039 (*OverrideVersionPrinter)();
1045 } // End anonymous namespace
1048 // Define the --version option that prints out the LLVM version for the tool
1049 static VersionPrinter VersionPrinterInstance;
1051 static cl::opt<VersionPrinter, true, parser<bool> >
1052 VersOp("version", cl::desc("Display the version of this program"),
1053 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1055 // Utility function for printing the help message.
1056 void cl::PrintHelpMessage() {
1057 // This looks weird, but it actually prints the help message. The
1058 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1059 // its operator= is invoked. That's because the "normal" usages of the
1060 // help printer is to be assigned true/false depending on whether the
1061 // --help option was given or not. Since we're circumventing that we have
1062 // to make it look like --help was given, so we assign true.
1063 NormalPrinter = true;
1066 /// Utility function for printing version number.
1067 void cl::PrintVersionMessage() {
1068 VersionPrinterInstance.print();
1071 void cl::SetVersionPrinter(void (*func)()) {
1072 OverrideVersionPrinter = func;