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::vector<Option*> &SinkOpts,
105 std::map<std::string, Option*> &OptionsMap) {
106 std::vector<const char*> OptionNames;
107 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
108 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
109 // If this option wants to handle multiple option names, get the full set.
110 // This handles enum options like "-O1 -O2" etc.
111 O->getExtraOptionNames(OptionNames);
113 OptionNames.push_back(O->ArgStr);
115 // Handle named options.
116 for (unsigned i = 0, e = OptionNames.size(); i != e; ++i) {
117 // Add argument to the argument map!
118 if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i],
120 cerr << ProgramName << ": CommandLine Error: Argument '"
121 << OptionNames[0] << "' defined more than once!\n";
127 // Remember information about positional options.
128 if (O->getFormattingFlag() == cl::Positional)
129 PositionalOpts.push_back(O);
130 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
131 SinkOpts.push_back(O);
132 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
134 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
140 PositionalOpts.push_back(CAOpt);
142 // Make sure that they are in order of registration not backwards.
143 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
147 /// LookupOption - Lookup the option specified by the specified option on the
148 /// command line. If there is a value specified (after an equal sign) return
150 static Option *LookupOption(const char *&Arg, const char *&Value,
151 std::map<std::string, Option*> &OptionsMap) {
152 while (*Arg == '-') ++Arg; // Eat leading dashes
154 const char *ArgEnd = Arg;
155 while (*ArgEnd && *ArgEnd != '=')
156 ++ArgEnd; // Scan till end of argument name.
158 if (*ArgEnd == '=') // If we have an equals sign...
159 Value = ArgEnd+1; // Get the value, not the equals
162 if (*Arg == 0) return 0;
164 // Look up the option.
165 std::map<std::string, Option*>::iterator I =
166 OptionsMap.find(std::string(Arg, ArgEnd));
167 return I != OptionsMap.end() ? I->second : 0;
170 static inline bool ProvideOption(Option *Handler, const char *ArgName,
171 const char *Value, int argc, char **argv,
173 // Enforce value requirements
174 switch (Handler->getValueExpectedFlag()) {
176 if (Value == 0) { // No value specified?
177 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
180 return Handler->error(" requires a value!");
184 case ValueDisallowed:
186 return Handler->error(" does not allow a value! '" +
187 std::string(Value) + "' specified.");
193 << ": Bad ValueMask flag! CommandLine usage error:"
194 << Handler->getValueExpectedFlag() << "\n";
199 // Run the handler now!
200 return Handler->addOccurrence(i, ArgName, Value ? Value : "");
203 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
206 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
210 // Option predicates...
211 static inline bool isGrouping(const Option *O) {
212 return O->getFormattingFlag() == cl::Grouping;
214 static inline bool isPrefixedOrGrouping(const Option *O) {
215 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
218 // getOptionPred - Check to see if there are any options that satisfy the
219 // specified predicate with names that are the prefixes in Name. This is
220 // checked by progressively stripping characters off of the name, checking to
221 // see if there options that satisfy the predicate. If we find one, return it,
222 // otherwise return null.
224 static Option *getOptionPred(std::string Name, unsigned &Length,
225 bool (*Pred)(const Option*),
226 std::map<std::string, Option*> &OptionsMap) {
228 std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name);
229 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
230 Length = Name.length();
234 if (Name.size() == 1) return 0;
236 Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
237 OMI = OptionsMap.find(Name);
239 // Loop while we haven't found an option and Name still has at least two
240 // characters in it (so that the next iteration will not be the empty
242 } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1);
244 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
245 Length = Name.length();
246 return OMI->second; // Found one!
248 return 0; // No option found!
251 static bool RequiresValue(const Option *O) {
252 return O->getNumOccurrencesFlag() == cl::Required ||
253 O->getNumOccurrencesFlag() == cl::OneOrMore;
256 static bool EatsUnboundedNumberOfValues(const Option *O) {
257 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
258 O->getNumOccurrencesFlag() == cl::OneOrMore;
261 /// ParseCStringVector - Break INPUT up wherever one or more
262 /// whitespace characters are found, and store the resulting tokens in
263 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
264 /// using strdup (), so it is the caller's responsibility to free ()
267 static void ParseCStringVector(std::vector<char *> &output,
269 // Characters which will be treated as token separators:
270 static const char *delims = " \v\f\t\r\n";
272 std::string work (input);
273 // Skip past any delims at head of input string.
274 size_t pos = work.find_first_not_of (delims);
275 // If the string consists entirely of delims, then exit early.
276 if (pos == std::string::npos) return;
277 // Otherwise, jump forward to beginning of first word.
278 work = work.substr (pos);
279 // Find position of first delimiter.
280 pos = work.find_first_of (delims);
282 while (!work.empty() && pos != std::string::npos) {
283 // Everything from 0 to POS is the next word to copy.
284 output.push_back (strdup (work.substr (0,pos).c_str ()));
285 // Is there another word in the string?
286 size_t nextpos = work.find_first_not_of (delims, pos + 1);
287 if (nextpos != std::string::npos) {
288 // Yes? Then remove delims from beginning ...
289 work = work.substr (work.find_first_not_of (delims, pos + 1));
290 // and find the end of the word.
291 pos = work.find_first_of (delims);
293 // No? (Remainder of string is delims.) End the loop.
295 pos = std::string::npos;
299 // If `input' ended with non-delim char, then we'll get here with
300 // the last word of `input' in `work'; copy it now.
301 if (!work.empty ()) {
302 output.push_back (strdup (work.c_str ()));
306 /// ParseEnvironmentOptions - An alternative entry point to the
307 /// CommandLine library, which allows you to read the program's name
308 /// from the caller (as PROGNAME) and its command-line arguments from
309 /// an environment variable (whose name is given in ENVVAR).
311 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
312 const char *Overview) {
314 assert(progName && "Program name not specified");
315 assert(envVar && "Environment variable name missing");
317 // Get the environment variable they want us to parse options out of.
318 const char *envValue = getenv(envVar);
322 // Get program's "name", which we wouldn't know without the caller
324 std::vector<char*> newArgv;
325 newArgv.push_back(strdup(progName));
327 // Parse the value of the environment variable into a "command line"
328 // and hand it off to ParseCommandLineOptions().
329 ParseCStringVector(newArgv, envValue);
330 int newArgc = newArgv.size();
331 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
333 // Free all the strdup()ed strings.
334 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
339 void cl::ParseCommandLineOptions(int argc, char **argv,
340 const char *Overview) {
341 // Process all registered options.
342 std::vector<Option*> PositionalOpts;
343 std::vector<Option*> SinkOpts;
344 std::map<std::string, Option*> Opts;
345 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
347 assert((!Opts.empty() || !PositionalOpts.empty()) &&
348 "No options specified!");
349 sys::Path progname(argv[0]);
351 // Copy the program name into ProgName, making sure not to overflow it.
352 std::string ProgName = sys::Path(argv[0]).getLast();
353 if (ProgName.size() > 79) ProgName.resize(79);
354 strcpy(ProgramName, ProgName.c_str());
356 ProgramOverview = Overview;
357 bool ErrorParsing = false;
359 // Check out the positional arguments to collect information about them.
360 unsigned NumPositionalRequired = 0;
362 // Determine whether or not there are an unlimited number of positionals
363 bool HasUnlimitedPositionals = false;
365 Option *ConsumeAfterOpt = 0;
366 if (!PositionalOpts.empty()) {
367 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
368 assert(PositionalOpts.size() > 1 &&
369 "Cannot specify cl::ConsumeAfter without a positional argument!");
370 ConsumeAfterOpt = PositionalOpts[0];
373 // Calculate how many positional values are _required_.
374 bool UnboundedFound = false;
375 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
377 Option *Opt = PositionalOpts[i];
378 if (RequiresValue(Opt))
379 ++NumPositionalRequired;
380 else if (ConsumeAfterOpt) {
381 // ConsumeAfter cannot be combined with "optional" positional options
382 // unless there is only one positional argument...
383 if (PositionalOpts.size() > 2)
385 Opt->error(" error - this positional option will never be matched, "
386 "because it does not Require a value, and a "
387 "cl::ConsumeAfter option is active!");
388 } else if (UnboundedFound && !Opt->ArgStr[0]) {
389 // This option does not "require" a value... Make sure this option is
390 // not specified after an option that eats all extra arguments, or this
391 // one will never get any!
393 ErrorParsing |= Opt->error(" error - option can never match, because "
394 "another positional argument will match an "
395 "unbounded number of values, and this option"
396 " does not require a value!");
398 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
400 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
403 // PositionalVals - A vector of "positional" arguments we accumulate into
404 // the process at the end...
406 std::vector<std::pair<std::string,unsigned> > PositionalVals;
408 // If the program has named positional arguments, and the name has been run
409 // across, keep track of which positional argument was named. Otherwise put
410 // the positional args into the PositionalVals list...
411 Option *ActivePositionalArg = 0;
413 // Loop over all of the arguments... processing them.
414 bool DashDashFound = false; // Have we read '--'?
415 for (int i = 1; i < argc; ++i) {
417 const char *Value = 0;
418 const char *ArgName = "";
420 // If the option list changed, this means that some command line
421 // option has just been registered or deregistered. This can occur in
422 // response to things like -load, etc. If this happens, rescan the options.
423 if (OptionListChanged) {
424 PositionalOpts.clear();
427 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
428 OptionListChanged = false;
431 // Check to see if this is a positional argument. This argument is
432 // considered to be positional if it doesn't start with '-', if it is "-"
433 // itself, or if we have seen "--" already.
435 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
436 // Positional argument!
437 if (ActivePositionalArg) {
438 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
439 continue; // We are done!
440 } else if (!PositionalOpts.empty()) {
441 PositionalVals.push_back(std::make_pair(argv[i],i));
443 // All of the positional arguments have been fulfulled, give the rest to
444 // the consume after option... if it's specified...
446 if (PositionalVals.size() >= NumPositionalRequired &&
447 ConsumeAfterOpt != 0) {
448 for (++i; i < argc; ++i)
449 PositionalVals.push_back(std::make_pair(argv[i],i));
450 break; // Handle outside of the argument processing loop...
453 // Delay processing positional arguments until the end...
456 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
458 DashDashFound = true; // This is the mythical "--"?
459 continue; // Don't try to process it as an argument itself.
460 } else if (ActivePositionalArg &&
461 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
462 // If there is a positional argument eating options, check to see if this
463 // option is another positional argument. If so, treat it as an argument,
464 // otherwise feed it to the eating positional.
466 Handler = LookupOption(ArgName, Value, Opts);
467 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
468 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
469 continue; // We are done!
472 } else { // We start with a '-', must be an argument...
474 Handler = LookupOption(ArgName, Value, Opts);
476 // Check to see if this "option" is really a prefixed or grouped argument.
478 std::string RealName(ArgName);
479 if (RealName.size() > 1) {
481 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping,
484 // If the option is a prefixed option, then the value is simply the
485 // rest of the name... so fall through to later processing, by
486 // setting up the argument name flags and value fields.
488 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
489 Value = ArgName+Length;
490 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
491 Opts.find(std::string(ArgName, Value))->second == PGOpt);
494 // This must be a grouped option... handle them now.
495 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
498 // Move current arg name out of RealName into RealArgName...
499 std::string RealArgName(RealName.begin(),
500 RealName.begin() + Length);
501 RealName.erase(RealName.begin(), RealName.begin() + Length);
503 // Because ValueRequired is an invalid flag for grouped arguments,
504 // we don't need to pass argc/argv in...
506 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
507 "Option can not be cl::Grouping AND cl::ValueRequired!");
509 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
512 // Get the next grouping option...
513 PGOpt = getOptionPred(RealName, Length, isGrouping, Opts);
514 } while (PGOpt && Length != RealName.size());
516 Handler = PGOpt; // Ate all of the options.
523 if (SinkOpts.empty()) {
524 cerr << ProgramName << ": Unknown command line argument '"
525 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
528 for (std::vector<Option*>::iterator I = SinkOpts.begin(),
529 E = SinkOpts.end(); I != E ; ++I)
530 (*I)->addOccurrence(i, "", argv[i]);
535 // Check to see if this option accepts a comma separated list of values. If
536 // it does, we have to split up the value into multiple values...
537 if (Value && Handler->getMiscFlags() & CommaSeparated) {
538 std::string Val(Value);
539 std::string::size_type Pos = Val.find(',');
541 while (Pos != std::string::npos) {
542 // Process the portion before the comma...
543 ErrorParsing |= ProvideOption(Handler, ArgName,
544 std::string(Val.begin(),
545 Val.begin()+Pos).c_str(),
547 // Erase the portion before the comma, AND the comma...
548 Val.erase(Val.begin(), Val.begin()+Pos+1);
549 Value += Pos+1; // Increment the original value pointer as well...
551 // Check for another comma...
556 // If this is a named positional argument, just remember that it is the
558 if (Handler->getFormattingFlag() == cl::Positional)
559 ActivePositionalArg = Handler;
561 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
564 // Check and handle positional arguments now...
565 if (NumPositionalRequired > PositionalVals.size()) {
567 << ": Not enough positional command line arguments specified!\n"
568 << "Must specify at least " << NumPositionalRequired
569 << " positional arguments: See: " << argv[0] << " --help\n";
572 } else if (!HasUnlimitedPositionals
573 && PositionalVals.size() > PositionalOpts.size()) {
575 << ": Too many positional arguments specified!\n"
576 << "Can specify at most " << PositionalOpts.size()
577 << " positional arguments: See: " << argv[0] << " --help\n";
580 } else if (ConsumeAfterOpt == 0) {
581 // Positional args have already been handled if ConsumeAfter is specified...
582 unsigned ValNo = 0, NumVals = PositionalVals.size();
583 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
584 if (RequiresValue(PositionalOpts[i])) {
585 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
586 PositionalVals[ValNo].second);
588 --NumPositionalRequired; // We fulfilled our duty...
591 // If we _can_ give this option more arguments, do so now, as long as we
592 // do not give it values that others need. 'Done' controls whether the
593 // option even _WANTS_ any more.
595 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
596 while (NumVals-ValNo > NumPositionalRequired && !Done) {
597 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
599 Done = true; // Optional arguments want _at most_ one value
601 case cl::ZeroOrMore: // Zero or more will take all they can get...
602 case cl::OneOrMore: // One or more will take all they can get...
603 ProvidePositionalOption(PositionalOpts[i],
604 PositionalVals[ValNo].first,
605 PositionalVals[ValNo].second);
609 assert(0 && "Internal error, unexpected NumOccurrences flag in "
610 "positional argument processing!");
615 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
617 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
618 if (RequiresValue(PositionalOpts[j])) {
619 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
620 PositionalVals[ValNo].first,
621 PositionalVals[ValNo].second);
625 // Handle the case where there is just one positional option, and it's
626 // optional. In this case, we want to give JUST THE FIRST option to the
627 // positional option and keep the rest for the consume after. The above
628 // loop would have assigned no values to positional options in this case.
630 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
631 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
632 PositionalVals[ValNo].first,
633 PositionalVals[ValNo].second);
637 // Handle over all of the rest of the arguments to the
638 // cl::ConsumeAfter command line option...
639 for (; ValNo != PositionalVals.size(); ++ValNo)
640 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
641 PositionalVals[ValNo].first,
642 PositionalVals[ValNo].second);
645 // Loop over args and make sure all required args are specified!
646 for (std::map<std::string, Option*>::iterator I = Opts.begin(),
647 E = Opts.end(); I != E; ++I) {
648 switch (I->second->getNumOccurrencesFlag()) {
651 if (I->second->getNumOccurrences() == 0) {
652 I->second->error(" must be specified at least once!");
661 // Free all of the memory allocated to the map. Command line options may only
662 // be processed once!
664 PositionalOpts.clear();
667 // If we had an error processing our arguments, don't let the program execute
668 if (ErrorParsing) exit(1);
671 //===----------------------------------------------------------------------===//
672 // Option Base class implementation
675 bool Option::error(std::string Message, const char *ArgName) {
676 if (ArgName == 0) ArgName = ArgStr;
678 cerr << HelpStr; // Be nice for positional arguments
680 cerr << ProgramName << ": for the -" << ArgName;
682 cerr << " option: " << Message << "\n";
686 bool Option::addOccurrence(unsigned pos, const char *ArgName,
687 const std::string &Value) {
688 NumOccurrences++; // Increment the number of times we have been seen
690 switch (getNumOccurrencesFlag()) {
692 if (NumOccurrences > 1)
693 return error(": may only occur zero or one times!", ArgName);
696 if (NumOccurrences > 1)
697 return error(": must occur exactly one time!", ArgName);
701 case ConsumeAfter: break;
702 default: return error(": bad num occurrences flag value!");
705 return handleOccurrence(pos, ArgName, Value);
709 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
710 // has been specified yet.
712 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
713 if (O.ValueStr[0] == 0) return DefaultMsg;
717 //===----------------------------------------------------------------------===//
718 // cl::alias class implementation
721 // Return the width of the option tag for printing...
722 unsigned alias::getOptionWidth() const {
723 return std::strlen(ArgStr)+6;
726 // Print out the option for the alias.
727 void alias::printOptionInfo(unsigned GlobalWidth) const {
728 unsigned L = std::strlen(ArgStr);
729 cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
735 //===----------------------------------------------------------------------===//
736 // Parser Implementation code...
739 // basic_parser implementation
742 // Return the width of the option tag for printing...
743 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
744 unsigned Len = std::strlen(O.ArgStr);
745 if (const char *ValName = getValueName())
746 Len += std::strlen(getValueStr(O, ValName))+3;
751 // printOptionInfo - Print out information about this option. The
752 // to-be-maintained width is specified.
754 void basic_parser_impl::printOptionInfo(const Option &O,
755 unsigned GlobalWidth) const {
756 cout << " -" << O.ArgStr;
758 if (const char *ValName = getValueName())
759 cout << "=<" << getValueStr(O, ValName) << ">";
761 cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
762 << O.HelpStr << "\n";
768 // parser<bool> implementation
770 bool parser<bool>::parse(Option &O, const char *ArgName,
771 const std::string &Arg, bool &Value) {
772 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
775 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
778 return O.error(": '" + Arg +
779 "' is invalid value for boolean argument! Try 0 or 1");
784 // parser<boolOrDefault> implementation
786 bool parser<boolOrDefault>::parse(Option &O, const char *ArgName,
787 const std::string &Arg, boolOrDefault &Value) {
788 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
791 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
794 return O.error(": '" + Arg +
795 "' is invalid value for boolean argument! Try 0 or 1");
800 // parser<int> implementation
802 bool parser<int>::parse(Option &O, const char *ArgName,
803 const std::string &Arg, int &Value) {
805 Value = (int)strtol(Arg.c_str(), &End, 0);
807 return O.error(": '" + Arg + "' value invalid for integer argument!");
811 // parser<unsigned> implementation
813 bool parser<unsigned>::parse(Option &O, const char *ArgName,
814 const std::string &Arg, unsigned &Value) {
817 unsigned long V = strtoul(Arg.c_str(), &End, 0);
819 if (((V == ULONG_MAX) && (errno == ERANGE))
822 return O.error(": '" + Arg + "' value invalid for uint argument!");
826 // parser<double>/parser<float> implementation
828 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
829 const char *ArgStart = Arg.c_str();
831 Value = strtod(ArgStart, &End);
833 return O.error(": '" +Arg+ "' value invalid for floating point argument!");
837 bool parser<double>::parse(Option &O, const char *AN,
838 const std::string &Arg, double &Val) {
839 return parseDouble(O, Arg, Val);
842 bool parser<float>::parse(Option &O, const char *AN,
843 const std::string &Arg, float &Val) {
845 if (parseDouble(O, Arg, dVal))
853 // generic_parser_base implementation
856 // findOption - Return the option number corresponding to the specified
857 // argument string. If the option is not found, getNumOptions() is returned.
859 unsigned generic_parser_base::findOption(const char *Name) {
860 unsigned i = 0, e = getNumOptions();
864 if (getOption(i) == N)
872 // Return the width of the option tag for printing...
873 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
875 unsigned Size = std::strlen(O.ArgStr)+6;
876 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
877 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
880 unsigned BaseSize = 0;
881 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
882 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
887 // printOptionInfo - Print out information about this option. The
888 // to-be-maintained width is specified.
890 void generic_parser_base::printOptionInfo(const Option &O,
891 unsigned GlobalWidth) const {
893 unsigned L = std::strlen(O.ArgStr);
894 cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
895 << " - " << O.HelpStr << "\n";
897 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
898 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
899 cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
900 << " - " << getDescription(i) << "\n";
904 cout << " " << O.HelpStr << "\n";
905 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
906 unsigned L = std::strlen(getOption(i));
907 cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
908 << " - " << getDescription(i) << "\n";
914 //===----------------------------------------------------------------------===//
915 // --help and --help-hidden option implementation
922 const Option *EmptyArg;
923 const bool ShowHidden;
925 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
926 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
927 return OptPair.second->getOptionHiddenFlag() >= Hidden;
929 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
930 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
934 HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
938 void operator=(bool Value) {
939 if (Value == false) return;
941 // Get all the options.
942 std::vector<Option*> PositionalOpts;
943 std::vector<Option*> SinkOpts;
944 std::map<std::string, Option*> OptMap;
945 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
947 // Copy Options into a vector so we can sort them as we like...
948 std::vector<std::pair<std::string, Option*> > Opts;
949 copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts));
951 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
952 Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
953 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
956 // Eliminate duplicate entries in table (from enum flags options, f.e.)
957 { // Give OptionSet a scope
958 std::set<Option*> OptionSet;
959 for (unsigned i = 0; i != Opts.size(); ++i)
960 if (OptionSet.count(Opts[i].second) == 0)
961 OptionSet.insert(Opts[i].second); // Add new entry to set
963 Opts.erase(Opts.begin()+i--); // Erase duplicate
967 cout << "OVERVIEW: " << ProgramOverview << "\n";
969 cout << "USAGE: " << ProgramName << " [options]";
971 // Print out the positional options.
972 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
973 if (!PositionalOpts.empty() &&
974 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
975 CAOpt = PositionalOpts[0];
977 for (unsigned i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
978 if (PositionalOpts[i]->ArgStr[0])
979 cout << " --" << PositionalOpts[i]->ArgStr;
980 cout << " " << PositionalOpts[i]->HelpStr;
983 // Print the consume after option info if it exists...
984 if (CAOpt) cout << " " << CAOpt->HelpStr;
988 // Compute the maximum argument length...
990 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
991 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
993 cout << "OPTIONS:\n";
994 for (unsigned i = 0, e = Opts.size(); i != e; ++i)
995 Opts[i].second->printOptionInfo(MaxArgLen);
997 // Print any extra help the user has declared.
998 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
999 E = MoreHelp->end(); I != E; ++I)
1003 // Halt the program since help information was printed
1007 } // End anonymous namespace
1009 // Define the two HelpPrinter instances that are used to print out help, or
1012 static HelpPrinter NormalPrinter(false);
1013 static HelpPrinter HiddenPrinter(true);
1015 static cl::opt<HelpPrinter, true, parser<bool> >
1016 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
1017 cl::location(NormalPrinter), cl::ValueDisallowed);
1019 static cl::opt<HelpPrinter, true, parser<bool> >
1020 HHOp("help-hidden", cl::desc("Display all available options"),
1021 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1023 static void (*OverrideVersionPrinter)() = 0;
1026 class VersionPrinter {
1029 cout << "Low Level Virtual Machine (http://llvm.org/):\n";
1030 cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1031 #ifdef LLVM_VERSION_INFO
1032 cout << LLVM_VERSION_INFO;
1035 #ifndef __OPTIMIZE__
1036 cout << "DEBUG build";
1038 cout << "Optimized build";
1041 cout << " with assertions";
1045 void operator=(bool OptionWasSpecified) {
1046 if (OptionWasSpecified) {
1047 if (OverrideVersionPrinter == 0) {
1051 (*OverrideVersionPrinter)();
1057 } // End anonymous namespace
1060 // Define the --version option that prints out the LLVM version for the tool
1061 static VersionPrinter VersionPrinterInstance;
1063 static cl::opt<VersionPrinter, true, parser<bool> >
1064 VersOp("version", cl::desc("Display the version of this program"),
1065 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1067 // Utility function for printing the help message.
1068 void cl::PrintHelpMessage() {
1069 // This looks weird, but it actually prints the help message. The
1070 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1071 // its operator= is invoked. That's because the "normal" usages of the
1072 // help printer is to be assigned true/false depending on whether the
1073 // --help option was given or not. Since we're circumventing that we have
1074 // to make it look like --help was given, so we assign true.
1075 NormalPrinter = true;
1078 /// Utility function for printing version number.
1079 void cl::PrintVersionMessage() {
1080 VersionPrinterInstance.print();
1083 void cl::SetVersionPrinter(void (*func)()) {
1084 OverrideVersionPrinter = func;