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/ADT/OwningPtr.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/Host.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/PathV1.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Support/system_error.h"
41 //===----------------------------------------------------------------------===//
42 // Template instantiations and anchors.
44 namespace llvm { namespace cl {
45 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
46 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
47 TEMPLATE_INSTANTIATION(class basic_parser<int>);
48 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
49 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
50 TEMPLATE_INSTANTIATION(class basic_parser<double>);
51 TEMPLATE_INSTANTIATION(class basic_parser<float>);
52 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
53 TEMPLATE_INSTANTIATION(class basic_parser<char>);
55 TEMPLATE_INSTANTIATION(class opt<unsigned>);
56 TEMPLATE_INSTANTIATION(class opt<int>);
57 TEMPLATE_INSTANTIATION(class opt<std::string>);
58 TEMPLATE_INSTANTIATION(class opt<char>);
59 TEMPLATE_INSTANTIATION(class opt<bool>);
60 } } // end namespace llvm::cl
62 void OptionValue<boolOrDefault>::anchor() {}
63 void OptionValue<std::string>::anchor() {}
64 void Option::anchor() {}
65 void basic_parser_impl::anchor() {}
66 void parser<bool>::anchor() {}
67 void parser<boolOrDefault>::anchor() {}
68 void parser<int>::anchor() {}
69 void parser<unsigned>::anchor() {}
70 void parser<unsigned long long>::anchor() {}
71 void parser<double>::anchor() {}
72 void parser<float>::anchor() {}
73 void parser<std::string>::anchor() {}
74 void parser<char>::anchor() {}
76 //===----------------------------------------------------------------------===//
78 // Globals for name and overview of program. Program name is not a string to
79 // avoid static ctor/dtor issues.
80 static char ProgramName[80] = "<premain>";
81 static const char *ProgramOverview = 0;
83 // This collects additional help to be printed.
84 static ManagedStatic<std::vector<const char*> > MoreHelp;
86 extrahelp::extrahelp(const char *Help)
88 MoreHelp->push_back(Help);
91 static bool OptionListChanged = false;
93 // MarkOptionsChanged - Internal helper function.
94 void cl::MarkOptionsChanged() {
95 OptionListChanged = true;
98 /// RegisteredOptionList - This is the list of the command line options that
99 /// have statically constructed themselves.
100 static Option *RegisteredOptionList = 0;
102 void Option::addArgument() {
103 assert(NextRegistered == 0 && "argument multiply registered!");
105 NextRegistered = RegisteredOptionList;
106 RegisteredOptionList = this;
107 MarkOptionsChanged();
110 // This collects the different option categories that have been registered.
111 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
112 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
114 // Initialise the general option category.
115 OptionCategory llvm::cl::GeneralCategory("General options");
117 void OptionCategory::registerCategory()
119 RegisteredOptionCategories->insert(this);
122 //===----------------------------------------------------------------------===//
123 // Basic, shared command line option processing machinery.
126 /// GetOptionInfo - Scan the list of registered options, turning them into data
127 /// structures that are easier to handle.
128 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
129 SmallVectorImpl<Option*> &SinkOpts,
130 StringMap<Option*> &OptionsMap) {
131 SmallVector<const char*, 16> OptionNames;
132 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
133 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
134 // If this option wants to handle multiple option names, get the full set.
135 // This handles enum options like "-O1 -O2" etc.
136 O->getExtraOptionNames(OptionNames);
138 OptionNames.push_back(O->ArgStr);
140 // Handle named options.
141 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
142 // Add argument to the argument map!
143 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
144 errs() << ProgramName << ": CommandLine Error: Argument '"
145 << OptionNames[i] << "' defined more than once!\n";
151 // Remember information about positional options.
152 if (O->getFormattingFlag() == cl::Positional)
153 PositionalOpts.push_back(O);
154 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
155 SinkOpts.push_back(O);
156 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
158 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
164 PositionalOpts.push_back(CAOpt);
166 // Make sure that they are in order of registration not backwards.
167 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
171 /// LookupOption - Lookup the option specified by the specified option on the
172 /// command line. If there is a value specified (after an equal sign) return
173 /// that as well. This assumes that leading dashes have already been stripped.
174 static Option *LookupOption(StringRef &Arg, StringRef &Value,
175 const StringMap<Option*> &OptionsMap) {
176 // Reject all dashes.
177 if (Arg.empty()) return 0;
179 size_t EqualPos = Arg.find('=');
181 // If we have an equals sign, remember the value.
182 if (EqualPos == StringRef::npos) {
183 // Look up the option.
184 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
185 return I != OptionsMap.end() ? I->second : 0;
188 // If the argument before the = is a valid option name, we match. If not,
189 // return Arg unmolested.
190 StringMap<Option*>::const_iterator I =
191 OptionsMap.find(Arg.substr(0, EqualPos));
192 if (I == OptionsMap.end()) return 0;
194 Value = Arg.substr(EqualPos+1);
195 Arg = Arg.substr(0, EqualPos);
199 /// LookupNearestOption - Lookup the closest match to the option specified by
200 /// the specified option on the command line. If there is a value specified
201 /// (after an equal sign) return that as well. This assumes that leading dashes
202 /// have already been stripped.
203 static Option *LookupNearestOption(StringRef Arg,
204 const StringMap<Option*> &OptionsMap,
205 std::string &NearestString) {
206 // Reject all dashes.
207 if (Arg.empty()) return 0;
209 // Split on any equal sign.
210 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
211 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
212 StringRef &RHS = SplitArg.second;
214 // Find the closest match.
216 unsigned BestDistance = 0;
217 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
218 ie = OptionsMap.end(); it != ie; ++it) {
219 Option *O = it->second;
220 SmallVector<const char*, 16> OptionNames;
221 O->getExtraOptionNames(OptionNames);
223 OptionNames.push_back(O->ArgStr);
225 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
226 StringRef Flag = PermitValue ? LHS : Arg;
227 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
228 StringRef Name = OptionNames[i];
229 unsigned Distance = StringRef(Name).edit_distance(
230 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
231 if (!Best || Distance < BestDistance) {
233 BestDistance = Distance;
234 if (RHS.empty() || !PermitValue)
235 NearestString = OptionNames[i];
237 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
245 /// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
246 /// does special handling of cl::CommaSeparated options.
247 static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
249 StringRef Value, bool MultiArg = false)
251 // Check to see if this option accepts a comma separated list of values. If
252 // it does, we have to split up the value into multiple values.
253 if (Handler->getMiscFlags() & CommaSeparated) {
254 StringRef Val(Value);
255 StringRef::size_type Pos = Val.find(',');
257 while (Pos != StringRef::npos) {
258 // Process the portion before the comma.
259 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
261 // Erase the portion before the comma, AND the comma.
262 Val = Val.substr(Pos+1);
263 Value.substr(Pos+1); // Increment the original value pointer as well.
264 // Check for another comma.
271 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
277 /// ProvideOption - For Value, this differentiates between an empty value ("")
278 /// and a null value (StringRef()). The later is accepted for arguments that
279 /// don't allow a value (-foo) the former is rejected (-foo=).
280 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
281 StringRef Value, int argc,
282 const char *const *argv, int &i) {
283 // Is this a multi-argument option?
284 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
286 // Enforce value requirements
287 switch (Handler->getValueExpectedFlag()) {
289 if (Value.data() == 0) { // No value specified?
291 return Handler->error("requires a value!");
292 // Steal the next argument, like for '-o filename'
296 case ValueDisallowed:
297 if (NumAdditionalVals > 0)
298 return Handler->error("multi-valued option specified"
299 " with ValueDisallowed modifier!");
302 return Handler->error("does not allow a value! '" +
303 Twine(Value) + "' specified.");
309 // If this isn't a multi-arg option, just run the handler.
310 if (NumAdditionalVals == 0)
311 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
313 // If it is, run the handle several times.
314 bool MultiArg = false;
317 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
323 while (NumAdditionalVals > 0) {
325 return Handler->error("not enough values!");
328 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
336 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
338 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
342 // Option predicates...
343 static inline bool isGrouping(const Option *O) {
344 return O->getFormattingFlag() == cl::Grouping;
346 static inline bool isPrefixedOrGrouping(const Option *O) {
347 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
350 // getOptionPred - Check to see if there are any options that satisfy the
351 // specified predicate with names that are the prefixes in Name. This is
352 // checked by progressively stripping characters off of the name, checking to
353 // see if there options that satisfy the predicate. If we find one, return it,
354 // otherwise return null.
356 static Option *getOptionPred(StringRef Name, size_t &Length,
357 bool (*Pred)(const Option*),
358 const StringMap<Option*> &OptionsMap) {
360 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
362 // Loop while we haven't found an option and Name still has at least two
363 // characters in it (so that the next iteration will not be the empty
365 while (OMI == OptionsMap.end() && Name.size() > 1) {
366 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
367 OMI = OptionsMap.find(Name);
370 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
371 Length = Name.size();
372 return OMI->second; // Found one!
374 return 0; // No option found!
377 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
378 /// with at least one '-') does not fully match an available option. Check to
379 /// see if this is a prefix or grouped option. If so, split arg into output an
380 /// Arg/Value pair and return the Option to parse it with.
381 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
383 const StringMap<Option*> &OptionsMap) {
384 if (Arg.size() == 1) return 0;
388 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
389 if (PGOpt == 0) return 0;
391 // If the option is a prefixed option, then the value is simply the
392 // rest of the name... so fall through to later processing, by
393 // setting up the argument name flags and value fields.
394 if (PGOpt->getFormattingFlag() == cl::Prefix) {
395 Value = Arg.substr(Length);
396 Arg = Arg.substr(0, Length);
397 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
401 // This must be a grouped option... handle them now. Grouping options can't
403 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
406 // Move current arg name out of Arg into OneArgName.
407 StringRef OneArgName = Arg.substr(0, Length);
408 Arg = Arg.substr(Length);
410 // Because ValueRequired is an invalid flag for grouped arguments,
411 // we don't need to pass argc/argv in.
412 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
413 "Option can not be cl::Grouping AND cl::ValueRequired!");
415 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
416 StringRef(), 0, 0, Dummy);
418 // Get the next grouping option.
419 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
420 } while (PGOpt && Length != Arg.size());
422 // Return the last option with Arg cut down to just the last one.
428 static bool RequiresValue(const Option *O) {
429 return O->getNumOccurrencesFlag() == cl::Required ||
430 O->getNumOccurrencesFlag() == cl::OneOrMore;
433 static bool EatsUnboundedNumberOfValues(const Option *O) {
434 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
435 O->getNumOccurrencesFlag() == cl::OneOrMore;
438 /// ParseCStringVector - Break INPUT up wherever one or more
439 /// whitespace characters are found, and store the resulting tokens in
440 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
441 /// using strdup(), so it is the caller's responsibility to free()
444 static void ParseCStringVector(std::vector<char *> &OutputVector,
446 // Characters which will be treated as token separators:
447 StringRef Delims = " \v\f\t\r\n";
449 StringRef WorkStr(Input);
450 while (!WorkStr.empty()) {
451 // If the first character is a delimiter, strip them off.
452 if (Delims.find(WorkStr[0]) != StringRef::npos) {
453 size_t Pos = WorkStr.find_first_not_of(Delims);
454 if (Pos == StringRef::npos) Pos = WorkStr.size();
455 WorkStr = WorkStr.substr(Pos);
459 // Find position of first delimiter.
460 size_t Pos = WorkStr.find_first_of(Delims);
461 if (Pos == StringRef::npos) Pos = WorkStr.size();
463 // Everything from 0 to Pos is the next word to copy.
464 char *NewStr = (char*)malloc(Pos+1);
465 memcpy(NewStr, WorkStr.data(), Pos);
467 OutputVector.push_back(NewStr);
469 WorkStr = WorkStr.substr(Pos);
473 /// ParseEnvironmentOptions - An alternative entry point to the
474 /// CommandLine library, which allows you to read the program's name
475 /// from the caller (as PROGNAME) and its command-line arguments from
476 /// an environment variable (whose name is given in ENVVAR).
478 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
479 const char *Overview) {
481 assert(progName && "Program name not specified");
482 assert(envVar && "Environment variable name missing");
484 // Get the environment variable they want us to parse options out of.
485 const char *envValue = getenv(envVar);
489 // Get program's "name", which we wouldn't know without the caller
491 std::vector<char*> newArgv;
492 newArgv.push_back(strdup(progName));
494 // Parse the value of the environment variable into a "command line"
495 // and hand it off to ParseCommandLineOptions().
496 ParseCStringVector(newArgv, envValue);
497 int newArgc = static_cast<int>(newArgv.size());
498 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
500 // Free all the strdup()ed strings.
501 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
507 /// ExpandResponseFiles - Copy the contents of argv into newArgv,
508 /// substituting the contents of the response files for the arguments
510 static void ExpandResponseFiles(unsigned argc, const char*const* argv,
511 std::vector<char*>& newArgv) {
512 for (unsigned i = 1; i != argc; ++i) {
513 const char *arg = argv[i];
516 sys::PathWithStatus respFile(++arg);
518 // Check that the response file is not empty (mmap'ing empty
519 // files can be problematic).
520 const sys::FileStatus *FileStat = respFile.getFileStatus();
521 if (FileStat && FileStat->getSize() != 0) {
523 // If we could open the file, parse its contents, otherwise
524 // pass the @file option verbatim.
526 // TODO: we should also support recursive loading of response files,
527 // since this is how gcc behaves. (From their man page: "The file may
528 // itself contain additional @file options; any such options will be
529 // processed recursively.")
531 // Mmap the response file into memory.
532 OwningPtr<MemoryBuffer> respFilePtr;
533 if (!MemoryBuffer::getFile(respFile.c_str(), respFilePtr)) {
534 ParseCStringVector(newArgv, respFilePtr->getBufferStart());
539 newArgv.push_back(strdup(arg));
543 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
544 const char *Overview) {
545 // Process all registered options.
546 SmallVector<Option*, 4> PositionalOpts;
547 SmallVector<Option*, 4> SinkOpts;
548 StringMap<Option*> Opts;
549 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
551 assert((!Opts.empty() || !PositionalOpts.empty()) &&
552 "No options specified!");
554 // Expand response files.
555 std::vector<char*> newArgv;
556 newArgv.push_back(strdup(argv[0]));
557 ExpandResponseFiles(argc, argv, newArgv);
559 argc = static_cast<int>(newArgv.size());
561 // Copy the program name into ProgName, making sure not to overflow it.
562 std::string ProgName = sys::path::filename(argv[0]);
563 size_t Len = std::min(ProgName.size(), size_t(79));
564 memcpy(ProgramName, ProgName.data(), Len);
565 ProgramName[Len] = '\0';
567 ProgramOverview = Overview;
568 bool ErrorParsing = false;
570 // Check out the positional arguments to collect information about them.
571 unsigned NumPositionalRequired = 0;
573 // Determine whether or not there are an unlimited number of positionals
574 bool HasUnlimitedPositionals = false;
576 Option *ConsumeAfterOpt = 0;
577 if (!PositionalOpts.empty()) {
578 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
579 assert(PositionalOpts.size() > 1 &&
580 "Cannot specify cl::ConsumeAfter without a positional argument!");
581 ConsumeAfterOpt = PositionalOpts[0];
584 // Calculate how many positional values are _required_.
585 bool UnboundedFound = false;
586 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
588 Option *Opt = PositionalOpts[i];
589 if (RequiresValue(Opt))
590 ++NumPositionalRequired;
591 else if (ConsumeAfterOpt) {
592 // ConsumeAfter cannot be combined with "optional" positional options
593 // unless there is only one positional argument...
594 if (PositionalOpts.size() > 2)
596 Opt->error("error - this positional option will never be matched, "
597 "because it does not Require a value, and a "
598 "cl::ConsumeAfter option is active!");
599 } else if (UnboundedFound && !Opt->ArgStr[0]) {
600 // This option does not "require" a value... Make sure this option is
601 // not specified after an option that eats all extra arguments, or this
602 // one will never get any!
604 ErrorParsing |= Opt->error("error - option can never match, because "
605 "another positional argument will match an "
606 "unbounded number of values, and this option"
607 " does not require a value!");
609 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
611 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
614 // PositionalVals - A vector of "positional" arguments we accumulate into
615 // the process at the end.
617 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
619 // If the program has named positional arguments, and the name has been run
620 // across, keep track of which positional argument was named. Otherwise put
621 // the positional args into the PositionalVals list...
622 Option *ActivePositionalArg = 0;
624 // Loop over all of the arguments... processing them.
625 bool DashDashFound = false; // Have we read '--'?
626 for (int i = 1; i < argc; ++i) {
628 Option *NearestHandler = 0;
629 std::string NearestHandlerString;
631 StringRef ArgName = "";
633 // If the option list changed, this means that some command line
634 // option has just been registered or deregistered. This can occur in
635 // response to things like -load, etc. If this happens, rescan the options.
636 if (OptionListChanged) {
637 PositionalOpts.clear();
640 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
641 OptionListChanged = false;
644 // Check to see if this is a positional argument. This argument is
645 // considered to be positional if it doesn't start with '-', if it is "-"
646 // itself, or if we have seen "--" already.
648 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
649 // Positional argument!
650 if (ActivePositionalArg) {
651 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
652 continue; // We are done!
655 if (!PositionalOpts.empty()) {
656 PositionalVals.push_back(std::make_pair(argv[i],i));
658 // All of the positional arguments have been fulfulled, give the rest to
659 // the consume after option... if it's specified...
661 if (PositionalVals.size() >= NumPositionalRequired &&
662 ConsumeAfterOpt != 0) {
663 for (++i; i < argc; ++i)
664 PositionalVals.push_back(std::make_pair(argv[i],i));
665 break; // Handle outside of the argument processing loop...
668 // Delay processing positional arguments until the end...
671 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
673 DashDashFound = true; // This is the mythical "--"?
674 continue; // Don't try to process it as an argument itself.
675 } else if (ActivePositionalArg &&
676 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
677 // If there is a positional argument eating options, check to see if this
678 // option is another positional argument. If so, treat it as an argument,
679 // otherwise feed it to the eating positional.
681 // Eat leading dashes.
682 while (!ArgName.empty() && ArgName[0] == '-')
683 ArgName = ArgName.substr(1);
685 Handler = LookupOption(ArgName, Value, Opts);
686 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
687 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
688 continue; // We are done!
691 } else { // We start with a '-', must be an argument.
693 // Eat leading dashes.
694 while (!ArgName.empty() && ArgName[0] == '-')
695 ArgName = ArgName.substr(1);
697 Handler = LookupOption(ArgName, Value, Opts);
699 // Check to see if this "option" is really a prefixed or grouped argument.
701 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
704 // Otherwise, look for the closest available option to report to the user
705 // in the upcoming error.
706 if (Handler == 0 && SinkOpts.empty())
707 NearestHandler = LookupNearestOption(ArgName, Opts,
708 NearestHandlerString);
712 if (SinkOpts.empty()) {
713 errs() << ProgramName << ": Unknown command line argument '"
714 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
716 if (NearestHandler) {
717 // If we know a near match, report it as well.
718 errs() << ProgramName << ": Did you mean '-"
719 << NearestHandlerString << "'?\n";
724 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
725 E = SinkOpts.end(); I != E ; ++I)
726 (*I)->addOccurrence(i, "", argv[i]);
731 // If this is a named positional argument, just remember that it is the
733 if (Handler->getFormattingFlag() == cl::Positional)
734 ActivePositionalArg = Handler;
736 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
739 // Check and handle positional arguments now...
740 if (NumPositionalRequired > PositionalVals.size()) {
741 errs() << ProgramName
742 << ": Not enough positional command line arguments specified!\n"
743 << "Must specify at least " << NumPositionalRequired
744 << " positional arguments: See: " << argv[0] << " -help\n";
747 } else if (!HasUnlimitedPositionals &&
748 PositionalVals.size() > PositionalOpts.size()) {
749 errs() << ProgramName
750 << ": Too many positional arguments specified!\n"
751 << "Can specify at most " << PositionalOpts.size()
752 << " positional arguments: See: " << argv[0] << " -help\n";
755 } else if (ConsumeAfterOpt == 0) {
756 // Positional args have already been handled if ConsumeAfter is specified.
757 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
758 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
759 if (RequiresValue(PositionalOpts[i])) {
760 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
761 PositionalVals[ValNo].second);
763 --NumPositionalRequired; // We fulfilled our duty...
766 // If we _can_ give this option more arguments, do so now, as long as we
767 // do not give it values that others need. 'Done' controls whether the
768 // option even _WANTS_ any more.
770 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
771 while (NumVals-ValNo > NumPositionalRequired && !Done) {
772 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
774 Done = true; // Optional arguments want _at most_ one value
776 case cl::ZeroOrMore: // Zero or more will take all they can get...
777 case cl::OneOrMore: // One or more will take all they can get...
778 ProvidePositionalOption(PositionalOpts[i],
779 PositionalVals[ValNo].first,
780 PositionalVals[ValNo].second);
784 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
785 "positional argument processing!");
790 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
792 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
793 if (RequiresValue(PositionalOpts[j])) {
794 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
795 PositionalVals[ValNo].first,
796 PositionalVals[ValNo].second);
800 // Handle the case where there is just one positional option, and it's
801 // optional. In this case, we want to give JUST THE FIRST option to the
802 // positional option and keep the rest for the consume after. The above
803 // loop would have assigned no values to positional options in this case.
805 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
806 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
807 PositionalVals[ValNo].first,
808 PositionalVals[ValNo].second);
812 // Handle over all of the rest of the arguments to the
813 // cl::ConsumeAfter command line option...
814 for (; ValNo != PositionalVals.size(); ++ValNo)
815 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
816 PositionalVals[ValNo].first,
817 PositionalVals[ValNo].second);
820 // Loop over args and make sure all required args are specified!
821 for (StringMap<Option*>::iterator I = Opts.begin(),
822 E = Opts.end(); I != E; ++I) {
823 switch (I->second->getNumOccurrencesFlag()) {
826 if (I->second->getNumOccurrences() == 0) {
827 I->second->error("must be specified at least once!");
836 // Now that we know if -debug is specified, we can use it.
837 // Note that if ReadResponseFiles == true, this must be done before the
838 // memory allocated for the expanded command line is free()d below.
839 DEBUG(dbgs() << "Args: ";
840 for (int i = 0; i < argc; ++i)
841 dbgs() << argv[i] << ' ';
845 // Free all of the memory allocated to the map. Command line options may only
846 // be processed once!
848 PositionalOpts.clear();
851 // Free the memory allocated by ExpandResponseFiles.
852 // Free all the strdup()ed strings.
853 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
857 // If we had an error processing our arguments, don't let the program execute
858 if (ErrorParsing) exit(1);
861 //===----------------------------------------------------------------------===//
862 // Option Base class implementation
865 bool Option::error(const Twine &Message, StringRef ArgName) {
866 if (ArgName.data() == 0) ArgName = ArgStr;
868 errs() << HelpStr; // Be nice for positional arguments
870 errs() << ProgramName << ": for the -" << ArgName;
872 errs() << " option: " << Message << "\n";
876 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
877 StringRef Value, bool MultiArg) {
879 NumOccurrences++; // Increment the number of times we have been seen
881 switch (getNumOccurrencesFlag()) {
883 if (NumOccurrences > 1)
884 return error("may only occur zero or one times!", ArgName);
887 if (NumOccurrences > 1)
888 return error("must occur exactly one time!", ArgName);
892 case ConsumeAfter: break;
895 return handleOccurrence(pos, ArgName, Value);
899 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
900 // has been specified yet.
902 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
903 if (O.ValueStr[0] == 0) return DefaultMsg;
907 //===----------------------------------------------------------------------===//
908 // cl::alias class implementation
911 // Return the width of the option tag for printing...
912 size_t alias::getOptionWidth() const {
913 return std::strlen(ArgStr)+6;
916 static void printHelpStr(StringRef HelpStr, size_t Indent,
917 size_t FirstLineIndentedBy) {
918 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
919 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
920 while (!Split.second.empty()) {
921 Split = Split.second.split('\n');
922 outs().indent(Indent) << Split.first << "\n";
926 // Print out the option for the alias.
927 void alias::printOptionInfo(size_t GlobalWidth) const {
928 outs() << " -" << ArgStr;
929 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
932 //===----------------------------------------------------------------------===//
933 // Parser Implementation code...
936 // basic_parser implementation
939 // Return the width of the option tag for printing...
940 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
941 size_t Len = std::strlen(O.ArgStr);
942 if (const char *ValName = getValueName())
943 Len += std::strlen(getValueStr(O, ValName))+3;
948 // printOptionInfo - Print out information about this option. The
949 // to-be-maintained width is specified.
951 void basic_parser_impl::printOptionInfo(const Option &O,
952 size_t GlobalWidth) const {
953 outs() << " -" << O.ArgStr;
955 if (const char *ValName = getValueName())
956 outs() << "=<" << getValueStr(O, ValName) << '>';
958 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
961 void basic_parser_impl::printOptionName(const Option &O,
962 size_t GlobalWidth) const {
963 outs() << " -" << O.ArgStr;
964 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
968 // parser<bool> implementation
970 bool parser<bool>::parse(Option &O, StringRef ArgName,
971 StringRef Arg, bool &Value) {
972 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
978 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
982 return O.error("'" + Arg +
983 "' is invalid value for boolean argument! Try 0 or 1");
986 // parser<boolOrDefault> implementation
988 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
989 StringRef Arg, boolOrDefault &Value) {
990 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
995 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1000 return O.error("'" + Arg +
1001 "' is invalid value for boolean argument! Try 0 or 1");
1004 // parser<int> implementation
1006 bool parser<int>::parse(Option &O, StringRef ArgName,
1007 StringRef Arg, int &Value) {
1008 if (Arg.getAsInteger(0, Value))
1009 return O.error("'" + Arg + "' value invalid for integer argument!");
1013 // parser<unsigned> implementation
1015 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1016 StringRef Arg, unsigned &Value) {
1018 if (Arg.getAsInteger(0, Value))
1019 return O.error("'" + Arg + "' value invalid for uint argument!");
1023 // parser<unsigned long long> implementation
1025 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1026 StringRef Arg, unsigned long long &Value){
1028 if (Arg.getAsInteger(0, Value))
1029 return O.error("'" + Arg + "' value invalid for uint argument!");
1033 // parser<double>/parser<float> implementation
1035 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1036 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1037 const char *ArgStart = TmpStr.c_str();
1039 Value = strtod(ArgStart, &End);
1041 return O.error("'" + Arg + "' value invalid for floating point argument!");
1045 bool parser<double>::parse(Option &O, StringRef ArgName,
1046 StringRef Arg, double &Val) {
1047 return parseDouble(O, Arg, Val);
1050 bool parser<float>::parse(Option &O, StringRef ArgName,
1051 StringRef Arg, float &Val) {
1053 if (parseDouble(O, Arg, dVal))
1061 // generic_parser_base implementation
1064 // findOption - Return the option number corresponding to the specified
1065 // argument string. If the option is not found, getNumOptions() is returned.
1067 unsigned generic_parser_base::findOption(const char *Name) {
1068 unsigned e = getNumOptions();
1070 for (unsigned i = 0; i != e; ++i) {
1071 if (strcmp(getOption(i), Name) == 0)
1078 // Return the width of the option tag for printing...
1079 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1080 if (O.hasArgStr()) {
1081 size_t Size = std::strlen(O.ArgStr)+6;
1082 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1083 Size = std::max(Size, std::strlen(getOption(i))+8);
1086 size_t BaseSize = 0;
1087 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1088 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1093 // printOptionInfo - Print out information about this option. The
1094 // to-be-maintained width is specified.
1096 void generic_parser_base::printOptionInfo(const Option &O,
1097 size_t GlobalWidth) const {
1098 if (O.hasArgStr()) {
1099 outs() << " -" << O.ArgStr;
1100 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1102 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1103 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1104 outs() << " =" << getOption(i);
1105 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1109 outs() << " " << O.HelpStr << '\n';
1110 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1111 const char *Option = getOption(i);
1112 outs() << " -" << Option;
1113 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1118 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1120 // printGenericOptionDiff - Print the value of this option and it's default.
1122 // "Generic" options have each value mapped to a name.
1123 void generic_parser_base::
1124 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1125 const GenericOptionValue &Default,
1126 size_t GlobalWidth) const {
1127 outs() << " -" << O.ArgStr;
1128 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1130 unsigned NumOpts = getNumOptions();
1131 for (unsigned i = 0; i != NumOpts; ++i) {
1132 if (Value.compare(getOptionValue(i)))
1135 outs() << "= " << getOption(i);
1136 size_t L = std::strlen(getOption(i));
1137 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1138 outs().indent(NumSpaces) << " (default: ";
1139 for (unsigned j = 0; j != NumOpts; ++j) {
1140 if (Default.compare(getOptionValue(j)))
1142 outs() << getOption(j);
1148 outs() << "= *unknown option value*\n";
1151 // printOptionDiff - Specializations for printing basic value types.
1153 #define PRINT_OPT_DIFF(T) \
1155 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1156 size_t GlobalWidth) const { \
1157 printOptionName(O, GlobalWidth); \
1160 raw_string_ostream SS(Str); \
1163 outs() << "= " << Str; \
1164 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1165 outs().indent(NumSpaces) << " (default: "; \
1167 outs() << D.getValue(); \
1169 outs() << "*no default*"; \
1173 PRINT_OPT_DIFF(bool)
1174 PRINT_OPT_DIFF(boolOrDefault)
1176 PRINT_OPT_DIFF(unsigned)
1177 PRINT_OPT_DIFF(unsigned long long)
1178 PRINT_OPT_DIFF(double)
1179 PRINT_OPT_DIFF(float)
1180 PRINT_OPT_DIFF(char)
1182 void parser<std::string>::
1183 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1184 size_t GlobalWidth) const {
1185 printOptionName(O, GlobalWidth);
1186 outs() << "= " << V;
1187 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1188 outs().indent(NumSpaces) << " (default: ";
1190 outs() << D.getValue();
1192 outs() << "*no default*";
1196 // Print a placeholder for options that don't yet support printOptionDiff().
1197 void basic_parser_impl::
1198 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1199 printOptionName(O, GlobalWidth);
1200 outs() << "= *cannot print option value*\n";
1203 //===----------------------------------------------------------------------===//
1204 // -help and -help-hidden option implementation
1207 static int OptNameCompare(const void *LHS, const void *RHS) {
1208 typedef std::pair<const char *, Option*> pair_ty;
1210 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1213 // Copy Options into a vector so we can sort them as we like.
1215 sortOpts(StringMap<Option*> &OptMap,
1216 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1218 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1220 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1222 // Ignore really-hidden options.
1223 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1226 // Unless showhidden is set, ignore hidden flags.
1227 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1230 // If we've already seen this option, don't add it to the list again.
1231 if (!OptionSet.insert(I->second))
1234 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1238 // Sort the options list alphabetically.
1239 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1246 const bool ShowHidden;
1247 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1248 // Print the options. Opts is assumed to be alphabetically sorted.
1249 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1250 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1251 Opts[i].second->printOptionInfo(MaxArgLen);
1255 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1256 virtual ~HelpPrinter() {}
1258 // Invoke the printer.
1259 void operator=(bool Value) {
1260 if (Value == false) return;
1262 // Get all the options.
1263 SmallVector<Option*, 4> PositionalOpts;
1264 SmallVector<Option*, 4> SinkOpts;
1265 StringMap<Option*> OptMap;
1266 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1268 StrOptionPairVector Opts;
1269 sortOpts(OptMap, Opts, ShowHidden);
1271 if (ProgramOverview)
1272 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1274 outs() << "USAGE: " << ProgramName << " [options]";
1276 // Print out the positional options.
1277 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
1278 if (!PositionalOpts.empty() &&
1279 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1280 CAOpt = PositionalOpts[0];
1282 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1283 if (PositionalOpts[i]->ArgStr[0])
1284 outs() << " --" << PositionalOpts[i]->ArgStr;
1285 outs() << " " << PositionalOpts[i]->HelpStr;
1288 // Print the consume after option info if it exists...
1289 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1293 // Compute the maximum argument length...
1294 size_t MaxArgLen = 0;
1295 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1296 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1298 outs() << "OPTIONS:\n";
1299 printOptions(Opts, MaxArgLen);
1301 // Print any extra help the user has declared.
1302 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1303 E = MoreHelp->end();
1308 // Halt the program since help information was printed
1313 class CategorizedHelpPrinter : public HelpPrinter {
1315 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1317 // Helper function for printOptions().
1318 // It shall return true if A's name should be lexographically
1319 // ordered before B's name. It returns false otherwise.
1320 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1321 int Length = strcmp(A->getName(), B->getName());
1322 assert(Length != 0 && "Duplicate option categories");
1326 // Make sure we inherit our base class's operator=()
1327 using HelpPrinter::operator= ;
1330 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1331 std::vector<OptionCategory *> SortedCategories;
1332 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1334 // Collect registered option categories into vector in preperation for
1336 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1337 E = RegisteredOptionCategories->end();
1339 SortedCategories.push_back(*I);
1341 // Sort the different option categories alphabetically.
1342 assert(SortedCategories.size() > 0 && "No option categories registered!");
1343 std::sort(SortedCategories.begin(), SortedCategories.end(),
1344 OptionCategoryCompare);
1346 // Create map to empty vectors.
1347 for (std::vector<OptionCategory *>::const_iterator
1348 I = SortedCategories.begin(),
1349 E = SortedCategories.end();
1351 CategorizedOptions[*I] = std::vector<Option *>();
1353 // Walk through pre-sorted options and assign into categories.
1354 // Because the options are already alphabetically sorted the
1355 // options within categories will also be alphabetically sorted.
1356 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1357 Option *Opt = Opts[I].second;
1358 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1359 "Option has an unregistered category");
1360 CategorizedOptions[Opt->Category].push_back(Opt);
1364 for (std::vector<OptionCategory *>::const_iterator
1365 Category = SortedCategories.begin(),
1366 E = SortedCategories.end();
1367 Category != E; ++Category) {
1368 // Hide empty categories for -help, but show for -help-hidden.
1369 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1370 if (!ShowHidden && IsEmptyCategory)
1373 // Print category information.
1375 outs() << (*Category)->getName() << ":\n";
1377 // Check if description is set.
1378 if ((*Category)->getDescription() != 0)
1379 outs() << (*Category)->getDescription() << "\n\n";
1383 // When using -help-hidden explicitly state if the category has no
1384 // options associated with it.
1385 if (IsEmptyCategory) {
1386 outs() << " This option category has no options.\n";
1389 // Loop over the options in the category and print.
1390 for (std::vector<Option *>::const_iterator
1391 Opt = CategorizedOptions[*Category].begin(),
1392 E = CategorizedOptions[*Category].end();
1394 (*Opt)->printOptionInfo(MaxArgLen);
1399 // This wraps the Uncategorizing and Categorizing printers and decides
1400 // at run time which should be invoked.
1401 class HelpPrinterWrapper {
1403 HelpPrinter &UncategorizedPrinter;
1404 CategorizedHelpPrinter &CategorizedPrinter;
1407 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1408 CategorizedHelpPrinter &CategorizedPrinter) :
1409 UncategorizedPrinter(UncategorizedPrinter),
1410 CategorizedPrinter(CategorizedPrinter) { }
1412 // Invoke the printer.
1413 void operator=(bool Value);
1416 } // End anonymous namespace
1418 // Declare the four HelpPrinter instances that are used to print out help, or
1419 // help-hidden as an uncategorized list or in categories.
1420 static HelpPrinter UncategorizedNormalPrinter(false);
1421 static HelpPrinter UncategorizedHiddenPrinter(true);
1422 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1423 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1426 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1427 // a categorizing help printer
1428 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1429 CategorizedNormalPrinter);
1430 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1431 CategorizedHiddenPrinter);
1433 // Define uncategorized help printers.
1434 // -help-list is hidden by default because if Option categories are being used
1435 // then -help behaves the same as -help-list.
1436 static cl::opt<HelpPrinter, true, parser<bool> >
1438 cl::desc("Display list of available options (-help-list-hidden for more)"),
1439 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1441 static cl::opt<HelpPrinter, true, parser<bool> >
1442 HLHOp("help-list-hidden",
1443 cl::desc("Display list of all available options"),
1444 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1446 // Define uncategorized/categorized help printers. These printers change their
1447 // behaviour at runtime depending on whether one or more Option categories have
1449 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1450 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1451 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1453 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1454 HHOp("help-hidden", cl::desc("Display all available options"),
1455 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1459 static cl::opt<bool>
1460 PrintOptions("print-options",
1461 cl::desc("Print non-default options after command line parsing"),
1462 cl::Hidden, cl::init(false));
1464 static cl::opt<bool>
1465 PrintAllOptions("print-all-options",
1466 cl::desc("Print all option values after command line parsing"),
1467 cl::Hidden, cl::init(false));
1469 void HelpPrinterWrapper::operator=(bool Value) {
1473 // Decide which printer to invoke. If more than one option category is
1474 // registered then it is useful to show the categorized help instead of
1475 // uncategorized help.
1476 if (RegisteredOptionCategories->size() > 1) {
1477 // unhide -help-list option so user can have uncategorized output if they
1479 HLOp.setHiddenFlag(NotHidden);
1481 CategorizedPrinter = true; // Invoke categorized printer
1484 UncategorizedPrinter = true; // Invoke uncategorized printer
1487 // Print the value of each option.
1488 void cl::PrintOptionValues() {
1489 if (!PrintOptions && !PrintAllOptions) return;
1491 // Get all the options.
1492 SmallVector<Option*, 4> PositionalOpts;
1493 SmallVector<Option*, 4> SinkOpts;
1494 StringMap<Option*> OptMap;
1495 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1497 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1498 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1500 // Compute the maximum argument length...
1501 size_t MaxArgLen = 0;
1502 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1503 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1505 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1506 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1509 static void (*OverrideVersionPrinter)() = 0;
1511 static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1514 class VersionPrinter {
1517 raw_ostream &OS = outs();
1518 OS << "LLVM (http://llvm.org/):\n"
1519 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1520 #ifdef LLVM_VERSION_INFO
1521 OS << LLVM_VERSION_INFO;
1524 #ifndef __OPTIMIZE__
1525 OS << "DEBUG build";
1527 OS << "Optimized build";
1530 OS << " with assertions";
1532 std::string CPU = sys::getHostCPUName();
1533 if (CPU == "generic") CPU = "(unknown)";
1535 #if (ENABLE_TIMESTAMPS == 1)
1536 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1538 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1539 << " Host CPU: " << CPU << '\n';
1541 void operator=(bool OptionWasSpecified) {
1542 if (!OptionWasSpecified) return;
1544 if (OverrideVersionPrinter != 0) {
1545 (*OverrideVersionPrinter)();
1550 // Iterate over any registered extra printers and call them to add further
1552 if (ExtraVersionPrinters != 0) {
1554 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1555 E = ExtraVersionPrinters->end();
1563 } // End anonymous namespace
1566 // Define the --version option that prints out the LLVM version for the tool
1567 static VersionPrinter VersionPrinterInstance;
1569 static cl::opt<VersionPrinter, true, parser<bool> >
1570 VersOp("version", cl::desc("Display the version of this program"),
1571 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1573 // Utility function for printing the help message.
1574 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1575 // This looks weird, but it actually prints the help message. The Printers are
1576 // types of HelpPrinter and the help gets printed when its operator= is
1577 // invoked. That's because the "normal" usages of the help printer is to be
1578 // assigned true/false depending on whether -help or -help-hidden was given or
1579 // not. Since we're circumventing that we have to make it look like -help or
1580 // -help-hidden were given, so we assign true.
1582 if (!Hidden && !Categorized)
1583 UncategorizedNormalPrinter = true;
1584 else if (!Hidden && Categorized)
1585 CategorizedNormalPrinter = true;
1586 else if (Hidden && !Categorized)
1587 UncategorizedHiddenPrinter = true;
1589 CategorizedHiddenPrinter = true;
1592 /// Utility function for printing version number.
1593 void cl::PrintVersionMessage() {
1594 VersionPrinterInstance.print();
1597 void cl::SetVersionPrinter(void (*func)()) {
1598 OverrideVersionPrinter = func;
1601 void cl::AddExtraVersionPrinter(void (*func)()) {
1602 if (ExtraVersionPrinters == 0)
1603 ExtraVersionPrinters = new std::vector<void (*)()>;
1605 ExtraVersionPrinters->push_back(func);
1608 void cl::getRegisteredOptions(StringMap<Option*> &Map)
1610 // Get all the options.
1611 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1612 SmallVector<Option*, 4> SinkOpts; //NOT USED
1613 assert(Map.size() == 0 && "StringMap must be empty");
1614 GetOptionInfo(PositionalOpts, SinkOpts, Map);