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"
43 //===----------------------------------------------------------------------===//
44 // Template instantiations and anchors.
46 namespace llvm { namespace cl {
47 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
48 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
49 TEMPLATE_INSTANTIATION(class basic_parser<int>);
50 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
51 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
52 TEMPLATE_INSTANTIATION(class basic_parser<double>);
53 TEMPLATE_INSTANTIATION(class basic_parser<float>);
54 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
55 TEMPLATE_INSTANTIATION(class basic_parser<char>);
57 TEMPLATE_INSTANTIATION(class opt<unsigned>);
58 TEMPLATE_INSTANTIATION(class opt<int>);
59 TEMPLATE_INSTANTIATION(class opt<std::string>);
60 TEMPLATE_INSTANTIATION(class opt<char>);
61 TEMPLATE_INSTANTIATION(class opt<bool>);
62 } } // end namespace llvm::cl
64 // Pin the vtables to this file.
65 void GenericOptionValue::anchor() {}
66 void OptionValue<boolOrDefault>::anchor() {}
67 void OptionValue<std::string>::anchor() {}
68 void Option::anchor() {}
69 void basic_parser_impl::anchor() {}
70 void parser<bool>::anchor() {}
71 void parser<boolOrDefault>::anchor() {}
72 void parser<int>::anchor() {}
73 void parser<unsigned>::anchor() {}
74 void parser<unsigned long long>::anchor() {}
75 void parser<double>::anchor() {}
76 void parser<float>::anchor() {}
77 void parser<std::string>::anchor() {}
78 void parser<char>::anchor() {}
79 void StringSaver::anchor() {}
81 //===----------------------------------------------------------------------===//
83 // Globals for name and overview of program. Program name is not a string to
84 // avoid static ctor/dtor issues.
85 static char ProgramName[80] = "<premain>";
86 static const char *ProgramOverview = 0;
88 // This collects additional help to be printed.
89 static ManagedStatic<std::vector<const char*> > MoreHelp;
91 extrahelp::extrahelp(const char *Help)
93 MoreHelp->push_back(Help);
96 static bool OptionListChanged = false;
98 // MarkOptionsChanged - Internal helper function.
99 void cl::MarkOptionsChanged() {
100 OptionListChanged = true;
103 /// RegisteredOptionList - This is the list of the command line options that
104 /// have statically constructed themselves.
105 static Option *RegisteredOptionList = 0;
107 void Option::addArgument() {
108 assert(NextRegistered == 0 && "argument multiply registered!");
110 NextRegistered = RegisteredOptionList;
111 RegisteredOptionList = this;
112 MarkOptionsChanged();
115 void Option::removeArgument() {
116 assert(NextRegistered != 0 && "argument never registered");
117 assert(RegisteredOptionList == this && "argument is not the last registered");
118 RegisteredOptionList = NextRegistered;
119 MarkOptionsChanged();
122 // This collects the different option categories that have been registered.
123 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
124 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
126 // Initialise the general option category.
127 OptionCategory llvm::cl::GeneralCategory("General options");
129 void OptionCategory::registerCategory()
131 RegisteredOptionCategories->insert(this);
134 //===----------------------------------------------------------------------===//
135 // Basic, shared command line option processing machinery.
138 /// GetOptionInfo - Scan the list of registered options, turning them into data
139 /// structures that are easier to handle.
140 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
141 SmallVectorImpl<Option*> &SinkOpts,
142 StringMap<Option*> &OptionsMap) {
143 SmallVector<const char*, 16> OptionNames;
144 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
145 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
146 // If this option wants to handle multiple option names, get the full set.
147 // This handles enum options like "-O1 -O2" etc.
148 O->getExtraOptionNames(OptionNames);
150 OptionNames.push_back(O->ArgStr);
152 // Handle named options.
153 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
154 // Add argument to the argument map!
155 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
156 errs() << ProgramName << ": CommandLine Error: Argument '"
157 << OptionNames[i] << "' defined more than once!\n";
163 // Remember information about positional options.
164 if (O->getFormattingFlag() == cl::Positional)
165 PositionalOpts.push_back(O);
166 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
167 SinkOpts.push_back(O);
168 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
170 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
176 PositionalOpts.push_back(CAOpt);
178 // Make sure that they are in order of registration not backwards.
179 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
183 /// LookupOption - Lookup the option specified by the specified option on the
184 /// command line. If there is a value specified (after an equal sign) return
185 /// that as well. This assumes that leading dashes have already been stripped.
186 static Option *LookupOption(StringRef &Arg, StringRef &Value,
187 const StringMap<Option*> &OptionsMap) {
188 // Reject all dashes.
189 if (Arg.empty()) return 0;
191 size_t EqualPos = Arg.find('=');
193 // If we have an equals sign, remember the value.
194 if (EqualPos == StringRef::npos) {
195 // Look up the option.
196 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
197 return I != OptionsMap.end() ? I->second : 0;
200 // If the argument before the = is a valid option name, we match. If not,
201 // return Arg unmolested.
202 StringMap<Option*>::const_iterator I =
203 OptionsMap.find(Arg.substr(0, EqualPos));
204 if (I == OptionsMap.end()) return 0;
206 Value = Arg.substr(EqualPos+1);
207 Arg = Arg.substr(0, EqualPos);
211 /// LookupNearestOption - Lookup the closest match to the option specified by
212 /// the specified option on the command line. If there is a value specified
213 /// (after an equal sign) return that as well. This assumes that leading dashes
214 /// have already been stripped.
215 static Option *LookupNearestOption(StringRef Arg,
216 const StringMap<Option*> &OptionsMap,
217 std::string &NearestString) {
218 // Reject all dashes.
219 if (Arg.empty()) return 0;
221 // Split on any equal sign.
222 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
223 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
224 StringRef &RHS = SplitArg.second;
226 // Find the closest match.
228 unsigned BestDistance = 0;
229 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
230 ie = OptionsMap.end(); it != ie; ++it) {
231 Option *O = it->second;
232 SmallVector<const char*, 16> OptionNames;
233 O->getExtraOptionNames(OptionNames);
235 OptionNames.push_back(O->ArgStr);
237 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
238 StringRef Flag = PermitValue ? LHS : Arg;
239 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
240 StringRef Name = OptionNames[i];
241 unsigned Distance = StringRef(Name).edit_distance(
242 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
243 if (!Best || Distance < BestDistance) {
245 BestDistance = Distance;
246 if (RHS.empty() || !PermitValue)
247 NearestString = OptionNames[i];
249 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
257 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
258 /// that does special handling of cl::CommaSeparated options.
259 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
260 StringRef ArgName, StringRef Value,
261 bool MultiArg = false) {
262 // Check to see if this option accepts a comma separated list of values. If
263 // it does, we have to split up the value into multiple values.
264 if (Handler->getMiscFlags() & CommaSeparated) {
265 StringRef Val(Value);
266 StringRef::size_type Pos = Val.find(',');
268 while (Pos != StringRef::npos) {
269 // Process the portion before the comma.
270 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
272 // Erase the portion before the comma, AND the comma.
273 Val = Val.substr(Pos+1);
274 Value.substr(Pos+1); // Increment the original value pointer as well.
275 // Check for another comma.
282 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
288 /// ProvideOption - For Value, this differentiates between an empty value ("")
289 /// and a null value (StringRef()). The later is accepted for arguments that
290 /// don't allow a value (-foo) the former is rejected (-foo=).
291 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
292 StringRef Value, int argc,
293 const char *const *argv, int &i) {
294 // Is this a multi-argument option?
295 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
297 // Enforce value requirements
298 switch (Handler->getValueExpectedFlag()) {
300 if (Value.data() == 0) { // No value specified?
302 return Handler->error("requires a value!");
303 // Steal the next argument, like for '-o filename'
307 case ValueDisallowed:
308 if (NumAdditionalVals > 0)
309 return Handler->error("multi-valued option specified"
310 " with ValueDisallowed modifier!");
313 return Handler->error("does not allow a value! '" +
314 Twine(Value) + "' specified.");
320 // If this isn't a multi-arg option, just run the handler.
321 if (NumAdditionalVals == 0)
322 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
324 // If it is, run the handle several times.
325 bool MultiArg = false;
328 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
334 while (NumAdditionalVals > 0) {
336 return Handler->error("not enough values!");
339 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
347 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
349 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
353 // Option predicates...
354 static inline bool isGrouping(const Option *O) {
355 return O->getFormattingFlag() == cl::Grouping;
357 static inline bool isPrefixedOrGrouping(const Option *O) {
358 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
361 // getOptionPred - Check to see if there are any options that satisfy the
362 // specified predicate with names that are the prefixes in Name. This is
363 // checked by progressively stripping characters off of the name, checking to
364 // see if there options that satisfy the predicate. If we find one, return it,
365 // otherwise return null.
367 static Option *getOptionPred(StringRef Name, size_t &Length,
368 bool (*Pred)(const Option*),
369 const StringMap<Option*> &OptionsMap) {
371 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
373 // Loop while we haven't found an option and Name still has at least two
374 // characters in it (so that the next iteration will not be the empty
376 while (OMI == OptionsMap.end() && Name.size() > 1) {
377 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
378 OMI = OptionsMap.find(Name);
381 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
382 Length = Name.size();
383 return OMI->second; // Found one!
385 return 0; // No option found!
388 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
389 /// with at least one '-') does not fully match an available option. Check to
390 /// see if this is a prefix or grouped option. If so, split arg into output an
391 /// Arg/Value pair and return the Option to parse it with.
392 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
394 const StringMap<Option*> &OptionsMap) {
395 if (Arg.size() == 1) return 0;
399 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
400 if (PGOpt == 0) return 0;
402 // If the option is a prefixed option, then the value is simply the
403 // rest of the name... so fall through to later processing, by
404 // setting up the argument name flags and value fields.
405 if (PGOpt->getFormattingFlag() == cl::Prefix) {
406 Value = Arg.substr(Length);
407 Arg = Arg.substr(0, Length);
408 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
412 // This must be a grouped option... handle them now. Grouping options can't
414 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
417 // Move current arg name out of Arg into OneArgName.
418 StringRef OneArgName = Arg.substr(0, Length);
419 Arg = Arg.substr(Length);
421 // Because ValueRequired is an invalid flag for grouped arguments,
422 // we don't need to pass argc/argv in.
423 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
424 "Option can not be cl::Grouping AND cl::ValueRequired!");
426 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
427 StringRef(), 0, 0, Dummy);
429 // Get the next grouping option.
430 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
431 } while (PGOpt && Length != Arg.size());
433 // Return the last option with Arg cut down to just the last one.
439 static bool RequiresValue(const Option *O) {
440 return O->getNumOccurrencesFlag() == cl::Required ||
441 O->getNumOccurrencesFlag() == cl::OneOrMore;
444 static bool EatsUnboundedNumberOfValues(const Option *O) {
445 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
446 O->getNumOccurrencesFlag() == cl::OneOrMore;
449 static bool isWhitespace(char C) {
450 return strchr(" \t\n\r\f\v", C);
453 static bool isQuote(char C) {
454 return C == '\"' || C == '\'';
457 static bool isGNUSpecial(char C) {
458 return strchr("\\\"\' ", C);
461 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
462 SmallVectorImpl<const char *> &NewArgv) {
463 SmallString<128> Token;
464 for (size_t I = 0, E = Src.size(); I != E; ++I) {
465 // Consume runs of whitespace.
467 while (I != E && isWhitespace(Src[I]))
472 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
473 // they are literal. This makes it much easier to read Windows file paths.
474 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
475 ++I; // Skip the escape.
476 Token.push_back(Src[I]);
480 // Consume a quoted string.
481 if (isQuote(Src[I])) {
482 char Quote = Src[I++];
483 while (I != E && Src[I] != Quote) {
484 // Backslashes are literal, unless they escape a special character.
485 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
487 Token.push_back(Src[I]);
494 // End the token if this is whitespace.
495 if (isWhitespace(Src[I])) {
497 NewArgv.push_back(Saver.SaveString(Token.c_str()));
502 // This is a normal character. Append it.
503 Token.push_back(Src[I]);
506 // Append the last token after hitting EOF with no whitespace.
508 NewArgv.push_back(Saver.SaveString(Token.c_str()));
511 /// Backslashes are interpreted in a rather complicated way in the Windows-style
512 /// command line, because backslashes are used both to separate path and to
513 /// escape double quote. This method consumes runs of backslashes as well as the
514 /// following double quote if it's escaped.
516 /// * If an even number of backslashes is followed by a double quote, one
517 /// backslash is output for every pair of backslashes, and the last double
518 /// quote remains unconsumed. The double quote will later be interpreted as
519 /// the start or end of a quoted string in the main loop outside of this
522 /// * If an odd number of backslashes is followed by a double quote, one
523 /// backslash is output for every pair of backslashes, and a double quote is
524 /// output for the last pair of backslash-double quote. The double quote is
525 /// consumed in this case.
527 /// * Otherwise, backslashes are interpreted literally.
528 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
529 size_t E = Src.size();
530 int BackslashCount = 0;
531 // Skip the backslashes.
535 } while (I != E && Src[I] == '\\');
537 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
538 if (FollowedByDoubleQuote) {
539 Token.append(BackslashCount / 2, '\\');
540 if (BackslashCount % 2 == 0)
542 Token.push_back('"');
545 Token.append(BackslashCount, '\\');
549 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
550 SmallVectorImpl<const char *> &NewArgv) {
551 SmallString<128> Token;
553 // This is a small state machine to consume characters until it reaches the
554 // end of the source string.
555 enum { INIT, UNQUOTED, QUOTED } State = INIT;
556 for (size_t I = 0, E = Src.size(); I != E; ++I) {
557 // INIT state indicates that the current input index is at the start of
558 // the string or between tokens.
560 if (isWhitespace(Src[I]))
566 if (Src[I] == '\\') {
567 I = parseBackslash(Src, I, Token);
571 Token.push_back(Src[I]);
576 // UNQUOTED state means that it's reading a token not quoted by double
578 if (State == UNQUOTED) {
579 // Whitespace means the end of the token.
580 if (isWhitespace(Src[I])) {
581 NewArgv.push_back(Saver.SaveString(Token.c_str()));
590 if (Src[I] == '\\') {
591 I = parseBackslash(Src, I, Token);
594 Token.push_back(Src[I]);
598 // QUOTED state means that it's reading a token quoted by double quotes.
599 if (State == QUOTED) {
604 if (Src[I] == '\\') {
605 I = parseBackslash(Src, I, Token);
608 Token.push_back(Src[I]);
611 // Append the last token after hitting EOF with no whitespace.
613 NewArgv.push_back(Saver.SaveString(Token.c_str()));
616 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
617 TokenizerCallback Tokenizer,
618 SmallVectorImpl<const char *> &NewArgv) {
619 OwningPtr<MemoryBuffer> MemBuf;
620 if (MemoryBuffer::getFile(FName, MemBuf))
622 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
624 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
625 ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd());
627 if (hasUTF16ByteOrderMark(BufRef)) {
628 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
630 Str = StringRef(UTF8Buf);
633 // Tokenize the contents into NewArgv.
634 Tokenizer(Str, Saver, NewArgv);
639 /// \brief Expand response files on a command line recursively using the given
640 /// StringSaver and tokenization strategy.
641 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
642 SmallVectorImpl<const char *> &Argv) {
643 unsigned RspFiles = 0;
644 bool AllExpanded = true;
646 // Don't cache Argv.size() because it can change.
647 for (unsigned I = 0; I != Argv.size(); ) {
648 const char *Arg = Argv[I];
654 // If we have too many response files, leave some unexpanded. This avoids
655 // crashing on self-referential response files.
659 // Replace this response file argument with the tokenization of its
660 // contents. Nested response files are expanded in subsequent iterations.
661 // FIXME: If a nested response file uses a relative path, is it relative to
662 // the cwd of the process or the response file?
663 SmallVector<const char *, 0> ExpandedArgv;
664 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
665 // We couldn't read this file, so we leave it in the argument stream and
671 Argv.erase(Argv.begin() + I);
672 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
678 class StrDupSaver : public StringSaver {
679 std::vector<char*> Dups;
682 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
688 const char *SaveString(const char *Str) LLVM_OVERRIDE {
689 char *Dup = strdup(Str);
696 /// ParseEnvironmentOptions - An alternative entry point to the
697 /// CommandLine library, which allows you to read the program's name
698 /// from the caller (as PROGNAME) and its command-line arguments from
699 /// an environment variable (whose name is given in ENVVAR).
701 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
702 const char *Overview) {
704 assert(progName && "Program name not specified");
705 assert(envVar && "Environment variable name missing");
707 // Get the environment variable they want us to parse options out of.
708 const char *envValue = getenv(envVar);
712 // Get program's "name", which we wouldn't know without the caller
714 SmallVector<const char *, 20> newArgv;
716 newArgv.push_back(Saver.SaveString(progName));
718 // Parse the value of the environment variable into a "command line"
719 // and hand it off to ParseCommandLineOptions().
720 TokenizeGNUCommandLine(envValue, Saver, newArgv);
721 int newArgc = static_cast<int>(newArgv.size());
722 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
725 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
726 const char *Overview) {
727 // Process all registered options.
728 SmallVector<Option*, 4> PositionalOpts;
729 SmallVector<Option*, 4> SinkOpts;
730 StringMap<Option*> Opts;
731 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
733 assert((!Opts.empty() || !PositionalOpts.empty()) &&
734 "No options specified!");
736 // Expand response files.
737 SmallVector<const char *, 20> newArgv;
738 for (int i = 0; i != argc; ++i)
739 newArgv.push_back(argv[i]);
741 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
743 argc = static_cast<int>(newArgv.size());
745 // Copy the program name into ProgName, making sure not to overflow it.
746 std::string ProgName = sys::path::filename(argv[0]);
747 size_t Len = std::min(ProgName.size(), size_t(79));
748 memcpy(ProgramName, ProgName.data(), Len);
749 ProgramName[Len] = '\0';
751 ProgramOverview = Overview;
752 bool ErrorParsing = false;
754 // Check out the positional arguments to collect information about them.
755 unsigned NumPositionalRequired = 0;
757 // Determine whether or not there are an unlimited number of positionals
758 bool HasUnlimitedPositionals = false;
760 Option *ConsumeAfterOpt = 0;
761 if (!PositionalOpts.empty()) {
762 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
763 assert(PositionalOpts.size() > 1 &&
764 "Cannot specify cl::ConsumeAfter without a positional argument!");
765 ConsumeAfterOpt = PositionalOpts[0];
768 // Calculate how many positional values are _required_.
769 bool UnboundedFound = false;
770 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
772 Option *Opt = PositionalOpts[i];
773 if (RequiresValue(Opt))
774 ++NumPositionalRequired;
775 else if (ConsumeAfterOpt) {
776 // ConsumeAfter cannot be combined with "optional" positional options
777 // unless there is only one positional argument...
778 if (PositionalOpts.size() > 2)
780 Opt->error("error - this positional option will never be matched, "
781 "because it does not Require a value, and a "
782 "cl::ConsumeAfter option is active!");
783 } else if (UnboundedFound && !Opt->ArgStr[0]) {
784 // This option does not "require" a value... Make sure this option is
785 // not specified after an option that eats all extra arguments, or this
786 // one will never get any!
788 ErrorParsing |= Opt->error("error - option can never match, because "
789 "another positional argument will match an "
790 "unbounded number of values, and this option"
791 " does not require a value!");
793 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
795 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
798 // PositionalVals - A vector of "positional" arguments we accumulate into
799 // the process at the end.
801 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
803 // If the program has named positional arguments, and the name has been run
804 // across, keep track of which positional argument was named. Otherwise put
805 // the positional args into the PositionalVals list...
806 Option *ActivePositionalArg = 0;
808 // Loop over all of the arguments... processing them.
809 bool DashDashFound = false; // Have we read '--'?
810 for (int i = 1; i < argc; ++i) {
812 Option *NearestHandler = 0;
813 std::string NearestHandlerString;
815 StringRef ArgName = "";
817 // If the option list changed, this means that some command line
818 // option has just been registered or deregistered. This can occur in
819 // response to things like -load, etc. If this happens, rescan the options.
820 if (OptionListChanged) {
821 PositionalOpts.clear();
824 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
825 OptionListChanged = false;
828 // Check to see if this is a positional argument. This argument is
829 // considered to be positional if it doesn't start with '-', if it is "-"
830 // itself, or if we have seen "--" already.
832 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
833 // Positional argument!
834 if (ActivePositionalArg) {
835 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
836 continue; // We are done!
839 if (!PositionalOpts.empty()) {
840 PositionalVals.push_back(std::make_pair(argv[i],i));
842 // All of the positional arguments have been fulfulled, give the rest to
843 // the consume after option... if it's specified...
845 if (PositionalVals.size() >= NumPositionalRequired &&
846 ConsumeAfterOpt != 0) {
847 for (++i; i < argc; ++i)
848 PositionalVals.push_back(std::make_pair(argv[i],i));
849 break; // Handle outside of the argument processing loop...
852 // Delay processing positional arguments until the end...
855 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
857 DashDashFound = true; // This is the mythical "--"?
858 continue; // Don't try to process it as an argument itself.
859 } else if (ActivePositionalArg &&
860 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
861 // If there is a positional argument eating options, check to see if this
862 // option is another positional argument. If so, treat it as an argument,
863 // otherwise feed it to the eating positional.
865 // Eat leading dashes.
866 while (!ArgName.empty() && ArgName[0] == '-')
867 ArgName = ArgName.substr(1);
869 Handler = LookupOption(ArgName, Value, Opts);
870 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
871 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
872 continue; // We are done!
875 } else { // We start with a '-', must be an argument.
877 // Eat leading dashes.
878 while (!ArgName.empty() && ArgName[0] == '-')
879 ArgName = ArgName.substr(1);
881 Handler = LookupOption(ArgName, Value, Opts);
883 // Check to see if this "option" is really a prefixed or grouped argument.
885 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
888 // Otherwise, look for the closest available option to report to the user
889 // in the upcoming error.
890 if (Handler == 0 && SinkOpts.empty())
891 NearestHandler = LookupNearestOption(ArgName, Opts,
892 NearestHandlerString);
896 if (SinkOpts.empty()) {
897 errs() << ProgramName << ": Unknown command line argument '"
898 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
900 if (NearestHandler) {
901 // If we know a near match, report it as well.
902 errs() << ProgramName << ": Did you mean '-"
903 << NearestHandlerString << "'?\n";
908 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
909 E = SinkOpts.end(); I != E ; ++I)
910 (*I)->addOccurrence(i, "", argv[i]);
915 // If this is a named positional argument, just remember that it is the
917 if (Handler->getFormattingFlag() == cl::Positional)
918 ActivePositionalArg = Handler;
920 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
923 // Check and handle positional arguments now...
924 if (NumPositionalRequired > PositionalVals.size()) {
925 errs() << ProgramName
926 << ": Not enough positional command line arguments specified!\n"
927 << "Must specify at least " << NumPositionalRequired
928 << " positional arguments: See: " << argv[0] << " -help\n";
931 } else if (!HasUnlimitedPositionals &&
932 PositionalVals.size() > PositionalOpts.size()) {
933 errs() << ProgramName
934 << ": Too many positional arguments specified!\n"
935 << "Can specify at most " << PositionalOpts.size()
936 << " positional arguments: See: " << argv[0] << " -help\n";
939 } else if (ConsumeAfterOpt == 0) {
940 // Positional args have already been handled if ConsumeAfter is specified.
941 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
942 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
943 if (RequiresValue(PositionalOpts[i])) {
944 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
945 PositionalVals[ValNo].second);
947 --NumPositionalRequired; // We fulfilled our duty...
950 // If we _can_ give this option more arguments, do so now, as long as we
951 // do not give it values that others need. 'Done' controls whether the
952 // option even _WANTS_ any more.
954 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
955 while (NumVals-ValNo > NumPositionalRequired && !Done) {
956 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
958 Done = true; // Optional arguments want _at most_ one value
960 case cl::ZeroOrMore: // Zero or more will take all they can get...
961 case cl::OneOrMore: // One or more will take all they can get...
962 ProvidePositionalOption(PositionalOpts[i],
963 PositionalVals[ValNo].first,
964 PositionalVals[ValNo].second);
968 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
969 "positional argument processing!");
974 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
976 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
977 if (RequiresValue(PositionalOpts[j])) {
978 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
979 PositionalVals[ValNo].first,
980 PositionalVals[ValNo].second);
984 // Handle the case where there is just one positional option, and it's
985 // optional. In this case, we want to give JUST THE FIRST option to the
986 // positional option and keep the rest for the consume after. The above
987 // loop would have assigned no values to positional options in this case.
989 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
990 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
991 PositionalVals[ValNo].first,
992 PositionalVals[ValNo].second);
996 // Handle over all of the rest of the arguments to the
997 // cl::ConsumeAfter command line option...
998 for (; ValNo != PositionalVals.size(); ++ValNo)
999 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
1000 PositionalVals[ValNo].first,
1001 PositionalVals[ValNo].second);
1004 // Loop over args and make sure all required args are specified!
1005 for (StringMap<Option*>::iterator I = Opts.begin(),
1006 E = Opts.end(); I != E; ++I) {
1007 switch (I->second->getNumOccurrencesFlag()) {
1010 if (I->second->getNumOccurrences() == 0) {
1011 I->second->error("must be specified at least once!");
1012 ErrorParsing = true;
1020 // Now that we know if -debug is specified, we can use it.
1021 // Note that if ReadResponseFiles == true, this must be done before the
1022 // memory allocated for the expanded command line is free()d below.
1023 DEBUG(dbgs() << "Args: ";
1024 for (int i = 0; i < argc; ++i)
1025 dbgs() << argv[i] << ' ';
1029 // Free all of the memory allocated to the map. Command line options may only
1030 // be processed once!
1032 PositionalOpts.clear();
1035 // If we had an error processing our arguments, don't let the program execute
1036 if (ErrorParsing) exit(1);
1039 //===----------------------------------------------------------------------===//
1040 // Option Base class implementation
1043 bool Option::error(const Twine &Message, StringRef ArgName) {
1044 if (ArgName.data() == 0) ArgName = ArgStr;
1045 if (ArgName.empty())
1046 errs() << HelpStr; // Be nice for positional arguments
1048 errs() << ProgramName << ": for the -" << ArgName;
1050 errs() << " option: " << Message << "\n";
1054 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
1055 StringRef Value, bool MultiArg) {
1057 NumOccurrences++; // Increment the number of times we have been seen
1059 switch (getNumOccurrencesFlag()) {
1061 if (NumOccurrences > 1)
1062 return error("may only occur zero or one times!", ArgName);
1065 if (NumOccurrences > 1)
1066 return error("must occur exactly one time!", ArgName);
1070 case ConsumeAfter: break;
1073 return handleOccurrence(pos, ArgName, Value);
1077 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1078 // has been specified yet.
1080 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1081 if (O.ValueStr[0] == 0) return DefaultMsg;
1085 //===----------------------------------------------------------------------===//
1086 // cl::alias class implementation
1089 // Return the width of the option tag for printing...
1090 size_t alias::getOptionWidth() const {
1091 return std::strlen(ArgStr)+6;
1094 static void printHelpStr(StringRef HelpStr, size_t Indent,
1095 size_t FirstLineIndentedBy) {
1096 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1097 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1098 while (!Split.second.empty()) {
1099 Split = Split.second.split('\n');
1100 outs().indent(Indent) << Split.first << "\n";
1104 // Print out the option for the alias.
1105 void alias::printOptionInfo(size_t GlobalWidth) const {
1106 outs() << " -" << ArgStr;
1107 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1110 //===----------------------------------------------------------------------===//
1111 // Parser Implementation code...
1114 // basic_parser implementation
1117 // Return the width of the option tag for printing...
1118 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1119 size_t Len = std::strlen(O.ArgStr);
1120 if (const char *ValName = getValueName())
1121 Len += std::strlen(getValueStr(O, ValName))+3;
1126 // printOptionInfo - Print out information about this option. The
1127 // to-be-maintained width is specified.
1129 void basic_parser_impl::printOptionInfo(const Option &O,
1130 size_t GlobalWidth) const {
1131 outs() << " -" << O.ArgStr;
1133 if (const char *ValName = getValueName())
1134 outs() << "=<" << getValueStr(O, ValName) << '>';
1136 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1139 void basic_parser_impl::printOptionName(const Option &O,
1140 size_t GlobalWidth) const {
1141 outs() << " -" << O.ArgStr;
1142 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1146 // parser<bool> implementation
1148 bool parser<bool>::parse(Option &O, StringRef ArgName,
1149 StringRef Arg, bool &Value) {
1150 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1156 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1160 return O.error("'" + Arg +
1161 "' is invalid value for boolean argument! Try 0 or 1");
1164 // parser<boolOrDefault> implementation
1166 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
1167 StringRef Arg, boolOrDefault &Value) {
1168 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1173 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1178 return O.error("'" + Arg +
1179 "' is invalid value for boolean argument! Try 0 or 1");
1182 // parser<int> implementation
1184 bool parser<int>::parse(Option &O, StringRef ArgName,
1185 StringRef Arg, int &Value) {
1186 if (Arg.getAsInteger(0, Value))
1187 return O.error("'" + Arg + "' value invalid for integer argument!");
1191 // parser<unsigned> implementation
1193 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1194 StringRef Arg, unsigned &Value) {
1196 if (Arg.getAsInteger(0, Value))
1197 return O.error("'" + Arg + "' value invalid for uint argument!");
1201 // parser<unsigned long long> implementation
1203 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1204 StringRef Arg, unsigned long long &Value){
1206 if (Arg.getAsInteger(0, Value))
1207 return O.error("'" + Arg + "' value invalid for uint argument!");
1211 // parser<double>/parser<float> implementation
1213 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1214 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1215 const char *ArgStart = TmpStr.c_str();
1217 Value = strtod(ArgStart, &End);
1219 return O.error("'" + Arg + "' value invalid for floating point argument!");
1223 bool parser<double>::parse(Option &O, StringRef ArgName,
1224 StringRef Arg, double &Val) {
1225 return parseDouble(O, Arg, Val);
1228 bool parser<float>::parse(Option &O, StringRef ArgName,
1229 StringRef Arg, float &Val) {
1231 if (parseDouble(O, Arg, dVal))
1239 // generic_parser_base implementation
1242 // findOption - Return the option number corresponding to the specified
1243 // argument string. If the option is not found, getNumOptions() is returned.
1245 unsigned generic_parser_base::findOption(const char *Name) {
1246 unsigned e = getNumOptions();
1248 for (unsigned i = 0; i != e; ++i) {
1249 if (strcmp(getOption(i), Name) == 0)
1256 // Return the width of the option tag for printing...
1257 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1258 if (O.hasArgStr()) {
1259 size_t Size = std::strlen(O.ArgStr)+6;
1260 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1261 Size = std::max(Size, std::strlen(getOption(i))+8);
1264 size_t BaseSize = 0;
1265 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1266 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1271 // printOptionInfo - Print out information about this option. The
1272 // to-be-maintained width is specified.
1274 void generic_parser_base::printOptionInfo(const Option &O,
1275 size_t GlobalWidth) const {
1276 if (O.hasArgStr()) {
1277 outs() << " -" << O.ArgStr;
1278 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1280 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1281 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1282 outs() << " =" << getOption(i);
1283 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1287 outs() << " " << O.HelpStr << '\n';
1288 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1289 const char *Option = getOption(i);
1290 outs() << " -" << Option;
1291 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1296 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1298 // printGenericOptionDiff - Print the value of this option and it's default.
1300 // "Generic" options have each value mapped to a name.
1301 void generic_parser_base::
1302 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1303 const GenericOptionValue &Default,
1304 size_t GlobalWidth) const {
1305 outs() << " -" << O.ArgStr;
1306 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1308 unsigned NumOpts = getNumOptions();
1309 for (unsigned i = 0; i != NumOpts; ++i) {
1310 if (Value.compare(getOptionValue(i)))
1313 outs() << "= " << getOption(i);
1314 size_t L = std::strlen(getOption(i));
1315 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1316 outs().indent(NumSpaces) << " (default: ";
1317 for (unsigned j = 0; j != NumOpts; ++j) {
1318 if (Default.compare(getOptionValue(j)))
1320 outs() << getOption(j);
1326 outs() << "= *unknown option value*\n";
1329 // printOptionDiff - Specializations for printing basic value types.
1331 #define PRINT_OPT_DIFF(T) \
1333 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1334 size_t GlobalWidth) const { \
1335 printOptionName(O, GlobalWidth); \
1338 raw_string_ostream SS(Str); \
1341 outs() << "= " << Str; \
1342 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1343 outs().indent(NumSpaces) << " (default: "; \
1345 outs() << D.getValue(); \
1347 outs() << "*no default*"; \
1351 PRINT_OPT_DIFF(bool)
1352 PRINT_OPT_DIFF(boolOrDefault)
1354 PRINT_OPT_DIFF(unsigned)
1355 PRINT_OPT_DIFF(unsigned long long)
1356 PRINT_OPT_DIFF(double)
1357 PRINT_OPT_DIFF(float)
1358 PRINT_OPT_DIFF(char)
1360 void parser<std::string>::
1361 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1362 size_t GlobalWidth) const {
1363 printOptionName(O, GlobalWidth);
1364 outs() << "= " << V;
1365 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1366 outs().indent(NumSpaces) << " (default: ";
1368 outs() << D.getValue();
1370 outs() << "*no default*";
1374 // Print a placeholder for options that don't yet support printOptionDiff().
1375 void basic_parser_impl::
1376 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1377 printOptionName(O, GlobalWidth);
1378 outs() << "= *cannot print option value*\n";
1381 //===----------------------------------------------------------------------===//
1382 // -help and -help-hidden option implementation
1385 static int OptNameCompare(const void *LHS, const void *RHS) {
1386 typedef std::pair<const char *, Option*> pair_ty;
1388 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1391 // Copy Options into a vector so we can sort them as we like.
1393 sortOpts(StringMap<Option*> &OptMap,
1394 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1396 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1398 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1400 // Ignore really-hidden options.
1401 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1404 // Unless showhidden is set, ignore hidden flags.
1405 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1408 // If we've already seen this option, don't add it to the list again.
1409 if (!OptionSet.insert(I->second))
1412 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1416 // Sort the options list alphabetically.
1417 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1424 const bool ShowHidden;
1425 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1426 // Print the options. Opts is assumed to be alphabetically sorted.
1427 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1428 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1429 Opts[i].second->printOptionInfo(MaxArgLen);
1433 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1434 virtual ~HelpPrinter() {}
1436 // Invoke the printer.
1437 void operator=(bool Value) {
1438 if (Value == false) return;
1440 // Get all the options.
1441 SmallVector<Option*, 4> PositionalOpts;
1442 SmallVector<Option*, 4> SinkOpts;
1443 StringMap<Option*> OptMap;
1444 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1446 StrOptionPairVector Opts;
1447 sortOpts(OptMap, Opts, ShowHidden);
1449 if (ProgramOverview)
1450 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1452 outs() << "USAGE: " << ProgramName << " [options]";
1454 // Print out the positional options.
1455 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
1456 if (!PositionalOpts.empty() &&
1457 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1458 CAOpt = PositionalOpts[0];
1460 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1461 if (PositionalOpts[i]->ArgStr[0])
1462 outs() << " --" << PositionalOpts[i]->ArgStr;
1463 outs() << " " << PositionalOpts[i]->HelpStr;
1466 // Print the consume after option info if it exists...
1467 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1471 // Compute the maximum argument length...
1472 size_t MaxArgLen = 0;
1473 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1474 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1476 outs() << "OPTIONS:\n";
1477 printOptions(Opts, MaxArgLen);
1479 // Print any extra help the user has declared.
1480 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1481 E = MoreHelp->end();
1486 // Halt the program since help information was printed
1491 class CategorizedHelpPrinter : public HelpPrinter {
1493 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1495 // Helper function for printOptions().
1496 // It shall return true if A's name should be lexographically
1497 // ordered before B's name. It returns false otherwise.
1498 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1499 return strcmp(A->getName(), B->getName()) < 0;
1502 // Make sure we inherit our base class's operator=()
1503 using HelpPrinter::operator= ;
1506 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1507 std::vector<OptionCategory *> SortedCategories;
1508 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1509 std::set<std::string> CategoryNames;
1511 // Collect registered option categories into vector in preparation for
1513 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1514 E = RegisteredOptionCategories->end();
1516 SortedCategories.push_back(*I);
1517 // FIXME: Move this check to OptionCategory::registerCategory after the
1518 // problem with analyzer plugins linking to llvm/Support and causing
1519 // assertion on the duplicate llvm::cl::GeneralCategory is solved.
1520 assert(CategoryNames.insert((*I)->getName()).second &&
1521 "Duplicate option categories");
1524 // Sort the different option categories alphabetically.
1525 assert(SortedCategories.size() > 0 && "No option categories registered!");
1526 std::sort(SortedCategories.begin(), SortedCategories.end(),
1527 OptionCategoryCompare);
1529 // Create map to empty vectors.
1530 for (std::vector<OptionCategory *>::const_iterator
1531 I = SortedCategories.begin(),
1532 E = SortedCategories.end();
1534 CategorizedOptions[*I] = std::vector<Option *>();
1536 // Walk through pre-sorted options and assign into categories.
1537 // Because the options are already alphabetically sorted the
1538 // options within categories will also be alphabetically sorted.
1539 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1540 Option *Opt = Opts[I].second;
1541 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1542 "Option has an unregistered category");
1543 CategorizedOptions[Opt->Category].push_back(Opt);
1547 for (std::vector<OptionCategory *>::const_iterator
1548 Category = SortedCategories.begin(),
1549 E = SortedCategories.end();
1550 Category != E; ++Category) {
1551 // Hide empty categories for -help, but show for -help-hidden.
1552 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1553 if (!ShowHidden && IsEmptyCategory)
1556 // Print category information.
1558 outs() << (*Category)->getName() << ":\n";
1560 // Check if description is set.
1561 if ((*Category)->getDescription() != 0)
1562 outs() << (*Category)->getDescription() << "\n\n";
1566 // When using -help-hidden explicitly state if the category has no
1567 // options associated with it.
1568 if (IsEmptyCategory) {
1569 outs() << " This option category has no options.\n";
1572 // Loop over the options in the category and print.
1573 for (std::vector<Option *>::const_iterator
1574 Opt = CategorizedOptions[*Category].begin(),
1575 E = CategorizedOptions[*Category].end();
1577 (*Opt)->printOptionInfo(MaxArgLen);
1582 // This wraps the Uncategorizing and Categorizing printers and decides
1583 // at run time which should be invoked.
1584 class HelpPrinterWrapper {
1586 HelpPrinter &UncategorizedPrinter;
1587 CategorizedHelpPrinter &CategorizedPrinter;
1590 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1591 CategorizedHelpPrinter &CategorizedPrinter) :
1592 UncategorizedPrinter(UncategorizedPrinter),
1593 CategorizedPrinter(CategorizedPrinter) { }
1595 // Invoke the printer.
1596 void operator=(bool Value);
1599 } // End anonymous namespace
1601 // Declare the four HelpPrinter instances that are used to print out help, or
1602 // help-hidden as an uncategorized list or in categories.
1603 static HelpPrinter UncategorizedNormalPrinter(false);
1604 static HelpPrinter UncategorizedHiddenPrinter(true);
1605 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1606 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1609 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1610 // a categorizing help printer
1611 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1612 CategorizedNormalPrinter);
1613 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1614 CategorizedHiddenPrinter);
1616 // Define uncategorized help printers.
1617 // -help-list is hidden by default because if Option categories are being used
1618 // then -help behaves the same as -help-list.
1619 static cl::opt<HelpPrinter, true, parser<bool> >
1621 cl::desc("Display list of available options (-help-list-hidden for more)"),
1622 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1624 static cl::opt<HelpPrinter, true, parser<bool> >
1625 HLHOp("help-list-hidden",
1626 cl::desc("Display list of all available options"),
1627 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1629 // Define uncategorized/categorized help printers. These printers change their
1630 // behaviour at runtime depending on whether one or more Option categories have
1632 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1633 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1634 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1636 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1637 HHOp("help-hidden", cl::desc("Display all available options"),
1638 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1642 static cl::opt<bool>
1643 PrintOptions("print-options",
1644 cl::desc("Print non-default options after command line parsing"),
1645 cl::Hidden, cl::init(false));
1647 static cl::opt<bool>
1648 PrintAllOptions("print-all-options",
1649 cl::desc("Print all option values after command line parsing"),
1650 cl::Hidden, cl::init(false));
1652 void HelpPrinterWrapper::operator=(bool Value) {
1656 // Decide which printer to invoke. If more than one option category is
1657 // registered then it is useful to show the categorized help instead of
1658 // uncategorized help.
1659 if (RegisteredOptionCategories->size() > 1) {
1660 // unhide -help-list option so user can have uncategorized output if they
1662 HLOp.setHiddenFlag(NotHidden);
1664 CategorizedPrinter = true; // Invoke categorized printer
1667 UncategorizedPrinter = true; // Invoke uncategorized printer
1670 // Print the value of each option.
1671 void cl::PrintOptionValues() {
1672 if (!PrintOptions && !PrintAllOptions) return;
1674 // Get all the options.
1675 SmallVector<Option*, 4> PositionalOpts;
1676 SmallVector<Option*, 4> SinkOpts;
1677 StringMap<Option*> OptMap;
1678 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1680 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1681 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1683 // Compute the maximum argument length...
1684 size_t MaxArgLen = 0;
1685 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1686 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1688 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1689 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1692 static void (*OverrideVersionPrinter)() = 0;
1694 static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1697 class VersionPrinter {
1700 raw_ostream &OS = outs();
1701 OS << "LLVM (http://llvm.org/):\n"
1702 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1703 #ifdef LLVM_VERSION_INFO
1704 OS << LLVM_VERSION_INFO;
1707 #ifndef __OPTIMIZE__
1708 OS << "DEBUG build";
1710 OS << "Optimized build";
1713 OS << " with assertions";
1715 std::string CPU = sys::getHostCPUName();
1716 if (CPU == "generic") CPU = "(unknown)";
1718 #if (ENABLE_TIMESTAMPS == 1)
1719 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1721 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1722 << " Host CPU: " << CPU << '\n';
1724 void operator=(bool OptionWasSpecified) {
1725 if (!OptionWasSpecified) return;
1727 if (OverrideVersionPrinter != 0) {
1728 (*OverrideVersionPrinter)();
1733 // Iterate over any registered extra printers and call them to add further
1735 if (ExtraVersionPrinters != 0) {
1737 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1738 E = ExtraVersionPrinters->end();
1746 } // End anonymous namespace
1749 // Define the --version option that prints out the LLVM version for the tool
1750 static VersionPrinter VersionPrinterInstance;
1752 static cl::opt<VersionPrinter, true, parser<bool> >
1753 VersOp("version", cl::desc("Display the version of this program"),
1754 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1756 // Utility function for printing the help message.
1757 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1758 // This looks weird, but it actually prints the help message. The Printers are
1759 // types of HelpPrinter and the help gets printed when its operator= is
1760 // invoked. That's because the "normal" usages of the help printer is to be
1761 // assigned true/false depending on whether -help or -help-hidden was given or
1762 // not. Since we're circumventing that we have to make it look like -help or
1763 // -help-hidden were given, so we assign true.
1765 if (!Hidden && !Categorized)
1766 UncategorizedNormalPrinter = true;
1767 else if (!Hidden && Categorized)
1768 CategorizedNormalPrinter = true;
1769 else if (Hidden && !Categorized)
1770 UncategorizedHiddenPrinter = true;
1772 CategorizedHiddenPrinter = true;
1775 /// Utility function for printing version number.
1776 void cl::PrintVersionMessage() {
1777 VersionPrinterInstance.print();
1780 void cl::SetVersionPrinter(void (*func)()) {
1781 OverrideVersionPrinter = func;
1784 void cl::AddExtraVersionPrinter(void (*func)()) {
1785 if (ExtraVersionPrinters == 0)
1786 ExtraVersionPrinters = new std::vector<void (*)()>;
1788 ExtraVersionPrinters->push_back(func);
1791 void cl::getRegisteredOptions(StringMap<Option*> &Map)
1793 // Get all the options.
1794 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1795 SmallVector<Option*, 4> SinkOpts; //NOT USED
1796 assert(Map.size() == 0 && "StringMap must be empty");
1797 GetOptionInfo(PositionalOpts, SinkOpts, Map);