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 OptionValue<boolOrDefault>::anchor() {}
64 void OptionValue<std::string>::anchor() {}
65 void Option::anchor() {}
66 void basic_parser_impl::anchor() {}
67 void parser<bool>::anchor() {}
68 void parser<boolOrDefault>::anchor() {}
69 void parser<int>::anchor() {}
70 void parser<unsigned>::anchor() {}
71 void parser<unsigned long long>::anchor() {}
72 void parser<double>::anchor() {}
73 void parser<float>::anchor() {}
74 void parser<std::string>::anchor() {}
75 void parser<char>::anchor() {}
77 //===----------------------------------------------------------------------===//
79 // Globals for name and overview of program. Program name is not a string to
80 // avoid static ctor/dtor issues.
81 static char ProgramName[80] = "<premain>";
82 static const char *ProgramOverview = 0;
84 // This collects additional help to be printed.
85 static ManagedStatic<std::vector<const char*> > MoreHelp;
87 extrahelp::extrahelp(const char *Help)
89 MoreHelp->push_back(Help);
92 static bool OptionListChanged = false;
94 // MarkOptionsChanged - Internal helper function.
95 void cl::MarkOptionsChanged() {
96 OptionListChanged = true;
99 /// RegisteredOptionList - This is the list of the command line options that
100 /// have statically constructed themselves.
101 static Option *RegisteredOptionList = 0;
103 void Option::addArgument() {
104 assert(NextRegistered == 0 && "argument multiply registered!");
106 NextRegistered = RegisteredOptionList;
107 RegisteredOptionList = this;
108 MarkOptionsChanged();
111 // This collects the different option categories that have been registered.
112 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
113 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
115 // Initialise the general option category.
116 OptionCategory llvm::cl::GeneralCategory("General options");
118 void OptionCategory::registerCategory()
120 RegisteredOptionCategories->insert(this);
123 //===----------------------------------------------------------------------===//
124 // Basic, shared command line option processing machinery.
127 /// GetOptionInfo - Scan the list of registered options, turning them into data
128 /// structures that are easier to handle.
129 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
130 SmallVectorImpl<Option*> &SinkOpts,
131 StringMap<Option*> &OptionsMap) {
132 SmallVector<const char*, 16> OptionNames;
133 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
134 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
135 // If this option wants to handle multiple option names, get the full set.
136 // This handles enum options like "-O1 -O2" etc.
137 O->getExtraOptionNames(OptionNames);
139 OptionNames.push_back(O->ArgStr);
141 // Handle named options.
142 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
143 // Add argument to the argument map!
144 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
145 errs() << ProgramName << ": CommandLine Error: Argument '"
146 << OptionNames[i] << "' defined more than once!\n";
152 // Remember information about positional options.
153 if (O->getFormattingFlag() == cl::Positional)
154 PositionalOpts.push_back(O);
155 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
156 SinkOpts.push_back(O);
157 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
159 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
165 PositionalOpts.push_back(CAOpt);
167 // Make sure that they are in order of registration not backwards.
168 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
172 /// LookupOption - Lookup the option specified by the specified option on the
173 /// command line. If there is a value specified (after an equal sign) return
174 /// that as well. This assumes that leading dashes have already been stripped.
175 static Option *LookupOption(StringRef &Arg, StringRef &Value,
176 const StringMap<Option*> &OptionsMap) {
177 // Reject all dashes.
178 if (Arg.empty()) return 0;
180 size_t EqualPos = Arg.find('=');
182 // If we have an equals sign, remember the value.
183 if (EqualPos == StringRef::npos) {
184 // Look up the option.
185 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
186 return I != OptionsMap.end() ? I->second : 0;
189 // If the argument before the = is a valid option name, we match. If not,
190 // return Arg unmolested.
191 StringMap<Option*>::const_iterator I =
192 OptionsMap.find(Arg.substr(0, EqualPos));
193 if (I == OptionsMap.end()) return 0;
195 Value = Arg.substr(EqualPos+1);
196 Arg = Arg.substr(0, EqualPos);
200 /// LookupNearestOption - Lookup the closest match to the option specified by
201 /// the specified option on the command line. If there is a value specified
202 /// (after an equal sign) return that as well. This assumes that leading dashes
203 /// have already been stripped.
204 static Option *LookupNearestOption(StringRef Arg,
205 const StringMap<Option*> &OptionsMap,
206 std::string &NearestString) {
207 // Reject all dashes.
208 if (Arg.empty()) return 0;
210 // Split on any equal sign.
211 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
212 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
213 StringRef &RHS = SplitArg.second;
215 // Find the closest match.
217 unsigned BestDistance = 0;
218 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
219 ie = OptionsMap.end(); it != ie; ++it) {
220 Option *O = it->second;
221 SmallVector<const char*, 16> OptionNames;
222 O->getExtraOptionNames(OptionNames);
224 OptionNames.push_back(O->ArgStr);
226 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
227 StringRef Flag = PermitValue ? LHS : Arg;
228 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
229 StringRef Name = OptionNames[i];
230 unsigned Distance = StringRef(Name).edit_distance(
231 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
232 if (!Best || Distance < BestDistance) {
234 BestDistance = Distance;
235 if (RHS.empty() || !PermitValue)
236 NearestString = OptionNames[i];
238 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
246 /// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
247 /// does special handling of cl::CommaSeparated options.
248 static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
250 StringRef Value, bool MultiArg = false)
252 // Check to see if this option accepts a comma separated list of values. If
253 // it does, we have to split up the value into multiple values.
254 if (Handler->getMiscFlags() & CommaSeparated) {
255 StringRef Val(Value);
256 StringRef::size_type Pos = Val.find(',');
258 while (Pos != StringRef::npos) {
259 // Process the portion before the comma.
260 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
262 // Erase the portion before the comma, AND the comma.
263 Val = Val.substr(Pos+1);
264 Value.substr(Pos+1); // Increment the original value pointer as well.
265 // Check for another comma.
272 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
278 /// ProvideOption - For Value, this differentiates between an empty value ("")
279 /// and a null value (StringRef()). The later is accepted for arguments that
280 /// don't allow a value (-foo) the former is rejected (-foo=).
281 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
282 StringRef Value, int argc,
283 const char *const *argv, int &i) {
284 // Is this a multi-argument option?
285 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
287 // Enforce value requirements
288 switch (Handler->getValueExpectedFlag()) {
290 if (Value.data() == 0) { // No value specified?
292 return Handler->error("requires a value!");
293 // Steal the next argument, like for '-o filename'
297 case ValueDisallowed:
298 if (NumAdditionalVals > 0)
299 return Handler->error("multi-valued option specified"
300 " with ValueDisallowed modifier!");
303 return Handler->error("does not allow a value! '" +
304 Twine(Value) + "' specified.");
310 // If this isn't a multi-arg option, just run the handler.
311 if (NumAdditionalVals == 0)
312 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
314 // If it is, run the handle several times.
315 bool MultiArg = false;
318 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
324 while (NumAdditionalVals > 0) {
326 return Handler->error("not enough values!");
329 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
337 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
339 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
343 // Option predicates...
344 static inline bool isGrouping(const Option *O) {
345 return O->getFormattingFlag() == cl::Grouping;
347 static inline bool isPrefixedOrGrouping(const Option *O) {
348 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
351 // getOptionPred - Check to see if there are any options that satisfy the
352 // specified predicate with names that are the prefixes in Name. This is
353 // checked by progressively stripping characters off of the name, checking to
354 // see if there options that satisfy the predicate. If we find one, return it,
355 // otherwise return null.
357 static Option *getOptionPred(StringRef Name, size_t &Length,
358 bool (*Pred)(const Option*),
359 const StringMap<Option*> &OptionsMap) {
361 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
363 // Loop while we haven't found an option and Name still has at least two
364 // characters in it (so that the next iteration will not be the empty
366 while (OMI == OptionsMap.end() && Name.size() > 1) {
367 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
368 OMI = OptionsMap.find(Name);
371 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
372 Length = Name.size();
373 return OMI->second; // Found one!
375 return 0; // No option found!
378 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
379 /// with at least one '-') does not fully match an available option. Check to
380 /// see if this is a prefix or grouped option. If so, split arg into output an
381 /// Arg/Value pair and return the Option to parse it with.
382 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
384 const StringMap<Option*> &OptionsMap) {
385 if (Arg.size() == 1) return 0;
389 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
390 if (PGOpt == 0) return 0;
392 // If the option is a prefixed option, then the value is simply the
393 // rest of the name... so fall through to later processing, by
394 // setting up the argument name flags and value fields.
395 if (PGOpt->getFormattingFlag() == cl::Prefix) {
396 Value = Arg.substr(Length);
397 Arg = Arg.substr(0, Length);
398 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
402 // This must be a grouped option... handle them now. Grouping options can't
404 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
407 // Move current arg name out of Arg into OneArgName.
408 StringRef OneArgName = Arg.substr(0, Length);
409 Arg = Arg.substr(Length);
411 // Because ValueRequired is an invalid flag for grouped arguments,
412 // we don't need to pass argc/argv in.
413 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
414 "Option can not be cl::Grouping AND cl::ValueRequired!");
416 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
417 StringRef(), 0, 0, Dummy);
419 // Get the next grouping option.
420 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
421 } while (PGOpt && Length != Arg.size());
423 // Return the last option with Arg cut down to just the last one.
429 static bool RequiresValue(const Option *O) {
430 return O->getNumOccurrencesFlag() == cl::Required ||
431 O->getNumOccurrencesFlag() == cl::OneOrMore;
434 static bool EatsUnboundedNumberOfValues(const Option *O) {
435 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
436 O->getNumOccurrencesFlag() == cl::OneOrMore;
439 static bool isWhitespace(char C) {
440 return strchr(" \t\n\r\f\v", C);
443 static bool isQuote(char C) {
444 return C == '\"' || C == '\'';
447 static bool isGNUSpecial(char C) {
448 return strchr("\\\"\' ", C);
451 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
452 SmallVectorImpl<const char *> &NewArgv) {
453 SmallString<128> Token;
454 for (size_t I = 0, E = Src.size(); I != E; ++I) {
455 // Consume runs of whitespace.
457 while (I != E && isWhitespace(Src[I]))
462 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
463 // they are literal. This makes it much easier to read Windows file paths.
464 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
465 ++I; // Skip the escape.
466 Token.push_back(Src[I]);
470 // Consume a quoted string.
471 if (isQuote(Src[I])) {
472 char Quote = Src[I++];
473 while (I != E && Src[I] != Quote) {
474 // Backslashes are literal, unless they escape a special character.
475 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
477 Token.push_back(Src[I]);
484 // End the token if this is whitespace.
485 if (isWhitespace(Src[I])) {
487 NewArgv.push_back(Saver.SaveString(Token.c_str()));
492 // This is a normal character. Append it.
493 Token.push_back(Src[I]);
496 // Append the last token after hitting EOF with no whitespace.
498 NewArgv.push_back(Saver.SaveString(Token.c_str()));
501 /// Backslashes are interpreted in a rather complicated way in the Windows-style
502 /// command line, because backslashes are used both to separate path and to
503 /// escape double quote. This method consumes runs of backslashes as well as the
504 /// following double quote if it's escaped.
506 /// * If an even number of backslashes is followed by a double quote, one
507 /// backslash is output for every pair of backslashes, and the last double
508 /// quote remains unconsumed. The double quote will later be interpreted as
509 /// the start or end of a quoted string in the main loop outside of this
512 /// * If an odd number of backslashes is followed by a double quote, one
513 /// backslash is output for every pair of backslashes, and a double quote is
514 /// output for the last pair of backslash-double quote. The double quote is
515 /// consumed in this case.
517 /// * Otherwise, backslashes are interpreted literally.
518 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
519 size_t E = Src.size();
520 int BackslashCount = 0;
521 // Skip the backslashes.
525 } while (I != E && Src[I] == '\\');
527 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
528 if (FollowedByDoubleQuote) {
529 Token.append(BackslashCount / 2, '\\');
530 if (BackslashCount % 2 == 0)
532 Token.push_back('"');
535 Token.append(BackslashCount, '\\');
539 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
540 SmallVectorImpl<const char *> &NewArgv) {
541 SmallString<128> Token;
543 // This is a small state machine to consume characters until it reaches the
544 // end of the source string.
545 enum { INIT, UNQUOTED, QUOTED } State = INIT;
546 for (size_t I = 0, E = Src.size(); I != E; ++I) {
547 // INIT state indicates that the current input index is at the start of
548 // the string or between tokens.
550 if (isWhitespace(Src[I]))
556 if (Src[I] == '\\') {
557 I = parseBackslash(Src, I, Token);
561 Token.push_back(Src[I]);
566 // UNQUOTED state means that it's reading a token not quoted by double
568 if (State == UNQUOTED) {
569 // Whitespace means the end of the token.
570 if (isWhitespace(Src[I])) {
571 NewArgv.push_back(Saver.SaveString(Token.c_str()));
580 if (Src[I] == '\\') {
581 I = parseBackslash(Src, I, Token);
584 Token.push_back(Src[I]);
588 // QUOTED state means that it's reading a token quoted by double quotes.
589 if (State == QUOTED) {
594 if (Src[I] == '\\') {
595 I = parseBackslash(Src, I, Token);
598 Token.push_back(Src[I]);
601 // Append the last token after hitting EOF with no whitespace.
603 NewArgv.push_back(Saver.SaveString(Token.c_str()));
606 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
607 TokenizerCallback Tokenizer,
608 SmallVectorImpl<const char *> &NewArgv) {
609 OwningPtr<MemoryBuffer> MemBuf;
610 if (MemoryBuffer::getFile(FName, MemBuf))
612 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
614 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
615 ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd());
617 if (hasUTF16ByteOrderMark(BufRef)) {
618 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
620 Str = StringRef(UTF8Buf);
623 // Tokenize the contents into NewArgv.
624 Tokenizer(Str, Saver, NewArgv);
629 /// \brief Expand response files on a command line recursively using the given
630 /// StringSaver and tokenization strategy.
631 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
632 SmallVectorImpl<const char *> &Argv) {
633 unsigned RspFiles = 0;
634 bool AllExpanded = false;
636 // Don't cache Argv.size() because it can change.
637 for (unsigned I = 0; I != Argv.size(); ) {
638 const char *Arg = Argv[I];
644 // If we have too many response files, leave some unexpanded. This avoids
645 // crashing on self-referential response files.
649 // Replace this response file argument with the tokenization of its
650 // contents. Nested response files are expanded in subsequent iterations.
651 // FIXME: If a nested response file uses a relative path, is it relative to
652 // the cwd of the process or the response file?
653 SmallVector<const char *, 0> ExpandedArgv;
654 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
658 Argv.erase(Argv.begin() + I);
659 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
665 class StrDupSaver : public StringSaver {
666 std::vector<char*> Dups;
669 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
675 const char *SaveString(const char *Str) LLVM_OVERRIDE {
676 char *Dup = strdup(Str);
683 /// ParseEnvironmentOptions - An alternative entry point to the
684 /// CommandLine library, which allows you to read the program's name
685 /// from the caller (as PROGNAME) and its command-line arguments from
686 /// an environment variable (whose name is given in ENVVAR).
688 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
689 const char *Overview) {
691 assert(progName && "Program name not specified");
692 assert(envVar && "Environment variable name missing");
694 // Get the environment variable they want us to parse options out of.
695 const char *envValue = getenv(envVar);
699 // Get program's "name", which we wouldn't know without the caller
701 SmallVector<const char *, 20> newArgv;
703 newArgv.push_back(Saver.SaveString(progName));
705 // Parse the value of the environment variable into a "command line"
706 // and hand it off to ParseCommandLineOptions().
707 TokenizeGNUCommandLine(envValue, Saver, newArgv);
708 int newArgc = static_cast<int>(newArgv.size());
709 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
712 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
713 const char *Overview) {
714 // Process all registered options.
715 SmallVector<Option*, 4> PositionalOpts;
716 SmallVector<Option*, 4> SinkOpts;
717 StringMap<Option*> Opts;
718 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
720 assert((!Opts.empty() || !PositionalOpts.empty()) &&
721 "No options specified!");
723 // Expand response files.
724 SmallVector<const char *, 20> newArgv;
725 for (int i = 0; i != argc; ++i)
726 newArgv.push_back(argv[i]);
728 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
730 argc = static_cast<int>(newArgv.size());
732 // Copy the program name into ProgName, making sure not to overflow it.
733 std::string ProgName = sys::path::filename(argv[0]);
734 size_t Len = std::min(ProgName.size(), size_t(79));
735 memcpy(ProgramName, ProgName.data(), Len);
736 ProgramName[Len] = '\0';
738 ProgramOverview = Overview;
739 bool ErrorParsing = false;
741 // Check out the positional arguments to collect information about them.
742 unsigned NumPositionalRequired = 0;
744 // Determine whether or not there are an unlimited number of positionals
745 bool HasUnlimitedPositionals = false;
747 Option *ConsumeAfterOpt = 0;
748 if (!PositionalOpts.empty()) {
749 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
750 assert(PositionalOpts.size() > 1 &&
751 "Cannot specify cl::ConsumeAfter without a positional argument!");
752 ConsumeAfterOpt = PositionalOpts[0];
755 // Calculate how many positional values are _required_.
756 bool UnboundedFound = false;
757 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
759 Option *Opt = PositionalOpts[i];
760 if (RequiresValue(Opt))
761 ++NumPositionalRequired;
762 else if (ConsumeAfterOpt) {
763 // ConsumeAfter cannot be combined with "optional" positional options
764 // unless there is only one positional argument...
765 if (PositionalOpts.size() > 2)
767 Opt->error("error - this positional option will never be matched, "
768 "because it does not Require a value, and a "
769 "cl::ConsumeAfter option is active!");
770 } else if (UnboundedFound && !Opt->ArgStr[0]) {
771 // This option does not "require" a value... Make sure this option is
772 // not specified after an option that eats all extra arguments, or this
773 // one will never get any!
775 ErrorParsing |= Opt->error("error - option can never match, because "
776 "another positional argument will match an "
777 "unbounded number of values, and this option"
778 " does not require a value!");
780 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
782 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
785 // PositionalVals - A vector of "positional" arguments we accumulate into
786 // the process at the end.
788 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
790 // If the program has named positional arguments, and the name has been run
791 // across, keep track of which positional argument was named. Otherwise put
792 // the positional args into the PositionalVals list...
793 Option *ActivePositionalArg = 0;
795 // Loop over all of the arguments... processing them.
796 bool DashDashFound = false; // Have we read '--'?
797 for (int i = 1; i < argc; ++i) {
799 Option *NearestHandler = 0;
800 std::string NearestHandlerString;
802 StringRef ArgName = "";
804 // If the option list changed, this means that some command line
805 // option has just been registered or deregistered. This can occur in
806 // response to things like -load, etc. If this happens, rescan the options.
807 if (OptionListChanged) {
808 PositionalOpts.clear();
811 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
812 OptionListChanged = false;
815 // Check to see if this is a positional argument. This argument is
816 // considered to be positional if it doesn't start with '-', if it is "-"
817 // itself, or if we have seen "--" already.
819 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
820 // Positional argument!
821 if (ActivePositionalArg) {
822 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
823 continue; // We are done!
826 if (!PositionalOpts.empty()) {
827 PositionalVals.push_back(std::make_pair(argv[i],i));
829 // All of the positional arguments have been fulfulled, give the rest to
830 // the consume after option... if it's specified...
832 if (PositionalVals.size() >= NumPositionalRequired &&
833 ConsumeAfterOpt != 0) {
834 for (++i; i < argc; ++i)
835 PositionalVals.push_back(std::make_pair(argv[i],i));
836 break; // Handle outside of the argument processing loop...
839 // Delay processing positional arguments until the end...
842 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
844 DashDashFound = true; // This is the mythical "--"?
845 continue; // Don't try to process it as an argument itself.
846 } else if (ActivePositionalArg &&
847 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
848 // If there is a positional argument eating options, check to see if this
849 // option is another positional argument. If so, treat it as an argument,
850 // otherwise feed it to the eating positional.
852 // Eat leading dashes.
853 while (!ArgName.empty() && ArgName[0] == '-')
854 ArgName = ArgName.substr(1);
856 Handler = LookupOption(ArgName, Value, Opts);
857 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
858 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
859 continue; // We are done!
862 } else { // We start with a '-', must be an argument.
864 // Eat leading dashes.
865 while (!ArgName.empty() && ArgName[0] == '-')
866 ArgName = ArgName.substr(1);
868 Handler = LookupOption(ArgName, Value, Opts);
870 // Check to see if this "option" is really a prefixed or grouped argument.
872 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
875 // Otherwise, look for the closest available option to report to the user
876 // in the upcoming error.
877 if (Handler == 0 && SinkOpts.empty())
878 NearestHandler = LookupNearestOption(ArgName, Opts,
879 NearestHandlerString);
883 if (SinkOpts.empty()) {
884 errs() << ProgramName << ": Unknown command line argument '"
885 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
887 if (NearestHandler) {
888 // If we know a near match, report it as well.
889 errs() << ProgramName << ": Did you mean '-"
890 << NearestHandlerString << "'?\n";
895 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
896 E = SinkOpts.end(); I != E ; ++I)
897 (*I)->addOccurrence(i, "", argv[i]);
902 // If this is a named positional argument, just remember that it is the
904 if (Handler->getFormattingFlag() == cl::Positional)
905 ActivePositionalArg = Handler;
907 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
910 // Check and handle positional arguments now...
911 if (NumPositionalRequired > PositionalVals.size()) {
912 errs() << ProgramName
913 << ": Not enough positional command line arguments specified!\n"
914 << "Must specify at least " << NumPositionalRequired
915 << " positional arguments: See: " << argv[0] << " -help\n";
918 } else if (!HasUnlimitedPositionals &&
919 PositionalVals.size() > PositionalOpts.size()) {
920 errs() << ProgramName
921 << ": Too many positional arguments specified!\n"
922 << "Can specify at most " << PositionalOpts.size()
923 << " positional arguments: See: " << argv[0] << " -help\n";
926 } else if (ConsumeAfterOpt == 0) {
927 // Positional args have already been handled if ConsumeAfter is specified.
928 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
929 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
930 if (RequiresValue(PositionalOpts[i])) {
931 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
932 PositionalVals[ValNo].second);
934 --NumPositionalRequired; // We fulfilled our duty...
937 // If we _can_ give this option more arguments, do so now, as long as we
938 // do not give it values that others need. 'Done' controls whether the
939 // option even _WANTS_ any more.
941 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
942 while (NumVals-ValNo > NumPositionalRequired && !Done) {
943 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
945 Done = true; // Optional arguments want _at most_ one value
947 case cl::ZeroOrMore: // Zero or more will take all they can get...
948 case cl::OneOrMore: // One or more will take all they can get...
949 ProvidePositionalOption(PositionalOpts[i],
950 PositionalVals[ValNo].first,
951 PositionalVals[ValNo].second);
955 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
956 "positional argument processing!");
961 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
963 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
964 if (RequiresValue(PositionalOpts[j])) {
965 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
966 PositionalVals[ValNo].first,
967 PositionalVals[ValNo].second);
971 // Handle the case where there is just one positional option, and it's
972 // optional. In this case, we want to give JUST THE FIRST option to the
973 // positional option and keep the rest for the consume after. The above
974 // loop would have assigned no values to positional options in this case.
976 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
977 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
978 PositionalVals[ValNo].first,
979 PositionalVals[ValNo].second);
983 // Handle over all of the rest of the arguments to the
984 // cl::ConsumeAfter command line option...
985 for (; ValNo != PositionalVals.size(); ++ValNo)
986 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
987 PositionalVals[ValNo].first,
988 PositionalVals[ValNo].second);
991 // Loop over args and make sure all required args are specified!
992 for (StringMap<Option*>::iterator I = Opts.begin(),
993 E = Opts.end(); I != E; ++I) {
994 switch (I->second->getNumOccurrencesFlag()) {
997 if (I->second->getNumOccurrences() == 0) {
998 I->second->error("must be specified at least once!");
1007 // Now that we know if -debug is specified, we can use it.
1008 // Note that if ReadResponseFiles == true, this must be done before the
1009 // memory allocated for the expanded command line is free()d below.
1010 DEBUG(dbgs() << "Args: ";
1011 for (int i = 0; i < argc; ++i)
1012 dbgs() << argv[i] << ' ';
1016 // Free all of the memory allocated to the map. Command line options may only
1017 // be processed once!
1019 PositionalOpts.clear();
1022 // If we had an error processing our arguments, don't let the program execute
1023 if (ErrorParsing) exit(1);
1026 //===----------------------------------------------------------------------===//
1027 // Option Base class implementation
1030 bool Option::error(const Twine &Message, StringRef ArgName) {
1031 if (ArgName.data() == 0) ArgName = ArgStr;
1032 if (ArgName.empty())
1033 errs() << HelpStr; // Be nice for positional arguments
1035 errs() << ProgramName << ": for the -" << ArgName;
1037 errs() << " option: " << Message << "\n";
1041 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
1042 StringRef Value, bool MultiArg) {
1044 NumOccurrences++; // Increment the number of times we have been seen
1046 switch (getNumOccurrencesFlag()) {
1048 if (NumOccurrences > 1)
1049 return error("may only occur zero or one times!", ArgName);
1052 if (NumOccurrences > 1)
1053 return error("must occur exactly one time!", ArgName);
1057 case ConsumeAfter: break;
1060 return handleOccurrence(pos, ArgName, Value);
1064 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1065 // has been specified yet.
1067 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1068 if (O.ValueStr[0] == 0) return DefaultMsg;
1072 //===----------------------------------------------------------------------===//
1073 // cl::alias class implementation
1076 // Return the width of the option tag for printing...
1077 size_t alias::getOptionWidth() const {
1078 return std::strlen(ArgStr)+6;
1081 static void printHelpStr(StringRef HelpStr, size_t Indent,
1082 size_t FirstLineIndentedBy) {
1083 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1084 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1085 while (!Split.second.empty()) {
1086 Split = Split.second.split('\n');
1087 outs().indent(Indent) << Split.first << "\n";
1091 // Print out the option for the alias.
1092 void alias::printOptionInfo(size_t GlobalWidth) const {
1093 outs() << " -" << ArgStr;
1094 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1097 //===----------------------------------------------------------------------===//
1098 // Parser Implementation code...
1101 // basic_parser implementation
1104 // Return the width of the option tag for printing...
1105 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1106 size_t Len = std::strlen(O.ArgStr);
1107 if (const char *ValName = getValueName())
1108 Len += std::strlen(getValueStr(O, ValName))+3;
1113 // printOptionInfo - Print out information about this option. The
1114 // to-be-maintained width is specified.
1116 void basic_parser_impl::printOptionInfo(const Option &O,
1117 size_t GlobalWidth) const {
1118 outs() << " -" << O.ArgStr;
1120 if (const char *ValName = getValueName())
1121 outs() << "=<" << getValueStr(O, ValName) << '>';
1123 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1126 void basic_parser_impl::printOptionName(const Option &O,
1127 size_t GlobalWidth) const {
1128 outs() << " -" << O.ArgStr;
1129 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1133 // parser<bool> implementation
1135 bool parser<bool>::parse(Option &O, StringRef ArgName,
1136 StringRef Arg, bool &Value) {
1137 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1143 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1147 return O.error("'" + Arg +
1148 "' is invalid value for boolean argument! Try 0 or 1");
1151 // parser<boolOrDefault> implementation
1153 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
1154 StringRef Arg, boolOrDefault &Value) {
1155 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1160 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1165 return O.error("'" + Arg +
1166 "' is invalid value for boolean argument! Try 0 or 1");
1169 // parser<int> implementation
1171 bool parser<int>::parse(Option &O, StringRef ArgName,
1172 StringRef Arg, int &Value) {
1173 if (Arg.getAsInteger(0, Value))
1174 return O.error("'" + Arg + "' value invalid for integer argument!");
1178 // parser<unsigned> implementation
1180 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1181 StringRef Arg, unsigned &Value) {
1183 if (Arg.getAsInteger(0, Value))
1184 return O.error("'" + Arg + "' value invalid for uint argument!");
1188 // parser<unsigned long long> implementation
1190 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1191 StringRef Arg, unsigned long long &Value){
1193 if (Arg.getAsInteger(0, Value))
1194 return O.error("'" + Arg + "' value invalid for uint argument!");
1198 // parser<double>/parser<float> implementation
1200 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1201 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1202 const char *ArgStart = TmpStr.c_str();
1204 Value = strtod(ArgStart, &End);
1206 return O.error("'" + Arg + "' value invalid for floating point argument!");
1210 bool parser<double>::parse(Option &O, StringRef ArgName,
1211 StringRef Arg, double &Val) {
1212 return parseDouble(O, Arg, Val);
1215 bool parser<float>::parse(Option &O, StringRef ArgName,
1216 StringRef Arg, float &Val) {
1218 if (parseDouble(O, Arg, dVal))
1226 // generic_parser_base implementation
1229 // findOption - Return the option number corresponding to the specified
1230 // argument string. If the option is not found, getNumOptions() is returned.
1232 unsigned generic_parser_base::findOption(const char *Name) {
1233 unsigned e = getNumOptions();
1235 for (unsigned i = 0; i != e; ++i) {
1236 if (strcmp(getOption(i), Name) == 0)
1243 // Return the width of the option tag for printing...
1244 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1245 if (O.hasArgStr()) {
1246 size_t Size = std::strlen(O.ArgStr)+6;
1247 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1248 Size = std::max(Size, std::strlen(getOption(i))+8);
1251 size_t BaseSize = 0;
1252 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1253 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1258 // printOptionInfo - Print out information about this option. The
1259 // to-be-maintained width is specified.
1261 void generic_parser_base::printOptionInfo(const Option &O,
1262 size_t GlobalWidth) const {
1263 if (O.hasArgStr()) {
1264 outs() << " -" << O.ArgStr;
1265 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1267 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1268 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1269 outs() << " =" << getOption(i);
1270 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1274 outs() << " " << O.HelpStr << '\n';
1275 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1276 const char *Option = getOption(i);
1277 outs() << " -" << Option;
1278 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1283 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1285 // printGenericOptionDiff - Print the value of this option and it's default.
1287 // "Generic" options have each value mapped to a name.
1288 void generic_parser_base::
1289 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1290 const GenericOptionValue &Default,
1291 size_t GlobalWidth) const {
1292 outs() << " -" << O.ArgStr;
1293 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1295 unsigned NumOpts = getNumOptions();
1296 for (unsigned i = 0; i != NumOpts; ++i) {
1297 if (Value.compare(getOptionValue(i)))
1300 outs() << "= " << getOption(i);
1301 size_t L = std::strlen(getOption(i));
1302 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1303 outs().indent(NumSpaces) << " (default: ";
1304 for (unsigned j = 0; j != NumOpts; ++j) {
1305 if (Default.compare(getOptionValue(j)))
1307 outs() << getOption(j);
1313 outs() << "= *unknown option value*\n";
1316 // printOptionDiff - Specializations for printing basic value types.
1318 #define PRINT_OPT_DIFF(T) \
1320 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1321 size_t GlobalWidth) const { \
1322 printOptionName(O, GlobalWidth); \
1325 raw_string_ostream SS(Str); \
1328 outs() << "= " << Str; \
1329 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1330 outs().indent(NumSpaces) << " (default: "; \
1332 outs() << D.getValue(); \
1334 outs() << "*no default*"; \
1338 PRINT_OPT_DIFF(bool)
1339 PRINT_OPT_DIFF(boolOrDefault)
1341 PRINT_OPT_DIFF(unsigned)
1342 PRINT_OPT_DIFF(unsigned long long)
1343 PRINT_OPT_DIFF(double)
1344 PRINT_OPT_DIFF(float)
1345 PRINT_OPT_DIFF(char)
1347 void parser<std::string>::
1348 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1349 size_t GlobalWidth) const {
1350 printOptionName(O, GlobalWidth);
1351 outs() << "= " << V;
1352 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1353 outs().indent(NumSpaces) << " (default: ";
1355 outs() << D.getValue();
1357 outs() << "*no default*";
1361 // Print a placeholder for options that don't yet support printOptionDiff().
1362 void basic_parser_impl::
1363 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1364 printOptionName(O, GlobalWidth);
1365 outs() << "= *cannot print option value*\n";
1368 //===----------------------------------------------------------------------===//
1369 // -help and -help-hidden option implementation
1372 static int OptNameCompare(const void *LHS, const void *RHS) {
1373 typedef std::pair<const char *, Option*> pair_ty;
1375 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1378 // Copy Options into a vector so we can sort them as we like.
1380 sortOpts(StringMap<Option*> &OptMap,
1381 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1383 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1385 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1387 // Ignore really-hidden options.
1388 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1391 // Unless showhidden is set, ignore hidden flags.
1392 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1395 // If we've already seen this option, don't add it to the list again.
1396 if (!OptionSet.insert(I->second))
1399 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1403 // Sort the options list alphabetically.
1404 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1411 const bool ShowHidden;
1412 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1413 // Print the options. Opts is assumed to be alphabetically sorted.
1414 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1415 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1416 Opts[i].second->printOptionInfo(MaxArgLen);
1420 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1421 virtual ~HelpPrinter() {}
1423 // Invoke the printer.
1424 void operator=(bool Value) {
1425 if (Value == false) return;
1427 // Get all the options.
1428 SmallVector<Option*, 4> PositionalOpts;
1429 SmallVector<Option*, 4> SinkOpts;
1430 StringMap<Option*> OptMap;
1431 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1433 StrOptionPairVector Opts;
1434 sortOpts(OptMap, Opts, ShowHidden);
1436 if (ProgramOverview)
1437 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1439 outs() << "USAGE: " << ProgramName << " [options]";
1441 // Print out the positional options.
1442 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
1443 if (!PositionalOpts.empty() &&
1444 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1445 CAOpt = PositionalOpts[0];
1447 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1448 if (PositionalOpts[i]->ArgStr[0])
1449 outs() << " --" << PositionalOpts[i]->ArgStr;
1450 outs() << " " << PositionalOpts[i]->HelpStr;
1453 // Print the consume after option info if it exists...
1454 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1458 // Compute the maximum argument length...
1459 size_t MaxArgLen = 0;
1460 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1461 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1463 outs() << "OPTIONS:\n";
1464 printOptions(Opts, MaxArgLen);
1466 // Print any extra help the user has declared.
1467 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1468 E = MoreHelp->end();
1473 // Halt the program since help information was printed
1478 class CategorizedHelpPrinter : public HelpPrinter {
1480 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1482 // Helper function for printOptions().
1483 // It shall return true if A's name should be lexographically
1484 // ordered before B's name. It returns false otherwise.
1485 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1486 int Length = strcmp(A->getName(), B->getName());
1487 assert(Length != 0 && "Duplicate option categories");
1491 // Make sure we inherit our base class's operator=()
1492 using HelpPrinter::operator= ;
1495 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1496 std::vector<OptionCategory *> SortedCategories;
1497 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1499 // Collect registered option categories into vector in preperation for
1501 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1502 E = RegisteredOptionCategories->end();
1504 SortedCategories.push_back(*I);
1506 // Sort the different option categories alphabetically.
1507 assert(SortedCategories.size() > 0 && "No option categories registered!");
1508 std::sort(SortedCategories.begin(), SortedCategories.end(),
1509 OptionCategoryCompare);
1511 // Create map to empty vectors.
1512 for (std::vector<OptionCategory *>::const_iterator
1513 I = SortedCategories.begin(),
1514 E = SortedCategories.end();
1516 CategorizedOptions[*I] = std::vector<Option *>();
1518 // Walk through pre-sorted options and assign into categories.
1519 // Because the options are already alphabetically sorted the
1520 // options within categories will also be alphabetically sorted.
1521 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1522 Option *Opt = Opts[I].second;
1523 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1524 "Option has an unregistered category");
1525 CategorizedOptions[Opt->Category].push_back(Opt);
1529 for (std::vector<OptionCategory *>::const_iterator
1530 Category = SortedCategories.begin(),
1531 E = SortedCategories.end();
1532 Category != E; ++Category) {
1533 // Hide empty categories for -help, but show for -help-hidden.
1534 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1535 if (!ShowHidden && IsEmptyCategory)
1538 // Print category information.
1540 outs() << (*Category)->getName() << ":\n";
1542 // Check if description is set.
1543 if ((*Category)->getDescription() != 0)
1544 outs() << (*Category)->getDescription() << "\n\n";
1548 // When using -help-hidden explicitly state if the category has no
1549 // options associated with it.
1550 if (IsEmptyCategory) {
1551 outs() << " This option category has no options.\n";
1554 // Loop over the options in the category and print.
1555 for (std::vector<Option *>::const_iterator
1556 Opt = CategorizedOptions[*Category].begin(),
1557 E = CategorizedOptions[*Category].end();
1559 (*Opt)->printOptionInfo(MaxArgLen);
1564 // This wraps the Uncategorizing and Categorizing printers and decides
1565 // at run time which should be invoked.
1566 class HelpPrinterWrapper {
1568 HelpPrinter &UncategorizedPrinter;
1569 CategorizedHelpPrinter &CategorizedPrinter;
1572 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1573 CategorizedHelpPrinter &CategorizedPrinter) :
1574 UncategorizedPrinter(UncategorizedPrinter),
1575 CategorizedPrinter(CategorizedPrinter) { }
1577 // Invoke the printer.
1578 void operator=(bool Value);
1581 } // End anonymous namespace
1583 // Declare the four HelpPrinter instances that are used to print out help, or
1584 // help-hidden as an uncategorized list or in categories.
1585 static HelpPrinter UncategorizedNormalPrinter(false);
1586 static HelpPrinter UncategorizedHiddenPrinter(true);
1587 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1588 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1591 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1592 // a categorizing help printer
1593 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1594 CategorizedNormalPrinter);
1595 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1596 CategorizedHiddenPrinter);
1598 // Define uncategorized help printers.
1599 // -help-list is hidden by default because if Option categories are being used
1600 // then -help behaves the same as -help-list.
1601 static cl::opt<HelpPrinter, true, parser<bool> >
1603 cl::desc("Display list of available options (-help-list-hidden for more)"),
1604 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1606 static cl::opt<HelpPrinter, true, parser<bool> >
1607 HLHOp("help-list-hidden",
1608 cl::desc("Display list of all available options"),
1609 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1611 // Define uncategorized/categorized help printers. These printers change their
1612 // behaviour at runtime depending on whether one or more Option categories have
1614 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1615 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1616 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1618 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1619 HHOp("help-hidden", cl::desc("Display all available options"),
1620 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1624 static cl::opt<bool>
1625 PrintOptions("print-options",
1626 cl::desc("Print non-default options after command line parsing"),
1627 cl::Hidden, cl::init(false));
1629 static cl::opt<bool>
1630 PrintAllOptions("print-all-options",
1631 cl::desc("Print all option values after command line parsing"),
1632 cl::Hidden, cl::init(false));
1634 void HelpPrinterWrapper::operator=(bool Value) {
1638 // Decide which printer to invoke. If more than one option category is
1639 // registered then it is useful to show the categorized help instead of
1640 // uncategorized help.
1641 if (RegisteredOptionCategories->size() > 1) {
1642 // unhide -help-list option so user can have uncategorized output if they
1644 HLOp.setHiddenFlag(NotHidden);
1646 CategorizedPrinter = true; // Invoke categorized printer
1649 UncategorizedPrinter = true; // Invoke uncategorized printer
1652 // Print the value of each option.
1653 void cl::PrintOptionValues() {
1654 if (!PrintOptions && !PrintAllOptions) return;
1656 // Get all the options.
1657 SmallVector<Option*, 4> PositionalOpts;
1658 SmallVector<Option*, 4> SinkOpts;
1659 StringMap<Option*> OptMap;
1660 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1662 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1663 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1665 // Compute the maximum argument length...
1666 size_t MaxArgLen = 0;
1667 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1668 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1670 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1671 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1674 static void (*OverrideVersionPrinter)() = 0;
1676 static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1679 class VersionPrinter {
1682 raw_ostream &OS = outs();
1683 OS << "LLVM (http://llvm.org/):\n"
1684 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1685 #ifdef LLVM_VERSION_INFO
1686 OS << LLVM_VERSION_INFO;
1689 #ifndef __OPTIMIZE__
1690 OS << "DEBUG build";
1692 OS << "Optimized build";
1695 OS << " with assertions";
1697 std::string CPU = sys::getHostCPUName();
1698 if (CPU == "generic") CPU = "(unknown)";
1700 #if (ENABLE_TIMESTAMPS == 1)
1701 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1703 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1704 << " Host CPU: " << CPU << '\n';
1706 void operator=(bool OptionWasSpecified) {
1707 if (!OptionWasSpecified) return;
1709 if (OverrideVersionPrinter != 0) {
1710 (*OverrideVersionPrinter)();
1715 // Iterate over any registered extra printers and call them to add further
1717 if (ExtraVersionPrinters != 0) {
1719 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1720 E = ExtraVersionPrinters->end();
1728 } // End anonymous namespace
1731 // Define the --version option that prints out the LLVM version for the tool
1732 static VersionPrinter VersionPrinterInstance;
1734 static cl::opt<VersionPrinter, true, parser<bool> >
1735 VersOp("version", cl::desc("Display the version of this program"),
1736 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1738 // Utility function for printing the help message.
1739 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1740 // This looks weird, but it actually prints the help message. The Printers are
1741 // types of HelpPrinter and the help gets printed when its operator= is
1742 // invoked. That's because the "normal" usages of the help printer is to be
1743 // assigned true/false depending on whether -help or -help-hidden was given or
1744 // not. Since we're circumventing that we have to make it look like -help or
1745 // -help-hidden were given, so we assign true.
1747 if (!Hidden && !Categorized)
1748 UncategorizedNormalPrinter = true;
1749 else if (!Hidden && Categorized)
1750 CategorizedNormalPrinter = true;
1751 else if (Hidden && !Categorized)
1752 UncategorizedHiddenPrinter = true;
1754 CategorizedHiddenPrinter = true;
1757 /// Utility function for printing version number.
1758 void cl::PrintVersionMessage() {
1759 VersionPrinterInstance.print();
1762 void cl::SetVersionPrinter(void (*func)()) {
1763 OverrideVersionPrinter = func;
1766 void cl::AddExtraVersionPrinter(void (*func)()) {
1767 if (ExtraVersionPrinters == 0)
1768 ExtraVersionPrinters = new std::vector<void (*)()>;
1770 ExtraVersionPrinters->push_back(func);
1773 void cl::getRegisteredOptions(StringMap<Option*> &Map)
1775 // Get all the options.
1776 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1777 SmallVector<Option*, 4> SinkOpts; //NOT USED
1778 assert(Map.size() == 0 && "StringMap must be empty");
1779 GetOptionInfo(PositionalOpts, SinkOpts, Map);