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/ArrayRef.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Config/config.h"
27 #include "llvm/Support/ConvertUTF.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/system_error.h"
42 //===----------------------------------------------------------------------===//
43 // Template instantiations and anchors.
45 namespace llvm { namespace cl {
46 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
47 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
48 TEMPLATE_INSTANTIATION(class basic_parser<int>);
49 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
50 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
51 TEMPLATE_INSTANTIATION(class basic_parser<double>);
52 TEMPLATE_INSTANTIATION(class basic_parser<float>);
53 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
54 TEMPLATE_INSTANTIATION(class basic_parser<char>);
56 TEMPLATE_INSTANTIATION(class opt<unsigned>);
57 TEMPLATE_INSTANTIATION(class opt<int>);
58 TEMPLATE_INSTANTIATION(class opt<std::string>);
59 TEMPLATE_INSTANTIATION(class opt<char>);
60 TEMPLATE_INSTANTIATION(class opt<bool>);
61 } } // end namespace llvm::cl
63 // Pin the vtables to this file.
64 void GenericOptionValue::anchor() {}
65 void OptionValue<boolOrDefault>::anchor() {}
66 void OptionValue<std::string>::anchor() {}
67 void Option::anchor() {}
68 void basic_parser_impl::anchor() {}
69 void parser<bool>::anchor() {}
70 void parser<boolOrDefault>::anchor() {}
71 void parser<int>::anchor() {}
72 void parser<unsigned>::anchor() {}
73 void parser<unsigned long long>::anchor() {}
74 void parser<double>::anchor() {}
75 void parser<float>::anchor() {}
76 void parser<std::string>::anchor() {}
77 void parser<char>::anchor() {}
78 void StringSaver::anchor() {}
80 //===----------------------------------------------------------------------===//
82 // Globals for name and overview of program. Program name is not a string to
83 // avoid static ctor/dtor issues.
84 static char ProgramName[80] = "<premain>";
85 static const char *ProgramOverview = 0;
87 // This collects additional help to be printed.
88 static ManagedStatic<std::vector<const char*> > MoreHelp;
90 extrahelp::extrahelp(const char *Help)
92 MoreHelp->push_back(Help);
95 static bool OptionListChanged = false;
97 // MarkOptionsChanged - Internal helper function.
98 void cl::MarkOptionsChanged() {
99 OptionListChanged = true;
102 /// RegisteredOptionList - This is the list of the command line options that
103 /// have statically constructed themselves.
104 static Option *RegisteredOptionList = 0;
106 void Option::addArgument() {
107 assert(NextRegistered == 0 && "argument multiply registered!");
109 NextRegistered = RegisteredOptionList;
110 RegisteredOptionList = this;
111 MarkOptionsChanged();
114 // This collects the different option categories that have been registered.
115 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
116 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
118 // Initialise the general option category.
119 OptionCategory llvm::cl::GeneralCategory("General options");
121 void OptionCategory::registerCategory()
123 RegisteredOptionCategories->insert(this);
126 //===----------------------------------------------------------------------===//
127 // Basic, shared command line option processing machinery.
130 /// GetOptionInfo - Scan the list of registered options, turning them into data
131 /// structures that are easier to handle.
132 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
133 SmallVectorImpl<Option*> &SinkOpts,
134 StringMap<Option*> &OptionsMap) {
135 SmallVector<const char*, 16> OptionNames;
136 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
137 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
138 // If this option wants to handle multiple option names, get the full set.
139 // This handles enum options like "-O1 -O2" etc.
140 O->getExtraOptionNames(OptionNames);
142 OptionNames.push_back(O->ArgStr);
144 // Handle named options.
145 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
146 // Add argument to the argument map!
147 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
148 errs() << ProgramName << ": CommandLine Error: Argument '"
149 << OptionNames[i] << "' defined more than once!\n";
155 // Remember information about positional options.
156 if (O->getFormattingFlag() == cl::Positional)
157 PositionalOpts.push_back(O);
158 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
159 SinkOpts.push_back(O);
160 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
162 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
168 PositionalOpts.push_back(CAOpt);
170 // Make sure that they are in order of registration not backwards.
171 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
175 /// LookupOption - Lookup the option specified by the specified option on the
176 /// command line. If there is a value specified (after an equal sign) return
177 /// that as well. This assumes that leading dashes have already been stripped.
178 static Option *LookupOption(StringRef &Arg, StringRef &Value,
179 const StringMap<Option*> &OptionsMap) {
180 // Reject all dashes.
181 if (Arg.empty()) return 0;
183 size_t EqualPos = Arg.find('=');
185 // If we have an equals sign, remember the value.
186 if (EqualPos == StringRef::npos) {
187 // Look up the option.
188 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
189 return I != OptionsMap.end() ? I->second : 0;
192 // If the argument before the = is a valid option name, we match. If not,
193 // return Arg unmolested.
194 StringMap<Option*>::const_iterator I =
195 OptionsMap.find(Arg.substr(0, EqualPos));
196 if (I == OptionsMap.end()) return 0;
198 Value = Arg.substr(EqualPos+1);
199 Arg = Arg.substr(0, EqualPos);
203 /// LookupNearestOption - Lookup the closest match to the option specified by
204 /// the specified option on the command line. If there is a value specified
205 /// (after an equal sign) return that as well. This assumes that leading dashes
206 /// have already been stripped.
207 static Option *LookupNearestOption(StringRef Arg,
208 const StringMap<Option*> &OptionsMap,
209 std::string &NearestString) {
210 // Reject all dashes.
211 if (Arg.empty()) return 0;
213 // Split on any equal sign.
214 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
215 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
216 StringRef &RHS = SplitArg.second;
218 // Find the closest match.
220 unsigned BestDistance = 0;
221 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
222 ie = OptionsMap.end(); it != ie; ++it) {
223 Option *O = it->second;
224 SmallVector<const char*, 16> OptionNames;
225 O->getExtraOptionNames(OptionNames);
227 OptionNames.push_back(O->ArgStr);
229 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
230 StringRef Flag = PermitValue ? LHS : Arg;
231 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
232 StringRef Name = OptionNames[i];
233 unsigned Distance = StringRef(Name).edit_distance(
234 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
235 if (!Best || Distance < BestDistance) {
237 BestDistance = Distance;
238 if (RHS.empty() || !PermitValue)
239 NearestString = OptionNames[i];
241 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
249 /// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
250 /// does special handling of cl::CommaSeparated options.
251 static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
253 StringRef Value, bool MultiArg = false)
255 // Check to see if this option accepts a comma separated list of values. If
256 // it does, we have to split up the value into multiple values.
257 if (Handler->getMiscFlags() & CommaSeparated) {
258 StringRef Val(Value);
259 StringRef::size_type Pos = Val.find(',');
261 while (Pos != StringRef::npos) {
262 // Process the portion before the comma.
263 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
265 // Erase the portion before the comma, AND the comma.
266 Val = Val.substr(Pos+1);
267 Value.substr(Pos+1); // Increment the original value pointer as well.
268 // Check for another comma.
275 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
281 /// ProvideOption - For Value, this differentiates between an empty value ("")
282 /// and a null value (StringRef()). The later is accepted for arguments that
283 /// don't allow a value (-foo) the former is rejected (-foo=).
284 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
285 StringRef Value, int argc,
286 const char *const *argv, int &i) {
287 // Is this a multi-argument option?
288 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
290 // Enforce value requirements
291 switch (Handler->getValueExpectedFlag()) {
293 if (Value.data() == 0) { // No value specified?
295 return Handler->error("requires a value!");
296 // Steal the next argument, like for '-o filename'
300 case ValueDisallowed:
301 if (NumAdditionalVals > 0)
302 return Handler->error("multi-valued option specified"
303 " with ValueDisallowed modifier!");
306 return Handler->error("does not allow a value! '" +
307 Twine(Value) + "' specified.");
313 // If this isn't a multi-arg option, just run the handler.
314 if (NumAdditionalVals == 0)
315 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
317 // If it is, run the handle several times.
318 bool MultiArg = false;
321 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
327 while (NumAdditionalVals > 0) {
329 return Handler->error("not enough values!");
332 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
340 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
342 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
346 // Option predicates...
347 static inline bool isGrouping(const Option *O) {
348 return O->getFormattingFlag() == cl::Grouping;
350 static inline bool isPrefixedOrGrouping(const Option *O) {
351 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
354 // getOptionPred - Check to see if there are any options that satisfy the
355 // specified predicate with names that are the prefixes in Name. This is
356 // checked by progressively stripping characters off of the name, checking to
357 // see if there options that satisfy the predicate. If we find one, return it,
358 // otherwise return null.
360 static Option *getOptionPred(StringRef Name, size_t &Length,
361 bool (*Pred)(const Option*),
362 const StringMap<Option*> &OptionsMap) {
364 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
366 // Loop while we haven't found an option and Name still has at least two
367 // characters in it (so that the next iteration will not be the empty
369 while (OMI == OptionsMap.end() && Name.size() > 1) {
370 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
371 OMI = OptionsMap.find(Name);
374 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
375 Length = Name.size();
376 return OMI->second; // Found one!
378 return 0; // No option found!
381 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
382 /// with at least one '-') does not fully match an available option. Check to
383 /// see if this is a prefix or grouped option. If so, split arg into output an
384 /// Arg/Value pair and return the Option to parse it with.
385 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
387 const StringMap<Option*> &OptionsMap) {
388 if (Arg.size() == 1) return 0;
392 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
393 if (PGOpt == 0) return 0;
395 // If the option is a prefixed option, then the value is simply the
396 // rest of the name... so fall through to later processing, by
397 // setting up the argument name flags and value fields.
398 if (PGOpt->getFormattingFlag() == cl::Prefix) {
399 Value = Arg.substr(Length);
400 Arg = Arg.substr(0, Length);
401 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
405 // This must be a grouped option... handle them now. Grouping options can't
407 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
410 // Move current arg name out of Arg into OneArgName.
411 StringRef OneArgName = Arg.substr(0, Length);
412 Arg = Arg.substr(Length);
414 // Because ValueRequired is an invalid flag for grouped arguments,
415 // we don't need to pass argc/argv in.
416 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
417 "Option can not be cl::Grouping AND cl::ValueRequired!");
419 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
420 StringRef(), 0, 0, Dummy);
422 // Get the next grouping option.
423 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
424 } while (PGOpt && Length != Arg.size());
426 // Return the last option with Arg cut down to just the last one.
432 static bool RequiresValue(const Option *O) {
433 return O->getNumOccurrencesFlag() == cl::Required ||
434 O->getNumOccurrencesFlag() == cl::OneOrMore;
437 static bool EatsUnboundedNumberOfValues(const Option *O) {
438 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
439 O->getNumOccurrencesFlag() == cl::OneOrMore;
442 static bool isWhitespace(char C) {
443 return strchr(" \t\n\r\f\v", C);
446 static bool isQuote(char C) {
447 return C == '\"' || C == '\'';
450 static bool isGNUSpecial(char C) {
451 return strchr("\\\"\' ", C);
454 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
455 SmallVectorImpl<const char *> &NewArgv) {
456 SmallString<128> Token;
457 for (size_t I = 0, E = Src.size(); I != E; ++I) {
458 // Consume runs of whitespace.
460 while (I != E && isWhitespace(Src[I]))
465 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
466 // they are literal. This makes it much easier to read Windows file paths.
467 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
468 ++I; // Skip the escape.
469 Token.push_back(Src[I]);
473 // Consume a quoted string.
474 if (isQuote(Src[I])) {
475 char Quote = Src[I++];
476 while (I != E && Src[I] != Quote) {
477 // Backslashes are literal, unless they escape a special character.
478 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
480 Token.push_back(Src[I]);
487 // End the token if this is whitespace.
488 if (isWhitespace(Src[I])) {
490 NewArgv.push_back(Saver.SaveString(Token.c_str()));
495 // This is a normal character. Append it.
496 Token.push_back(Src[I]);
499 // Append the last token after hitting EOF with no whitespace.
501 NewArgv.push_back(Saver.SaveString(Token.c_str()));
504 /// Backslashes are interpreted in a rather complicated way in the Windows-style
505 /// command line, because backslashes are used both to separate path and to
506 /// escape double quote. This method consumes runs of backslashes as well as the
507 /// following double quote if it's escaped.
509 /// * If an even number of backslashes is followed by a double quote, one
510 /// backslash is output for every pair of backslashes, and the last double
511 /// quote remains unconsumed. The double quote will later be interpreted as
512 /// the start or end of a quoted string in the main loop outside of this
515 /// * If an odd number of backslashes is followed by a double quote, one
516 /// backslash is output for every pair of backslashes, and a double quote is
517 /// output for the last pair of backslash-double quote. The double quote is
518 /// consumed in this case.
520 /// * Otherwise, backslashes are interpreted literally.
521 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
522 size_t E = Src.size();
523 int BackslashCount = 0;
524 // Skip the backslashes.
528 } while (I != E && Src[I] == '\\');
530 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
531 if (FollowedByDoubleQuote) {
532 Token.append(BackslashCount / 2, '\\');
533 if (BackslashCount % 2 == 0)
535 Token.push_back('"');
538 Token.append(BackslashCount, '\\');
542 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
543 SmallVectorImpl<const char *> &NewArgv) {
544 SmallString<128> Token;
546 // This is a small state machine to consume characters until it reaches the
547 // end of the source string.
548 enum { INIT, UNQUOTED, QUOTED } State = INIT;
549 for (size_t I = 0, E = Src.size(); I != E; ++I) {
550 // INIT state indicates that the current input index is at the start of
551 // the string or between tokens.
553 if (isWhitespace(Src[I]))
559 if (Src[I] == '\\') {
560 I = parseBackslash(Src, I, Token);
564 Token.push_back(Src[I]);
569 // UNQUOTED state means that it's reading a token not quoted by double
571 if (State == UNQUOTED) {
572 // Whitespace means the end of the token.
573 if (isWhitespace(Src[I])) {
574 NewArgv.push_back(Saver.SaveString(Token.c_str()));
583 if (Src[I] == '\\') {
584 I = parseBackslash(Src, I, Token);
587 Token.push_back(Src[I]);
591 // QUOTED state means that it's reading a token quoted by double quotes.
592 if (State == QUOTED) {
597 if (Src[I] == '\\') {
598 I = parseBackslash(Src, I, Token);
601 Token.push_back(Src[I]);
604 // Append the last token after hitting EOF with no whitespace.
606 NewArgv.push_back(Saver.SaveString(Token.c_str()));
609 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
610 TokenizerCallback Tokenizer,
611 SmallVectorImpl<const char *> &NewArgv) {
612 OwningPtr<MemoryBuffer> MemBuf;
613 if (MemoryBuffer::getFile(FName, MemBuf))
615 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
617 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
618 ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd());
620 if (hasUTF16ByteOrderMark(BufRef)) {
621 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
623 Str = StringRef(UTF8Buf);
626 // Tokenize the contents into NewArgv.
627 Tokenizer(Str, Saver, NewArgv);
632 /// \brief Expand response files on a command line recursively using the given
633 /// StringSaver and tokenization strategy.
634 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
635 SmallVectorImpl<const char *> &Argv) {
636 unsigned RspFiles = 0;
637 bool AllExpanded = true;
639 // Don't cache Argv.size() because it can change.
640 for (unsigned I = 0; I != Argv.size(); ) {
641 const char *Arg = Argv[I];
647 // If we have too many response files, leave some unexpanded. This avoids
648 // crashing on self-referential response files.
652 // Replace this response file argument with the tokenization of its
653 // contents. Nested response files are expanded in subsequent iterations.
654 // FIXME: If a nested response file uses a relative path, is it relative to
655 // the cwd of the process or the response file?
656 SmallVector<const char *, 0> ExpandedArgv;
657 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
661 Argv.erase(Argv.begin() + I);
662 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
668 class StrDupSaver : public StringSaver {
669 std::vector<char*> Dups;
672 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
678 const char *SaveString(const char *Str) LLVM_OVERRIDE {
679 char *Dup = strdup(Str);
686 /// ParseEnvironmentOptions - An alternative entry point to the
687 /// CommandLine library, which allows you to read the program's name
688 /// from the caller (as PROGNAME) and its command-line arguments from
689 /// an environment variable (whose name is given in ENVVAR).
691 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
692 const char *Overview) {
694 assert(progName && "Program name not specified");
695 assert(envVar && "Environment variable name missing");
697 // Get the environment variable they want us to parse options out of.
698 const char *envValue = getenv(envVar);
702 // Get program's "name", which we wouldn't know without the caller
704 SmallVector<const char *, 20> newArgv;
706 newArgv.push_back(Saver.SaveString(progName));
708 // Parse the value of the environment variable into a "command line"
709 // and hand it off to ParseCommandLineOptions().
710 TokenizeGNUCommandLine(envValue, Saver, newArgv);
711 int newArgc = static_cast<int>(newArgv.size());
712 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
715 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
716 const char *Overview) {
717 // Process all registered options.
718 SmallVector<Option*, 4> PositionalOpts;
719 SmallVector<Option*, 4> SinkOpts;
720 StringMap<Option*> Opts;
721 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
723 assert((!Opts.empty() || !PositionalOpts.empty()) &&
724 "No options specified!");
726 // Expand response files.
727 SmallVector<const char *, 20> newArgv;
728 for (int i = 0; i != argc; ++i)
729 newArgv.push_back(argv[i]);
731 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
733 argc = static_cast<int>(newArgv.size());
735 // Copy the program name into ProgName, making sure not to overflow it.
736 std::string ProgName = sys::path::filename(argv[0]);
737 size_t Len = std::min(ProgName.size(), size_t(79));
738 memcpy(ProgramName, ProgName.data(), Len);
739 ProgramName[Len] = '\0';
741 ProgramOverview = Overview;
742 bool ErrorParsing = false;
744 // Check out the positional arguments to collect information about them.
745 unsigned NumPositionalRequired = 0;
747 // Determine whether or not there are an unlimited number of positionals
748 bool HasUnlimitedPositionals = false;
750 Option *ConsumeAfterOpt = 0;
751 if (!PositionalOpts.empty()) {
752 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
753 assert(PositionalOpts.size() > 1 &&
754 "Cannot specify cl::ConsumeAfter without a positional argument!");
755 ConsumeAfterOpt = PositionalOpts[0];
758 // Calculate how many positional values are _required_.
759 bool UnboundedFound = false;
760 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
762 Option *Opt = PositionalOpts[i];
763 if (RequiresValue(Opt))
764 ++NumPositionalRequired;
765 else if (ConsumeAfterOpt) {
766 // ConsumeAfter cannot be combined with "optional" positional options
767 // unless there is only one positional argument...
768 if (PositionalOpts.size() > 2)
770 Opt->error("error - this positional option will never be matched, "
771 "because it does not Require a value, and a "
772 "cl::ConsumeAfter option is active!");
773 } else if (UnboundedFound && !Opt->ArgStr[0]) {
774 // This option does not "require" a value... Make sure this option is
775 // not specified after an option that eats all extra arguments, or this
776 // one will never get any!
778 ErrorParsing |= Opt->error("error - option can never match, because "
779 "another positional argument will match an "
780 "unbounded number of values, and this option"
781 " does not require a value!");
783 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
785 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
788 // PositionalVals - A vector of "positional" arguments we accumulate into
789 // the process at the end.
791 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
793 // If the program has named positional arguments, and the name has been run
794 // across, keep track of which positional argument was named. Otherwise put
795 // the positional args into the PositionalVals list...
796 Option *ActivePositionalArg = 0;
798 // Loop over all of the arguments... processing them.
799 bool DashDashFound = false; // Have we read '--'?
800 for (int i = 1; i < argc; ++i) {
802 Option *NearestHandler = 0;
803 std::string NearestHandlerString;
805 StringRef ArgName = "";
807 // If the option list changed, this means that some command line
808 // option has just been registered or deregistered. This can occur in
809 // response to things like -load, etc. If this happens, rescan the options.
810 if (OptionListChanged) {
811 PositionalOpts.clear();
814 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
815 OptionListChanged = false;
818 // Check to see if this is a positional argument. This argument is
819 // considered to be positional if it doesn't start with '-', if it is "-"
820 // itself, or if we have seen "--" already.
822 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
823 // Positional argument!
824 if (ActivePositionalArg) {
825 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
826 continue; // We are done!
829 if (!PositionalOpts.empty()) {
830 PositionalVals.push_back(std::make_pair(argv[i],i));
832 // All of the positional arguments have been fulfulled, give the rest to
833 // the consume after option... if it's specified...
835 if (PositionalVals.size() >= NumPositionalRequired &&
836 ConsumeAfterOpt != 0) {
837 for (++i; i < argc; ++i)
838 PositionalVals.push_back(std::make_pair(argv[i],i));
839 break; // Handle outside of the argument processing loop...
842 // Delay processing positional arguments until the end...
845 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
847 DashDashFound = true; // This is the mythical "--"?
848 continue; // Don't try to process it as an argument itself.
849 } else if (ActivePositionalArg &&
850 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
851 // If there is a positional argument eating options, check to see if this
852 // option is another positional argument. If so, treat it as an argument,
853 // otherwise feed it to the eating positional.
855 // Eat leading dashes.
856 while (!ArgName.empty() && ArgName[0] == '-')
857 ArgName = ArgName.substr(1);
859 Handler = LookupOption(ArgName, Value, Opts);
860 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
861 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
862 continue; // We are done!
865 } else { // We start with a '-', must be an argument.
867 // Eat leading dashes.
868 while (!ArgName.empty() && ArgName[0] == '-')
869 ArgName = ArgName.substr(1);
871 Handler = LookupOption(ArgName, Value, Opts);
873 // Check to see if this "option" is really a prefixed or grouped argument.
875 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
878 // Otherwise, look for the closest available option to report to the user
879 // in the upcoming error.
880 if (Handler == 0 && SinkOpts.empty())
881 NearestHandler = LookupNearestOption(ArgName, Opts,
882 NearestHandlerString);
886 if (SinkOpts.empty()) {
887 errs() << ProgramName << ": Unknown command line argument '"
888 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
890 if (NearestHandler) {
891 // If we know a near match, report it as well.
892 errs() << ProgramName << ": Did you mean '-"
893 << NearestHandlerString << "'?\n";
898 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
899 E = SinkOpts.end(); I != E ; ++I)
900 (*I)->addOccurrence(i, "", argv[i]);
905 // If this is a named positional argument, just remember that it is the
907 if (Handler->getFormattingFlag() == cl::Positional)
908 ActivePositionalArg = Handler;
910 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
913 // Check and handle positional arguments now...
914 if (NumPositionalRequired > PositionalVals.size()) {
915 errs() << ProgramName
916 << ": Not enough positional command line arguments specified!\n"
917 << "Must specify at least " << NumPositionalRequired
918 << " positional arguments: See: " << argv[0] << " -help\n";
921 } else if (!HasUnlimitedPositionals &&
922 PositionalVals.size() > PositionalOpts.size()) {
923 errs() << ProgramName
924 << ": Too many positional arguments specified!\n"
925 << "Can specify at most " << PositionalOpts.size()
926 << " positional arguments: See: " << argv[0] << " -help\n";
929 } else if (ConsumeAfterOpt == 0) {
930 // Positional args have already been handled if ConsumeAfter is specified.
931 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
932 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
933 if (RequiresValue(PositionalOpts[i])) {
934 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
935 PositionalVals[ValNo].second);
937 --NumPositionalRequired; // We fulfilled our duty...
940 // If we _can_ give this option more arguments, do so now, as long as we
941 // do not give it values that others need. 'Done' controls whether the
942 // option even _WANTS_ any more.
944 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
945 while (NumVals-ValNo > NumPositionalRequired && !Done) {
946 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
948 Done = true; // Optional arguments want _at most_ one value
950 case cl::ZeroOrMore: // Zero or more will take all they can get...
951 case cl::OneOrMore: // One or more will take all they can get...
952 ProvidePositionalOption(PositionalOpts[i],
953 PositionalVals[ValNo].first,
954 PositionalVals[ValNo].second);
958 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
959 "positional argument processing!");
964 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
966 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
967 if (RequiresValue(PositionalOpts[j])) {
968 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
969 PositionalVals[ValNo].first,
970 PositionalVals[ValNo].second);
974 // Handle the case where there is just one positional option, and it's
975 // optional. In this case, we want to give JUST THE FIRST option to the
976 // positional option and keep the rest for the consume after. The above
977 // loop would have assigned no values to positional options in this case.
979 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
980 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
981 PositionalVals[ValNo].first,
982 PositionalVals[ValNo].second);
986 // Handle over all of the rest of the arguments to the
987 // cl::ConsumeAfter command line option...
988 for (; ValNo != PositionalVals.size(); ++ValNo)
989 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
990 PositionalVals[ValNo].first,
991 PositionalVals[ValNo].second);
994 // Loop over args and make sure all required args are specified!
995 for (StringMap<Option*>::iterator I = Opts.begin(),
996 E = Opts.end(); I != E; ++I) {
997 switch (I->second->getNumOccurrencesFlag()) {
1000 if (I->second->getNumOccurrences() == 0) {
1001 I->second->error("must be specified at least once!");
1002 ErrorParsing = true;
1010 // Now that we know if -debug is specified, we can use it.
1011 // Note that if ReadResponseFiles == true, this must be done before the
1012 // memory allocated for the expanded command line is free()d below.
1013 DEBUG(dbgs() << "Args: ";
1014 for (int i = 0; i < argc; ++i)
1015 dbgs() << argv[i] << ' ';
1019 // Free all of the memory allocated to the map. Command line options may only
1020 // be processed once!
1022 PositionalOpts.clear();
1025 // If we had an error processing our arguments, don't let the program execute
1026 if (ErrorParsing) exit(1);
1029 //===----------------------------------------------------------------------===//
1030 // Option Base class implementation
1033 bool Option::error(const Twine &Message, StringRef ArgName) {
1034 if (ArgName.data() == 0) ArgName = ArgStr;
1035 if (ArgName.empty())
1036 errs() << HelpStr; // Be nice for positional arguments
1038 errs() << ProgramName << ": for the -" << ArgName;
1040 errs() << " option: " << Message << "\n";
1044 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
1045 StringRef Value, bool MultiArg) {
1047 NumOccurrences++; // Increment the number of times we have been seen
1049 switch (getNumOccurrencesFlag()) {
1051 if (NumOccurrences > 1)
1052 return error("may only occur zero or one times!", ArgName);
1055 if (NumOccurrences > 1)
1056 return error("must occur exactly one time!", ArgName);
1060 case ConsumeAfter: break;
1063 return handleOccurrence(pos, ArgName, Value);
1067 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1068 // has been specified yet.
1070 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1071 if (O.ValueStr[0] == 0) return DefaultMsg;
1075 //===----------------------------------------------------------------------===//
1076 // cl::alias class implementation
1079 // Return the width of the option tag for printing...
1080 size_t alias::getOptionWidth() const {
1081 return std::strlen(ArgStr)+6;
1084 static void printHelpStr(StringRef HelpStr, size_t Indent,
1085 size_t FirstLineIndentedBy) {
1086 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1087 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1088 while (!Split.second.empty()) {
1089 Split = Split.second.split('\n');
1090 outs().indent(Indent) << Split.first << "\n";
1094 // Print out the option for the alias.
1095 void alias::printOptionInfo(size_t GlobalWidth) const {
1096 outs() << " -" << ArgStr;
1097 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1100 //===----------------------------------------------------------------------===//
1101 // Parser Implementation code...
1104 // basic_parser implementation
1107 // Return the width of the option tag for printing...
1108 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1109 size_t Len = std::strlen(O.ArgStr);
1110 if (const char *ValName = getValueName())
1111 Len += std::strlen(getValueStr(O, ValName))+3;
1116 // printOptionInfo - Print out information about this option. The
1117 // to-be-maintained width is specified.
1119 void basic_parser_impl::printOptionInfo(const Option &O,
1120 size_t GlobalWidth) const {
1121 outs() << " -" << O.ArgStr;
1123 if (const char *ValName = getValueName())
1124 outs() << "=<" << getValueStr(O, ValName) << '>';
1126 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1129 void basic_parser_impl::printOptionName(const Option &O,
1130 size_t GlobalWidth) const {
1131 outs() << " -" << O.ArgStr;
1132 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1136 // parser<bool> implementation
1138 bool parser<bool>::parse(Option &O, StringRef ArgName,
1139 StringRef Arg, bool &Value) {
1140 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1146 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1150 return O.error("'" + Arg +
1151 "' is invalid value for boolean argument! Try 0 or 1");
1154 // parser<boolOrDefault> implementation
1156 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
1157 StringRef Arg, boolOrDefault &Value) {
1158 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1163 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1168 return O.error("'" + Arg +
1169 "' is invalid value for boolean argument! Try 0 or 1");
1172 // parser<int> implementation
1174 bool parser<int>::parse(Option &O, StringRef ArgName,
1175 StringRef Arg, int &Value) {
1176 if (Arg.getAsInteger(0, Value))
1177 return O.error("'" + Arg + "' value invalid for integer argument!");
1181 // parser<unsigned> implementation
1183 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1184 StringRef Arg, unsigned &Value) {
1186 if (Arg.getAsInteger(0, Value))
1187 return O.error("'" + Arg + "' value invalid for uint argument!");
1191 // parser<unsigned long long> implementation
1193 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1194 StringRef Arg, unsigned long long &Value){
1196 if (Arg.getAsInteger(0, Value))
1197 return O.error("'" + Arg + "' value invalid for uint argument!");
1201 // parser<double>/parser<float> implementation
1203 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1204 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1205 const char *ArgStart = TmpStr.c_str();
1207 Value = strtod(ArgStart, &End);
1209 return O.error("'" + Arg + "' value invalid for floating point argument!");
1213 bool parser<double>::parse(Option &O, StringRef ArgName,
1214 StringRef Arg, double &Val) {
1215 return parseDouble(O, Arg, Val);
1218 bool parser<float>::parse(Option &O, StringRef ArgName,
1219 StringRef Arg, float &Val) {
1221 if (parseDouble(O, Arg, dVal))
1229 // generic_parser_base implementation
1232 // findOption - Return the option number corresponding to the specified
1233 // argument string. If the option is not found, getNumOptions() is returned.
1235 unsigned generic_parser_base::findOption(const char *Name) {
1236 unsigned e = getNumOptions();
1238 for (unsigned i = 0; i != e; ++i) {
1239 if (strcmp(getOption(i), Name) == 0)
1246 // Return the width of the option tag for printing...
1247 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1248 if (O.hasArgStr()) {
1249 size_t Size = std::strlen(O.ArgStr)+6;
1250 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1251 Size = std::max(Size, std::strlen(getOption(i))+8);
1254 size_t BaseSize = 0;
1255 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1256 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1261 // printOptionInfo - Print out information about this option. The
1262 // to-be-maintained width is specified.
1264 void generic_parser_base::printOptionInfo(const Option &O,
1265 size_t GlobalWidth) const {
1266 if (O.hasArgStr()) {
1267 outs() << " -" << O.ArgStr;
1268 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1270 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1271 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1272 outs() << " =" << getOption(i);
1273 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1277 outs() << " " << O.HelpStr << '\n';
1278 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1279 const char *Option = getOption(i);
1280 outs() << " -" << Option;
1281 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1286 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1288 // printGenericOptionDiff - Print the value of this option and it's default.
1290 // "Generic" options have each value mapped to a name.
1291 void generic_parser_base::
1292 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1293 const GenericOptionValue &Default,
1294 size_t GlobalWidth) const {
1295 outs() << " -" << O.ArgStr;
1296 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1298 unsigned NumOpts = getNumOptions();
1299 for (unsigned i = 0; i != NumOpts; ++i) {
1300 if (Value.compare(getOptionValue(i)))
1303 outs() << "= " << getOption(i);
1304 size_t L = std::strlen(getOption(i));
1305 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1306 outs().indent(NumSpaces) << " (default: ";
1307 for (unsigned j = 0; j != NumOpts; ++j) {
1308 if (Default.compare(getOptionValue(j)))
1310 outs() << getOption(j);
1316 outs() << "= *unknown option value*\n";
1319 // printOptionDiff - Specializations for printing basic value types.
1321 #define PRINT_OPT_DIFF(T) \
1323 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1324 size_t GlobalWidth) const { \
1325 printOptionName(O, GlobalWidth); \
1328 raw_string_ostream SS(Str); \
1331 outs() << "= " << Str; \
1332 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1333 outs().indent(NumSpaces) << " (default: "; \
1335 outs() << D.getValue(); \
1337 outs() << "*no default*"; \
1341 PRINT_OPT_DIFF(bool)
1342 PRINT_OPT_DIFF(boolOrDefault)
1344 PRINT_OPT_DIFF(unsigned)
1345 PRINT_OPT_DIFF(unsigned long long)
1346 PRINT_OPT_DIFF(double)
1347 PRINT_OPT_DIFF(float)
1348 PRINT_OPT_DIFF(char)
1350 void parser<std::string>::
1351 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1352 size_t GlobalWidth) const {
1353 printOptionName(O, GlobalWidth);
1354 outs() << "= " << V;
1355 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1356 outs().indent(NumSpaces) << " (default: ";
1358 outs() << D.getValue();
1360 outs() << "*no default*";
1364 // Print a placeholder for options that don't yet support printOptionDiff().
1365 void basic_parser_impl::
1366 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1367 printOptionName(O, GlobalWidth);
1368 outs() << "= *cannot print option value*\n";
1371 //===----------------------------------------------------------------------===//
1372 // -help and -help-hidden option implementation
1375 static int OptNameCompare(const void *LHS, const void *RHS) {
1376 typedef std::pair<const char *, Option*> pair_ty;
1378 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1381 // Copy Options into a vector so we can sort them as we like.
1383 sortOpts(StringMap<Option*> &OptMap,
1384 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1386 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1388 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1390 // Ignore really-hidden options.
1391 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1394 // Unless showhidden is set, ignore hidden flags.
1395 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1398 // If we've already seen this option, don't add it to the list again.
1399 if (!OptionSet.insert(I->second))
1402 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1406 // Sort the options list alphabetically.
1407 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1414 const bool ShowHidden;
1415 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1416 // Print the options. Opts is assumed to be alphabetically sorted.
1417 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1418 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1419 Opts[i].second->printOptionInfo(MaxArgLen);
1423 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1424 virtual ~HelpPrinter() {}
1426 // Invoke the printer.
1427 void operator=(bool Value) {
1428 if (Value == false) return;
1430 // Get all the options.
1431 SmallVector<Option*, 4> PositionalOpts;
1432 SmallVector<Option*, 4> SinkOpts;
1433 StringMap<Option*> OptMap;
1434 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1436 StrOptionPairVector Opts;
1437 sortOpts(OptMap, Opts, ShowHidden);
1439 if (ProgramOverview)
1440 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1442 outs() << "USAGE: " << ProgramName << " [options]";
1444 // Print out the positional options.
1445 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
1446 if (!PositionalOpts.empty() &&
1447 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1448 CAOpt = PositionalOpts[0];
1450 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1451 if (PositionalOpts[i]->ArgStr[0])
1452 outs() << " --" << PositionalOpts[i]->ArgStr;
1453 outs() << " " << PositionalOpts[i]->HelpStr;
1456 // Print the consume after option info if it exists...
1457 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1461 // Compute the maximum argument length...
1462 size_t MaxArgLen = 0;
1463 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1464 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1466 outs() << "OPTIONS:\n";
1467 printOptions(Opts, MaxArgLen);
1469 // Print any extra help the user has declared.
1470 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1471 E = MoreHelp->end();
1476 // Halt the program since help information was printed
1481 class CategorizedHelpPrinter : public HelpPrinter {
1483 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1485 // Helper function for printOptions().
1486 // It shall return true if A's name should be lexographically
1487 // ordered before B's name. It returns false otherwise.
1488 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1489 int Length = strcmp(A->getName(), B->getName());
1490 assert(Length != 0 && "Duplicate option categories");
1494 // Make sure we inherit our base class's operator=()
1495 using HelpPrinter::operator= ;
1498 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1499 std::vector<OptionCategory *> SortedCategories;
1500 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1502 // Collect registered option categories into vector in preperation for
1504 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1505 E = RegisteredOptionCategories->end();
1507 SortedCategories.push_back(*I);
1509 // Sort the different option categories alphabetically.
1510 assert(SortedCategories.size() > 0 && "No option categories registered!");
1511 std::sort(SortedCategories.begin(), SortedCategories.end(),
1512 OptionCategoryCompare);
1514 // Create map to empty vectors.
1515 for (std::vector<OptionCategory *>::const_iterator
1516 I = SortedCategories.begin(),
1517 E = SortedCategories.end();
1519 CategorizedOptions[*I] = std::vector<Option *>();
1521 // Walk through pre-sorted options and assign into categories.
1522 // Because the options are already alphabetically sorted the
1523 // options within categories will also be alphabetically sorted.
1524 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1525 Option *Opt = Opts[I].second;
1526 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1527 "Option has an unregistered category");
1528 CategorizedOptions[Opt->Category].push_back(Opt);
1532 for (std::vector<OptionCategory *>::const_iterator
1533 Category = SortedCategories.begin(),
1534 E = SortedCategories.end();
1535 Category != E; ++Category) {
1536 // Hide empty categories for -help, but show for -help-hidden.
1537 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1538 if (!ShowHidden && IsEmptyCategory)
1541 // Print category information.
1543 outs() << (*Category)->getName() << ":\n";
1545 // Check if description is set.
1546 if ((*Category)->getDescription() != 0)
1547 outs() << (*Category)->getDescription() << "\n\n";
1551 // When using -help-hidden explicitly state if the category has no
1552 // options associated with it.
1553 if (IsEmptyCategory) {
1554 outs() << " This option category has no options.\n";
1557 // Loop over the options in the category and print.
1558 for (std::vector<Option *>::const_iterator
1559 Opt = CategorizedOptions[*Category].begin(),
1560 E = CategorizedOptions[*Category].end();
1562 (*Opt)->printOptionInfo(MaxArgLen);
1567 // This wraps the Uncategorizing and Categorizing printers and decides
1568 // at run time which should be invoked.
1569 class HelpPrinterWrapper {
1571 HelpPrinter &UncategorizedPrinter;
1572 CategorizedHelpPrinter &CategorizedPrinter;
1575 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1576 CategorizedHelpPrinter &CategorizedPrinter) :
1577 UncategorizedPrinter(UncategorizedPrinter),
1578 CategorizedPrinter(CategorizedPrinter) { }
1580 // Invoke the printer.
1581 void operator=(bool Value);
1584 } // End anonymous namespace
1586 // Declare the four HelpPrinter instances that are used to print out help, or
1587 // help-hidden as an uncategorized list or in categories.
1588 static HelpPrinter UncategorizedNormalPrinter(false);
1589 static HelpPrinter UncategorizedHiddenPrinter(true);
1590 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1591 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1594 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1595 // a categorizing help printer
1596 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1597 CategorizedNormalPrinter);
1598 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1599 CategorizedHiddenPrinter);
1601 // Define uncategorized help printers.
1602 // -help-list is hidden by default because if Option categories are being used
1603 // then -help behaves the same as -help-list.
1604 static cl::opt<HelpPrinter, true, parser<bool> >
1606 cl::desc("Display list of available options (-help-list-hidden for more)"),
1607 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1609 static cl::opt<HelpPrinter, true, parser<bool> >
1610 HLHOp("help-list-hidden",
1611 cl::desc("Display list of all available options"),
1612 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1614 // Define uncategorized/categorized help printers. These printers change their
1615 // behaviour at runtime depending on whether one or more Option categories have
1617 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1618 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1619 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1621 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1622 HHOp("help-hidden", cl::desc("Display all available options"),
1623 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1627 static cl::opt<bool>
1628 PrintOptions("print-options",
1629 cl::desc("Print non-default options after command line parsing"),
1630 cl::Hidden, cl::init(false));
1632 static cl::opt<bool>
1633 PrintAllOptions("print-all-options",
1634 cl::desc("Print all option values after command line parsing"),
1635 cl::Hidden, cl::init(false));
1637 void HelpPrinterWrapper::operator=(bool Value) {
1641 // Decide which printer to invoke. If more than one option category is
1642 // registered then it is useful to show the categorized help instead of
1643 // uncategorized help.
1644 if (RegisteredOptionCategories->size() > 1) {
1645 // unhide -help-list option so user can have uncategorized output if they
1647 HLOp.setHiddenFlag(NotHidden);
1649 CategorizedPrinter = true; // Invoke categorized printer
1652 UncategorizedPrinter = true; // Invoke uncategorized printer
1655 // Print the value of each option.
1656 void cl::PrintOptionValues() {
1657 if (!PrintOptions && !PrintAllOptions) return;
1659 // Get all the options.
1660 SmallVector<Option*, 4> PositionalOpts;
1661 SmallVector<Option*, 4> SinkOpts;
1662 StringMap<Option*> OptMap;
1663 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1665 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1666 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1668 // Compute the maximum argument length...
1669 size_t MaxArgLen = 0;
1670 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1671 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1673 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1674 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1677 static void (*OverrideVersionPrinter)() = 0;
1679 static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1682 class VersionPrinter {
1685 raw_ostream &OS = outs();
1686 OS << "LLVM (http://llvm.org/):\n"
1687 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1688 #ifdef LLVM_VERSION_INFO
1689 OS << LLVM_VERSION_INFO;
1692 #ifndef __OPTIMIZE__
1693 OS << "DEBUG build";
1695 OS << "Optimized build";
1698 OS << " with assertions";
1700 std::string CPU = sys::getHostCPUName();
1701 if (CPU == "generic") CPU = "(unknown)";
1703 #if (ENABLE_TIMESTAMPS == 1)
1704 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1706 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1707 << " Host CPU: " << CPU << '\n';
1709 void operator=(bool OptionWasSpecified) {
1710 if (!OptionWasSpecified) return;
1712 if (OverrideVersionPrinter != 0) {
1713 (*OverrideVersionPrinter)();
1718 // Iterate over any registered extra printers and call them to add further
1720 if (ExtraVersionPrinters != 0) {
1722 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1723 E = ExtraVersionPrinters->end();
1731 } // End anonymous namespace
1734 // Define the --version option that prints out the LLVM version for the tool
1735 static VersionPrinter VersionPrinterInstance;
1737 static cl::opt<VersionPrinter, true, parser<bool> >
1738 VersOp("version", cl::desc("Display the version of this program"),
1739 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1741 // Utility function for printing the help message.
1742 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1743 // This looks weird, but it actually prints the help message. The Printers are
1744 // types of HelpPrinter and the help gets printed when its operator= is
1745 // invoked. That's because the "normal" usages of the help printer is to be
1746 // assigned true/false depending on whether -help or -help-hidden was given or
1747 // not. Since we're circumventing that we have to make it look like -help or
1748 // -help-hidden were given, so we assign true.
1750 if (!Hidden && !Categorized)
1751 UncategorizedNormalPrinter = true;
1752 else if (!Hidden && Categorized)
1753 CategorizedNormalPrinter = true;
1754 else if (Hidden && !Categorized)
1755 UncategorizedHiddenPrinter = true;
1757 CategorizedHiddenPrinter = true;
1760 /// Utility function for printing version number.
1761 void cl::PrintVersionMessage() {
1762 VersionPrinterInstance.print();
1765 void cl::SetVersionPrinter(void (*func)()) {
1766 OverrideVersionPrinter = func;
1769 void cl::AddExtraVersionPrinter(void (*func)()) {
1770 if (ExtraVersionPrinters == 0)
1771 ExtraVersionPrinters = new std::vector<void (*)()>;
1773 ExtraVersionPrinters->push_back(func);
1776 void cl::getRegisteredOptions(StringMap<Option*> &Map)
1778 // Get all the options.
1779 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1780 SmallVector<Option*, 4> SinkOpts; //NOT USED
1781 assert(Map.size() == 0 && "StringMap must be empty");
1782 GetOptionInfo(PositionalOpts, SinkOpts, Map);