1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements a command line argument processor that is useful when
11 // creating a tool. It provides a simple, minimalistic interface that is easily
12 // extensible and supports nonlocal (library) command line options.
14 // Note that rather than trying to figure out what this code does, you could try
15 // reading the library documentation located in docs/CommandLine.html
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Config/config.h"
27 #include "llvm/Support/ConvertUTF.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/system_error.h"
42 //===----------------------------------------------------------------------===//
43 // Template instantiations and anchors.
45 namespace llvm { namespace cl {
46 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
47 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
48 TEMPLATE_INSTANTIATION(class basic_parser<int>);
49 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
50 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
51 TEMPLATE_INSTANTIATION(class basic_parser<double>);
52 TEMPLATE_INSTANTIATION(class basic_parser<float>);
53 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
54 TEMPLATE_INSTANTIATION(class basic_parser<char>);
56 TEMPLATE_INSTANTIATION(class opt<unsigned>);
57 TEMPLATE_INSTANTIATION(class opt<int>);
58 TEMPLATE_INSTANTIATION(class opt<std::string>);
59 TEMPLATE_INSTANTIATION(class opt<char>);
60 TEMPLATE_INSTANTIATION(class opt<bool>);
61 } } // end namespace llvm::cl
63 // Pin the vtables to this file.
64 void GenericOptionValue::anchor() {}
65 void OptionValue<boolOrDefault>::anchor() {}
66 void OptionValue<std::string>::anchor() {}
67 void Option::anchor() {}
68 void basic_parser_impl::anchor() {}
69 void parser<bool>::anchor() {}
70 void parser<boolOrDefault>::anchor() {}
71 void parser<int>::anchor() {}
72 void parser<unsigned>::anchor() {}
73 void parser<unsigned long long>::anchor() {}
74 void parser<double>::anchor() {}
75 void parser<float>::anchor() {}
76 void parser<std::string>::anchor() {}
77 void parser<char>::anchor() {}
78 void StringSaver::anchor() {}
80 //===----------------------------------------------------------------------===//
82 // Globals for name and overview of program. Program name is not a string to
83 // avoid static ctor/dtor issues.
84 static char ProgramName[80] = "<premain>";
85 static const char *ProgramOverview = 0;
87 // This collects additional help to be printed.
88 static ManagedStatic<std::vector<const char*> > MoreHelp;
90 extrahelp::extrahelp(const char *Help)
92 MoreHelp->push_back(Help);
95 static bool OptionListChanged = false;
97 // MarkOptionsChanged - Internal helper function.
98 void cl::MarkOptionsChanged() {
99 OptionListChanged = true;
102 /// RegisteredOptionList - This is the list of the command line options that
103 /// have statically constructed themselves.
104 static Option *RegisteredOptionList = 0;
106 void Option::addArgument() {
107 assert(NextRegistered == 0 && "argument multiply registered!");
109 NextRegistered = RegisteredOptionList;
110 RegisteredOptionList = this;
111 MarkOptionsChanged();
114 void Option::removeArgument() {
115 assert(NextRegistered != 0 && "argument never registered");
116 assert(RegisteredOptionList == this && "argument is not the last registered");
117 RegisteredOptionList = NextRegistered;
118 MarkOptionsChanged();
121 // This collects the different option categories that have been registered.
122 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
123 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
125 // Initialise the general option category.
126 OptionCategory llvm::cl::GeneralCategory("General options");
129 HasName(StringRef Name) : Name(Name) {}
130 bool operator()(const OptionCategory *Category) const {
131 return Name == Category->getName();
136 void OptionCategory::registerCategory()
138 assert(std::count_if(RegisteredOptionCategories->begin(),
139 RegisteredOptionCategories->end(),
140 HasName(getName())) == 0 &&
141 "Duplicate option categories");
143 RegisteredOptionCategories->insert(this);
146 //===----------------------------------------------------------------------===//
147 // Basic, shared command line option processing machinery.
150 /// GetOptionInfo - Scan the list of registered options, turning them into data
151 /// structures that are easier to handle.
152 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
153 SmallVectorImpl<Option*> &SinkOpts,
154 StringMap<Option*> &OptionsMap) {
155 SmallVector<const char*, 16> OptionNames;
156 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
157 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
158 // If this option wants to handle multiple option names, get the full set.
159 // This handles enum options like "-O1 -O2" etc.
160 O->getExtraOptionNames(OptionNames);
162 OptionNames.push_back(O->ArgStr);
164 // Handle named options.
165 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
166 // Add argument to the argument map!
167 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
168 errs() << ProgramName << ": CommandLine Error: Argument '"
169 << OptionNames[i] << "' defined more than once!\n";
175 // Remember information about positional options.
176 if (O->getFormattingFlag() == cl::Positional)
177 PositionalOpts.push_back(O);
178 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
179 SinkOpts.push_back(O);
180 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
182 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
188 PositionalOpts.push_back(CAOpt);
190 // Make sure that they are in order of registration not backwards.
191 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
195 /// LookupOption - Lookup the option specified by the specified option on the
196 /// command line. If there is a value specified (after an equal sign) return
197 /// that as well. This assumes that leading dashes have already been stripped.
198 static Option *LookupOption(StringRef &Arg, StringRef &Value,
199 const StringMap<Option*> &OptionsMap) {
200 // Reject all dashes.
201 if (Arg.empty()) return 0;
203 size_t EqualPos = Arg.find('=');
205 // If we have an equals sign, remember the value.
206 if (EqualPos == StringRef::npos) {
207 // Look up the option.
208 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
209 return I != OptionsMap.end() ? I->second : 0;
212 // If the argument before the = is a valid option name, we match. If not,
213 // return Arg unmolested.
214 StringMap<Option*>::const_iterator I =
215 OptionsMap.find(Arg.substr(0, EqualPos));
216 if (I == OptionsMap.end()) return 0;
218 Value = Arg.substr(EqualPos+1);
219 Arg = Arg.substr(0, EqualPos);
223 /// LookupNearestOption - Lookup the closest match to the option specified by
224 /// the specified option on the command line. If there is a value specified
225 /// (after an equal sign) return that as well. This assumes that leading dashes
226 /// have already been stripped.
227 static Option *LookupNearestOption(StringRef Arg,
228 const StringMap<Option*> &OptionsMap,
229 std::string &NearestString) {
230 // Reject all dashes.
231 if (Arg.empty()) return 0;
233 // Split on any equal sign.
234 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
235 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
236 StringRef &RHS = SplitArg.second;
238 // Find the closest match.
240 unsigned BestDistance = 0;
241 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
242 ie = OptionsMap.end(); it != ie; ++it) {
243 Option *O = it->second;
244 SmallVector<const char*, 16> OptionNames;
245 O->getExtraOptionNames(OptionNames);
247 OptionNames.push_back(O->ArgStr);
249 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
250 StringRef Flag = PermitValue ? LHS : Arg;
251 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
252 StringRef Name = OptionNames[i];
253 unsigned Distance = StringRef(Name).edit_distance(
254 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
255 if (!Best || Distance < BestDistance) {
257 BestDistance = Distance;
258 if (RHS.empty() || !PermitValue)
259 NearestString = OptionNames[i];
261 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
269 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
270 /// that does special handling of cl::CommaSeparated options.
271 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
272 StringRef ArgName, StringRef Value,
273 bool MultiArg = false) {
274 // Check to see if this option accepts a comma separated list of values. If
275 // it does, we have to split up the value into multiple values.
276 if (Handler->getMiscFlags() & CommaSeparated) {
277 StringRef Val(Value);
278 StringRef::size_type Pos = Val.find(',');
280 while (Pos != StringRef::npos) {
281 // Process the portion before the comma.
282 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
284 // Erase the portion before the comma, AND the comma.
285 Val = Val.substr(Pos+1);
286 Value.substr(Pos+1); // Increment the original value pointer as well.
287 // Check for another comma.
294 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
300 /// ProvideOption - For Value, this differentiates between an empty value ("")
301 /// and a null value (StringRef()). The later is accepted for arguments that
302 /// don't allow a value (-foo) the former is rejected (-foo=).
303 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
304 StringRef Value, int argc,
305 const char *const *argv, int &i) {
306 // Is this a multi-argument option?
307 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
309 // Enforce value requirements
310 switch (Handler->getValueExpectedFlag()) {
312 if (Value.data() == 0) { // No value specified?
314 return Handler->error("requires a value!");
315 // Steal the next argument, like for '-o filename'
319 case ValueDisallowed:
320 if (NumAdditionalVals > 0)
321 return Handler->error("multi-valued option specified"
322 " with ValueDisallowed modifier!");
325 return Handler->error("does not allow a value! '" +
326 Twine(Value) + "' specified.");
332 // If this isn't a multi-arg option, just run the handler.
333 if (NumAdditionalVals == 0)
334 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
336 // If it is, run the handle several times.
337 bool MultiArg = false;
340 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
346 while (NumAdditionalVals > 0) {
348 return Handler->error("not enough values!");
351 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
359 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
361 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
365 // Option predicates...
366 static inline bool isGrouping(const Option *O) {
367 return O->getFormattingFlag() == cl::Grouping;
369 static inline bool isPrefixedOrGrouping(const Option *O) {
370 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
373 // getOptionPred - Check to see if there are any options that satisfy the
374 // specified predicate with names that are the prefixes in Name. This is
375 // checked by progressively stripping characters off of the name, checking to
376 // see if there options that satisfy the predicate. If we find one, return it,
377 // otherwise return null.
379 static Option *getOptionPred(StringRef Name, size_t &Length,
380 bool (*Pred)(const Option*),
381 const StringMap<Option*> &OptionsMap) {
383 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
385 // Loop while we haven't found an option and Name still has at least two
386 // characters in it (so that the next iteration will not be the empty
388 while (OMI == OptionsMap.end() && Name.size() > 1) {
389 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
390 OMI = OptionsMap.find(Name);
393 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
394 Length = Name.size();
395 return OMI->second; // Found one!
397 return 0; // No option found!
400 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
401 /// with at least one '-') does not fully match an available option. Check to
402 /// see if this is a prefix or grouped option. If so, split arg into output an
403 /// Arg/Value pair and return the Option to parse it with.
404 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
406 const StringMap<Option*> &OptionsMap) {
407 if (Arg.size() == 1) return 0;
411 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
412 if (PGOpt == 0) return 0;
414 // If the option is a prefixed option, then the value is simply the
415 // rest of the name... so fall through to later processing, by
416 // setting up the argument name flags and value fields.
417 if (PGOpt->getFormattingFlag() == cl::Prefix) {
418 Value = Arg.substr(Length);
419 Arg = Arg.substr(0, Length);
420 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
424 // This must be a grouped option... handle them now. Grouping options can't
426 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
429 // Move current arg name out of Arg into OneArgName.
430 StringRef OneArgName = Arg.substr(0, Length);
431 Arg = Arg.substr(Length);
433 // Because ValueRequired is an invalid flag for grouped arguments,
434 // we don't need to pass argc/argv in.
435 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
436 "Option can not be cl::Grouping AND cl::ValueRequired!");
438 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
439 StringRef(), 0, 0, Dummy);
441 // Get the next grouping option.
442 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
443 } while (PGOpt && Length != Arg.size());
445 // Return the last option with Arg cut down to just the last one.
451 static bool RequiresValue(const Option *O) {
452 return O->getNumOccurrencesFlag() == cl::Required ||
453 O->getNumOccurrencesFlag() == cl::OneOrMore;
456 static bool EatsUnboundedNumberOfValues(const Option *O) {
457 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
458 O->getNumOccurrencesFlag() == cl::OneOrMore;
461 static bool isWhitespace(char C) {
462 return strchr(" \t\n\r\f\v", C);
465 static bool isQuote(char C) {
466 return C == '\"' || C == '\'';
469 static bool isGNUSpecial(char C) {
470 return strchr("\\\"\' ", C);
473 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
474 SmallVectorImpl<const char *> &NewArgv) {
475 SmallString<128> Token;
476 for (size_t I = 0, E = Src.size(); I != E; ++I) {
477 // Consume runs of whitespace.
479 while (I != E && isWhitespace(Src[I]))
484 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
485 // they are literal. This makes it much easier to read Windows file paths.
486 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
487 ++I; // Skip the escape.
488 Token.push_back(Src[I]);
492 // Consume a quoted string.
493 if (isQuote(Src[I])) {
494 char Quote = Src[I++];
495 while (I != E && Src[I] != Quote) {
496 // Backslashes are literal, unless they escape a special character.
497 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
499 Token.push_back(Src[I]);
506 // End the token if this is whitespace.
507 if (isWhitespace(Src[I])) {
509 NewArgv.push_back(Saver.SaveString(Token.c_str()));
514 // This is a normal character. Append it.
515 Token.push_back(Src[I]);
518 // Append the last token after hitting EOF with no whitespace.
520 NewArgv.push_back(Saver.SaveString(Token.c_str()));
523 /// Backslashes are interpreted in a rather complicated way in the Windows-style
524 /// command line, because backslashes are used both to separate path and to
525 /// escape double quote. This method consumes runs of backslashes as well as the
526 /// following double quote if it's escaped.
528 /// * If an even number of backslashes is followed by a double quote, one
529 /// backslash is output for every pair of backslashes, and the last double
530 /// quote remains unconsumed. The double quote will later be interpreted as
531 /// the start or end of a quoted string in the main loop outside of this
534 /// * If an odd number of backslashes is followed by a double quote, one
535 /// backslash is output for every pair of backslashes, and a double quote is
536 /// output for the last pair of backslash-double quote. The double quote is
537 /// consumed in this case.
539 /// * Otherwise, backslashes are interpreted literally.
540 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
541 size_t E = Src.size();
542 int BackslashCount = 0;
543 // Skip the backslashes.
547 } while (I != E && Src[I] == '\\');
549 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
550 if (FollowedByDoubleQuote) {
551 Token.append(BackslashCount / 2, '\\');
552 if (BackslashCount % 2 == 0)
554 Token.push_back('"');
557 Token.append(BackslashCount, '\\');
561 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
562 SmallVectorImpl<const char *> &NewArgv) {
563 SmallString<128> Token;
565 // This is a small state machine to consume characters until it reaches the
566 // end of the source string.
567 enum { INIT, UNQUOTED, QUOTED } State = INIT;
568 for (size_t I = 0, E = Src.size(); I != E; ++I) {
569 // INIT state indicates that the current input index is at the start of
570 // the string or between tokens.
572 if (isWhitespace(Src[I]))
578 if (Src[I] == '\\') {
579 I = parseBackslash(Src, I, Token);
583 Token.push_back(Src[I]);
588 // UNQUOTED state means that it's reading a token not quoted by double
590 if (State == UNQUOTED) {
591 // Whitespace means the end of the token.
592 if (isWhitespace(Src[I])) {
593 NewArgv.push_back(Saver.SaveString(Token.c_str()));
602 if (Src[I] == '\\') {
603 I = parseBackslash(Src, I, Token);
606 Token.push_back(Src[I]);
610 // QUOTED state means that it's reading a token quoted by double quotes.
611 if (State == QUOTED) {
616 if (Src[I] == '\\') {
617 I = parseBackslash(Src, I, Token);
620 Token.push_back(Src[I]);
623 // Append the last token after hitting EOF with no whitespace.
625 NewArgv.push_back(Saver.SaveString(Token.c_str()));
628 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
629 TokenizerCallback Tokenizer,
630 SmallVectorImpl<const char *> &NewArgv) {
631 OwningPtr<MemoryBuffer> MemBuf;
632 if (MemoryBuffer::getFile(FName, MemBuf))
634 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
636 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
637 ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd());
639 if (hasUTF16ByteOrderMark(BufRef)) {
640 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
642 Str = StringRef(UTF8Buf);
645 // Tokenize the contents into NewArgv.
646 Tokenizer(Str, Saver, NewArgv);
651 /// \brief Expand response files on a command line recursively using the given
652 /// StringSaver and tokenization strategy.
653 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
654 SmallVectorImpl<const char *> &Argv) {
655 unsigned RspFiles = 0;
656 bool AllExpanded = true;
658 // Don't cache Argv.size() because it can change.
659 for (unsigned I = 0; I != Argv.size(); ) {
660 const char *Arg = Argv[I];
666 // If we have too many response files, leave some unexpanded. This avoids
667 // crashing on self-referential response files.
671 // Replace this response file argument with the tokenization of its
672 // contents. Nested response files are expanded in subsequent iterations.
673 // FIXME: If a nested response file uses a relative path, is it relative to
674 // the cwd of the process or the response file?
675 SmallVector<const char *, 0> ExpandedArgv;
676 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
677 // We couldn't read this file, so we leave it in the argument stream and
683 Argv.erase(Argv.begin() + I);
684 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
690 class StrDupSaver : public StringSaver {
691 std::vector<char*> Dups;
694 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
700 const char *SaveString(const char *Str) LLVM_OVERRIDE {
701 char *Dup = strdup(Str);
708 /// ParseEnvironmentOptions - An alternative entry point to the
709 /// CommandLine library, which allows you to read the program's name
710 /// from the caller (as PROGNAME) and its command-line arguments from
711 /// an environment variable (whose name is given in ENVVAR).
713 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
714 const char *Overview) {
716 assert(progName && "Program name not specified");
717 assert(envVar && "Environment variable name missing");
719 // Get the environment variable they want us to parse options out of.
720 const char *envValue = getenv(envVar);
724 // Get program's "name", which we wouldn't know without the caller
726 SmallVector<const char *, 20> newArgv;
728 newArgv.push_back(Saver.SaveString(progName));
730 // Parse the value of the environment variable into a "command line"
731 // and hand it off to ParseCommandLineOptions().
732 TokenizeGNUCommandLine(envValue, Saver, newArgv);
733 int newArgc = static_cast<int>(newArgv.size());
734 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
737 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
738 const char *Overview) {
739 // Process all registered options.
740 SmallVector<Option*, 4> PositionalOpts;
741 SmallVector<Option*, 4> SinkOpts;
742 StringMap<Option*> Opts;
743 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
745 assert((!Opts.empty() || !PositionalOpts.empty()) &&
746 "No options specified!");
748 // Expand response files.
749 SmallVector<const char *, 20> newArgv;
750 for (int i = 0; i != argc; ++i)
751 newArgv.push_back(argv[i]);
753 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
755 argc = static_cast<int>(newArgv.size());
757 // Copy the program name into ProgName, making sure not to overflow it.
758 std::string ProgName = sys::path::filename(argv[0]);
759 size_t Len = std::min(ProgName.size(), size_t(79));
760 memcpy(ProgramName, ProgName.data(), Len);
761 ProgramName[Len] = '\0';
763 ProgramOverview = Overview;
764 bool ErrorParsing = false;
766 // Check out the positional arguments to collect information about them.
767 unsigned NumPositionalRequired = 0;
769 // Determine whether or not there are an unlimited number of positionals
770 bool HasUnlimitedPositionals = false;
772 Option *ConsumeAfterOpt = 0;
773 if (!PositionalOpts.empty()) {
774 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
775 assert(PositionalOpts.size() > 1 &&
776 "Cannot specify cl::ConsumeAfter without a positional argument!");
777 ConsumeAfterOpt = PositionalOpts[0];
780 // Calculate how many positional values are _required_.
781 bool UnboundedFound = false;
782 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
784 Option *Opt = PositionalOpts[i];
785 if (RequiresValue(Opt))
786 ++NumPositionalRequired;
787 else if (ConsumeAfterOpt) {
788 // ConsumeAfter cannot be combined with "optional" positional options
789 // unless there is only one positional argument...
790 if (PositionalOpts.size() > 2)
792 Opt->error("error - this positional option will never be matched, "
793 "because it does not Require a value, and a "
794 "cl::ConsumeAfter option is active!");
795 } else if (UnboundedFound && !Opt->ArgStr[0]) {
796 // This option does not "require" a value... Make sure this option is
797 // not specified after an option that eats all extra arguments, or this
798 // one will never get any!
800 ErrorParsing |= Opt->error("error - option can never match, because "
801 "another positional argument will match an "
802 "unbounded number of values, and this option"
803 " does not require a value!");
805 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
807 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
810 // PositionalVals - A vector of "positional" arguments we accumulate into
811 // the process at the end.
813 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
815 // If the program has named positional arguments, and the name has been run
816 // across, keep track of which positional argument was named. Otherwise put
817 // the positional args into the PositionalVals list...
818 Option *ActivePositionalArg = 0;
820 // Loop over all of the arguments... processing them.
821 bool DashDashFound = false; // Have we read '--'?
822 for (int i = 1; i < argc; ++i) {
824 Option *NearestHandler = 0;
825 std::string NearestHandlerString;
827 StringRef ArgName = "";
829 // If the option list changed, this means that some command line
830 // option has just been registered or deregistered. This can occur in
831 // response to things like -load, etc. If this happens, rescan the options.
832 if (OptionListChanged) {
833 PositionalOpts.clear();
836 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
837 OptionListChanged = false;
840 // Check to see if this is a positional argument. This argument is
841 // considered to be positional if it doesn't start with '-', if it is "-"
842 // itself, or if we have seen "--" already.
844 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
845 // Positional argument!
846 if (ActivePositionalArg) {
847 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
848 continue; // We are done!
851 if (!PositionalOpts.empty()) {
852 PositionalVals.push_back(std::make_pair(argv[i],i));
854 // All of the positional arguments have been fulfulled, give the rest to
855 // the consume after option... if it's specified...
857 if (PositionalVals.size() >= NumPositionalRequired &&
858 ConsumeAfterOpt != 0) {
859 for (++i; i < argc; ++i)
860 PositionalVals.push_back(std::make_pair(argv[i],i));
861 break; // Handle outside of the argument processing loop...
864 // Delay processing positional arguments until the end...
867 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
869 DashDashFound = true; // This is the mythical "--"?
870 continue; // Don't try to process it as an argument itself.
871 } else if (ActivePositionalArg &&
872 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
873 // If there is a positional argument eating options, check to see if this
874 // option is another positional argument. If so, treat it as an argument,
875 // otherwise feed it to the eating positional.
877 // Eat leading dashes.
878 while (!ArgName.empty() && ArgName[0] == '-')
879 ArgName = ArgName.substr(1);
881 Handler = LookupOption(ArgName, Value, Opts);
882 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
883 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
884 continue; // We are done!
887 } else { // We start with a '-', must be an argument.
889 // Eat leading dashes.
890 while (!ArgName.empty() && ArgName[0] == '-')
891 ArgName = ArgName.substr(1);
893 Handler = LookupOption(ArgName, Value, Opts);
895 // Check to see if this "option" is really a prefixed or grouped argument.
897 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
900 // Otherwise, look for the closest available option to report to the user
901 // in the upcoming error.
902 if (Handler == 0 && SinkOpts.empty())
903 NearestHandler = LookupNearestOption(ArgName, Opts,
904 NearestHandlerString);
908 if (SinkOpts.empty()) {
909 errs() << ProgramName << ": Unknown command line argument '"
910 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
912 if (NearestHandler) {
913 // If we know a near match, report it as well.
914 errs() << ProgramName << ": Did you mean '-"
915 << NearestHandlerString << "'?\n";
920 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
921 E = SinkOpts.end(); I != E ; ++I)
922 (*I)->addOccurrence(i, "", argv[i]);
927 // If this is a named positional argument, just remember that it is the
929 if (Handler->getFormattingFlag() == cl::Positional)
930 ActivePositionalArg = Handler;
932 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
935 // Check and handle positional arguments now...
936 if (NumPositionalRequired > PositionalVals.size()) {
937 errs() << ProgramName
938 << ": Not enough positional command line arguments specified!\n"
939 << "Must specify at least " << NumPositionalRequired
940 << " positional arguments: See: " << argv[0] << " -help\n";
943 } else if (!HasUnlimitedPositionals &&
944 PositionalVals.size() > PositionalOpts.size()) {
945 errs() << ProgramName
946 << ": Too many positional arguments specified!\n"
947 << "Can specify at most " << PositionalOpts.size()
948 << " positional arguments: See: " << argv[0] << " -help\n";
951 } else if (ConsumeAfterOpt == 0) {
952 // Positional args have already been handled if ConsumeAfter is specified.
953 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
954 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
955 if (RequiresValue(PositionalOpts[i])) {
956 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
957 PositionalVals[ValNo].second);
959 --NumPositionalRequired; // We fulfilled our duty...
962 // If we _can_ give this option more arguments, do so now, as long as we
963 // do not give it values that others need. 'Done' controls whether the
964 // option even _WANTS_ any more.
966 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
967 while (NumVals-ValNo > NumPositionalRequired && !Done) {
968 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
970 Done = true; // Optional arguments want _at most_ one value
972 case cl::ZeroOrMore: // Zero or more will take all they can get...
973 case cl::OneOrMore: // One or more will take all they can get...
974 ProvidePositionalOption(PositionalOpts[i],
975 PositionalVals[ValNo].first,
976 PositionalVals[ValNo].second);
980 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
981 "positional argument processing!");
986 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
988 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
989 if (RequiresValue(PositionalOpts[j])) {
990 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
991 PositionalVals[ValNo].first,
992 PositionalVals[ValNo].second);
996 // Handle the case where there is just one positional option, and it's
997 // optional. In this case, we want to give JUST THE FIRST option to the
998 // positional option and keep the rest for the consume after. The above
999 // loop would have assigned no values to positional options in this case.
1001 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
1002 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
1003 PositionalVals[ValNo].first,
1004 PositionalVals[ValNo].second);
1008 // Handle over all of the rest of the arguments to the
1009 // cl::ConsumeAfter command line option...
1010 for (; ValNo != PositionalVals.size(); ++ValNo)
1011 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
1012 PositionalVals[ValNo].first,
1013 PositionalVals[ValNo].second);
1016 // Loop over args and make sure all required args are specified!
1017 for (StringMap<Option*>::iterator I = Opts.begin(),
1018 E = Opts.end(); I != E; ++I) {
1019 switch (I->second->getNumOccurrencesFlag()) {
1022 if (I->second->getNumOccurrences() == 0) {
1023 I->second->error("must be specified at least once!");
1024 ErrorParsing = true;
1032 // Now that we know if -debug is specified, we can use it.
1033 // Note that if ReadResponseFiles == true, this must be done before the
1034 // memory allocated for the expanded command line is free()d below.
1035 DEBUG(dbgs() << "Args: ";
1036 for (int i = 0; i < argc; ++i)
1037 dbgs() << argv[i] << ' ';
1041 // Free all of the memory allocated to the map. Command line options may only
1042 // be processed once!
1044 PositionalOpts.clear();
1047 // If we had an error processing our arguments, don't let the program execute
1048 if (ErrorParsing) exit(1);
1051 //===----------------------------------------------------------------------===//
1052 // Option Base class implementation
1055 bool Option::error(const Twine &Message, StringRef ArgName) {
1056 if (ArgName.data() == 0) ArgName = ArgStr;
1057 if (ArgName.empty())
1058 errs() << HelpStr; // Be nice for positional arguments
1060 errs() << ProgramName << ": for the -" << ArgName;
1062 errs() << " option: " << Message << "\n";
1066 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
1067 StringRef Value, bool MultiArg) {
1069 NumOccurrences++; // Increment the number of times we have been seen
1071 switch (getNumOccurrencesFlag()) {
1073 if (NumOccurrences > 1)
1074 return error("may only occur zero or one times!", ArgName);
1077 if (NumOccurrences > 1)
1078 return error("must occur exactly one time!", ArgName);
1082 case ConsumeAfter: break;
1085 return handleOccurrence(pos, ArgName, Value);
1089 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1090 // has been specified yet.
1092 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1093 if (O.ValueStr[0] == 0) return DefaultMsg;
1097 //===----------------------------------------------------------------------===//
1098 // cl::alias class implementation
1101 // Return the width of the option tag for printing...
1102 size_t alias::getOptionWidth() const {
1103 return std::strlen(ArgStr)+6;
1106 static void printHelpStr(StringRef HelpStr, size_t Indent,
1107 size_t FirstLineIndentedBy) {
1108 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1109 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1110 while (!Split.second.empty()) {
1111 Split = Split.second.split('\n');
1112 outs().indent(Indent) << Split.first << "\n";
1116 // Print out the option for the alias.
1117 void alias::printOptionInfo(size_t GlobalWidth) const {
1118 outs() << " -" << ArgStr;
1119 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1122 //===----------------------------------------------------------------------===//
1123 // Parser Implementation code...
1126 // basic_parser implementation
1129 // Return the width of the option tag for printing...
1130 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1131 size_t Len = std::strlen(O.ArgStr);
1132 if (const char *ValName = getValueName())
1133 Len += std::strlen(getValueStr(O, ValName))+3;
1138 // printOptionInfo - Print out information about this option. The
1139 // to-be-maintained width is specified.
1141 void basic_parser_impl::printOptionInfo(const Option &O,
1142 size_t GlobalWidth) const {
1143 outs() << " -" << O.ArgStr;
1145 if (const char *ValName = getValueName())
1146 outs() << "=<" << getValueStr(O, ValName) << '>';
1148 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1151 void basic_parser_impl::printOptionName(const Option &O,
1152 size_t GlobalWidth) const {
1153 outs() << " -" << O.ArgStr;
1154 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1158 // parser<bool> implementation
1160 bool parser<bool>::parse(Option &O, StringRef ArgName,
1161 StringRef Arg, bool &Value) {
1162 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1168 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1172 return O.error("'" + Arg +
1173 "' is invalid value for boolean argument! Try 0 or 1");
1176 // parser<boolOrDefault> implementation
1178 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
1179 StringRef Arg, boolOrDefault &Value) {
1180 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1185 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1190 return O.error("'" + Arg +
1191 "' is invalid value for boolean argument! Try 0 or 1");
1194 // parser<int> implementation
1196 bool parser<int>::parse(Option &O, StringRef ArgName,
1197 StringRef Arg, int &Value) {
1198 if (Arg.getAsInteger(0, Value))
1199 return O.error("'" + Arg + "' value invalid for integer argument!");
1203 // parser<unsigned> implementation
1205 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1206 StringRef Arg, unsigned &Value) {
1208 if (Arg.getAsInteger(0, Value))
1209 return O.error("'" + Arg + "' value invalid for uint argument!");
1213 // parser<unsigned long long> implementation
1215 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1216 StringRef Arg, unsigned long long &Value){
1218 if (Arg.getAsInteger(0, Value))
1219 return O.error("'" + Arg + "' value invalid for uint argument!");
1223 // parser<double>/parser<float> implementation
1225 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1226 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1227 const char *ArgStart = TmpStr.c_str();
1229 Value = strtod(ArgStart, &End);
1231 return O.error("'" + Arg + "' value invalid for floating point argument!");
1235 bool parser<double>::parse(Option &O, StringRef ArgName,
1236 StringRef Arg, double &Val) {
1237 return parseDouble(O, Arg, Val);
1240 bool parser<float>::parse(Option &O, StringRef ArgName,
1241 StringRef Arg, float &Val) {
1243 if (parseDouble(O, Arg, dVal))
1251 // generic_parser_base implementation
1254 // findOption - Return the option number corresponding to the specified
1255 // argument string. If the option is not found, getNumOptions() is returned.
1257 unsigned generic_parser_base::findOption(const char *Name) {
1258 unsigned e = getNumOptions();
1260 for (unsigned i = 0; i != e; ++i) {
1261 if (strcmp(getOption(i), Name) == 0)
1268 // Return the width of the option tag for printing...
1269 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1270 if (O.hasArgStr()) {
1271 size_t Size = std::strlen(O.ArgStr)+6;
1272 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1273 Size = std::max(Size, std::strlen(getOption(i))+8);
1276 size_t BaseSize = 0;
1277 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1278 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1283 // printOptionInfo - Print out information about this option. The
1284 // to-be-maintained width is specified.
1286 void generic_parser_base::printOptionInfo(const Option &O,
1287 size_t GlobalWidth) const {
1288 if (O.hasArgStr()) {
1289 outs() << " -" << O.ArgStr;
1290 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1292 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1293 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1294 outs() << " =" << getOption(i);
1295 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1299 outs() << " " << O.HelpStr << '\n';
1300 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1301 const char *Option = getOption(i);
1302 outs() << " -" << Option;
1303 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1308 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1310 // printGenericOptionDiff - Print the value of this option and it's default.
1312 // "Generic" options have each value mapped to a name.
1313 void generic_parser_base::
1314 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1315 const GenericOptionValue &Default,
1316 size_t GlobalWidth) const {
1317 outs() << " -" << O.ArgStr;
1318 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1320 unsigned NumOpts = getNumOptions();
1321 for (unsigned i = 0; i != NumOpts; ++i) {
1322 if (Value.compare(getOptionValue(i)))
1325 outs() << "= " << getOption(i);
1326 size_t L = std::strlen(getOption(i));
1327 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1328 outs().indent(NumSpaces) << " (default: ";
1329 for (unsigned j = 0; j != NumOpts; ++j) {
1330 if (Default.compare(getOptionValue(j)))
1332 outs() << getOption(j);
1338 outs() << "= *unknown option value*\n";
1341 // printOptionDiff - Specializations for printing basic value types.
1343 #define PRINT_OPT_DIFF(T) \
1345 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1346 size_t GlobalWidth) const { \
1347 printOptionName(O, GlobalWidth); \
1350 raw_string_ostream SS(Str); \
1353 outs() << "= " << Str; \
1354 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1355 outs().indent(NumSpaces) << " (default: "; \
1357 outs() << D.getValue(); \
1359 outs() << "*no default*"; \
1363 PRINT_OPT_DIFF(bool)
1364 PRINT_OPT_DIFF(boolOrDefault)
1366 PRINT_OPT_DIFF(unsigned)
1367 PRINT_OPT_DIFF(unsigned long long)
1368 PRINT_OPT_DIFF(double)
1369 PRINT_OPT_DIFF(float)
1370 PRINT_OPT_DIFF(char)
1372 void parser<std::string>::
1373 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1374 size_t GlobalWidth) const {
1375 printOptionName(O, GlobalWidth);
1376 outs() << "= " << V;
1377 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1378 outs().indent(NumSpaces) << " (default: ";
1380 outs() << D.getValue();
1382 outs() << "*no default*";
1386 // Print a placeholder for options that don't yet support printOptionDiff().
1387 void basic_parser_impl::
1388 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1389 printOptionName(O, GlobalWidth);
1390 outs() << "= *cannot print option value*\n";
1393 //===----------------------------------------------------------------------===//
1394 // -help and -help-hidden option implementation
1397 static int OptNameCompare(const void *LHS, const void *RHS) {
1398 typedef std::pair<const char *, Option*> pair_ty;
1400 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1403 // Copy Options into a vector so we can sort them as we like.
1405 sortOpts(StringMap<Option*> &OptMap,
1406 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1408 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1410 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1412 // Ignore really-hidden options.
1413 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1416 // Unless showhidden is set, ignore hidden flags.
1417 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1420 // If we've already seen this option, don't add it to the list again.
1421 if (!OptionSet.insert(I->second))
1424 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1428 // Sort the options list alphabetically.
1429 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1436 const bool ShowHidden;
1437 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1438 // Print the options. Opts is assumed to be alphabetically sorted.
1439 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1440 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1441 Opts[i].second->printOptionInfo(MaxArgLen);
1445 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1446 virtual ~HelpPrinter() {}
1448 // Invoke the printer.
1449 void operator=(bool Value) {
1450 if (Value == false) return;
1452 // Get all the options.
1453 SmallVector<Option*, 4> PositionalOpts;
1454 SmallVector<Option*, 4> SinkOpts;
1455 StringMap<Option*> OptMap;
1456 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1458 StrOptionPairVector Opts;
1459 sortOpts(OptMap, Opts, ShowHidden);
1461 if (ProgramOverview)
1462 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1464 outs() << "USAGE: " << ProgramName << " [options]";
1466 // Print out the positional options.
1467 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
1468 if (!PositionalOpts.empty() &&
1469 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1470 CAOpt = PositionalOpts[0];
1472 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1473 if (PositionalOpts[i]->ArgStr[0])
1474 outs() << " --" << PositionalOpts[i]->ArgStr;
1475 outs() << " " << PositionalOpts[i]->HelpStr;
1478 // Print the consume after option info if it exists...
1479 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1483 // Compute the maximum argument length...
1484 size_t MaxArgLen = 0;
1485 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1486 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1488 outs() << "OPTIONS:\n";
1489 printOptions(Opts, MaxArgLen);
1491 // Print any extra help the user has declared.
1492 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1493 E = MoreHelp->end();
1498 // Halt the program since help information was printed
1503 class CategorizedHelpPrinter : public HelpPrinter {
1505 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1507 // Helper function for printOptions().
1508 // It shall return true if A's name should be lexographically
1509 // ordered before B's name. It returns false otherwise.
1510 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1511 return strcmp(A->getName(), B->getName()) < 0;
1514 // Make sure we inherit our base class's operator=()
1515 using HelpPrinter::operator= ;
1518 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1519 std::vector<OptionCategory *> SortedCategories;
1520 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1522 // Collect registered option categories into vector in preparation for
1524 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1525 E = RegisteredOptionCategories->end();
1527 SortedCategories.push_back(*I);
1529 // Sort the different option categories alphabetically.
1530 assert(SortedCategories.size() > 0 && "No option categories registered!");
1531 std::sort(SortedCategories.begin(), SortedCategories.end(),
1532 OptionCategoryCompare);
1534 // Create map to empty vectors.
1535 for (std::vector<OptionCategory *>::const_iterator
1536 I = SortedCategories.begin(),
1537 E = SortedCategories.end();
1539 CategorizedOptions[*I] = std::vector<Option *>();
1541 // Walk through pre-sorted options and assign into categories.
1542 // Because the options are already alphabetically sorted the
1543 // options within categories will also be alphabetically sorted.
1544 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1545 Option *Opt = Opts[I].second;
1546 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1547 "Option has an unregistered category");
1548 CategorizedOptions[Opt->Category].push_back(Opt);
1552 for (std::vector<OptionCategory *>::const_iterator
1553 Category = SortedCategories.begin(),
1554 E = SortedCategories.end();
1555 Category != E; ++Category) {
1556 // Hide empty categories for -help, but show for -help-hidden.
1557 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1558 if (!ShowHidden && IsEmptyCategory)
1561 // Print category information.
1563 outs() << (*Category)->getName() << ":\n";
1565 // Check if description is set.
1566 if ((*Category)->getDescription() != 0)
1567 outs() << (*Category)->getDescription() << "\n\n";
1571 // When using -help-hidden explicitly state if the category has no
1572 // options associated with it.
1573 if (IsEmptyCategory) {
1574 outs() << " This option category has no options.\n";
1577 // Loop over the options in the category and print.
1578 for (std::vector<Option *>::const_iterator
1579 Opt = CategorizedOptions[*Category].begin(),
1580 E = CategorizedOptions[*Category].end();
1582 (*Opt)->printOptionInfo(MaxArgLen);
1587 // This wraps the Uncategorizing and Categorizing printers and decides
1588 // at run time which should be invoked.
1589 class HelpPrinterWrapper {
1591 HelpPrinter &UncategorizedPrinter;
1592 CategorizedHelpPrinter &CategorizedPrinter;
1595 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1596 CategorizedHelpPrinter &CategorizedPrinter) :
1597 UncategorizedPrinter(UncategorizedPrinter),
1598 CategorizedPrinter(CategorizedPrinter) { }
1600 // Invoke the printer.
1601 void operator=(bool Value);
1604 } // End anonymous namespace
1606 // Declare the four HelpPrinter instances that are used to print out help, or
1607 // help-hidden as an uncategorized list or in categories.
1608 static HelpPrinter UncategorizedNormalPrinter(false);
1609 static HelpPrinter UncategorizedHiddenPrinter(true);
1610 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1611 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1614 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1615 // a categorizing help printer
1616 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1617 CategorizedNormalPrinter);
1618 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1619 CategorizedHiddenPrinter);
1621 // Define uncategorized help printers.
1622 // -help-list is hidden by default because if Option categories are being used
1623 // then -help behaves the same as -help-list.
1624 static cl::opt<HelpPrinter, true, parser<bool> >
1626 cl::desc("Display list of available options (-help-list-hidden for more)"),
1627 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1629 static cl::opt<HelpPrinter, true, parser<bool> >
1630 HLHOp("help-list-hidden",
1631 cl::desc("Display list of all available options"),
1632 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1634 // Define uncategorized/categorized help printers. These printers change their
1635 // behaviour at runtime depending on whether one or more Option categories have
1637 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1638 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1639 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1641 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1642 HHOp("help-hidden", cl::desc("Display all available options"),
1643 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1647 static cl::opt<bool>
1648 PrintOptions("print-options",
1649 cl::desc("Print non-default options after command line parsing"),
1650 cl::Hidden, cl::init(false));
1652 static cl::opt<bool>
1653 PrintAllOptions("print-all-options",
1654 cl::desc("Print all option values after command line parsing"),
1655 cl::Hidden, cl::init(false));
1657 void HelpPrinterWrapper::operator=(bool Value) {
1661 // Decide which printer to invoke. If more than one option category is
1662 // registered then it is useful to show the categorized help instead of
1663 // uncategorized help.
1664 if (RegisteredOptionCategories->size() > 1) {
1665 // unhide -help-list option so user can have uncategorized output if they
1667 HLOp.setHiddenFlag(NotHidden);
1669 CategorizedPrinter = true; // Invoke categorized printer
1672 UncategorizedPrinter = true; // Invoke uncategorized printer
1675 // Print the value of each option.
1676 void cl::PrintOptionValues() {
1677 if (!PrintOptions && !PrintAllOptions) return;
1679 // Get all the options.
1680 SmallVector<Option*, 4> PositionalOpts;
1681 SmallVector<Option*, 4> SinkOpts;
1682 StringMap<Option*> OptMap;
1683 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1685 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1686 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1688 // Compute the maximum argument length...
1689 size_t MaxArgLen = 0;
1690 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1691 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1693 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1694 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1697 static void (*OverrideVersionPrinter)() = 0;
1699 static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1702 class VersionPrinter {
1705 raw_ostream &OS = outs();
1706 OS << "LLVM (http://llvm.org/):\n"
1707 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1708 #ifdef LLVM_VERSION_INFO
1709 OS << LLVM_VERSION_INFO;
1712 #ifndef __OPTIMIZE__
1713 OS << "DEBUG build";
1715 OS << "Optimized build";
1718 OS << " with assertions";
1720 std::string CPU = sys::getHostCPUName();
1721 if (CPU == "generic") CPU = "(unknown)";
1723 #if (ENABLE_TIMESTAMPS == 1)
1724 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1726 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1727 << " Host CPU: " << CPU << '\n';
1729 void operator=(bool OptionWasSpecified) {
1730 if (!OptionWasSpecified) return;
1732 if (OverrideVersionPrinter != 0) {
1733 (*OverrideVersionPrinter)();
1738 // Iterate over any registered extra printers and call them to add further
1740 if (ExtraVersionPrinters != 0) {
1742 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1743 E = ExtraVersionPrinters->end();
1751 } // End anonymous namespace
1754 // Define the --version option that prints out the LLVM version for the tool
1755 static VersionPrinter VersionPrinterInstance;
1757 static cl::opt<VersionPrinter, true, parser<bool> >
1758 VersOp("version", cl::desc("Display the version of this program"),
1759 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1761 // Utility function for printing the help message.
1762 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1763 // This looks weird, but it actually prints the help message. The Printers are
1764 // types of HelpPrinter and the help gets printed when its operator= is
1765 // invoked. That's because the "normal" usages of the help printer is to be
1766 // assigned true/false depending on whether -help or -help-hidden was given or
1767 // not. Since we're circumventing that we have to make it look like -help or
1768 // -help-hidden were given, so we assign true.
1770 if (!Hidden && !Categorized)
1771 UncategorizedNormalPrinter = true;
1772 else if (!Hidden && Categorized)
1773 CategorizedNormalPrinter = true;
1774 else if (Hidden && !Categorized)
1775 UncategorizedHiddenPrinter = true;
1777 CategorizedHiddenPrinter = true;
1780 /// Utility function for printing version number.
1781 void cl::PrintVersionMessage() {
1782 VersionPrinterInstance.print();
1785 void cl::SetVersionPrinter(void (*func)()) {
1786 OverrideVersionPrinter = func;
1789 void cl::AddExtraVersionPrinter(void (*func)()) {
1790 if (ExtraVersionPrinters == 0)
1791 ExtraVersionPrinters = new std::vector<void (*)()>;
1793 ExtraVersionPrinters->push_back(func);
1796 void cl::getRegisteredOptions(StringMap<Option*> &Map)
1798 // Get all the options.
1799 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1800 SmallVector<Option*, 4> SinkOpts; //NOT USED
1801 assert(Map.size() == 0 && "StringMap must be empty");
1802 GetOptionInfo(PositionalOpts, SinkOpts, Map);