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 void GenericOptionValue::anchor() {}
64 void OptionValue<boolOrDefault>::anchor() {}
65 void OptionValue<std::string>::anchor() {}
66 void Option::anchor() {}
67 void basic_parser_impl::anchor() {}
68 void parser<bool>::anchor() {}
69 void parser<boolOrDefault>::anchor() {}
70 void parser<int>::anchor() {}
71 void parser<unsigned>::anchor() {}
72 void parser<unsigned long long>::anchor() {}
73 void parser<double>::anchor() {}
74 void parser<float>::anchor() {}
75 void parser<std::string>::anchor() {}
76 void parser<char>::anchor() {}
77 void StringSaver::anchor() {}
79 //===----------------------------------------------------------------------===//
81 // Globals for name and overview of program. Program name is not a string to
82 // avoid static ctor/dtor issues.
83 static char ProgramName[80] = "<premain>";
84 static const char *ProgramOverview = 0;
86 // This collects additional help to be printed.
87 static ManagedStatic<std::vector<const char*> > MoreHelp;
89 extrahelp::extrahelp(const char *Help)
91 MoreHelp->push_back(Help);
94 static bool OptionListChanged = false;
96 // MarkOptionsChanged - Internal helper function.
97 void cl::MarkOptionsChanged() {
98 OptionListChanged = true;
101 /// RegisteredOptionList - This is the list of the command line options that
102 /// have statically constructed themselves.
103 static Option *RegisteredOptionList = 0;
105 void Option::addArgument() {
106 assert(NextRegistered == 0 && "argument multiply registered!");
108 NextRegistered = RegisteredOptionList;
109 RegisteredOptionList = this;
110 MarkOptionsChanged();
113 // This collects the different option categories that have been registered.
114 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
115 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
117 // Initialise the general option category.
118 OptionCategory llvm::cl::GeneralCategory("General options");
120 void OptionCategory::registerCategory()
122 RegisteredOptionCategories->insert(this);
125 //===----------------------------------------------------------------------===//
126 // Basic, shared command line option processing machinery.
129 /// GetOptionInfo - Scan the list of registered options, turning them into data
130 /// structures that are easier to handle.
131 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
132 SmallVectorImpl<Option*> &SinkOpts,
133 StringMap<Option*> &OptionsMap) {
134 SmallVector<const char*, 16> OptionNames;
135 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
136 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
137 // If this option wants to handle multiple option names, get the full set.
138 // This handles enum options like "-O1 -O2" etc.
139 O->getExtraOptionNames(OptionNames);
141 OptionNames.push_back(O->ArgStr);
143 // Handle named options.
144 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
145 // Add argument to the argument map!
146 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
147 errs() << ProgramName << ": CommandLine Error: Argument '"
148 << OptionNames[i] << "' defined more than once!\n";
154 // Remember information about positional options.
155 if (O->getFormattingFlag() == cl::Positional)
156 PositionalOpts.push_back(O);
157 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
158 SinkOpts.push_back(O);
159 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
161 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
167 PositionalOpts.push_back(CAOpt);
169 // Make sure that they are in order of registration not backwards.
170 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
174 /// LookupOption - Lookup the option specified by the specified option on the
175 /// command line. If there is a value specified (after an equal sign) return
176 /// that as well. This assumes that leading dashes have already been stripped.
177 static Option *LookupOption(StringRef &Arg, StringRef &Value,
178 const StringMap<Option*> &OptionsMap) {
179 // Reject all dashes.
180 if (Arg.empty()) return 0;
182 size_t EqualPos = Arg.find('=');
184 // If we have an equals sign, remember the value.
185 if (EqualPos == StringRef::npos) {
186 // Look up the option.
187 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
188 return I != OptionsMap.end() ? I->second : 0;
191 // If the argument before the = is a valid option name, we match. If not,
192 // return Arg unmolested.
193 StringMap<Option*>::const_iterator I =
194 OptionsMap.find(Arg.substr(0, EqualPos));
195 if (I == OptionsMap.end()) return 0;
197 Value = Arg.substr(EqualPos+1);
198 Arg = Arg.substr(0, EqualPos);
202 /// LookupNearestOption - Lookup the closest match to the option specified by
203 /// the specified option on the command line. If there is a value specified
204 /// (after an equal sign) return that as well. This assumes that leading dashes
205 /// have already been stripped.
206 static Option *LookupNearestOption(StringRef Arg,
207 const StringMap<Option*> &OptionsMap,
208 std::string &NearestString) {
209 // Reject all dashes.
210 if (Arg.empty()) return 0;
212 // Split on any equal sign.
213 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
214 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
215 StringRef &RHS = SplitArg.second;
217 // Find the closest match.
219 unsigned BestDistance = 0;
220 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
221 ie = OptionsMap.end(); it != ie; ++it) {
222 Option *O = it->second;
223 SmallVector<const char*, 16> OptionNames;
224 O->getExtraOptionNames(OptionNames);
226 OptionNames.push_back(O->ArgStr);
228 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
229 StringRef Flag = PermitValue ? LHS : Arg;
230 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
231 StringRef Name = OptionNames[i];
232 unsigned Distance = StringRef(Name).edit_distance(
233 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
234 if (!Best || Distance < BestDistance) {
236 BestDistance = Distance;
237 if (RHS.empty() || !PermitValue)
238 NearestString = OptionNames[i];
240 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
248 /// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
249 /// does special handling of cl::CommaSeparated options.
250 static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
252 StringRef Value, bool MultiArg = false)
254 // Check to see if this option accepts a comma separated list of values. If
255 // it does, we have to split up the value into multiple values.
256 if (Handler->getMiscFlags() & CommaSeparated) {
257 StringRef Val(Value);
258 StringRef::size_type Pos = Val.find(',');
260 while (Pos != StringRef::npos) {
261 // Process the portion before the comma.
262 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
264 // Erase the portion before the comma, AND the comma.
265 Val = Val.substr(Pos+1);
266 Value.substr(Pos+1); // Increment the original value pointer as well.
267 // Check for another comma.
274 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
280 /// ProvideOption - For Value, this differentiates between an empty value ("")
281 /// and a null value (StringRef()). The later is accepted for arguments that
282 /// don't allow a value (-foo) the former is rejected (-foo=).
283 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
284 StringRef Value, int argc,
285 const char *const *argv, int &i) {
286 // Is this a multi-argument option?
287 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
289 // Enforce value requirements
290 switch (Handler->getValueExpectedFlag()) {
292 if (Value.data() == 0) { // No value specified?
294 return Handler->error("requires a value!");
295 // Steal the next argument, like for '-o filename'
299 case ValueDisallowed:
300 if (NumAdditionalVals > 0)
301 return Handler->error("multi-valued option specified"
302 " with ValueDisallowed modifier!");
305 return Handler->error("does not allow a value! '" +
306 Twine(Value) + "' specified.");
312 // If this isn't a multi-arg option, just run the handler.
313 if (NumAdditionalVals == 0)
314 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
316 // If it is, run the handle several times.
317 bool MultiArg = false;
320 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
326 while (NumAdditionalVals > 0) {
328 return Handler->error("not enough values!");
331 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
339 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
341 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
345 // Option predicates...
346 static inline bool isGrouping(const Option *O) {
347 return O->getFormattingFlag() == cl::Grouping;
349 static inline bool isPrefixedOrGrouping(const Option *O) {
350 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
353 // getOptionPred - Check to see if there are any options that satisfy the
354 // specified predicate with names that are the prefixes in Name. This is
355 // checked by progressively stripping characters off of the name, checking to
356 // see if there options that satisfy the predicate. If we find one, return it,
357 // otherwise return null.
359 static Option *getOptionPred(StringRef Name, size_t &Length,
360 bool (*Pred)(const Option*),
361 const StringMap<Option*> &OptionsMap) {
363 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
365 // Loop while we haven't found an option and Name still has at least two
366 // characters in it (so that the next iteration will not be the empty
368 while (OMI == OptionsMap.end() && Name.size() > 1) {
369 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
370 OMI = OptionsMap.find(Name);
373 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
374 Length = Name.size();
375 return OMI->second; // Found one!
377 return 0; // No option found!
380 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
381 /// with at least one '-') does not fully match an available option. Check to
382 /// see if this is a prefix or grouped option. If so, split arg into output an
383 /// Arg/Value pair and return the Option to parse it with.
384 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
386 const StringMap<Option*> &OptionsMap) {
387 if (Arg.size() == 1) return 0;
391 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
392 if (PGOpt == 0) return 0;
394 // If the option is a prefixed option, then the value is simply the
395 // rest of the name... so fall through to later processing, by
396 // setting up the argument name flags and value fields.
397 if (PGOpt->getFormattingFlag() == cl::Prefix) {
398 Value = Arg.substr(Length);
399 Arg = Arg.substr(0, Length);
400 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
404 // This must be a grouped option... handle them now. Grouping options can't
406 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
409 // Move current arg name out of Arg into OneArgName.
410 StringRef OneArgName = Arg.substr(0, Length);
411 Arg = Arg.substr(Length);
413 // Because ValueRequired is an invalid flag for grouped arguments,
414 // we don't need to pass argc/argv in.
415 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
416 "Option can not be cl::Grouping AND cl::ValueRequired!");
418 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
419 StringRef(), 0, 0, Dummy);
421 // Get the next grouping option.
422 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
423 } while (PGOpt && Length != Arg.size());
425 // Return the last option with Arg cut down to just the last one.
431 static bool RequiresValue(const Option *O) {
432 return O->getNumOccurrencesFlag() == cl::Required ||
433 O->getNumOccurrencesFlag() == cl::OneOrMore;
436 static bool EatsUnboundedNumberOfValues(const Option *O) {
437 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
438 O->getNumOccurrencesFlag() == cl::OneOrMore;
441 static bool isWhitespace(char C) {
442 return strchr(" \t\n\r\f\v", C);
445 static bool isQuote(char C) {
446 return C == '\"' || C == '\'';
449 static bool isGNUSpecial(char C) {
450 return strchr("\\\"\' ", C);
453 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
454 SmallVectorImpl<const char *> &NewArgv) {
455 SmallString<128> Token;
456 for (size_t I = 0, E = Src.size(); I != E; ++I) {
457 // Consume runs of whitespace.
459 while (I != E && isWhitespace(Src[I]))
464 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
465 // they are literal. This makes it much easier to read Windows file paths.
466 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
467 ++I; // Skip the escape.
468 Token.push_back(Src[I]);
472 // Consume a quoted string.
473 if (isQuote(Src[I])) {
474 char Quote = Src[I++];
475 while (I != E && Src[I] != Quote) {
476 // Backslashes are literal, unless they escape a special character.
477 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
479 Token.push_back(Src[I]);
486 // End the token if this is whitespace.
487 if (isWhitespace(Src[I])) {
489 NewArgv.push_back(Saver.SaveString(Token.c_str()));
494 // This is a normal character. Append it.
495 Token.push_back(Src[I]);
498 // Append the last token after hitting EOF with no whitespace.
500 NewArgv.push_back(Saver.SaveString(Token.c_str()));
503 /// Backslashes are interpreted in a rather complicated way in the Windows-style
504 /// command line, because backslashes are used both to separate path and to
505 /// escape double quote. This method consumes runs of backslashes as well as the
506 /// following double quote if it's escaped.
508 /// * If an even number of backslashes is followed by a double quote, one
509 /// backslash is output for every pair of backslashes, and the last double
510 /// quote remains unconsumed. The double quote will later be interpreted as
511 /// the start or end of a quoted string in the main loop outside of this
514 /// * If an odd number of backslashes is followed by a double quote, one
515 /// backslash is output for every pair of backslashes, and a double quote is
516 /// output for the last pair of backslash-double quote. The double quote is
517 /// consumed in this case.
519 /// * Otherwise, backslashes are interpreted literally.
520 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
521 size_t E = Src.size();
522 int BackslashCount = 0;
523 // Skip the backslashes.
527 } while (I != E && Src[I] == '\\');
529 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
530 if (FollowedByDoubleQuote) {
531 Token.append(BackslashCount / 2, '\\');
532 if (BackslashCount % 2 == 0)
534 Token.push_back('"');
537 Token.append(BackslashCount, '\\');
541 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
542 SmallVectorImpl<const char *> &NewArgv) {
543 SmallString<128> Token;
545 // This is a small state machine to consume characters until it reaches the
546 // end of the source string.
547 enum { INIT, UNQUOTED, QUOTED } State = INIT;
548 for (size_t I = 0, E = Src.size(); I != E; ++I) {
549 // INIT state indicates that the current input index is at the start of
550 // the string or between tokens.
552 if (isWhitespace(Src[I]))
558 if (Src[I] == '\\') {
559 I = parseBackslash(Src, I, Token);
563 Token.push_back(Src[I]);
568 // UNQUOTED state means that it's reading a token not quoted by double
570 if (State == UNQUOTED) {
571 // Whitespace means the end of the token.
572 if (isWhitespace(Src[I])) {
573 NewArgv.push_back(Saver.SaveString(Token.c_str()));
582 if (Src[I] == '\\') {
583 I = parseBackslash(Src, I, Token);
586 Token.push_back(Src[I]);
590 // QUOTED state means that it's reading a token quoted by double quotes.
591 if (State == QUOTED) {
596 if (Src[I] == '\\') {
597 I = parseBackslash(Src, I, Token);
600 Token.push_back(Src[I]);
603 // Append the last token after hitting EOF with no whitespace.
605 NewArgv.push_back(Saver.SaveString(Token.c_str()));
608 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
609 TokenizerCallback Tokenizer,
610 SmallVectorImpl<const char *> &NewArgv) {
611 OwningPtr<MemoryBuffer> MemBuf;
612 if (MemoryBuffer::getFile(FName, MemBuf))
614 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
616 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
617 ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd());
619 if (hasUTF16ByteOrderMark(BufRef)) {
620 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
622 Str = StringRef(UTF8Buf);
625 // Tokenize the contents into NewArgv.
626 Tokenizer(Str, Saver, NewArgv);
631 /// \brief Expand response files on a command line recursively using the given
632 /// StringSaver and tokenization strategy.
633 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
634 SmallVectorImpl<const char *> &Argv) {
635 unsigned RspFiles = 0;
636 bool AllExpanded = false;
638 // Don't cache Argv.size() because it can change.
639 for (unsigned I = 0; I != Argv.size(); ) {
640 const char *Arg = Argv[I];
646 // If we have too many response files, leave some unexpanded. This avoids
647 // crashing on self-referential response files.
651 // Replace this response file argument with the tokenization of its
652 // contents. Nested response files are expanded in subsequent iterations.
653 // FIXME: If a nested response file uses a relative path, is it relative to
654 // the cwd of the process or the response file?
655 SmallVector<const char *, 0> ExpandedArgv;
656 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
660 Argv.erase(Argv.begin() + I);
661 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
667 class StrDupSaver : public StringSaver {
668 std::vector<char*> Dups;
671 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
677 const char *SaveString(const char *Str) LLVM_OVERRIDE {
678 char *Dup = strdup(Str);
685 /// ParseEnvironmentOptions - An alternative entry point to the
686 /// CommandLine library, which allows you to read the program's name
687 /// from the caller (as PROGNAME) and its command-line arguments from
688 /// an environment variable (whose name is given in ENVVAR).
690 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
691 const char *Overview) {
693 assert(progName && "Program name not specified");
694 assert(envVar && "Environment variable name missing");
696 // Get the environment variable they want us to parse options out of.
697 const char *envValue = getenv(envVar);
701 // Get program's "name", which we wouldn't know without the caller
703 SmallVector<const char *, 20> newArgv;
705 newArgv.push_back(Saver.SaveString(progName));
707 // Parse the value of the environment variable into a "command line"
708 // and hand it off to ParseCommandLineOptions().
709 TokenizeGNUCommandLine(envValue, Saver, newArgv);
710 int newArgc = static_cast<int>(newArgv.size());
711 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
714 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
715 const char *Overview) {
716 // Process all registered options.
717 SmallVector<Option*, 4> PositionalOpts;
718 SmallVector<Option*, 4> SinkOpts;
719 StringMap<Option*> Opts;
720 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
722 assert((!Opts.empty() || !PositionalOpts.empty()) &&
723 "No options specified!");
725 // Expand response files.
726 SmallVector<const char *, 20> newArgv;
727 for (int i = 0; i != argc; ++i)
728 newArgv.push_back(argv[i]);
730 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
732 argc = static_cast<int>(newArgv.size());
734 // Copy the program name into ProgName, making sure not to overflow it.
735 std::string ProgName = sys::path::filename(argv[0]);
736 size_t Len = std::min(ProgName.size(), size_t(79));
737 memcpy(ProgramName, ProgName.data(), Len);
738 ProgramName[Len] = '\0';
740 ProgramOverview = Overview;
741 bool ErrorParsing = false;
743 // Check out the positional arguments to collect information about them.
744 unsigned NumPositionalRequired = 0;
746 // Determine whether or not there are an unlimited number of positionals
747 bool HasUnlimitedPositionals = false;
749 Option *ConsumeAfterOpt = 0;
750 if (!PositionalOpts.empty()) {
751 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
752 assert(PositionalOpts.size() > 1 &&
753 "Cannot specify cl::ConsumeAfter without a positional argument!");
754 ConsumeAfterOpt = PositionalOpts[0];
757 // Calculate how many positional values are _required_.
758 bool UnboundedFound = false;
759 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
761 Option *Opt = PositionalOpts[i];
762 if (RequiresValue(Opt))
763 ++NumPositionalRequired;
764 else if (ConsumeAfterOpt) {
765 // ConsumeAfter cannot be combined with "optional" positional options
766 // unless there is only one positional argument...
767 if (PositionalOpts.size() > 2)
769 Opt->error("error - this positional option will never be matched, "
770 "because it does not Require a value, and a "
771 "cl::ConsumeAfter option is active!");
772 } else if (UnboundedFound && !Opt->ArgStr[0]) {
773 // This option does not "require" a value... Make sure this option is
774 // not specified after an option that eats all extra arguments, or this
775 // one will never get any!
777 ErrorParsing |= Opt->error("error - option can never match, because "
778 "another positional argument will match an "
779 "unbounded number of values, and this option"
780 " does not require a value!");
782 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
784 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
787 // PositionalVals - A vector of "positional" arguments we accumulate into
788 // the process at the end.
790 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
792 // If the program has named positional arguments, and the name has been run
793 // across, keep track of which positional argument was named. Otherwise put
794 // the positional args into the PositionalVals list...
795 Option *ActivePositionalArg = 0;
797 // Loop over all of the arguments... processing them.
798 bool DashDashFound = false; // Have we read '--'?
799 for (int i = 1; i < argc; ++i) {
801 Option *NearestHandler = 0;
802 std::string NearestHandlerString;
804 StringRef ArgName = "";
806 // If the option list changed, this means that some command line
807 // option has just been registered or deregistered. This can occur in
808 // response to things like -load, etc. If this happens, rescan the options.
809 if (OptionListChanged) {
810 PositionalOpts.clear();
813 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
814 OptionListChanged = false;
817 // Check to see if this is a positional argument. This argument is
818 // considered to be positional if it doesn't start with '-', if it is "-"
819 // itself, or if we have seen "--" already.
821 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
822 // Positional argument!
823 if (ActivePositionalArg) {
824 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
825 continue; // We are done!
828 if (!PositionalOpts.empty()) {
829 PositionalVals.push_back(std::make_pair(argv[i],i));
831 // All of the positional arguments have been fulfulled, give the rest to
832 // the consume after option... if it's specified...
834 if (PositionalVals.size() >= NumPositionalRequired &&
835 ConsumeAfterOpt != 0) {
836 for (++i; i < argc; ++i)
837 PositionalVals.push_back(std::make_pair(argv[i],i));
838 break; // Handle outside of the argument processing loop...
841 // Delay processing positional arguments until the end...
844 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
846 DashDashFound = true; // This is the mythical "--"?
847 continue; // Don't try to process it as an argument itself.
848 } else if (ActivePositionalArg &&
849 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
850 // If there is a positional argument eating options, check to see if this
851 // option is another positional argument. If so, treat it as an argument,
852 // otherwise feed it to the eating positional.
854 // Eat leading dashes.
855 while (!ArgName.empty() && ArgName[0] == '-')
856 ArgName = ArgName.substr(1);
858 Handler = LookupOption(ArgName, Value, Opts);
859 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
860 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
861 continue; // We are done!
864 } else { // We start with a '-', must be an argument.
866 // Eat leading dashes.
867 while (!ArgName.empty() && ArgName[0] == '-')
868 ArgName = ArgName.substr(1);
870 Handler = LookupOption(ArgName, Value, Opts);
872 // Check to see if this "option" is really a prefixed or grouped argument.
874 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
877 // Otherwise, look for the closest available option to report to the user
878 // in the upcoming error.
879 if (Handler == 0 && SinkOpts.empty())
880 NearestHandler = LookupNearestOption(ArgName, Opts,
881 NearestHandlerString);
885 if (SinkOpts.empty()) {
886 errs() << ProgramName << ": Unknown command line argument '"
887 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
889 if (NearestHandler) {
890 // If we know a near match, report it as well.
891 errs() << ProgramName << ": Did you mean '-"
892 << NearestHandlerString << "'?\n";
897 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
898 E = SinkOpts.end(); I != E ; ++I)
899 (*I)->addOccurrence(i, "", argv[i]);
904 // If this is a named positional argument, just remember that it is the
906 if (Handler->getFormattingFlag() == cl::Positional)
907 ActivePositionalArg = Handler;
909 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
912 // Check and handle positional arguments now...
913 if (NumPositionalRequired > PositionalVals.size()) {
914 errs() << ProgramName
915 << ": Not enough positional command line arguments specified!\n"
916 << "Must specify at least " << NumPositionalRequired
917 << " positional arguments: See: " << argv[0] << " -help\n";
920 } else if (!HasUnlimitedPositionals &&
921 PositionalVals.size() > PositionalOpts.size()) {
922 errs() << ProgramName
923 << ": Too many positional arguments specified!\n"
924 << "Can specify at most " << PositionalOpts.size()
925 << " positional arguments: See: " << argv[0] << " -help\n";
928 } else if (ConsumeAfterOpt == 0) {
929 // Positional args have already been handled if ConsumeAfter is specified.
930 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
931 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
932 if (RequiresValue(PositionalOpts[i])) {
933 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
934 PositionalVals[ValNo].second);
936 --NumPositionalRequired; // We fulfilled our duty...
939 // If we _can_ give this option more arguments, do so now, as long as we
940 // do not give it values that others need. 'Done' controls whether the
941 // option even _WANTS_ any more.
943 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
944 while (NumVals-ValNo > NumPositionalRequired && !Done) {
945 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
947 Done = true; // Optional arguments want _at most_ one value
949 case cl::ZeroOrMore: // Zero or more will take all they can get...
950 case cl::OneOrMore: // One or more will take all they can get...
951 ProvidePositionalOption(PositionalOpts[i],
952 PositionalVals[ValNo].first,
953 PositionalVals[ValNo].second);
957 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
958 "positional argument processing!");
963 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
965 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
966 if (RequiresValue(PositionalOpts[j])) {
967 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
968 PositionalVals[ValNo].first,
969 PositionalVals[ValNo].second);
973 // Handle the case where there is just one positional option, and it's
974 // optional. In this case, we want to give JUST THE FIRST option to the
975 // positional option and keep the rest for the consume after. The above
976 // loop would have assigned no values to positional options in this case.
978 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
979 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
980 PositionalVals[ValNo].first,
981 PositionalVals[ValNo].second);
985 // Handle over all of the rest of the arguments to the
986 // cl::ConsumeAfter command line option...
987 for (; ValNo != PositionalVals.size(); ++ValNo)
988 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
989 PositionalVals[ValNo].first,
990 PositionalVals[ValNo].second);
993 // Loop over args and make sure all required args are specified!
994 for (StringMap<Option*>::iterator I = Opts.begin(),
995 E = Opts.end(); I != E; ++I) {
996 switch (I->second->getNumOccurrencesFlag()) {
999 if (I->second->getNumOccurrences() == 0) {
1000 I->second->error("must be specified at least once!");
1001 ErrorParsing = true;
1009 // Now that we know if -debug is specified, we can use it.
1010 // Note that if ReadResponseFiles == true, this must be done before the
1011 // memory allocated for the expanded command line is free()d below.
1012 DEBUG(dbgs() << "Args: ";
1013 for (int i = 0; i < argc; ++i)
1014 dbgs() << argv[i] << ' ';
1018 // Free all of the memory allocated to the map. Command line options may only
1019 // be processed once!
1021 PositionalOpts.clear();
1024 // If we had an error processing our arguments, don't let the program execute
1025 if (ErrorParsing) exit(1);
1028 //===----------------------------------------------------------------------===//
1029 // Option Base class implementation
1032 bool Option::error(const Twine &Message, StringRef ArgName) {
1033 if (ArgName.data() == 0) ArgName = ArgStr;
1034 if (ArgName.empty())
1035 errs() << HelpStr; // Be nice for positional arguments
1037 errs() << ProgramName << ": for the -" << ArgName;
1039 errs() << " option: " << Message << "\n";
1043 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
1044 StringRef Value, bool MultiArg) {
1046 NumOccurrences++; // Increment the number of times we have been seen
1048 switch (getNumOccurrencesFlag()) {
1050 if (NumOccurrences > 1)
1051 return error("may only occur zero or one times!", ArgName);
1054 if (NumOccurrences > 1)
1055 return error("must occur exactly one time!", ArgName);
1059 case ConsumeAfter: break;
1062 return handleOccurrence(pos, ArgName, Value);
1066 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1067 // has been specified yet.
1069 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1070 if (O.ValueStr[0] == 0) return DefaultMsg;
1074 //===----------------------------------------------------------------------===//
1075 // cl::alias class implementation
1078 // Return the width of the option tag for printing...
1079 size_t alias::getOptionWidth() const {
1080 return std::strlen(ArgStr)+6;
1083 static void printHelpStr(StringRef HelpStr, size_t Indent,
1084 size_t FirstLineIndentedBy) {
1085 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1086 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1087 while (!Split.second.empty()) {
1088 Split = Split.second.split('\n');
1089 outs().indent(Indent) << Split.first << "\n";
1093 // Print out the option for the alias.
1094 void alias::printOptionInfo(size_t GlobalWidth) const {
1095 outs() << " -" << ArgStr;
1096 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1099 //===----------------------------------------------------------------------===//
1100 // Parser Implementation code...
1103 // basic_parser implementation
1106 // Return the width of the option tag for printing...
1107 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1108 size_t Len = std::strlen(O.ArgStr);
1109 if (const char *ValName = getValueName())
1110 Len += std::strlen(getValueStr(O, ValName))+3;
1115 // printOptionInfo - Print out information about this option. The
1116 // to-be-maintained width is specified.
1118 void basic_parser_impl::printOptionInfo(const Option &O,
1119 size_t GlobalWidth) const {
1120 outs() << " -" << O.ArgStr;
1122 if (const char *ValName = getValueName())
1123 outs() << "=<" << getValueStr(O, ValName) << '>';
1125 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1128 void basic_parser_impl::printOptionName(const Option &O,
1129 size_t GlobalWidth) const {
1130 outs() << " -" << O.ArgStr;
1131 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1135 // parser<bool> implementation
1137 bool parser<bool>::parse(Option &O, StringRef ArgName,
1138 StringRef Arg, bool &Value) {
1139 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1145 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1149 return O.error("'" + Arg +
1150 "' is invalid value for boolean argument! Try 0 or 1");
1153 // parser<boolOrDefault> implementation
1155 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
1156 StringRef Arg, boolOrDefault &Value) {
1157 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1162 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1167 return O.error("'" + Arg +
1168 "' is invalid value for boolean argument! Try 0 or 1");
1171 // parser<int> implementation
1173 bool parser<int>::parse(Option &O, StringRef ArgName,
1174 StringRef Arg, int &Value) {
1175 if (Arg.getAsInteger(0, Value))
1176 return O.error("'" + Arg + "' value invalid for integer argument!");
1180 // parser<unsigned> implementation
1182 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1183 StringRef Arg, unsigned &Value) {
1185 if (Arg.getAsInteger(0, Value))
1186 return O.error("'" + Arg + "' value invalid for uint argument!");
1190 // parser<unsigned long long> implementation
1192 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1193 StringRef Arg, unsigned long long &Value){
1195 if (Arg.getAsInteger(0, Value))
1196 return O.error("'" + Arg + "' value invalid for uint argument!");
1200 // parser<double>/parser<float> implementation
1202 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1203 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1204 const char *ArgStart = TmpStr.c_str();
1206 Value = strtod(ArgStart, &End);
1208 return O.error("'" + Arg + "' value invalid for floating point argument!");
1212 bool parser<double>::parse(Option &O, StringRef ArgName,
1213 StringRef Arg, double &Val) {
1214 return parseDouble(O, Arg, Val);
1217 bool parser<float>::parse(Option &O, StringRef ArgName,
1218 StringRef Arg, float &Val) {
1220 if (parseDouble(O, Arg, dVal))
1228 // generic_parser_base implementation
1231 // findOption - Return the option number corresponding to the specified
1232 // argument string. If the option is not found, getNumOptions() is returned.
1234 unsigned generic_parser_base::findOption(const char *Name) {
1235 unsigned e = getNumOptions();
1237 for (unsigned i = 0; i != e; ++i) {
1238 if (strcmp(getOption(i), Name) == 0)
1245 // Return the width of the option tag for printing...
1246 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1247 if (O.hasArgStr()) {
1248 size_t Size = std::strlen(O.ArgStr)+6;
1249 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1250 Size = std::max(Size, std::strlen(getOption(i))+8);
1253 size_t BaseSize = 0;
1254 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1255 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1260 // printOptionInfo - Print out information about this option. The
1261 // to-be-maintained width is specified.
1263 void generic_parser_base::printOptionInfo(const Option &O,
1264 size_t GlobalWidth) const {
1265 if (O.hasArgStr()) {
1266 outs() << " -" << O.ArgStr;
1267 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1269 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1270 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1271 outs() << " =" << getOption(i);
1272 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1276 outs() << " " << O.HelpStr << '\n';
1277 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1278 const char *Option = getOption(i);
1279 outs() << " -" << Option;
1280 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1285 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1287 // printGenericOptionDiff - Print the value of this option and it's default.
1289 // "Generic" options have each value mapped to a name.
1290 void generic_parser_base::
1291 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1292 const GenericOptionValue &Default,
1293 size_t GlobalWidth) const {
1294 outs() << " -" << O.ArgStr;
1295 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1297 unsigned NumOpts = getNumOptions();
1298 for (unsigned i = 0; i != NumOpts; ++i) {
1299 if (Value.compare(getOptionValue(i)))
1302 outs() << "= " << getOption(i);
1303 size_t L = std::strlen(getOption(i));
1304 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1305 outs().indent(NumSpaces) << " (default: ";
1306 for (unsigned j = 0; j != NumOpts; ++j) {
1307 if (Default.compare(getOptionValue(j)))
1309 outs() << getOption(j);
1315 outs() << "= *unknown option value*\n";
1318 // printOptionDiff - Specializations for printing basic value types.
1320 #define PRINT_OPT_DIFF(T) \
1322 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1323 size_t GlobalWidth) const { \
1324 printOptionName(O, GlobalWidth); \
1327 raw_string_ostream SS(Str); \
1330 outs() << "= " << Str; \
1331 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1332 outs().indent(NumSpaces) << " (default: "; \
1334 outs() << D.getValue(); \
1336 outs() << "*no default*"; \
1340 PRINT_OPT_DIFF(bool)
1341 PRINT_OPT_DIFF(boolOrDefault)
1343 PRINT_OPT_DIFF(unsigned)
1344 PRINT_OPT_DIFF(unsigned long long)
1345 PRINT_OPT_DIFF(double)
1346 PRINT_OPT_DIFF(float)
1347 PRINT_OPT_DIFF(char)
1349 void parser<std::string>::
1350 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1351 size_t GlobalWidth) const {
1352 printOptionName(O, GlobalWidth);
1353 outs() << "= " << V;
1354 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1355 outs().indent(NumSpaces) << " (default: ";
1357 outs() << D.getValue();
1359 outs() << "*no default*";
1363 // Print a placeholder for options that don't yet support printOptionDiff().
1364 void basic_parser_impl::
1365 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1366 printOptionName(O, GlobalWidth);
1367 outs() << "= *cannot print option value*\n";
1370 //===----------------------------------------------------------------------===//
1371 // -help and -help-hidden option implementation
1374 static int OptNameCompare(const void *LHS, const void *RHS) {
1375 typedef std::pair<const char *, Option*> pair_ty;
1377 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1380 // Copy Options into a vector so we can sort them as we like.
1382 sortOpts(StringMap<Option*> &OptMap,
1383 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1385 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1387 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1389 // Ignore really-hidden options.
1390 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1393 // Unless showhidden is set, ignore hidden flags.
1394 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1397 // If we've already seen this option, don't add it to the list again.
1398 if (!OptionSet.insert(I->second))
1401 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1405 // Sort the options list alphabetically.
1406 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1413 const bool ShowHidden;
1414 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1415 // Print the options. Opts is assumed to be alphabetically sorted.
1416 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1417 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1418 Opts[i].second->printOptionInfo(MaxArgLen);
1422 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1423 virtual ~HelpPrinter() {}
1425 // Invoke the printer.
1426 void operator=(bool Value) {
1427 if (Value == false) return;
1429 // Get all the options.
1430 SmallVector<Option*, 4> PositionalOpts;
1431 SmallVector<Option*, 4> SinkOpts;
1432 StringMap<Option*> OptMap;
1433 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1435 StrOptionPairVector Opts;
1436 sortOpts(OptMap, Opts, ShowHidden);
1438 if (ProgramOverview)
1439 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1441 outs() << "USAGE: " << ProgramName << " [options]";
1443 // Print out the positional options.
1444 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
1445 if (!PositionalOpts.empty() &&
1446 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1447 CAOpt = PositionalOpts[0];
1449 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1450 if (PositionalOpts[i]->ArgStr[0])
1451 outs() << " --" << PositionalOpts[i]->ArgStr;
1452 outs() << " " << PositionalOpts[i]->HelpStr;
1455 // Print the consume after option info if it exists...
1456 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1460 // Compute the maximum argument length...
1461 size_t MaxArgLen = 0;
1462 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1463 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1465 outs() << "OPTIONS:\n";
1466 printOptions(Opts, MaxArgLen);
1468 // Print any extra help the user has declared.
1469 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1470 E = MoreHelp->end();
1475 // Halt the program since help information was printed
1480 class CategorizedHelpPrinter : public HelpPrinter {
1482 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1484 // Helper function for printOptions().
1485 // It shall return true if A's name should be lexographically
1486 // ordered before B's name. It returns false otherwise.
1487 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1488 int Length = strcmp(A->getName(), B->getName());
1489 assert(Length != 0 && "Duplicate option categories");
1493 // Make sure we inherit our base class's operator=()
1494 using HelpPrinter::operator= ;
1497 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1498 std::vector<OptionCategory *> SortedCategories;
1499 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1501 // Collect registered option categories into vector in preperation for
1503 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1504 E = RegisteredOptionCategories->end();
1506 SortedCategories.push_back(*I);
1508 // Sort the different option categories alphabetically.
1509 assert(SortedCategories.size() > 0 && "No option categories registered!");
1510 std::sort(SortedCategories.begin(), SortedCategories.end(),
1511 OptionCategoryCompare);
1513 // Create map to empty vectors.
1514 for (std::vector<OptionCategory *>::const_iterator
1515 I = SortedCategories.begin(),
1516 E = SortedCategories.end();
1518 CategorizedOptions[*I] = std::vector<Option *>();
1520 // Walk through pre-sorted options and assign into categories.
1521 // Because the options are already alphabetically sorted the
1522 // options within categories will also be alphabetically sorted.
1523 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1524 Option *Opt = Opts[I].second;
1525 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1526 "Option has an unregistered category");
1527 CategorizedOptions[Opt->Category].push_back(Opt);
1531 for (std::vector<OptionCategory *>::const_iterator
1532 Category = SortedCategories.begin(),
1533 E = SortedCategories.end();
1534 Category != E; ++Category) {
1535 // Hide empty categories for -help, but show for -help-hidden.
1536 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1537 if (!ShowHidden && IsEmptyCategory)
1540 // Print category information.
1542 outs() << (*Category)->getName() << ":\n";
1544 // Check if description is set.
1545 if ((*Category)->getDescription() != 0)
1546 outs() << (*Category)->getDescription() << "\n\n";
1550 // When using -help-hidden explicitly state if the category has no
1551 // options associated with it.
1552 if (IsEmptyCategory) {
1553 outs() << " This option category has no options.\n";
1556 // Loop over the options in the category and print.
1557 for (std::vector<Option *>::const_iterator
1558 Opt = CategorizedOptions[*Category].begin(),
1559 E = CategorizedOptions[*Category].end();
1561 (*Opt)->printOptionInfo(MaxArgLen);
1566 // This wraps the Uncategorizing and Categorizing printers and decides
1567 // at run time which should be invoked.
1568 class HelpPrinterWrapper {
1570 HelpPrinter &UncategorizedPrinter;
1571 CategorizedHelpPrinter &CategorizedPrinter;
1574 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1575 CategorizedHelpPrinter &CategorizedPrinter) :
1576 UncategorizedPrinter(UncategorizedPrinter),
1577 CategorizedPrinter(CategorizedPrinter) { }
1579 // Invoke the printer.
1580 void operator=(bool Value);
1583 } // End anonymous namespace
1585 // Declare the four HelpPrinter instances that are used to print out help, or
1586 // help-hidden as an uncategorized list or in categories.
1587 static HelpPrinter UncategorizedNormalPrinter(false);
1588 static HelpPrinter UncategorizedHiddenPrinter(true);
1589 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1590 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1593 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1594 // a categorizing help printer
1595 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1596 CategorizedNormalPrinter);
1597 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1598 CategorizedHiddenPrinter);
1600 // Define uncategorized help printers.
1601 // -help-list is hidden by default because if Option categories are being used
1602 // then -help behaves the same as -help-list.
1603 static cl::opt<HelpPrinter, true, parser<bool> >
1605 cl::desc("Display list of available options (-help-list-hidden for more)"),
1606 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1608 static cl::opt<HelpPrinter, true, parser<bool> >
1609 HLHOp("help-list-hidden",
1610 cl::desc("Display list of all available options"),
1611 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1613 // Define uncategorized/categorized help printers. These printers change their
1614 // behaviour at runtime depending on whether one or more Option categories have
1616 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1617 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1618 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1620 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1621 HHOp("help-hidden", cl::desc("Display all available options"),
1622 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1626 static cl::opt<bool>
1627 PrintOptions("print-options",
1628 cl::desc("Print non-default options after command line parsing"),
1629 cl::Hidden, cl::init(false));
1631 static cl::opt<bool>
1632 PrintAllOptions("print-all-options",
1633 cl::desc("Print all option values after command line parsing"),
1634 cl::Hidden, cl::init(false));
1636 void HelpPrinterWrapper::operator=(bool Value) {
1640 // Decide which printer to invoke. If more than one option category is
1641 // registered then it is useful to show the categorized help instead of
1642 // uncategorized help.
1643 if (RegisteredOptionCategories->size() > 1) {
1644 // unhide -help-list option so user can have uncategorized output if they
1646 HLOp.setHiddenFlag(NotHidden);
1648 CategorizedPrinter = true; // Invoke categorized printer
1651 UncategorizedPrinter = true; // Invoke uncategorized printer
1654 // Print the value of each option.
1655 void cl::PrintOptionValues() {
1656 if (!PrintOptions && !PrintAllOptions) return;
1658 // Get all the options.
1659 SmallVector<Option*, 4> PositionalOpts;
1660 SmallVector<Option*, 4> SinkOpts;
1661 StringMap<Option*> OptMap;
1662 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1664 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1665 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1667 // Compute the maximum argument length...
1668 size_t MaxArgLen = 0;
1669 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1670 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1672 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1673 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1676 static void (*OverrideVersionPrinter)() = 0;
1678 static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1681 class VersionPrinter {
1684 raw_ostream &OS = outs();
1685 OS << "LLVM (http://llvm.org/):\n"
1686 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1687 #ifdef LLVM_VERSION_INFO
1688 OS << LLVM_VERSION_INFO;
1691 #ifndef __OPTIMIZE__
1692 OS << "DEBUG build";
1694 OS << "Optimized build";
1697 OS << " with assertions";
1699 std::string CPU = sys::getHostCPUName();
1700 if (CPU == "generic") CPU = "(unknown)";
1702 #if (ENABLE_TIMESTAMPS == 1)
1703 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1705 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1706 << " Host CPU: " << CPU << '\n';
1708 void operator=(bool OptionWasSpecified) {
1709 if (!OptionWasSpecified) return;
1711 if (OverrideVersionPrinter != 0) {
1712 (*OverrideVersionPrinter)();
1717 // Iterate over any registered extra printers and call them to add further
1719 if (ExtraVersionPrinters != 0) {
1721 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1722 E = ExtraVersionPrinters->end();
1730 } // End anonymous namespace
1733 // Define the --version option that prints out the LLVM version for the tool
1734 static VersionPrinter VersionPrinterInstance;
1736 static cl::opt<VersionPrinter, true, parser<bool> >
1737 VersOp("version", cl::desc("Display the version of this program"),
1738 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1740 // Utility function for printing the help message.
1741 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1742 // This looks weird, but it actually prints the help message. The Printers are
1743 // types of HelpPrinter and the help gets printed when its operator= is
1744 // invoked. That's because the "normal" usages of the help printer is to be
1745 // assigned true/false depending on whether -help or -help-hidden was given or
1746 // not. Since we're circumventing that we have to make it look like -help or
1747 // -help-hidden were given, so we assign true.
1749 if (!Hidden && !Categorized)
1750 UncategorizedNormalPrinter = true;
1751 else if (!Hidden && Categorized)
1752 CategorizedNormalPrinter = true;
1753 else if (Hidden && !Categorized)
1754 UncategorizedHiddenPrinter = true;
1756 CategorizedHiddenPrinter = true;
1759 /// Utility function for printing version number.
1760 void cl::PrintVersionMessage() {
1761 VersionPrinterInstance.print();
1764 void cl::SetVersionPrinter(void (*func)()) {
1765 OverrideVersionPrinter = func;
1768 void cl::AddExtraVersionPrinter(void (*func)()) {
1769 if (ExtraVersionPrinters == 0)
1770 ExtraVersionPrinters = new std::vector<void (*)()>;
1772 ExtraVersionPrinters->push_back(func);
1775 void cl::getRegisteredOptions(StringMap<Option*> &Map)
1777 // Get all the options.
1778 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1779 SmallVector<Option*, 4> SinkOpts; //NOT USED
1780 assert(Map.size() == 0 && "StringMap must be empty");
1781 GetOptionInfo(PositionalOpts, SinkOpts, Map);