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/System/Path.h"
34 //===----------------------------------------------------------------------===//
35 // Template instantiations and anchors.
37 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
38 TEMPLATE_INSTANTIATION(class basic_parser<int>);
39 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
40 TEMPLATE_INSTANTIATION(class basic_parser<double>);
41 TEMPLATE_INSTANTIATION(class basic_parser<float>);
42 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
44 TEMPLATE_INSTANTIATION(class opt<unsigned>);
45 TEMPLATE_INSTANTIATION(class opt<int>);
46 TEMPLATE_INSTANTIATION(class opt<std::string>);
47 TEMPLATE_INSTANTIATION(class opt<bool>);
49 void Option::anchor() {}
50 void basic_parser_impl::anchor() {}
51 void parser<bool>::anchor() {}
52 void parser<int>::anchor() {}
53 void parser<unsigned>::anchor() {}
54 void parser<double>::anchor() {}
55 void parser<float>::anchor() {}
56 void parser<std::string>::anchor() {}
58 //===----------------------------------------------------------------------===//
60 // Globals for name and overview of program. Program name is not a string to
61 // avoid static ctor/dtor issues.
62 static char ProgramName[80] = "<premain>";
63 static const char *ProgramOverview = 0;
65 // This collects additional help to be printed.
66 static ManagedStatic<std::vector<const char*> > MoreHelp;
68 extrahelp::extrahelp(const char *Help)
70 MoreHelp->push_back(Help);
73 //===----------------------------------------------------------------------===//
74 // Basic, shared command line option processing machinery.
77 static ManagedStatic<std::map<std::string, Option*> > Options;
78 static ManagedStatic<std::vector<Option*> > PositionalOptions;
80 static Option *getOption(const std::string &Str) {
81 std::map<std::string,Option*>::iterator I = Options->find(Str);
82 return I != Options->end() ? I->second : 0;
85 static void AddArgument(const char *ArgName, Option *Opt) {
86 if (getOption(ArgName)) {
87 std::cerr << ProgramName << ": CommandLine Error: Argument '"
88 << ArgName << "' defined more than once!\n";
90 // Add argument to the argument map!
91 (*Options)[ArgName] = Opt;
95 // RemoveArgument - It's possible that the argument is no longer in the map if
96 // options have already been processed and the map has been deleted!
98 static void RemoveArgument(const char *ArgName, Option *Opt) {
99 if (Options->empty()) return;
102 // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
103 // If we pass ArgName directly into getOption here.
104 std::string Tmp = ArgName;
105 assert(getOption(Tmp) == Opt && "Arg not in map!");
107 Options->erase(ArgName);
110 static inline bool ProvideOption(Option *Handler, const char *ArgName,
111 const char *Value, int argc, char **argv,
113 // Enforce value requirements
114 switch (Handler->getValueExpectedFlag()) {
116 if (Value == 0) { // No value specified?
117 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
120 return Handler->error(" requires a value!");
124 case ValueDisallowed:
126 return Handler->error(" does not allow a value! '" +
127 std::string(Value) + "' specified.");
132 std::cerr << ProgramName
133 << ": Bad ValueMask flag! CommandLine usage error:"
134 << Handler->getValueExpectedFlag() << "\n";
139 // Run the handler now!
140 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
143 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
146 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
150 // Option predicates...
151 static inline bool isGrouping(const Option *O) {
152 return O->getFormattingFlag() == cl::Grouping;
154 static inline bool isPrefixedOrGrouping(const Option *O) {
155 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
158 // getOptionPred - Check to see if there are any options that satisfy the
159 // specified predicate with names that are the prefixes in Name. This is
160 // checked by progressively stripping characters off of the name, checking to
161 // see if there options that satisfy the predicate. If we find one, return it,
162 // otherwise return null.
164 static Option *getOptionPred(std::string Name, unsigned &Length,
165 bool (*Pred)(const Option*)) {
167 Option *Op = getOption(Name);
168 if (Op && Pred(Op)) {
169 Length = Name.length();
173 if (Name.size() == 1) return 0;
175 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
176 Op = getOption(Name);
178 // Loop while we haven't found an option and Name still has at least two
179 // characters in it (so that the next iteration will not be the empty
181 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
183 if (Op && Pred(Op)) {
184 Length = Name.length();
185 return Op; // Found one!
187 return 0; // No option found!
190 static bool RequiresValue(const Option *O) {
191 return O->getNumOccurrencesFlag() == cl::Required ||
192 O->getNumOccurrencesFlag() == cl::OneOrMore;
195 static bool EatsUnboundedNumberOfValues(const Option *O) {
196 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
197 O->getNumOccurrencesFlag() == cl::OneOrMore;
200 /// ParseCStringVector - Break INPUT up wherever one or more
201 /// whitespace characters are found, and store the resulting tokens in
202 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
203 /// using strdup (), so it is the caller's responsibility to free ()
206 static void ParseCStringVector(std::vector<char *> &output,
208 // Characters which will be treated as token separators:
209 static const char *delims = " \v\f\t\r\n";
211 std::string work (input);
212 // Skip past any delims at head of input string.
213 size_t pos = work.find_first_not_of (delims);
214 // If the string consists entirely of delims, then exit early.
215 if (pos == std::string::npos) return;
216 // Otherwise, jump forward to beginning of first word.
217 work = work.substr (pos);
218 // Find position of first delimiter.
219 pos = work.find_first_of (delims);
221 while (!work.empty() && pos != std::string::npos) {
222 // Everything from 0 to POS is the next word to copy.
223 output.push_back (strdup (work.substr (0,pos).c_str ()));
224 // Is there another word in the string?
225 size_t nextpos = work.find_first_not_of (delims, pos + 1);
226 if (nextpos != std::string::npos) {
227 // Yes? Then remove delims from beginning ...
228 work = work.substr (work.find_first_not_of (delims, pos + 1));
229 // and find the end of the word.
230 pos = work.find_first_of (delims);
232 // No? (Remainder of string is delims.) End the loop.
234 pos = std::string::npos;
238 // If `input' ended with non-delim char, then we'll get here with
239 // the last word of `input' in `work'; copy it now.
240 if (!work.empty ()) {
241 output.push_back (strdup (work.c_str ()));
245 /// ParseEnvironmentOptions - An alternative entry point to the
246 /// CommandLine library, which allows you to read the program's name
247 /// from the caller (as PROGNAME) and its command-line arguments from
248 /// an environment variable (whose name is given in ENVVAR).
250 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
251 const char *Overview) {
253 assert(progName && "Program name not specified");
254 assert(envVar && "Environment variable name missing");
256 // Get the environment variable they want us to parse options out of.
257 const char *envValue = getenv(envVar);
261 // Get program's "name", which we wouldn't know without the caller
263 std::vector<char*> newArgv;
264 newArgv.push_back(strdup(progName));
266 // Parse the value of the environment variable into a "command line"
267 // and hand it off to ParseCommandLineOptions().
268 ParseCStringVector(newArgv, envValue);
269 int newArgc = newArgv.size();
270 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
272 // Free all the strdup()ed strings.
273 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
278 /// LookupOption - Lookup the option specified by the specified option on the
279 /// command line. If there is a value specified (after an equal sign) return
281 static Option *LookupOption(const char *&Arg, const char *&Value) {
282 while (*Arg == '-') ++Arg; // Eat leading dashes
284 const char *ArgEnd = Arg;
285 while (*ArgEnd && *ArgEnd != '=')
286 ++ArgEnd; // Scan till end of argument name.
288 if (*ArgEnd == '=') // If we have an equals sign...
289 Value = ArgEnd+1; // Get the value, not the equals
292 if (*Arg == 0) return 0;
294 // Look up the option.
295 std::map<std::string, Option*> &Opts = *Options;
296 std::map<std::string, Option*>::iterator I =
297 Opts.find(std::string(Arg, ArgEnd));
298 return (I != Opts.end()) ? I->second : 0;
301 void cl::ParseCommandLineOptions(int &argc, char **argv,
302 const char *Overview) {
303 assert((!Options->empty() || !PositionalOptions->empty()) &&
304 "No options specified, or ParseCommandLineOptions called more"
306 sys::Path progname(argv[0]);
308 // Copy the program name into ProgName, making sure not to overflow it.
309 std::string ProgName = sys::Path(argv[0]).getLast();
310 if (ProgName.size() > 79) ProgName.resize(79);
311 strcpy(ProgramName, ProgName.c_str());
313 ProgramOverview = Overview;
314 bool ErrorParsing = false;
316 std::map<std::string, Option*> &Opts = *Options;
317 std::vector<Option*> &PositionalOpts = *PositionalOptions;
319 // Check out the positional arguments to collect information about them.
320 unsigned NumPositionalRequired = 0;
322 // Determine whether or not there are an unlimited number of positionals
323 bool HasUnlimitedPositionals = false;
325 Option *ConsumeAfterOpt = 0;
326 if (!PositionalOpts.empty()) {
327 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
328 assert(PositionalOpts.size() > 1 &&
329 "Cannot specify cl::ConsumeAfter without a positional argument!");
330 ConsumeAfterOpt = PositionalOpts[0];
333 // Calculate how many positional values are _required_.
334 bool UnboundedFound = false;
335 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
337 Option *Opt = PositionalOpts[i];
338 if (RequiresValue(Opt))
339 ++NumPositionalRequired;
340 else if (ConsumeAfterOpt) {
341 // ConsumeAfter cannot be combined with "optional" positional options
342 // unless there is only one positional argument...
343 if (PositionalOpts.size() > 2)
345 Opt->error(" error - this positional option will never be matched, "
346 "because it does not Require a value, and a "
347 "cl::ConsumeAfter option is active!");
348 } else if (UnboundedFound && !Opt->ArgStr[0]) {
349 // This option does not "require" a value... Make sure this option is
350 // not specified after an option that eats all extra arguments, or this
351 // one will never get any!
353 ErrorParsing |= Opt->error(" error - option can never match, because "
354 "another positional argument will match an "
355 "unbounded number of values, and this option"
356 " does not require a value!");
358 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
360 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
363 // PositionalVals - A vector of "positional" arguments we accumulate into
364 // the process at the end...
366 std::vector<std::pair<std::string,unsigned> > PositionalVals;
368 // If the program has named positional arguments, and the name has been run
369 // across, keep track of which positional argument was named. Otherwise put
370 // the positional args into the PositionalVals list...
371 Option *ActivePositionalArg = 0;
373 // Loop over all of the arguments... processing them.
374 bool DashDashFound = false; // Have we read '--'?
375 for (int i = 1; i < argc; ++i) {
377 const char *Value = 0;
378 const char *ArgName = "";
380 // Check to see if this is a positional argument. This argument is
381 // considered to be positional if it doesn't start with '-', if it is "-"
382 // itself, or if we have seen "--" already.
384 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
385 // Positional argument!
386 if (ActivePositionalArg) {
387 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
388 continue; // We are done!
389 } else if (!PositionalOpts.empty()) {
390 PositionalVals.push_back(std::make_pair(argv[i],i));
392 // All of the positional arguments have been fulfulled, give the rest to
393 // the consume after option... if it's specified...
395 if (PositionalVals.size() >= NumPositionalRequired &&
396 ConsumeAfterOpt != 0) {
397 for (++i; i < argc; ++i)
398 PositionalVals.push_back(std::make_pair(argv[i],i));
399 break; // Handle outside of the argument processing loop...
402 // Delay processing positional arguments until the end...
405 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
407 DashDashFound = true; // This is the mythical "--"?
408 continue; // Don't try to process it as an argument itself.
409 } else if (ActivePositionalArg &&
410 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
411 // If there is a positional argument eating options, check to see if this
412 // option is another positional argument. If so, treat it as an argument,
413 // otherwise feed it to the eating positional.
415 Handler = LookupOption(ArgName, Value);
416 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
417 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
418 continue; // We are done!
421 } else { // We start with a '-', must be an argument...
423 Handler = LookupOption(ArgName, Value);
425 // Check to see if this "option" is really a prefixed or grouped argument.
427 std::string RealName(ArgName);
428 if (RealName.size() > 1) {
430 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
432 // If the option is a prefixed option, then the value is simply the
433 // rest of the name... so fall through to later processing, by
434 // setting up the argument name flags and value fields.
436 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
437 Value = ArgName+Length;
438 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
439 Opts.find(std::string(ArgName, Value))->second == PGOpt);
442 // This must be a grouped option... handle them now.
443 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
446 // Move current arg name out of RealName into RealArgName...
447 std::string RealArgName(RealName.begin(),
448 RealName.begin() + Length);
449 RealName.erase(RealName.begin(), RealName.begin() + Length);
451 // Because ValueRequired is an invalid flag for grouped arguments,
452 // we don't need to pass argc/argv in...
454 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
455 "Option can not be cl::Grouping AND cl::ValueRequired!");
457 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
460 // Get the next grouping option...
461 PGOpt = getOptionPred(RealName, Length, isGrouping);
462 } while (PGOpt && Length != RealName.size());
464 Handler = PGOpt; // Ate all of the options.
471 std::cerr << ProgramName << ": Unknown command line argument '"
472 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
477 // Check to see if this option accepts a comma separated list of values. If
478 // it does, we have to split up the value into multiple values...
479 if (Value && Handler->getMiscFlags() & CommaSeparated) {
480 std::string Val(Value);
481 std::string::size_type Pos = Val.find(',');
483 while (Pos != std::string::npos) {
484 // Process the portion before the comma...
485 ErrorParsing |= ProvideOption(Handler, ArgName,
486 std::string(Val.begin(),
487 Val.begin()+Pos).c_str(),
489 // Erase the portion before the comma, AND the comma...
490 Val.erase(Val.begin(), Val.begin()+Pos+1);
491 Value += Pos+1; // Increment the original value pointer as well...
493 // Check for another comma...
498 // If this is a named positional argument, just remember that it is the
500 if (Handler->getFormattingFlag() == cl::Positional)
501 ActivePositionalArg = Handler;
503 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
506 // Check and handle positional arguments now...
507 if (NumPositionalRequired > PositionalVals.size()) {
508 std::cerr << ProgramName
509 << ": Not enough positional command line arguments specified!\n"
510 << "Must specify at least " << NumPositionalRequired
511 << " positional arguments: See: " << argv[0] << " --help\n";
514 } else if (!HasUnlimitedPositionals
515 && PositionalVals.size() > PositionalOpts.size()) {
516 std::cerr << ProgramName
517 << ": Too many positional arguments specified!\n"
518 << "Can specify at most " << PositionalOpts.size()
519 << " positional arguments: See: " << argv[0] << " --help\n";
522 } else if (ConsumeAfterOpt == 0) {
523 // Positional args have already been handled if ConsumeAfter is specified...
524 unsigned ValNo = 0, NumVals = PositionalVals.size();
525 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
526 if (RequiresValue(PositionalOpts[i])) {
527 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
528 PositionalVals[ValNo].second);
530 --NumPositionalRequired; // We fulfilled our duty...
533 // If we _can_ give this option more arguments, do so now, as long as we
534 // do not give it values that others need. 'Done' controls whether the
535 // option even _WANTS_ any more.
537 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
538 while (NumVals-ValNo > NumPositionalRequired && !Done) {
539 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
541 Done = true; // Optional arguments want _at most_ one value
543 case cl::ZeroOrMore: // Zero or more will take all they can get...
544 case cl::OneOrMore: // One or more will take all they can get...
545 ProvidePositionalOption(PositionalOpts[i],
546 PositionalVals[ValNo].first,
547 PositionalVals[ValNo].second);
551 assert(0 && "Internal error, unexpected NumOccurrences flag in "
552 "positional argument processing!");
557 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
559 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
560 if (RequiresValue(PositionalOpts[j])) {
561 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
562 PositionalVals[ValNo].first,
563 PositionalVals[ValNo].second);
567 // Handle the case where there is just one positional option, and it's
568 // optional. In this case, we want to give JUST THE FIRST option to the
569 // positional option and keep the rest for the consume after. The above
570 // loop would have assigned no values to positional options in this case.
572 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
573 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
574 PositionalVals[ValNo].first,
575 PositionalVals[ValNo].second);
579 // Handle over all of the rest of the arguments to the
580 // cl::ConsumeAfter command line option...
581 for (; ValNo != PositionalVals.size(); ++ValNo)
582 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
583 PositionalVals[ValNo].first,
584 PositionalVals[ValNo].second);
587 // Loop over args and make sure all required args are specified!
588 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
589 E = Opts.end(); I != E; ++I) {
590 switch (I->second->getNumOccurrencesFlag()) {
593 if (I->second->getNumOccurrences() == 0) {
594 I->second->error(" must be specified at least once!");
603 // Free all of the memory allocated to the map. Command line options may only
604 // be processed once!
606 PositionalOpts.clear();
609 // If we had an error processing our arguments, don't let the program execute
610 if (ErrorParsing) exit(1);
613 //===----------------------------------------------------------------------===//
614 // Option Base class implementation
617 bool Option::error(std::string Message, const char *ArgName) {
618 if (ArgName == 0) ArgName = ArgStr;
620 std::cerr << HelpStr; // Be nice for positional arguments
622 std::cerr << ProgramName << ": for the -" << ArgName;
624 std::cerr << " option: " << Message << "\n";
628 bool Option::addOccurrence(unsigned pos, const char *ArgName,
629 const std::string &Value) {
630 NumOccurrences++; // Increment the number of times we have been seen
632 switch (getNumOccurrencesFlag()) {
634 if (NumOccurrences > 1)
635 return error(": may only occur zero or one times!", ArgName);
638 if (NumOccurrences > 1)
639 return error(": must occur exactly one time!", ArgName);
643 case ConsumeAfter: break;
644 default: return error(": bad num occurrences flag value!");
647 return handleOccurrence(pos, ArgName, Value);
650 // addArgument - Tell the system that this Option subclass will handle all
651 // occurrences of -ArgStr on the command line.
653 void Option::addArgument(const char *ArgStr) {
655 AddArgument(ArgStr, this);
657 if (getFormattingFlag() == Positional)
658 PositionalOptions->push_back(this);
659 else if (getNumOccurrencesFlag() == ConsumeAfter) {
660 if (!PositionalOptions->empty() &&
661 PositionalOptions->front()->getNumOccurrencesFlag() == ConsumeAfter)
662 error("Cannot specify more than one option with cl::ConsumeAfter!");
663 PositionalOptions->insert(PositionalOptions->begin(), this);
667 void Option::removeArgument(const char *ArgStr) {
669 RemoveArgument(ArgStr, this);
671 if (getFormattingFlag() == Positional) {
672 std::vector<Option*>::iterator I =
673 std::find(PositionalOptions->begin(), PositionalOptions->end(), this);
674 assert(I != PositionalOptions->end() && "Arg not registered!");
675 PositionalOptions->erase(I);
676 } else if (getNumOccurrencesFlag() == ConsumeAfter) {
677 assert(!PositionalOptions->empty() && (*PositionalOptions)[0] == this &&
678 "Arg not registered correctly!");
679 PositionalOptions->erase(PositionalOptions->begin());
684 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
685 // has been specified yet.
687 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
688 if (O.ValueStr[0] == 0) return DefaultMsg;
692 //===----------------------------------------------------------------------===//
693 // cl::alias class implementation
696 // Return the width of the option tag for printing...
697 unsigned alias::getOptionWidth() const {
698 return std::strlen(ArgStr)+6;
701 // Print out the option for the alias.
702 void alias::printOptionInfo(unsigned GlobalWidth) const {
703 unsigned L = std::strlen(ArgStr);
704 std::cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
710 //===----------------------------------------------------------------------===//
711 // Parser Implementation code...
714 // basic_parser implementation
717 // Return the width of the option tag for printing...
718 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
719 unsigned Len = std::strlen(O.ArgStr);
720 if (const char *ValName = getValueName())
721 Len += std::strlen(getValueStr(O, ValName))+3;
726 // printOptionInfo - Print out information about this option. The
727 // to-be-maintained width is specified.
729 void basic_parser_impl::printOptionInfo(const Option &O,
730 unsigned GlobalWidth) const {
731 std::cout << " -" << O.ArgStr;
733 if (const char *ValName = getValueName())
734 std::cout << "=<" << getValueStr(O, ValName) << ">";
736 std::cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
737 << O.HelpStr << "\n";
743 // parser<bool> implementation
745 bool parser<bool>::parse(Option &O, const char *ArgName,
746 const std::string &Arg, bool &Value) {
747 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
750 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
753 return O.error(": '" + Arg +
754 "' is invalid value for boolean argument! Try 0 or 1");
759 // parser<int> implementation
761 bool parser<int>::parse(Option &O, const char *ArgName,
762 const std::string &Arg, int &Value) {
764 Value = (int)strtol(Arg.c_str(), &End, 0);
766 return O.error(": '" + Arg + "' value invalid for integer argument!");
770 // parser<unsigned> implementation
772 bool parser<unsigned>::parse(Option &O, const char *ArgName,
773 const std::string &Arg, unsigned &Value) {
776 unsigned long V = strtoul(Arg.c_str(), &End, 0);
778 if (((V == ULONG_MAX) && (errno == ERANGE))
781 return O.error(": '" + Arg + "' value invalid for uint argument!");
785 // parser<double>/parser<float> implementation
787 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
788 const char *ArgStart = Arg.c_str();
790 Value = strtod(ArgStart, &End);
792 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
796 bool parser<double>::parse(Option &O, const char *AN,
797 const std::string &Arg, double &Val) {
798 return parseDouble(O, Arg, Val);
801 bool parser<float>::parse(Option &O, const char *AN,
802 const std::string &Arg, float &Val) {
804 if (parseDouble(O, Arg, dVal))
812 // generic_parser_base implementation
815 // findOption - Return the option number corresponding to the specified
816 // argument string. If the option is not found, getNumOptions() is returned.
818 unsigned generic_parser_base::findOption(const char *Name) {
819 unsigned i = 0, e = getNumOptions();
823 if (getOption(i) == N)
831 // Return the width of the option tag for printing...
832 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
834 unsigned Size = std::strlen(O.ArgStr)+6;
835 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
836 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
839 unsigned BaseSize = 0;
840 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
841 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
846 // printOptionInfo - Print out information about this option. The
847 // to-be-maintained width is specified.
849 void generic_parser_base::printOptionInfo(const Option &O,
850 unsigned GlobalWidth) const {
852 unsigned L = std::strlen(O.ArgStr);
853 std::cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
854 << " - " << O.HelpStr << "\n";
856 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
857 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
858 std::cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
859 << " - " << getDescription(i) << "\n";
863 std::cout << " " << O.HelpStr << "\n";
864 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
865 unsigned L = std::strlen(getOption(i));
866 std::cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
867 << " - " << getDescription(i) << "\n";
873 //===----------------------------------------------------------------------===//
874 // --help and --help-hidden option implementation
881 const Option *EmptyArg;
882 const bool ShowHidden;
884 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
885 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
886 return OptPair.second->getOptionHiddenFlag() >= Hidden;
888 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
889 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
893 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
897 void operator=(bool Value) {
898 if (Value == false) return;
900 // Copy Options into a vector so we can sort them as we like...
901 std::vector<std::pair<std::string, Option*> > Opts;
902 copy(Options->begin(), Options->end(), std::back_inserter(Opts));
904 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
905 Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
906 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
909 // Eliminate duplicate entries in table (from enum flags options, f.e.)
910 { // Give OptionSet a scope
911 std::set<Option*> OptionSet;
912 for (unsigned i = 0; i != Opts.size(); ++i)
913 if (OptionSet.count(Opts[i].second) == 0)
914 OptionSet.insert(Opts[i].second); // Add new entry to set
916 Opts.erase(Opts.begin()+i--); // Erase duplicate
920 std::cout << "OVERVIEW:" << ProgramOverview << "\n";
922 std::cout << "USAGE: " << ProgramName << " [options]";
924 // Print out the positional options.
925 std::vector<Option*> &PosOpts = *PositionalOptions;
926 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
927 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
930 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
931 if (PosOpts[i]->ArgStr[0])
932 std::cout << " --" << PosOpts[i]->ArgStr;
933 std::cout << " " << PosOpts[i]->HelpStr;
936 // Print the consume after option info if it exists...
937 if (CAOpt) std::cout << " " << CAOpt->HelpStr;
941 // Compute the maximum argument length...
943 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
944 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
946 std::cout << "OPTIONS:\n";
947 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
948 Opts[i].second->printOptionInfo(MaxArgLen);
950 // Print any extra help the user has declared.
951 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
952 E = MoreHelp->end(); I != E; ++I)
956 // Halt the program since help information was printed
957 Options->clear(); // Don't bother making option dtors remove from map.
961 } // End anonymous namespace
963 // Define the two HelpPrinter instances that are used to print out help, or
966 static HelpPrinter NormalPrinter(false);
967 static HelpPrinter HiddenPrinter(true);
969 static cl::opt<HelpPrinter, true, parser<bool> >
970 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
971 cl::location(NormalPrinter), cl::ValueDisallowed);
973 static cl::opt<HelpPrinter, true, parser<bool> >
974 HHOp("help-hidden", cl::desc("Display all available options"),
975 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
977 static void (*OverrideVersionPrinter)() = 0;
980 class VersionPrinter {
982 void operator=(bool OptionWasSpecified) {
983 if (OptionWasSpecified) {
984 if (OverrideVersionPrinter == 0) {
985 std::cout << "Low Level Virtual Machine (http://llvm.org/):\n";
986 std::cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
987 #ifdef LLVM_VERSION_INFO
988 std::cout << LLVM_VERSION_INFO;
992 std::cout << "DEBUG build";
994 std::cout << "Optimized build";
997 std::cout << " with assertions";
1000 Options->clear(); // Don't bother making option dtors remove from map.
1003 (*OverrideVersionPrinter)();
1009 } // End anonymous namespace
1012 // Define the --version option that prints out the LLVM version for the tool
1013 static VersionPrinter VersionPrinterInstance;
1015 static cl::opt<VersionPrinter, true, parser<bool> >
1016 VersOp("version", cl::desc("Display the version of this program"),
1017 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1019 // Utility function for printing the help message.
1020 void cl::PrintHelpMessage() {
1021 // This looks weird, but it actually prints the help message. The
1022 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1023 // its operator= is invoked. That's because the "normal" usages of the
1024 // help printer is to be assigned true/false depending on whether the
1025 // --help option was given or not. Since we're circumventing that we have
1026 // to make it look like --help was given, so we assign true.
1027 NormalPrinter = true;
1030 void cl::SetVersionPrinter(void (*func)()) {
1031 OverrideVersionPrinter = func;