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/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Support/system_error.h"
26 #include "llvm/Support/Host.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Config/config.h"
39 //===----------------------------------------------------------------------===//
40 // Template instantiations and anchors.
42 namespace llvm { namespace cl {
43 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
44 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
45 TEMPLATE_INSTANTIATION(class basic_parser<int>);
46 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
47 TEMPLATE_INSTANTIATION(class basic_parser<double>);
48 TEMPLATE_INSTANTIATION(class basic_parser<float>);
49 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
50 TEMPLATE_INSTANTIATION(class basic_parser<char>);
52 TEMPLATE_INSTANTIATION(class opt<unsigned>);
53 TEMPLATE_INSTANTIATION(class opt<int>);
54 TEMPLATE_INSTANTIATION(class opt<std::string>);
55 TEMPLATE_INSTANTIATION(class opt<char>);
56 TEMPLATE_INSTANTIATION(class opt<bool>);
57 } } // end namespace llvm::cl
59 void Option::anchor() {}
60 void basic_parser_impl::anchor() {}
61 void parser<bool>::anchor() {}
62 void parser<boolOrDefault>::anchor() {}
63 void parser<int>::anchor() {}
64 void parser<unsigned>::anchor() {}
65 void parser<double>::anchor() {}
66 void parser<float>::anchor() {}
67 void parser<std::string>::anchor() {}
68 void parser<char>::anchor() {}
70 //===----------------------------------------------------------------------===//
72 // Globals for name and overview of program. Program name is not a string to
73 // avoid static ctor/dtor issues.
74 static char ProgramName[80] = "<premain>";
75 static const char *ProgramOverview = 0;
77 // This collects additional help to be printed.
78 static ManagedStatic<std::vector<const char*> > MoreHelp;
80 extrahelp::extrahelp(const char *Help)
82 MoreHelp->push_back(Help);
85 static bool OptionListChanged = false;
87 // MarkOptionsChanged - Internal helper function.
88 void cl::MarkOptionsChanged() {
89 OptionListChanged = true;
92 /// RegisteredOptionList - This is the list of the command line options that
93 /// have statically constructed themselves.
94 static Option *RegisteredOptionList = 0;
96 void Option::addArgument() {
97 assert(NextRegistered == 0 && "argument multiply registered!");
99 NextRegistered = RegisteredOptionList;
100 RegisteredOptionList = this;
101 MarkOptionsChanged();
105 //===----------------------------------------------------------------------===//
106 // Basic, shared command line option processing machinery.
109 /// GetOptionInfo - Scan the list of registered options, turning them into data
110 /// structures that are easier to handle.
111 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
112 SmallVectorImpl<Option*> &SinkOpts,
113 StringMap<Option*> &OptionsMap) {
114 SmallVector<const char*, 16> OptionNames;
115 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
116 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
117 // If this option wants to handle multiple option names, get the full set.
118 // This handles enum options like "-O1 -O2" etc.
119 O->getExtraOptionNames(OptionNames);
121 OptionNames.push_back(O->ArgStr);
123 // Handle named options.
124 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
125 // Add argument to the argument map!
126 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
127 errs() << ProgramName << ": CommandLine Error: Argument '"
128 << OptionNames[i] << "' defined more than once!\n";
134 // Remember information about positional options.
135 if (O->getFormattingFlag() == cl::Positional)
136 PositionalOpts.push_back(O);
137 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
138 SinkOpts.push_back(O);
139 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
141 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
147 PositionalOpts.push_back(CAOpt);
149 // Make sure that they are in order of registration not backwards.
150 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
154 /// LookupOption - Lookup the option specified by the specified option on the
155 /// command line. If there is a value specified (after an equal sign) return
156 /// that as well. This assumes that leading dashes have already been stripped.
157 static Option *LookupOption(StringRef &Arg, StringRef &Value,
158 const StringMap<Option*> &OptionsMap) {
159 // Reject all dashes.
160 if (Arg.empty()) return 0;
162 size_t EqualPos = Arg.find('=');
164 // If we have an equals sign, remember the value.
165 if (EqualPos == StringRef::npos) {
166 // Look up the option.
167 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
168 return I != OptionsMap.end() ? I->second : 0;
171 // If the argument before the = is a valid option name, we match. If not,
172 // return Arg unmolested.
173 StringMap<Option*>::const_iterator I =
174 OptionsMap.find(Arg.substr(0, EqualPos));
175 if (I == OptionsMap.end()) return 0;
177 Value = Arg.substr(EqualPos+1);
178 Arg = Arg.substr(0, EqualPos);
182 /// LookupNearestOption - Lookup the closest match to the option specified by
183 /// the specified option on the command line. If there is a value specified
184 /// (after an equal sign) return that as well. This assumes that leading dashes
185 /// have already been stripped.
186 static Option *LookupNearestOption(StringRef Arg,
187 const StringMap<Option*> &OptionsMap,
188 std::string &NearestString) {
189 // Reject all dashes.
190 if (Arg.empty()) return 0;
192 // Split on any equal sign.
193 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
194 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
195 StringRef &RHS = SplitArg.second;
197 // Find the closest match.
199 unsigned BestDistance = 0;
200 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
201 ie = OptionsMap.end(); it != ie; ++it) {
202 Option *O = it->second;
203 SmallVector<const char*, 16> OptionNames;
204 O->getExtraOptionNames(OptionNames);
206 OptionNames.push_back(O->ArgStr);
208 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
209 StringRef Flag = PermitValue ? LHS : Arg;
210 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
211 StringRef Name = OptionNames[i];
212 unsigned Distance = StringRef(Name).edit_distance(
213 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
214 if (!Best || Distance < BestDistance) {
216 BestDistance = Distance;
217 if (RHS.empty() || !PermitValue)
218 NearestString = OptionNames[i];
220 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
228 /// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
229 /// does special handling of cl::CommaSeparated options.
230 static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
232 StringRef Value, bool MultiArg = false)
234 // Check to see if this option accepts a comma separated list of values. If
235 // it does, we have to split up the value into multiple values.
236 if (Handler->getMiscFlags() & CommaSeparated) {
237 StringRef Val(Value);
238 StringRef::size_type Pos = Val.find(',');
240 while (Pos != StringRef::npos) {
241 // Process the portion before the comma.
242 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
244 // Erase the portion before the comma, AND the comma.
245 Val = Val.substr(Pos+1);
246 Value.substr(Pos+1); // Increment the original value pointer as well.
247 // Check for another comma.
254 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
260 /// ProvideOption - For Value, this differentiates between an empty value ("")
261 /// and a null value (StringRef()). The later is accepted for arguments that
262 /// don't allow a value (-foo) the former is rejected (-foo=).
263 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
264 StringRef Value, int argc, char **argv,
266 // Is this a multi-argument option?
267 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
269 // Enforce value requirements
270 switch (Handler->getValueExpectedFlag()) {
272 if (Value.data() == 0) { // No value specified?
274 return Handler->error("requires a value!");
275 // Steal the next argument, like for '-o filename'
279 case ValueDisallowed:
280 if (NumAdditionalVals > 0)
281 return Handler->error("multi-valued option specified"
282 " with ValueDisallowed modifier!");
285 return Handler->error("does not allow a value! '" +
286 Twine(Value) + "' specified.");
292 errs() << ProgramName
293 << ": Bad ValueMask flag! CommandLine usage error:"
294 << Handler->getValueExpectedFlag() << "\n";
298 // If this isn't a multi-arg option, just run the handler.
299 if (NumAdditionalVals == 0)
300 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
302 // If it is, run the handle several times.
303 bool MultiArg = false;
306 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
312 while (NumAdditionalVals > 0) {
314 return Handler->error("not enough values!");
317 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
325 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
327 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
331 // Option predicates...
332 static inline bool isGrouping(const Option *O) {
333 return O->getFormattingFlag() == cl::Grouping;
335 static inline bool isPrefixedOrGrouping(const Option *O) {
336 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
339 // getOptionPred - Check to see if there are any options that satisfy the
340 // specified predicate with names that are the prefixes in Name. This is
341 // checked by progressively stripping characters off of the name, checking to
342 // see if there options that satisfy the predicate. If we find one, return it,
343 // otherwise return null.
345 static Option *getOptionPred(StringRef Name, size_t &Length,
346 bool (*Pred)(const Option*),
347 const StringMap<Option*> &OptionsMap) {
349 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
351 // Loop while we haven't found an option and Name still has at least two
352 // characters in it (so that the next iteration will not be the empty
354 while (OMI == OptionsMap.end() && Name.size() > 1) {
355 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
356 OMI = OptionsMap.find(Name);
359 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
360 Length = Name.size();
361 return OMI->second; // Found one!
363 return 0; // No option found!
366 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
367 /// with at least one '-') does not fully match an available option. Check to
368 /// see if this is a prefix or grouped option. If so, split arg into output an
369 /// Arg/Value pair and return the Option to parse it with.
370 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
372 const StringMap<Option*> &OptionsMap) {
373 if (Arg.size() == 1) return 0;
377 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
378 if (PGOpt == 0) return 0;
380 // If the option is a prefixed option, then the value is simply the
381 // rest of the name... so fall through to later processing, by
382 // setting up the argument name flags and value fields.
383 if (PGOpt->getFormattingFlag() == cl::Prefix) {
384 Value = Arg.substr(Length);
385 Arg = Arg.substr(0, Length);
386 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
390 // This must be a grouped option... handle them now. Grouping options can't
392 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
395 // Move current arg name out of Arg into OneArgName.
396 StringRef OneArgName = Arg.substr(0, Length);
397 Arg = Arg.substr(Length);
399 // Because ValueRequired is an invalid flag for grouped arguments,
400 // we don't need to pass argc/argv in.
401 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
402 "Option can not be cl::Grouping AND cl::ValueRequired!");
404 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
405 StringRef(), 0, 0, Dummy);
407 // Get the next grouping option.
408 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
409 } while (PGOpt && Length != Arg.size());
411 // Return the last option with Arg cut down to just the last one.
417 static bool RequiresValue(const Option *O) {
418 return O->getNumOccurrencesFlag() == cl::Required ||
419 O->getNumOccurrencesFlag() == cl::OneOrMore;
422 static bool EatsUnboundedNumberOfValues(const Option *O) {
423 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
424 O->getNumOccurrencesFlag() == cl::OneOrMore;
427 /// ParseCStringVector - Break INPUT up wherever one or more
428 /// whitespace characters are found, and store the resulting tokens in
429 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
430 /// using strdup(), so it is the caller's responsibility to free()
433 static void ParseCStringVector(std::vector<char *> &OutputVector,
435 // Characters which will be treated as token separators:
436 StringRef Delims = " \v\f\t\r\n";
438 StringRef WorkStr(Input);
439 while (!WorkStr.empty()) {
440 // If the first character is a delimiter, strip them off.
441 if (Delims.find(WorkStr[0]) != StringRef::npos) {
442 size_t Pos = WorkStr.find_first_not_of(Delims);
443 if (Pos == StringRef::npos) Pos = WorkStr.size();
444 WorkStr = WorkStr.substr(Pos);
448 // Find position of first delimiter.
449 size_t Pos = WorkStr.find_first_of(Delims);
450 if (Pos == StringRef::npos) Pos = WorkStr.size();
452 // Everything from 0 to Pos is the next word to copy.
453 char *NewStr = (char*)malloc(Pos+1);
454 memcpy(NewStr, WorkStr.data(), Pos);
456 OutputVector.push_back(NewStr);
458 WorkStr = WorkStr.substr(Pos);
462 /// ParseEnvironmentOptions - An alternative entry point to the
463 /// CommandLine library, which allows you to read the program's name
464 /// from the caller (as PROGNAME) and its command-line arguments from
465 /// an environment variable (whose name is given in ENVVAR).
467 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
468 const char *Overview, bool ReadResponseFiles) {
470 assert(progName && "Program name not specified");
471 assert(envVar && "Environment variable name missing");
473 // Get the environment variable they want us to parse options out of.
474 const char *envValue = getenv(envVar);
478 // Get program's "name", which we wouldn't know without the caller
480 std::vector<char*> newArgv;
481 newArgv.push_back(strdup(progName));
483 // Parse the value of the environment variable into a "command line"
484 // and hand it off to ParseCommandLineOptions().
485 ParseCStringVector(newArgv, envValue);
486 int newArgc = static_cast<int>(newArgv.size());
487 ParseCommandLineOptions(newArgc, &newArgv[0], Overview, ReadResponseFiles);
489 // Free all the strdup()ed strings.
490 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
496 /// ExpandResponseFiles - Copy the contents of argv into newArgv,
497 /// substituting the contents of the response files for the arguments
499 static void ExpandResponseFiles(unsigned argc, char** argv,
500 std::vector<char*>& newArgv) {
501 for (unsigned i = 1; i != argc; ++i) {
505 sys::PathWithStatus respFile(++arg);
507 // Check that the response file is not empty (mmap'ing empty
508 // files can be problematic).
509 const sys::FileStatus *FileStat = respFile.getFileStatus();
510 if (FileStat && FileStat->getSize() != 0) {
512 // If we could open the file, parse its contents, otherwise
513 // pass the @file option verbatim.
515 // TODO: we should also support recursive loading of response files,
516 // since this is how gcc behaves. (From their man page: "The file may
517 // itself contain additional @file options; any such options will be
518 // processed recursively.")
520 // Mmap the response file into memory.
521 OwningPtr<MemoryBuffer> respFilePtr;
522 if (!MemoryBuffer::getFile(respFile.c_str(), respFilePtr)) {
523 ParseCStringVector(newArgv, respFilePtr->getBufferStart());
528 newArgv.push_back(strdup(arg));
532 void cl::ParseCommandLineOptions(int argc, char **argv,
533 const char *Overview, bool ReadResponseFiles) {
534 // Process all registered options.
535 SmallVector<Option*, 4> PositionalOpts;
536 SmallVector<Option*, 4> SinkOpts;
537 StringMap<Option*> Opts;
538 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
540 assert((!Opts.empty() || !PositionalOpts.empty()) &&
541 "No options specified!");
543 // Expand response files.
544 std::vector<char*> newArgv;
545 if (ReadResponseFiles) {
546 newArgv.push_back(strdup(argv[0]));
547 ExpandResponseFiles(argc, argv, newArgv);
549 argc = static_cast<int>(newArgv.size());
552 // Copy the program name into ProgName, making sure not to overflow it.
553 std::string ProgName = sys::path::filename(argv[0]);
554 size_t Len = std::min(ProgName.size(), size_t(79));
555 memcpy(ProgramName, ProgName.data(), Len);
556 ProgramName[Len] = '\0';
558 ProgramOverview = Overview;
559 bool ErrorParsing = false;
561 // Check out the positional arguments to collect information about them.
562 unsigned NumPositionalRequired = 0;
564 // Determine whether or not there are an unlimited number of positionals
565 bool HasUnlimitedPositionals = false;
567 Option *ConsumeAfterOpt = 0;
568 if (!PositionalOpts.empty()) {
569 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
570 assert(PositionalOpts.size() > 1 &&
571 "Cannot specify cl::ConsumeAfter without a positional argument!");
572 ConsumeAfterOpt = PositionalOpts[0];
575 // Calculate how many positional values are _required_.
576 bool UnboundedFound = false;
577 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
579 Option *Opt = PositionalOpts[i];
580 if (RequiresValue(Opt))
581 ++NumPositionalRequired;
582 else if (ConsumeAfterOpt) {
583 // ConsumeAfter cannot be combined with "optional" positional options
584 // unless there is only one positional argument...
585 if (PositionalOpts.size() > 2)
587 Opt->error("error - this positional option will never be matched, "
588 "because it does not Require a value, and a "
589 "cl::ConsumeAfter option is active!");
590 } else if (UnboundedFound && !Opt->ArgStr[0]) {
591 // This option does not "require" a value... Make sure this option is
592 // not specified after an option that eats all extra arguments, or this
593 // one will never get any!
595 ErrorParsing |= Opt->error("error - option can never match, because "
596 "another positional argument will match an "
597 "unbounded number of values, and this option"
598 " does not require a value!");
600 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
602 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
605 // PositionalVals - A vector of "positional" arguments we accumulate into
606 // the process at the end.
608 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
610 // If the program has named positional arguments, and the name has been run
611 // across, keep track of which positional argument was named. Otherwise put
612 // the positional args into the PositionalVals list...
613 Option *ActivePositionalArg = 0;
615 // Loop over all of the arguments... processing them.
616 bool DashDashFound = false; // Have we read '--'?
617 for (int i = 1; i < argc; ++i) {
619 Option *NearestHandler = 0;
620 std::string NearestHandlerString;
622 StringRef ArgName = "";
624 // If the option list changed, this means that some command line
625 // option has just been registered or deregistered. This can occur in
626 // response to things like -load, etc. If this happens, rescan the options.
627 if (OptionListChanged) {
628 PositionalOpts.clear();
631 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
632 OptionListChanged = false;
635 // Check to see if this is a positional argument. This argument is
636 // considered to be positional if it doesn't start with '-', if it is "-"
637 // itself, or if we have seen "--" already.
639 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
640 // Positional argument!
641 if (ActivePositionalArg) {
642 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
643 continue; // We are done!
646 if (!PositionalOpts.empty()) {
647 PositionalVals.push_back(std::make_pair(argv[i],i));
649 // All of the positional arguments have been fulfulled, give the rest to
650 // the consume after option... if it's specified...
652 if (PositionalVals.size() >= NumPositionalRequired &&
653 ConsumeAfterOpt != 0) {
654 for (++i; i < argc; ++i)
655 PositionalVals.push_back(std::make_pair(argv[i],i));
656 break; // Handle outside of the argument processing loop...
659 // Delay processing positional arguments until the end...
662 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
664 DashDashFound = true; // This is the mythical "--"?
665 continue; // Don't try to process it as an argument itself.
666 } else if (ActivePositionalArg &&
667 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
668 // If there is a positional argument eating options, check to see if this
669 // option is another positional argument. If so, treat it as an argument,
670 // otherwise feed it to the eating positional.
672 // Eat leading dashes.
673 while (!ArgName.empty() && ArgName[0] == '-')
674 ArgName = ArgName.substr(1);
676 Handler = LookupOption(ArgName, Value, Opts);
677 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
678 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
679 continue; // We are done!
682 } else { // We start with a '-', must be an argument.
684 // Eat leading dashes.
685 while (!ArgName.empty() && ArgName[0] == '-')
686 ArgName = ArgName.substr(1);
688 Handler = LookupOption(ArgName, Value, Opts);
690 // Check to see if this "option" is really a prefixed or grouped argument.
692 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
695 // Otherwise, look for the closest available option to report to the user
696 // in the upcoming error.
697 if (Handler == 0 && SinkOpts.empty())
698 NearestHandler = LookupNearestOption(ArgName, Opts,
699 NearestHandlerString);
703 if (SinkOpts.empty()) {
704 errs() << ProgramName << ": Unknown command line argument '"
705 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
707 if (NearestHandler) {
708 // If we know a near match, report it as well.
709 errs() << ProgramName << ": Did you mean '-"
710 << NearestHandlerString << "'?\n";
715 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
716 E = SinkOpts.end(); I != E ; ++I)
717 (*I)->addOccurrence(i, "", argv[i]);
722 // If this is a named positional argument, just remember that it is the
724 if (Handler->getFormattingFlag() == cl::Positional)
725 ActivePositionalArg = Handler;
727 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
730 // Check and handle positional arguments now...
731 if (NumPositionalRequired > PositionalVals.size()) {
732 errs() << ProgramName
733 << ": Not enough positional command line arguments specified!\n"
734 << "Must specify at least " << NumPositionalRequired
735 << " positional arguments: See: " << argv[0] << " -help\n";
738 } else if (!HasUnlimitedPositionals &&
739 PositionalVals.size() > PositionalOpts.size()) {
740 errs() << ProgramName
741 << ": Too many positional arguments specified!\n"
742 << "Can specify at most " << PositionalOpts.size()
743 << " positional arguments: See: " << argv[0] << " -help\n";
746 } else if (ConsumeAfterOpt == 0) {
747 // Positional args have already been handled if ConsumeAfter is specified.
748 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
749 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
750 if (RequiresValue(PositionalOpts[i])) {
751 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
752 PositionalVals[ValNo].second);
754 --NumPositionalRequired; // We fulfilled our duty...
757 // If we _can_ give this option more arguments, do so now, as long as we
758 // do not give it values that others need. 'Done' controls whether the
759 // option even _WANTS_ any more.
761 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
762 while (NumVals-ValNo > NumPositionalRequired && !Done) {
763 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
765 Done = true; // Optional arguments want _at most_ one value
767 case cl::ZeroOrMore: // Zero or more will take all they can get...
768 case cl::OneOrMore: // One or more will take all they can get...
769 ProvidePositionalOption(PositionalOpts[i],
770 PositionalVals[ValNo].first,
771 PositionalVals[ValNo].second);
775 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
776 "positional argument processing!");
781 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
783 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
784 if (RequiresValue(PositionalOpts[j])) {
785 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
786 PositionalVals[ValNo].first,
787 PositionalVals[ValNo].second);
791 // Handle the case where there is just one positional option, and it's
792 // optional. In this case, we want to give JUST THE FIRST option to the
793 // positional option and keep the rest for the consume after. The above
794 // loop would have assigned no values to positional options in this case.
796 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
797 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
798 PositionalVals[ValNo].first,
799 PositionalVals[ValNo].second);
803 // Handle over all of the rest of the arguments to the
804 // cl::ConsumeAfter command line option...
805 for (; ValNo != PositionalVals.size(); ++ValNo)
806 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
807 PositionalVals[ValNo].first,
808 PositionalVals[ValNo].second);
811 // Loop over args and make sure all required args are specified!
812 for (StringMap<Option*>::iterator I = Opts.begin(),
813 E = Opts.end(); I != E; ++I) {
814 switch (I->second->getNumOccurrencesFlag()) {
817 if (I->second->getNumOccurrences() == 0) {
818 I->second->error("must be specified at least once!");
827 // Now that we know if -debug is specified, we can use it.
828 // Note that if ReadResponseFiles == true, this must be done before the
829 // memory allocated for the expanded command line is free()d below.
830 DEBUG(dbgs() << "Args: ";
831 for (int i = 0; i < argc; ++i)
832 dbgs() << argv[i] << ' ';
836 // Free all of the memory allocated to the map. Command line options may only
837 // be processed once!
839 PositionalOpts.clear();
842 // Free the memory allocated by ExpandResponseFiles.
843 if (ReadResponseFiles) {
844 // Free all the strdup()ed strings.
845 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
850 // If we had an error processing our arguments, don't let the program execute
851 if (ErrorParsing) exit(1);
854 //===----------------------------------------------------------------------===//
855 // Option Base class implementation
858 bool Option::error(const Twine &Message, StringRef ArgName) {
859 if (ArgName.data() == 0) ArgName = ArgStr;
861 errs() << HelpStr; // Be nice for positional arguments
863 errs() << ProgramName << ": for the -" << ArgName;
865 errs() << " option: " << Message << "\n";
869 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
870 StringRef Value, bool MultiArg) {
872 NumOccurrences++; // Increment the number of times we have been seen
874 switch (getNumOccurrencesFlag()) {
876 if (NumOccurrences > 1)
877 return error("may only occur zero or one times!", ArgName);
880 if (NumOccurrences > 1)
881 return error("must occur exactly one time!", ArgName);
885 case ConsumeAfter: break;
886 default: return error("bad num occurrences flag value!");
889 return handleOccurrence(pos, ArgName, Value);
893 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
894 // has been specified yet.
896 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
897 if (O.ValueStr[0] == 0) return DefaultMsg;
901 //===----------------------------------------------------------------------===//
902 // cl::alias class implementation
905 // Return the width of the option tag for printing...
906 size_t alias::getOptionWidth() const {
907 return std::strlen(ArgStr)+6;
910 // Print out the option for the alias.
911 void alias::printOptionInfo(size_t GlobalWidth) const {
912 size_t L = std::strlen(ArgStr);
913 outs() << " -" << ArgStr;
914 outs().indent(GlobalWidth-L-6) << " - " << HelpStr << "\n";
917 //===----------------------------------------------------------------------===//
918 // Parser Implementation code...
921 // basic_parser implementation
924 // Return the width of the option tag for printing...
925 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
926 size_t Len = std::strlen(O.ArgStr);
927 if (const char *ValName = getValueName())
928 Len += std::strlen(getValueStr(O, ValName))+3;
933 // printOptionInfo - Print out information about this option. The
934 // to-be-maintained width is specified.
936 void basic_parser_impl::printOptionInfo(const Option &O,
937 size_t GlobalWidth) const {
938 outs() << " -" << O.ArgStr;
940 if (const char *ValName = getValueName())
941 outs() << "=<" << getValueStr(O, ValName) << '>';
943 outs().indent(GlobalWidth-getOptionWidth(O)) << " - " << O.HelpStr << '\n';
946 void basic_parser_impl::printOptionName(const Option &O,
947 size_t GlobalWidth) const {
948 outs() << " -" << O.ArgStr;
949 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
953 // parser<bool> implementation
955 bool parser<bool>::parse(Option &O, StringRef ArgName,
956 StringRef Arg, bool &Value) {
957 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
963 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
967 return O.error("'" + Arg +
968 "' is invalid value for boolean argument! Try 0 or 1");
971 // parser<boolOrDefault> implementation
973 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
974 StringRef Arg, boolOrDefault &Value) {
975 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
980 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
985 return O.error("'" + Arg +
986 "' is invalid value for boolean argument! Try 0 or 1");
989 // parser<int> implementation
991 bool parser<int>::parse(Option &O, StringRef ArgName,
992 StringRef Arg, int &Value) {
993 if (Arg.getAsInteger(0, Value))
994 return O.error("'" + Arg + "' value invalid for integer argument!");
998 // parser<unsigned> implementation
1000 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1001 StringRef Arg, unsigned &Value) {
1003 if (Arg.getAsInteger(0, Value))
1004 return O.error("'" + Arg + "' value invalid for uint argument!");
1008 // parser<double>/parser<float> implementation
1010 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1011 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1012 const char *ArgStart = TmpStr.c_str();
1014 Value = strtod(ArgStart, &End);
1016 return O.error("'" + Arg + "' value invalid for floating point argument!");
1020 bool parser<double>::parse(Option &O, StringRef ArgName,
1021 StringRef Arg, double &Val) {
1022 return parseDouble(O, Arg, Val);
1025 bool parser<float>::parse(Option &O, StringRef ArgName,
1026 StringRef Arg, float &Val) {
1028 if (parseDouble(O, Arg, dVal))
1036 // generic_parser_base implementation
1039 // findOption - Return the option number corresponding to the specified
1040 // argument string. If the option is not found, getNumOptions() is returned.
1042 unsigned generic_parser_base::findOption(const char *Name) {
1043 unsigned e = getNumOptions();
1045 for (unsigned i = 0; i != e; ++i) {
1046 if (strcmp(getOption(i), Name) == 0)
1053 // Return the width of the option tag for printing...
1054 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1055 if (O.hasArgStr()) {
1056 size_t Size = std::strlen(O.ArgStr)+6;
1057 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1058 Size = std::max(Size, std::strlen(getOption(i))+8);
1061 size_t BaseSize = 0;
1062 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1063 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1068 // printOptionInfo - Print out information about this option. The
1069 // to-be-maintained width is specified.
1071 void generic_parser_base::printOptionInfo(const Option &O,
1072 size_t GlobalWidth) const {
1073 if (O.hasArgStr()) {
1074 size_t L = std::strlen(O.ArgStr);
1075 outs() << " -" << O.ArgStr;
1076 outs().indent(GlobalWidth-L-6) << " - " << O.HelpStr << '\n';
1078 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1079 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1080 outs() << " =" << getOption(i);
1081 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1085 outs() << " " << O.HelpStr << '\n';
1086 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1087 size_t L = std::strlen(getOption(i));
1088 outs() << " -" << getOption(i);
1089 outs().indent(GlobalWidth-L-8) << " - " << getDescription(i) << '\n';
1094 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1096 // printGenericOptionDiff - Print the value of this option and it's default.
1098 // "Generic" options have each value mapped to a name.
1099 void generic_parser_base::
1100 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1101 const GenericOptionValue &Default,
1102 size_t GlobalWidth) const {
1103 outs() << " -" << O.ArgStr;
1104 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1106 unsigned NumOpts = getNumOptions();
1107 for (unsigned i = 0; i != NumOpts; ++i) {
1108 if (Value.compare(getOptionValue(i)))
1111 outs() << "= " << getOption(i);
1112 size_t L = std::strlen(getOption(i));
1113 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1114 outs().indent(NumSpaces) << " (default: ";
1115 for (unsigned j = 0; j != NumOpts; ++j) {
1116 if (Default.compare(getOptionValue(j)))
1118 outs() << getOption(j);
1124 outs() << "= *unknown option value*\n";
1127 // printOptionDiff - Specializations for printing basic value types.
1129 #define PRINT_OPT_DIFF(T) \
1131 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1132 size_t GlobalWidth) const { \
1133 printOptionName(O, GlobalWidth); \
1136 raw_string_ostream SS(Str); \
1139 outs() << "= " << Str; \
1140 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1141 outs().indent(NumSpaces) << " (default: "; \
1143 outs() << D.getValue(); \
1145 outs() << "*no default*"; \
1149 PRINT_OPT_DIFF(bool)
1150 PRINT_OPT_DIFF(boolOrDefault)
1152 PRINT_OPT_DIFF(unsigned)
1153 PRINT_OPT_DIFF(double)
1154 PRINT_OPT_DIFF(float)
1155 PRINT_OPT_DIFF(char)
1157 void parser<std::string>::
1158 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1159 size_t GlobalWidth) const {
1160 printOptionName(O, GlobalWidth);
1161 outs() << "= " << V;
1162 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1163 outs().indent(NumSpaces) << " (default: ";
1165 outs() << D.getValue();
1167 outs() << "*no default*";
1171 // Print a placeholder for options that don't yet support printOptionDiff().
1172 void basic_parser_impl::
1173 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1174 printOptionName(O, GlobalWidth);
1175 outs() << "= *cannot print option value*\n";
1178 //===----------------------------------------------------------------------===//
1179 // -help and -help-hidden option implementation
1182 static int OptNameCompare(const void *LHS, const void *RHS) {
1183 typedef std::pair<const char *, Option*> pair_ty;
1185 return strcmp(((pair_ty*)LHS)->first, ((pair_ty*)RHS)->first);
1188 // Copy Options into a vector so we can sort them as we like.
1190 sortOpts(StringMap<Option*> &OptMap,
1191 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1193 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1195 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1197 // Ignore really-hidden options.
1198 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1201 // Unless showhidden is set, ignore hidden flags.
1202 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1205 // If we've already seen this option, don't add it to the list again.
1206 if (!OptionSet.insert(I->second))
1209 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1213 // Sort the options list alphabetically.
1214 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1221 const Option *EmptyArg;
1222 const bool ShowHidden;
1225 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
1229 void operator=(bool Value) {
1230 if (Value == false) return;
1232 // Get all the options.
1233 SmallVector<Option*, 4> PositionalOpts;
1234 SmallVector<Option*, 4> SinkOpts;
1235 StringMap<Option*> OptMap;
1236 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1238 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1239 sortOpts(OptMap, Opts, ShowHidden);
1241 if (ProgramOverview)
1242 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1244 outs() << "USAGE: " << ProgramName << " [options]";
1246 // Print out the positional options.
1247 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
1248 if (!PositionalOpts.empty() &&
1249 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1250 CAOpt = PositionalOpts[0];
1252 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1253 if (PositionalOpts[i]->ArgStr[0])
1254 outs() << " --" << PositionalOpts[i]->ArgStr;
1255 outs() << " " << PositionalOpts[i]->HelpStr;
1258 // Print the consume after option info if it exists...
1259 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1263 // Compute the maximum argument length...
1265 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1266 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1268 outs() << "OPTIONS:\n";
1269 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1270 Opts[i].second->printOptionInfo(MaxArgLen);
1272 // Print any extra help the user has declared.
1273 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1274 E = MoreHelp->end(); I != E; ++I)
1278 // Halt the program since help information was printed
1282 } // End anonymous namespace
1284 // Define the two HelpPrinter instances that are used to print out help, or
1287 static HelpPrinter NormalPrinter(false);
1288 static HelpPrinter HiddenPrinter(true);
1290 static cl::opt<HelpPrinter, true, parser<bool> >
1291 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1292 cl::location(NormalPrinter), cl::ValueDisallowed);
1294 static cl::opt<HelpPrinter, true, parser<bool> >
1295 HHOp("help-hidden", cl::desc("Display all available options"),
1296 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1298 static cl::opt<bool>
1299 PrintOptions("print-options",
1300 cl::desc("Print non-default options after command line parsing"),
1301 cl::Hidden, cl::init(false));
1303 static cl::opt<bool>
1304 PrintAllOptions("print-all-options",
1305 cl::desc("Print all option values after command line parsing"),
1306 cl::Hidden, cl::init(false));
1308 // Print the value of each option.
1309 void cl::PrintOptionValues() {
1310 if (!PrintOptions && !PrintAllOptions) return;
1312 // Get all the options.
1313 SmallVector<Option*, 4> PositionalOpts;
1314 SmallVector<Option*, 4> SinkOpts;
1315 StringMap<Option*> OptMap;
1316 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1318 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1319 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1321 // Compute the maximum argument length...
1322 size_t MaxArgLen = 0;
1323 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1324 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1326 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1327 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1330 static void (*OverrideVersionPrinter)() = 0;
1332 static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1335 class VersionPrinter {
1338 raw_ostream &OS = outs();
1339 OS << "Low Level Virtual Machine (http://llvm.org/):\n"
1340 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1341 #ifdef LLVM_VERSION_INFO
1342 OS << LLVM_VERSION_INFO;
1345 #ifndef __OPTIMIZE__
1346 OS << "DEBUG build";
1348 OS << "Optimized build";
1351 OS << " with assertions";
1353 std::string CPU = sys::getHostCPUName();
1354 if (CPU == "generic") CPU = "(unknown)";
1356 #if (ENABLE_TIMESTAMPS == 1)
1357 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1359 << " Host: " << sys::getHostTriple() << '\n'
1360 << " Host CPU: " << CPU << '\n';
1362 void operator=(bool OptionWasSpecified) {
1363 if (!OptionWasSpecified) return;
1365 if (OverrideVersionPrinter != 0) {
1366 (*OverrideVersionPrinter)();
1371 // Iterate over any registered extra printers and call them to add further
1373 if (ExtraVersionPrinters != 0) {
1375 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1376 E = ExtraVersionPrinters->end();
1384 } // End anonymous namespace
1387 // Define the --version option that prints out the LLVM version for the tool
1388 static VersionPrinter VersionPrinterInstance;
1390 static cl::opt<VersionPrinter, true, parser<bool> >
1391 VersOp("version", cl::desc("Display the version of this program"),
1392 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1394 // Utility function for printing the help message.
1395 void cl::PrintHelpMessage() {
1396 // This looks weird, but it actually prints the help message. The
1397 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1398 // its operator= is invoked. That's because the "normal" usages of the
1399 // help printer is to be assigned true/false depending on whether the
1400 // -help option was given or not. Since we're circumventing that we have
1401 // to make it look like -help was given, so we assign true.
1402 NormalPrinter = true;
1405 /// Utility function for printing version number.
1406 void cl::PrintVersionMessage() {
1407 VersionPrinterInstance.print();
1410 void cl::SetVersionPrinter(void (*func)()) {
1411 OverrideVersionPrinter = func;
1414 void cl::AddExtraVersionPrinter(void (*func)()) {
1415 if (ExtraVersionPrinters == 0)
1416 ExtraVersionPrinters = new std::vector<void (*)()>;
1418 ExtraVersionPrinters->push_back(func);