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 void Option::removeArgument() {
115 assert(NextRegistered != 0 && "argument never registered");
116 assert(RegisteredOptionList == this && "argument is not the last registered");
117 RegisteredOptionList = NextRegistered;
118 MarkOptionsChanged();
121 // This collects the different option categories that have been registered.
122 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
123 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
125 // Initialise the general option category.
126 OptionCategory llvm::cl::GeneralCategory("General options");
128 void OptionCategory::registerCategory()
130 RegisteredOptionCategories->insert(this);
133 //===----------------------------------------------------------------------===//
134 // Basic, shared command line option processing machinery.
137 /// GetOptionInfo - Scan the list of registered options, turning them into data
138 /// structures that are easier to handle.
139 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
140 SmallVectorImpl<Option*> &SinkOpts,
141 StringMap<Option*> &OptionsMap) {
142 SmallVector<const char*, 16> OptionNames;
143 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
144 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
145 // If this option wants to handle multiple option names, get the full set.
146 // This handles enum options like "-O1 -O2" etc.
147 O->getExtraOptionNames(OptionNames);
149 OptionNames.push_back(O->ArgStr);
151 // Handle named options.
152 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
153 // Add argument to the argument map!
154 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
155 errs() << ProgramName << ": CommandLine Error: Argument '"
156 << OptionNames[i] << "' defined more than once!\n";
162 // Remember information about positional options.
163 if (O->getFormattingFlag() == cl::Positional)
164 PositionalOpts.push_back(O);
165 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
166 SinkOpts.push_back(O);
167 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
169 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
175 PositionalOpts.push_back(CAOpt);
177 // Make sure that they are in order of registration not backwards.
178 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
182 /// LookupOption - Lookup the option specified by the specified option on the
183 /// command line. If there is a value specified (after an equal sign) return
184 /// that as well. This assumes that leading dashes have already been stripped.
185 static Option *LookupOption(StringRef &Arg, StringRef &Value,
186 const StringMap<Option*> &OptionsMap) {
187 // Reject all dashes.
188 if (Arg.empty()) return 0;
190 size_t EqualPos = Arg.find('=');
192 // If we have an equals sign, remember the value.
193 if (EqualPos == StringRef::npos) {
194 // Look up the option.
195 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
196 return I != OptionsMap.end() ? I->second : 0;
199 // If the argument before the = is a valid option name, we match. If not,
200 // return Arg unmolested.
201 StringMap<Option*>::const_iterator I =
202 OptionsMap.find(Arg.substr(0, EqualPos));
203 if (I == OptionsMap.end()) return 0;
205 Value = Arg.substr(EqualPos+1);
206 Arg = Arg.substr(0, EqualPos);
210 /// LookupNearestOption - Lookup the closest match to the option specified by
211 /// the specified option on the command line. If there is a value specified
212 /// (after an equal sign) return that as well. This assumes that leading dashes
213 /// have already been stripped.
214 static Option *LookupNearestOption(StringRef Arg,
215 const StringMap<Option*> &OptionsMap,
216 std::string &NearestString) {
217 // Reject all dashes.
218 if (Arg.empty()) return 0;
220 // Split on any equal sign.
221 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
222 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
223 StringRef &RHS = SplitArg.second;
225 // Find the closest match.
227 unsigned BestDistance = 0;
228 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
229 ie = OptionsMap.end(); it != ie; ++it) {
230 Option *O = it->second;
231 SmallVector<const char*, 16> OptionNames;
232 O->getExtraOptionNames(OptionNames);
234 OptionNames.push_back(O->ArgStr);
236 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
237 StringRef Flag = PermitValue ? LHS : Arg;
238 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
239 StringRef Name = OptionNames[i];
240 unsigned Distance = StringRef(Name).edit_distance(
241 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
242 if (!Best || Distance < BestDistance) {
244 BestDistance = Distance;
245 if (RHS.empty() || !PermitValue)
246 NearestString = OptionNames[i];
248 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
256 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
257 /// that does special handling of cl::CommaSeparated options.
258 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
259 StringRef ArgName, StringRef Value,
260 bool MultiArg = false) {
261 // Check to see if this option accepts a comma separated list of values. If
262 // it does, we have to split up the value into multiple values.
263 if (Handler->getMiscFlags() & CommaSeparated) {
264 StringRef Val(Value);
265 StringRef::size_type Pos = Val.find(',');
267 while (Pos != StringRef::npos) {
268 // Process the portion before the comma.
269 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
271 // Erase the portion before the comma, AND the comma.
272 Val = Val.substr(Pos+1);
273 Value.substr(Pos+1); // Increment the original value pointer as well.
274 // Check for another comma.
281 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
287 /// ProvideOption - For Value, this differentiates between an empty value ("")
288 /// and a null value (StringRef()). The later is accepted for arguments that
289 /// don't allow a value (-foo) the former is rejected (-foo=).
290 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
291 StringRef Value, int argc,
292 const char *const *argv, int &i) {
293 // Is this a multi-argument option?
294 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
296 // Enforce value requirements
297 switch (Handler->getValueExpectedFlag()) {
299 if (Value.data() == 0) { // No value specified?
301 return Handler->error("requires a value!");
302 // Steal the next argument, like for '-o filename'
306 case ValueDisallowed:
307 if (NumAdditionalVals > 0)
308 return Handler->error("multi-valued option specified"
309 " with ValueDisallowed modifier!");
312 return Handler->error("does not allow a value! '" +
313 Twine(Value) + "' specified.");
319 // If this isn't a multi-arg option, just run the handler.
320 if (NumAdditionalVals == 0)
321 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
323 // If it is, run the handle several times.
324 bool MultiArg = false;
327 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
333 while (NumAdditionalVals > 0) {
335 return Handler->error("not enough values!");
338 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
346 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
348 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
352 // Option predicates...
353 static inline bool isGrouping(const Option *O) {
354 return O->getFormattingFlag() == cl::Grouping;
356 static inline bool isPrefixedOrGrouping(const Option *O) {
357 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
360 // getOptionPred - Check to see if there are any options that satisfy the
361 // specified predicate with names that are the prefixes in Name. This is
362 // checked by progressively stripping characters off of the name, checking to
363 // see if there options that satisfy the predicate. If we find one, return it,
364 // otherwise return null.
366 static Option *getOptionPred(StringRef Name, size_t &Length,
367 bool (*Pred)(const Option*),
368 const StringMap<Option*> &OptionsMap) {
370 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
372 // Loop while we haven't found an option and Name still has at least two
373 // characters in it (so that the next iteration will not be the empty
375 while (OMI == OptionsMap.end() && Name.size() > 1) {
376 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
377 OMI = OptionsMap.find(Name);
380 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
381 Length = Name.size();
382 return OMI->second; // Found one!
384 return 0; // No option found!
387 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
388 /// with at least one '-') does not fully match an available option. Check to
389 /// see if this is a prefix or grouped option. If so, split arg into output an
390 /// Arg/Value pair and return the Option to parse it with.
391 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
393 const StringMap<Option*> &OptionsMap) {
394 if (Arg.size() == 1) return 0;
398 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
399 if (PGOpt == 0) return 0;
401 // If the option is a prefixed option, then the value is simply the
402 // rest of the name... so fall through to later processing, by
403 // setting up the argument name flags and value fields.
404 if (PGOpt->getFormattingFlag() == cl::Prefix) {
405 Value = Arg.substr(Length);
406 Arg = Arg.substr(0, Length);
407 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
411 // This must be a grouped option... handle them now. Grouping options can't
413 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
416 // Move current arg name out of Arg into OneArgName.
417 StringRef OneArgName = Arg.substr(0, Length);
418 Arg = Arg.substr(Length);
420 // Because ValueRequired is an invalid flag for grouped arguments,
421 // we don't need to pass argc/argv in.
422 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
423 "Option can not be cl::Grouping AND cl::ValueRequired!");
425 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
426 StringRef(), 0, 0, Dummy);
428 // Get the next grouping option.
429 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
430 } while (PGOpt && Length != Arg.size());
432 // Return the last option with Arg cut down to just the last one.
438 static bool RequiresValue(const Option *O) {
439 return O->getNumOccurrencesFlag() == cl::Required ||
440 O->getNumOccurrencesFlag() == cl::OneOrMore;
443 static bool EatsUnboundedNumberOfValues(const Option *O) {
444 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
445 O->getNumOccurrencesFlag() == cl::OneOrMore;
448 static bool isWhitespace(char C) {
449 return strchr(" \t\n\r\f\v", C);
452 static bool isQuote(char C) {
453 return C == '\"' || C == '\'';
456 static bool isGNUSpecial(char C) {
457 return strchr("\\\"\' ", C);
460 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
461 SmallVectorImpl<const char *> &NewArgv) {
462 SmallString<128> Token;
463 for (size_t I = 0, E = Src.size(); I != E; ++I) {
464 // Consume runs of whitespace.
466 while (I != E && isWhitespace(Src[I]))
471 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
472 // they are literal. This makes it much easier to read Windows file paths.
473 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
474 ++I; // Skip the escape.
475 Token.push_back(Src[I]);
479 // Consume a quoted string.
480 if (isQuote(Src[I])) {
481 char Quote = Src[I++];
482 while (I != E && Src[I] != Quote) {
483 // Backslashes are literal, unless they escape a special character.
484 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
486 Token.push_back(Src[I]);
493 // End the token if this is whitespace.
494 if (isWhitespace(Src[I])) {
496 NewArgv.push_back(Saver.SaveString(Token.c_str()));
501 // This is a normal character. Append it.
502 Token.push_back(Src[I]);
505 // Append the last token after hitting EOF with no whitespace.
507 NewArgv.push_back(Saver.SaveString(Token.c_str()));
510 /// Backslashes are interpreted in a rather complicated way in the Windows-style
511 /// command line, because backslashes are used both to separate path and to
512 /// escape double quote. This method consumes runs of backslashes as well as the
513 /// following double quote if it's escaped.
515 /// * If an even number of backslashes is followed by a double quote, one
516 /// backslash is output for every pair of backslashes, and the last double
517 /// quote remains unconsumed. The double quote will later be interpreted as
518 /// the start or end of a quoted string in the main loop outside of this
521 /// * If an odd number of backslashes is followed by a double quote, one
522 /// backslash is output for every pair of backslashes, and a double quote is
523 /// output for the last pair of backslash-double quote. The double quote is
524 /// consumed in this case.
526 /// * Otherwise, backslashes are interpreted literally.
527 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
528 size_t E = Src.size();
529 int BackslashCount = 0;
530 // Skip the backslashes.
534 } while (I != E && Src[I] == '\\');
536 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
537 if (FollowedByDoubleQuote) {
538 Token.append(BackslashCount / 2, '\\');
539 if (BackslashCount % 2 == 0)
541 Token.push_back('"');
544 Token.append(BackslashCount, '\\');
548 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
549 SmallVectorImpl<const char *> &NewArgv) {
550 SmallString<128> Token;
552 // This is a small state machine to consume characters until it reaches the
553 // end of the source string.
554 enum { INIT, UNQUOTED, QUOTED } State = INIT;
555 for (size_t I = 0, E = Src.size(); I != E; ++I) {
556 // INIT state indicates that the current input index is at the start of
557 // the string or between tokens.
559 if (isWhitespace(Src[I]))
565 if (Src[I] == '\\') {
566 I = parseBackslash(Src, I, Token);
570 Token.push_back(Src[I]);
575 // UNQUOTED state means that it's reading a token not quoted by double
577 if (State == UNQUOTED) {
578 // Whitespace means the end of the token.
579 if (isWhitespace(Src[I])) {
580 NewArgv.push_back(Saver.SaveString(Token.c_str()));
589 if (Src[I] == '\\') {
590 I = parseBackslash(Src, I, Token);
593 Token.push_back(Src[I]);
597 // QUOTED state means that it's reading a token quoted by double quotes.
598 if (State == QUOTED) {
603 if (Src[I] == '\\') {
604 I = parseBackslash(Src, I, Token);
607 Token.push_back(Src[I]);
610 // Append the last token after hitting EOF with no whitespace.
612 NewArgv.push_back(Saver.SaveString(Token.c_str()));
615 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
616 TokenizerCallback Tokenizer,
617 SmallVectorImpl<const char *> &NewArgv) {
618 OwningPtr<MemoryBuffer> MemBuf;
619 if (MemoryBuffer::getFile(FName, MemBuf))
621 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
623 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
624 ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd());
626 if (hasUTF16ByteOrderMark(BufRef)) {
627 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
629 Str = StringRef(UTF8Buf);
632 // Tokenize the contents into NewArgv.
633 Tokenizer(Str, Saver, NewArgv);
638 /// \brief Expand response files on a command line recursively using the given
639 /// StringSaver and tokenization strategy.
640 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
641 SmallVectorImpl<const char *> &Argv) {
642 unsigned RspFiles = 0;
643 bool AllExpanded = true;
645 // Don't cache Argv.size() because it can change.
646 for (unsigned I = 0; I != Argv.size(); ) {
647 const char *Arg = Argv[I];
653 // If we have too many response files, leave some unexpanded. This avoids
654 // crashing on self-referential response files.
658 // Replace this response file argument with the tokenization of its
659 // contents. Nested response files are expanded in subsequent iterations.
660 // FIXME: If a nested response file uses a relative path, is it relative to
661 // the cwd of the process or the response file?
662 SmallVector<const char *, 0> ExpandedArgv;
663 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
664 // We couldn't read this file, so we leave it in the argument stream and
670 Argv.erase(Argv.begin() + I);
671 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
677 class StrDupSaver : public StringSaver {
678 std::vector<char*> Dups;
681 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
687 const char *SaveString(const char *Str) LLVM_OVERRIDE {
688 char *Dup = strdup(Str);
695 /// ParseEnvironmentOptions - An alternative entry point to the
696 /// CommandLine library, which allows you to read the program's name
697 /// from the caller (as PROGNAME) and its command-line arguments from
698 /// an environment variable (whose name is given in ENVVAR).
700 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
701 const char *Overview) {
703 assert(progName && "Program name not specified");
704 assert(envVar && "Environment variable name missing");
706 // Get the environment variable they want us to parse options out of.
707 const char *envValue = getenv(envVar);
711 // Get program's "name", which we wouldn't know without the caller
713 SmallVector<const char *, 20> newArgv;
715 newArgv.push_back(Saver.SaveString(progName));
717 // Parse the value of the environment variable into a "command line"
718 // and hand it off to ParseCommandLineOptions().
719 TokenizeGNUCommandLine(envValue, Saver, newArgv);
720 int newArgc = static_cast<int>(newArgv.size());
721 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
724 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
725 const char *Overview) {
726 // Process all registered options.
727 SmallVector<Option*, 4> PositionalOpts;
728 SmallVector<Option*, 4> SinkOpts;
729 StringMap<Option*> Opts;
730 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
732 assert((!Opts.empty() || !PositionalOpts.empty()) &&
733 "No options specified!");
735 // Expand response files.
736 SmallVector<const char *, 20> newArgv;
737 for (int i = 0; i != argc; ++i)
738 newArgv.push_back(argv[i]);
740 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
742 argc = static_cast<int>(newArgv.size());
744 // Copy the program name into ProgName, making sure not to overflow it.
745 std::string ProgName = sys::path::filename(argv[0]);
746 size_t Len = std::min(ProgName.size(), size_t(79));
747 memcpy(ProgramName, ProgName.data(), Len);
748 ProgramName[Len] = '\0';
750 ProgramOverview = Overview;
751 bool ErrorParsing = false;
753 // Check out the positional arguments to collect information about them.
754 unsigned NumPositionalRequired = 0;
756 // Determine whether or not there are an unlimited number of positionals
757 bool HasUnlimitedPositionals = false;
759 Option *ConsumeAfterOpt = 0;
760 if (!PositionalOpts.empty()) {
761 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
762 assert(PositionalOpts.size() > 1 &&
763 "Cannot specify cl::ConsumeAfter without a positional argument!");
764 ConsumeAfterOpt = PositionalOpts[0];
767 // Calculate how many positional values are _required_.
768 bool UnboundedFound = false;
769 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
771 Option *Opt = PositionalOpts[i];
772 if (RequiresValue(Opt))
773 ++NumPositionalRequired;
774 else if (ConsumeAfterOpt) {
775 // ConsumeAfter cannot be combined with "optional" positional options
776 // unless there is only one positional argument...
777 if (PositionalOpts.size() > 2)
779 Opt->error("error - this positional option will never be matched, "
780 "because it does not Require a value, and a "
781 "cl::ConsumeAfter option is active!");
782 } else if (UnboundedFound && !Opt->ArgStr[0]) {
783 // This option does not "require" a value... Make sure this option is
784 // not specified after an option that eats all extra arguments, or this
785 // one will never get any!
787 ErrorParsing |= Opt->error("error - option can never match, because "
788 "another positional argument will match an "
789 "unbounded number of values, and this option"
790 " does not require a value!");
792 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
794 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
797 // PositionalVals - A vector of "positional" arguments we accumulate into
798 // the process at the end.
800 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
802 // If the program has named positional arguments, and the name has been run
803 // across, keep track of which positional argument was named. Otherwise put
804 // the positional args into the PositionalVals list...
805 Option *ActivePositionalArg = 0;
807 // Loop over all of the arguments... processing them.
808 bool DashDashFound = false; // Have we read '--'?
809 for (int i = 1; i < argc; ++i) {
811 Option *NearestHandler = 0;
812 std::string NearestHandlerString;
814 StringRef ArgName = "";
816 // If the option list changed, this means that some command line
817 // option has just been registered or deregistered. This can occur in
818 // response to things like -load, etc. If this happens, rescan the options.
819 if (OptionListChanged) {
820 PositionalOpts.clear();
823 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
824 OptionListChanged = false;
827 // Check to see if this is a positional argument. This argument is
828 // considered to be positional if it doesn't start with '-', if it is "-"
829 // itself, or if we have seen "--" already.
831 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
832 // Positional argument!
833 if (ActivePositionalArg) {
834 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
835 continue; // We are done!
838 if (!PositionalOpts.empty()) {
839 PositionalVals.push_back(std::make_pair(argv[i],i));
841 // All of the positional arguments have been fulfulled, give the rest to
842 // the consume after option... if it's specified...
844 if (PositionalVals.size() >= NumPositionalRequired &&
845 ConsumeAfterOpt != 0) {
846 for (++i; i < argc; ++i)
847 PositionalVals.push_back(std::make_pair(argv[i],i));
848 break; // Handle outside of the argument processing loop...
851 // Delay processing positional arguments until the end...
854 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
856 DashDashFound = true; // This is the mythical "--"?
857 continue; // Don't try to process it as an argument itself.
858 } else if (ActivePositionalArg &&
859 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
860 // If there is a positional argument eating options, check to see if this
861 // option is another positional argument. If so, treat it as an argument,
862 // otherwise feed it to the eating positional.
864 // Eat leading dashes.
865 while (!ArgName.empty() && ArgName[0] == '-')
866 ArgName = ArgName.substr(1);
868 Handler = LookupOption(ArgName, Value, Opts);
869 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
870 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
871 continue; // We are done!
874 } else { // We start with a '-', must be an argument.
876 // Eat leading dashes.
877 while (!ArgName.empty() && ArgName[0] == '-')
878 ArgName = ArgName.substr(1);
880 Handler = LookupOption(ArgName, Value, Opts);
882 // Check to see if this "option" is really a prefixed or grouped argument.
884 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
887 // Otherwise, look for the closest available option to report to the user
888 // in the upcoming error.
889 if (Handler == 0 && SinkOpts.empty())
890 NearestHandler = LookupNearestOption(ArgName, Opts,
891 NearestHandlerString);
895 if (SinkOpts.empty()) {
896 errs() << ProgramName << ": Unknown command line argument '"
897 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
899 if (NearestHandler) {
900 // If we know a near match, report it as well.
901 errs() << ProgramName << ": Did you mean '-"
902 << NearestHandlerString << "'?\n";
907 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
908 E = SinkOpts.end(); I != E ; ++I)
909 (*I)->addOccurrence(i, "", argv[i]);
914 // If this is a named positional argument, just remember that it is the
916 if (Handler->getFormattingFlag() == cl::Positional)
917 ActivePositionalArg = Handler;
919 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
922 // Check and handle positional arguments now...
923 if (NumPositionalRequired > PositionalVals.size()) {
924 errs() << ProgramName
925 << ": Not enough positional command line arguments specified!\n"
926 << "Must specify at least " << NumPositionalRequired
927 << " positional arguments: See: " << argv[0] << " -help\n";
930 } else if (!HasUnlimitedPositionals &&
931 PositionalVals.size() > PositionalOpts.size()) {
932 errs() << ProgramName
933 << ": Too many positional arguments specified!\n"
934 << "Can specify at most " << PositionalOpts.size()
935 << " positional arguments: See: " << argv[0] << " -help\n";
938 } else if (ConsumeAfterOpt == 0) {
939 // Positional args have already been handled if ConsumeAfter is specified.
940 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
941 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
942 if (RequiresValue(PositionalOpts[i])) {
943 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
944 PositionalVals[ValNo].second);
946 --NumPositionalRequired; // We fulfilled our duty...
949 // If we _can_ give this option more arguments, do so now, as long as we
950 // do not give it values that others need. 'Done' controls whether the
951 // option even _WANTS_ any more.
953 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
954 while (NumVals-ValNo > NumPositionalRequired && !Done) {
955 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
957 Done = true; // Optional arguments want _at most_ one value
959 case cl::ZeroOrMore: // Zero or more will take all they can get...
960 case cl::OneOrMore: // One or more will take all they can get...
961 ProvidePositionalOption(PositionalOpts[i],
962 PositionalVals[ValNo].first,
963 PositionalVals[ValNo].second);
967 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
968 "positional argument processing!");
973 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
975 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
976 if (RequiresValue(PositionalOpts[j])) {
977 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
978 PositionalVals[ValNo].first,
979 PositionalVals[ValNo].second);
983 // Handle the case where there is just one positional option, and it's
984 // optional. In this case, we want to give JUST THE FIRST option to the
985 // positional option and keep the rest for the consume after. The above
986 // loop would have assigned no values to positional options in this case.
988 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
989 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
990 PositionalVals[ValNo].first,
991 PositionalVals[ValNo].second);
995 // Handle over all of the rest of the arguments to the
996 // cl::ConsumeAfter command line option...
997 for (; ValNo != PositionalVals.size(); ++ValNo)
998 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
999 PositionalVals[ValNo].first,
1000 PositionalVals[ValNo].second);
1003 // Loop over args and make sure all required args are specified!
1004 for (StringMap<Option*>::iterator I = Opts.begin(),
1005 E = Opts.end(); I != E; ++I) {
1006 switch (I->second->getNumOccurrencesFlag()) {
1009 if (I->second->getNumOccurrences() == 0) {
1010 I->second->error("must be specified at least once!");
1011 ErrorParsing = true;
1019 // Now that we know if -debug is specified, we can use it.
1020 // Note that if ReadResponseFiles == true, this must be done before the
1021 // memory allocated for the expanded command line is free()d below.
1022 DEBUG(dbgs() << "Args: ";
1023 for (int i = 0; i < argc; ++i)
1024 dbgs() << argv[i] << ' ';
1028 // Free all of the memory allocated to the map. Command line options may only
1029 // be processed once!
1031 PositionalOpts.clear();
1034 // If we had an error processing our arguments, don't let the program execute
1035 if (ErrorParsing) exit(1);
1038 //===----------------------------------------------------------------------===//
1039 // Option Base class implementation
1042 bool Option::error(const Twine &Message, StringRef ArgName) {
1043 if (ArgName.data() == 0) ArgName = ArgStr;
1044 if (ArgName.empty())
1045 errs() << HelpStr; // Be nice for positional arguments
1047 errs() << ProgramName << ": for the -" << ArgName;
1049 errs() << " option: " << Message << "\n";
1053 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
1054 StringRef Value, bool MultiArg) {
1056 NumOccurrences++; // Increment the number of times we have been seen
1058 switch (getNumOccurrencesFlag()) {
1060 if (NumOccurrences > 1)
1061 return error("may only occur zero or one times!", ArgName);
1064 if (NumOccurrences > 1)
1065 return error("must occur exactly one time!", ArgName);
1069 case ConsumeAfter: break;
1072 return handleOccurrence(pos, ArgName, Value);
1076 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1077 // has been specified yet.
1079 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1080 if (O.ValueStr[0] == 0) return DefaultMsg;
1084 //===----------------------------------------------------------------------===//
1085 // cl::alias class implementation
1088 // Return the width of the option tag for printing...
1089 size_t alias::getOptionWidth() const {
1090 return std::strlen(ArgStr)+6;
1093 static void printHelpStr(StringRef HelpStr, size_t Indent,
1094 size_t FirstLineIndentedBy) {
1095 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1096 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1097 while (!Split.second.empty()) {
1098 Split = Split.second.split('\n');
1099 outs().indent(Indent) << Split.first << "\n";
1103 // Print out the option for the alias.
1104 void alias::printOptionInfo(size_t GlobalWidth) const {
1105 outs() << " -" << ArgStr;
1106 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1109 //===----------------------------------------------------------------------===//
1110 // Parser Implementation code...
1113 // basic_parser implementation
1116 // Return the width of the option tag for printing...
1117 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1118 size_t Len = std::strlen(O.ArgStr);
1119 if (const char *ValName = getValueName())
1120 Len += std::strlen(getValueStr(O, ValName))+3;
1125 // printOptionInfo - Print out information about this option. The
1126 // to-be-maintained width is specified.
1128 void basic_parser_impl::printOptionInfo(const Option &O,
1129 size_t GlobalWidth) const {
1130 outs() << " -" << O.ArgStr;
1132 if (const char *ValName = getValueName())
1133 outs() << "=<" << getValueStr(O, ValName) << '>';
1135 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1138 void basic_parser_impl::printOptionName(const Option &O,
1139 size_t GlobalWidth) const {
1140 outs() << " -" << O.ArgStr;
1141 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1145 // parser<bool> implementation
1147 bool parser<bool>::parse(Option &O, StringRef ArgName,
1148 StringRef Arg, bool &Value) {
1149 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1155 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1159 return O.error("'" + Arg +
1160 "' is invalid value for boolean argument! Try 0 or 1");
1163 // parser<boolOrDefault> implementation
1165 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
1166 StringRef Arg, boolOrDefault &Value) {
1167 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1172 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1177 return O.error("'" + Arg +
1178 "' is invalid value for boolean argument! Try 0 or 1");
1181 // parser<int> implementation
1183 bool parser<int>::parse(Option &O, StringRef ArgName,
1184 StringRef Arg, int &Value) {
1185 if (Arg.getAsInteger(0, Value))
1186 return O.error("'" + Arg + "' value invalid for integer argument!");
1190 // parser<unsigned> implementation
1192 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1193 StringRef Arg, unsigned &Value) {
1195 if (Arg.getAsInteger(0, Value))
1196 return O.error("'" + Arg + "' value invalid for uint argument!");
1200 // parser<unsigned long long> implementation
1202 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1203 StringRef Arg, unsigned long long &Value){
1205 if (Arg.getAsInteger(0, Value))
1206 return O.error("'" + Arg + "' value invalid for uint argument!");
1210 // parser<double>/parser<float> implementation
1212 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1213 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1214 const char *ArgStart = TmpStr.c_str();
1216 Value = strtod(ArgStart, &End);
1218 return O.error("'" + Arg + "' value invalid for floating point argument!");
1222 bool parser<double>::parse(Option &O, StringRef ArgName,
1223 StringRef Arg, double &Val) {
1224 return parseDouble(O, Arg, Val);
1227 bool parser<float>::parse(Option &O, StringRef ArgName,
1228 StringRef Arg, float &Val) {
1230 if (parseDouble(O, Arg, dVal))
1238 // generic_parser_base implementation
1241 // findOption - Return the option number corresponding to the specified
1242 // argument string. If the option is not found, getNumOptions() is returned.
1244 unsigned generic_parser_base::findOption(const char *Name) {
1245 unsigned e = getNumOptions();
1247 for (unsigned i = 0; i != e; ++i) {
1248 if (strcmp(getOption(i), Name) == 0)
1255 // Return the width of the option tag for printing...
1256 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1257 if (O.hasArgStr()) {
1258 size_t Size = std::strlen(O.ArgStr)+6;
1259 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1260 Size = std::max(Size, std::strlen(getOption(i))+8);
1263 size_t BaseSize = 0;
1264 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1265 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1270 // printOptionInfo - Print out information about this option. The
1271 // to-be-maintained width is specified.
1273 void generic_parser_base::printOptionInfo(const Option &O,
1274 size_t GlobalWidth) const {
1275 if (O.hasArgStr()) {
1276 outs() << " -" << O.ArgStr;
1277 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1279 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1280 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1281 outs() << " =" << getOption(i);
1282 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1286 outs() << " " << O.HelpStr << '\n';
1287 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1288 const char *Option = getOption(i);
1289 outs() << " -" << Option;
1290 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1295 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1297 // printGenericOptionDiff - Print the value of this option and it's default.
1299 // "Generic" options have each value mapped to a name.
1300 void generic_parser_base::
1301 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1302 const GenericOptionValue &Default,
1303 size_t GlobalWidth) const {
1304 outs() << " -" << O.ArgStr;
1305 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1307 unsigned NumOpts = getNumOptions();
1308 for (unsigned i = 0; i != NumOpts; ++i) {
1309 if (Value.compare(getOptionValue(i)))
1312 outs() << "= " << getOption(i);
1313 size_t L = std::strlen(getOption(i));
1314 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1315 outs().indent(NumSpaces) << " (default: ";
1316 for (unsigned j = 0; j != NumOpts; ++j) {
1317 if (Default.compare(getOptionValue(j)))
1319 outs() << getOption(j);
1325 outs() << "= *unknown option value*\n";
1328 // printOptionDiff - Specializations for printing basic value types.
1330 #define PRINT_OPT_DIFF(T) \
1332 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1333 size_t GlobalWidth) const { \
1334 printOptionName(O, GlobalWidth); \
1337 raw_string_ostream SS(Str); \
1340 outs() << "= " << Str; \
1341 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1342 outs().indent(NumSpaces) << " (default: "; \
1344 outs() << D.getValue(); \
1346 outs() << "*no default*"; \
1350 PRINT_OPT_DIFF(bool)
1351 PRINT_OPT_DIFF(boolOrDefault)
1353 PRINT_OPT_DIFF(unsigned)
1354 PRINT_OPT_DIFF(unsigned long long)
1355 PRINT_OPT_DIFF(double)
1356 PRINT_OPT_DIFF(float)
1357 PRINT_OPT_DIFF(char)
1359 void parser<std::string>::
1360 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1361 size_t GlobalWidth) const {
1362 printOptionName(O, GlobalWidth);
1363 outs() << "= " << V;
1364 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1365 outs().indent(NumSpaces) << " (default: ";
1367 outs() << D.getValue();
1369 outs() << "*no default*";
1373 // Print a placeholder for options that don't yet support printOptionDiff().
1374 void basic_parser_impl::
1375 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1376 printOptionName(O, GlobalWidth);
1377 outs() << "= *cannot print option value*\n";
1380 //===----------------------------------------------------------------------===//
1381 // -help and -help-hidden option implementation
1384 static int OptNameCompare(const void *LHS, const void *RHS) {
1385 typedef std::pair<const char *, Option*> pair_ty;
1387 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1390 // Copy Options into a vector so we can sort them as we like.
1392 sortOpts(StringMap<Option*> &OptMap,
1393 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1395 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1397 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1399 // Ignore really-hidden options.
1400 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1403 // Unless showhidden is set, ignore hidden flags.
1404 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1407 // If we've already seen this option, don't add it to the list again.
1408 if (!OptionSet.insert(I->second))
1411 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1415 // Sort the options list alphabetically.
1416 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1423 const bool ShowHidden;
1424 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1425 // Print the options. Opts is assumed to be alphabetically sorted.
1426 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1427 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1428 Opts[i].second->printOptionInfo(MaxArgLen);
1432 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1433 virtual ~HelpPrinter() {}
1435 // Invoke the printer.
1436 void operator=(bool Value) {
1437 if (Value == false) return;
1439 // Get all the options.
1440 SmallVector<Option*, 4> PositionalOpts;
1441 SmallVector<Option*, 4> SinkOpts;
1442 StringMap<Option*> OptMap;
1443 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1445 StrOptionPairVector Opts;
1446 sortOpts(OptMap, Opts, ShowHidden);
1448 if (ProgramOverview)
1449 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1451 outs() << "USAGE: " << ProgramName << " [options]";
1453 // Print out the positional options.
1454 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
1455 if (!PositionalOpts.empty() &&
1456 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1457 CAOpt = PositionalOpts[0];
1459 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1460 if (PositionalOpts[i]->ArgStr[0])
1461 outs() << " --" << PositionalOpts[i]->ArgStr;
1462 outs() << " " << PositionalOpts[i]->HelpStr;
1465 // Print the consume after option info if it exists...
1466 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1470 // Compute the maximum argument length...
1471 size_t MaxArgLen = 0;
1472 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1473 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1475 outs() << "OPTIONS:\n";
1476 printOptions(Opts, MaxArgLen);
1478 // Print any extra help the user has declared.
1479 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1480 E = MoreHelp->end();
1485 // Halt the program since help information was printed
1490 class CategorizedHelpPrinter : public HelpPrinter {
1492 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1494 // Helper function for printOptions().
1495 // It shall return true if A's name should be lexographically
1496 // ordered before B's name. It returns false otherwise.
1497 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1498 int Length = strcmp(A->getName(), B->getName());
1499 assert(Length != 0 && "Duplicate option categories");
1503 // Make sure we inherit our base class's operator=()
1504 using HelpPrinter::operator= ;
1507 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1508 std::vector<OptionCategory *> SortedCategories;
1509 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
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);
1518 // Sort the different option categories alphabetically.
1519 assert(SortedCategories.size() > 0 && "No option categories registered!");
1520 std::sort(SortedCategories.begin(), SortedCategories.end(),
1521 OptionCategoryCompare);
1523 // Create map to empty vectors.
1524 for (std::vector<OptionCategory *>::const_iterator
1525 I = SortedCategories.begin(),
1526 E = SortedCategories.end();
1528 CategorizedOptions[*I] = std::vector<Option *>();
1530 // Walk through pre-sorted options and assign into categories.
1531 // Because the options are already alphabetically sorted the
1532 // options within categories will also be alphabetically sorted.
1533 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1534 Option *Opt = Opts[I].second;
1535 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1536 "Option has an unregistered category");
1537 CategorizedOptions[Opt->Category].push_back(Opt);
1541 for (std::vector<OptionCategory *>::const_iterator
1542 Category = SortedCategories.begin(),
1543 E = SortedCategories.end();
1544 Category != E; ++Category) {
1545 // Hide empty categories for -help, but show for -help-hidden.
1546 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1547 if (!ShowHidden && IsEmptyCategory)
1550 // Print category information.
1552 outs() << (*Category)->getName() << ":\n";
1554 // Check if description is set.
1555 if ((*Category)->getDescription() != 0)
1556 outs() << (*Category)->getDescription() << "\n\n";
1560 // When using -help-hidden explicitly state if the category has no
1561 // options associated with it.
1562 if (IsEmptyCategory) {
1563 outs() << " This option category has no options.\n";
1566 // Loop over the options in the category and print.
1567 for (std::vector<Option *>::const_iterator
1568 Opt = CategorizedOptions[*Category].begin(),
1569 E = CategorizedOptions[*Category].end();
1571 (*Opt)->printOptionInfo(MaxArgLen);
1576 // This wraps the Uncategorizing and Categorizing printers and decides
1577 // at run time which should be invoked.
1578 class HelpPrinterWrapper {
1580 HelpPrinter &UncategorizedPrinter;
1581 CategorizedHelpPrinter &CategorizedPrinter;
1584 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1585 CategorizedHelpPrinter &CategorizedPrinter) :
1586 UncategorizedPrinter(UncategorizedPrinter),
1587 CategorizedPrinter(CategorizedPrinter) { }
1589 // Invoke the printer.
1590 void operator=(bool Value);
1593 } // End anonymous namespace
1595 // Declare the four HelpPrinter instances that are used to print out help, or
1596 // help-hidden as an uncategorized list or in categories.
1597 static HelpPrinter UncategorizedNormalPrinter(false);
1598 static HelpPrinter UncategorizedHiddenPrinter(true);
1599 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1600 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1603 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1604 // a categorizing help printer
1605 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1606 CategorizedNormalPrinter);
1607 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1608 CategorizedHiddenPrinter);
1610 // Define uncategorized help printers.
1611 // -help-list is hidden by default because if Option categories are being used
1612 // then -help behaves the same as -help-list.
1613 static cl::opt<HelpPrinter, true, parser<bool> >
1615 cl::desc("Display list of available options (-help-list-hidden for more)"),
1616 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1618 static cl::opt<HelpPrinter, true, parser<bool> >
1619 HLHOp("help-list-hidden",
1620 cl::desc("Display list of all available options"),
1621 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1623 // Define uncategorized/categorized help printers. These printers change their
1624 // behaviour at runtime depending on whether one or more Option categories have
1626 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1627 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1628 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1630 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1631 HHOp("help-hidden", cl::desc("Display all available options"),
1632 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1636 static cl::opt<bool>
1637 PrintOptions("print-options",
1638 cl::desc("Print non-default options after command line parsing"),
1639 cl::Hidden, cl::init(false));
1641 static cl::opt<bool>
1642 PrintAllOptions("print-all-options",
1643 cl::desc("Print all option values after command line parsing"),
1644 cl::Hidden, cl::init(false));
1646 void HelpPrinterWrapper::operator=(bool Value) {
1650 // Decide which printer to invoke. If more than one option category is
1651 // registered then it is useful to show the categorized help instead of
1652 // uncategorized help.
1653 if (RegisteredOptionCategories->size() > 1) {
1654 // unhide -help-list option so user can have uncategorized output if they
1656 HLOp.setHiddenFlag(NotHidden);
1658 CategorizedPrinter = true; // Invoke categorized printer
1661 UncategorizedPrinter = true; // Invoke uncategorized printer
1664 // Print the value of each option.
1665 void cl::PrintOptionValues() {
1666 if (!PrintOptions && !PrintAllOptions) return;
1668 // Get all the options.
1669 SmallVector<Option*, 4> PositionalOpts;
1670 SmallVector<Option*, 4> SinkOpts;
1671 StringMap<Option*> OptMap;
1672 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1674 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1675 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1677 // Compute the maximum argument length...
1678 size_t MaxArgLen = 0;
1679 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1680 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1682 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1683 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1686 static void (*OverrideVersionPrinter)() = 0;
1688 static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1691 class VersionPrinter {
1694 raw_ostream &OS = outs();
1695 OS << "LLVM (http://llvm.org/):\n"
1696 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1697 #ifdef LLVM_VERSION_INFO
1698 OS << LLVM_VERSION_INFO;
1701 #ifndef __OPTIMIZE__
1702 OS << "DEBUG build";
1704 OS << "Optimized build";
1707 OS << " with assertions";
1709 std::string CPU = sys::getHostCPUName();
1710 if (CPU == "generic") CPU = "(unknown)";
1712 #if (ENABLE_TIMESTAMPS == 1)
1713 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1715 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1716 << " Host CPU: " << CPU << '\n';
1718 void operator=(bool OptionWasSpecified) {
1719 if (!OptionWasSpecified) return;
1721 if (OverrideVersionPrinter != 0) {
1722 (*OverrideVersionPrinter)();
1727 // Iterate over any registered extra printers and call them to add further
1729 if (ExtraVersionPrinters != 0) {
1731 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1732 E = ExtraVersionPrinters->end();
1740 } // End anonymous namespace
1743 // Define the --version option that prints out the LLVM version for the tool
1744 static VersionPrinter VersionPrinterInstance;
1746 static cl::opt<VersionPrinter, true, parser<bool> >
1747 VersOp("version", cl::desc("Display the version of this program"),
1748 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1750 // Utility function for printing the help message.
1751 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1752 // This looks weird, but it actually prints the help message. The Printers are
1753 // types of HelpPrinter and the help gets printed when its operator= is
1754 // invoked. That's because the "normal" usages of the help printer is to be
1755 // assigned true/false depending on whether -help or -help-hidden was given or
1756 // not. Since we're circumventing that we have to make it look like -help or
1757 // -help-hidden were given, so we assign true.
1759 if (!Hidden && !Categorized)
1760 UncategorizedNormalPrinter = true;
1761 else if (!Hidden && Categorized)
1762 CategorizedNormalPrinter = true;
1763 else if (Hidden && !Categorized)
1764 UncategorizedHiddenPrinter = true;
1766 CategorizedHiddenPrinter = true;
1769 /// Utility function for printing version number.
1770 void cl::PrintVersionMessage() {
1771 VersionPrinterInstance.print();
1774 void cl::SetVersionPrinter(void (*func)()) {
1775 OverrideVersionPrinter = func;
1778 void cl::AddExtraVersionPrinter(void (*func)()) {
1779 if (ExtraVersionPrinters == 0)
1780 ExtraVersionPrinters = new std::vector<void (*)()>;
1782 ExtraVersionPrinters->push_back(func);
1785 void cl::getRegisteredOptions(StringMap<Option*> &Map)
1787 // Get all the options.
1788 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1789 SmallVector<Option*, 4> SinkOpts; //NOT USED
1790 assert(Map.size() == 0 && "StringMap must be empty");
1791 GetOptionInfo(PositionalOpts, SinkOpts, Map);