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/SmallPtrSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/Support/ConvertUTF.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/Host.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Support/system_error.h"
41 //===----------------------------------------------------------------------===//
42 // Template instantiations and anchors.
44 namespace llvm { namespace cl {
45 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
46 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
47 TEMPLATE_INSTANTIATION(class basic_parser<int>);
48 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
49 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
50 TEMPLATE_INSTANTIATION(class basic_parser<double>);
51 TEMPLATE_INSTANTIATION(class basic_parser<float>);
52 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
53 TEMPLATE_INSTANTIATION(class basic_parser<char>);
55 TEMPLATE_INSTANTIATION(class opt<unsigned>);
56 TEMPLATE_INSTANTIATION(class opt<int>);
57 TEMPLATE_INSTANTIATION(class opt<std::string>);
58 TEMPLATE_INSTANTIATION(class opt<char>);
59 TEMPLATE_INSTANTIATION(class opt<bool>);
60 } } // end namespace llvm::cl
62 // Pin the vtables to this file.
63 void GenericOptionValue::anchor() {}
64 void OptionValue<boolOrDefault>::anchor() {}
65 void OptionValue<std::string>::anchor() {}
66 void Option::anchor() {}
67 void basic_parser_impl::anchor() {}
68 void parser<bool>::anchor() {}
69 void parser<boolOrDefault>::anchor() {}
70 void parser<int>::anchor() {}
71 void parser<unsigned>::anchor() {}
72 void parser<unsigned long long>::anchor() {}
73 void parser<double>::anchor() {}
74 void parser<float>::anchor() {}
75 void parser<std::string>::anchor() {}
76 void parser<char>::anchor() {}
77 void StringSaver::anchor() {}
79 //===----------------------------------------------------------------------===//
81 // Globals for name and overview of program. Program name is not a string to
82 // avoid static ctor/dtor issues.
83 static char ProgramName[80] = "<premain>";
84 static const char *ProgramOverview = 0;
86 // This collects additional help to be printed.
87 static ManagedStatic<std::vector<const char*> > MoreHelp;
89 extrahelp::extrahelp(const char *Help)
91 MoreHelp->push_back(Help);
94 static bool OptionListChanged = false;
96 // MarkOptionsChanged - Internal helper function.
97 void cl::MarkOptionsChanged() {
98 OptionListChanged = true;
101 /// RegisteredOptionList - This is the list of the command line options that
102 /// have statically constructed themselves.
103 static Option *RegisteredOptionList = 0;
105 void Option::addArgument() {
106 assert(NextRegistered == 0 && "argument multiply registered!");
108 NextRegistered = RegisteredOptionList;
109 RegisteredOptionList = this;
110 MarkOptionsChanged();
113 void Option::removeArgument() {
114 assert(NextRegistered != 0 && "argument never registered");
115 assert(RegisteredOptionList == this && "argument is not the last registered");
116 RegisteredOptionList = NextRegistered;
117 MarkOptionsChanged();
120 // This collects the different option categories that have been registered.
121 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
122 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
124 // Initialise the general option category.
125 OptionCategory llvm::cl::GeneralCategory("General options");
127 void OptionCategory::registerCategory() {
128 assert(std::count_if(RegisteredOptionCategories->begin(),
129 RegisteredOptionCategories->end(),
130 [this](const OptionCategory *Category) {
131 return getName() == Category->getName();
132 }) == 0 && "Duplicate option categories");
134 RegisteredOptionCategories->insert(this);
137 //===----------------------------------------------------------------------===//
138 // Basic, shared command line option processing machinery.
141 /// GetOptionInfo - Scan the list of registered options, turning them into data
142 /// structures that are easier to handle.
143 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
144 SmallVectorImpl<Option*> &SinkOpts,
145 StringMap<Option*> &OptionsMap) {
146 SmallVector<const char*, 16> OptionNames;
147 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
148 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
149 // If this option wants to handle multiple option names, get the full set.
150 // This handles enum options like "-O1 -O2" etc.
151 O->getExtraOptionNames(OptionNames);
153 OptionNames.push_back(O->ArgStr);
155 // Handle named options.
156 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
157 // Add argument to the argument map!
158 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
159 errs() << ProgramName << ": CommandLine Error: Argument '"
160 << OptionNames[i] << "' defined more than once!\n";
166 // Remember information about positional options.
167 if (O->getFormattingFlag() == cl::Positional)
168 PositionalOpts.push_back(O);
169 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
170 SinkOpts.push_back(O);
171 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
173 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
179 PositionalOpts.push_back(CAOpt);
181 // Make sure that they are in order of registration not backwards.
182 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
186 /// LookupOption - Lookup the option specified by the specified option on the
187 /// command line. If there is a value specified (after an equal sign) return
188 /// that as well. This assumes that leading dashes have already been stripped.
189 static Option *LookupOption(StringRef &Arg, StringRef &Value,
190 const StringMap<Option*> &OptionsMap) {
191 // Reject all dashes.
192 if (Arg.empty()) return 0;
194 size_t EqualPos = Arg.find('=');
196 // If we have an equals sign, remember the value.
197 if (EqualPos == StringRef::npos) {
198 // Look up the option.
199 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
200 return I != OptionsMap.end() ? I->second : 0;
203 // If the argument before the = is a valid option name, we match. If not,
204 // return Arg unmolested.
205 StringMap<Option*>::const_iterator I =
206 OptionsMap.find(Arg.substr(0, EqualPos));
207 if (I == OptionsMap.end()) return 0;
209 Value = Arg.substr(EqualPos+1);
210 Arg = Arg.substr(0, EqualPos);
214 /// LookupNearestOption - Lookup the closest match to the option specified by
215 /// the specified option on the command line. If there is a value specified
216 /// (after an equal sign) return that as well. This assumes that leading dashes
217 /// have already been stripped.
218 static Option *LookupNearestOption(StringRef Arg,
219 const StringMap<Option*> &OptionsMap,
220 std::string &NearestString) {
221 // Reject all dashes.
222 if (Arg.empty()) return 0;
224 // Split on any equal sign.
225 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
226 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
227 StringRef &RHS = SplitArg.second;
229 // Find the closest match.
231 unsigned BestDistance = 0;
232 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
233 ie = OptionsMap.end(); it != ie; ++it) {
234 Option *O = it->second;
235 SmallVector<const char*, 16> OptionNames;
236 O->getExtraOptionNames(OptionNames);
238 OptionNames.push_back(O->ArgStr);
240 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
241 StringRef Flag = PermitValue ? LHS : Arg;
242 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
243 StringRef Name = OptionNames[i];
244 unsigned Distance = StringRef(Name).edit_distance(
245 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
246 if (!Best || Distance < BestDistance) {
248 BestDistance = Distance;
249 if (RHS.empty() || !PermitValue)
250 NearestString = OptionNames[i];
252 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
260 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
261 /// that does special handling of cl::CommaSeparated options.
262 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
263 StringRef ArgName, StringRef Value,
264 bool MultiArg = false) {
265 // Check to see if this option accepts a comma separated list of values. If
266 // it does, we have to split up the value into multiple values.
267 if (Handler->getMiscFlags() & CommaSeparated) {
268 StringRef Val(Value);
269 StringRef::size_type Pos = Val.find(',');
271 while (Pos != StringRef::npos) {
272 // Process the portion before the comma.
273 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
275 // Erase the portion before the comma, AND the comma.
276 Val = Val.substr(Pos+1);
277 Value.substr(Pos+1); // Increment the original value pointer as well.
278 // Check for another comma.
285 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
291 /// ProvideOption - For Value, this differentiates between an empty value ("")
292 /// and a null value (StringRef()). The later is accepted for arguments that
293 /// don't allow a value (-foo) the former is rejected (-foo=).
294 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
295 StringRef Value, int argc,
296 const char *const *argv, int &i) {
297 // Is this a multi-argument option?
298 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
300 // Enforce value requirements
301 switch (Handler->getValueExpectedFlag()) {
303 if (Value.data() == 0) { // No value specified?
305 return Handler->error("requires a value!");
306 // Steal the next argument, like for '-o filename'
310 case ValueDisallowed:
311 if (NumAdditionalVals > 0)
312 return Handler->error("multi-valued option specified"
313 " with ValueDisallowed modifier!");
316 return Handler->error("does not allow a value! '" +
317 Twine(Value) + "' specified.");
323 // If this isn't a multi-arg option, just run the handler.
324 if (NumAdditionalVals == 0)
325 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
327 // If it is, run the handle several times.
328 bool MultiArg = false;
331 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
337 while (NumAdditionalVals > 0) {
339 return Handler->error("not enough values!");
342 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
350 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
352 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
356 // Option predicates...
357 static inline bool isGrouping(const Option *O) {
358 return O->getFormattingFlag() == cl::Grouping;
360 static inline bool isPrefixedOrGrouping(const Option *O) {
361 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
364 // getOptionPred - Check to see if there are any options that satisfy the
365 // specified predicate with names that are the prefixes in Name. This is
366 // checked by progressively stripping characters off of the name, checking to
367 // see if there options that satisfy the predicate. If we find one, return it,
368 // otherwise return null.
370 static Option *getOptionPred(StringRef Name, size_t &Length,
371 bool (*Pred)(const Option*),
372 const StringMap<Option*> &OptionsMap) {
374 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
376 // Loop while we haven't found an option and Name still has at least two
377 // characters in it (so that the next iteration will not be the empty
379 while (OMI == OptionsMap.end() && Name.size() > 1) {
380 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
381 OMI = OptionsMap.find(Name);
384 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
385 Length = Name.size();
386 return OMI->second; // Found one!
388 return 0; // No option found!
391 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
392 /// with at least one '-') does not fully match an available option. Check to
393 /// see if this is a prefix or grouped option. If so, split arg into output an
394 /// Arg/Value pair and return the Option to parse it with.
395 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
397 const StringMap<Option*> &OptionsMap) {
398 if (Arg.size() == 1) return 0;
402 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
403 if (PGOpt == 0) return 0;
405 // If the option is a prefixed option, then the value is simply the
406 // rest of the name... so fall through to later processing, by
407 // setting up the argument name flags and value fields.
408 if (PGOpt->getFormattingFlag() == cl::Prefix) {
409 Value = Arg.substr(Length);
410 Arg = Arg.substr(0, Length);
411 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
415 // This must be a grouped option... handle them now. Grouping options can't
417 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
420 // Move current arg name out of Arg into OneArgName.
421 StringRef OneArgName = Arg.substr(0, Length);
422 Arg = Arg.substr(Length);
424 // Because ValueRequired is an invalid flag for grouped arguments,
425 // we don't need to pass argc/argv in.
426 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
427 "Option can not be cl::Grouping AND cl::ValueRequired!");
429 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
430 StringRef(), 0, 0, Dummy);
432 // Get the next grouping option.
433 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
434 } while (PGOpt && Length != Arg.size());
436 // Return the last option with Arg cut down to just the last one.
442 static bool RequiresValue(const Option *O) {
443 return O->getNumOccurrencesFlag() == cl::Required ||
444 O->getNumOccurrencesFlag() == cl::OneOrMore;
447 static bool EatsUnboundedNumberOfValues(const Option *O) {
448 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
449 O->getNumOccurrencesFlag() == cl::OneOrMore;
452 static bool isWhitespace(char C) {
453 return strchr(" \t\n\r\f\v", C);
456 static bool isQuote(char C) {
457 return C == '\"' || C == '\'';
460 static bool isGNUSpecial(char C) {
461 return strchr("\\\"\' ", C);
464 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
465 SmallVectorImpl<const char *> &NewArgv) {
466 SmallString<128> Token;
467 for (size_t I = 0, E = Src.size(); I != E; ++I) {
468 // Consume runs of whitespace.
470 while (I != E && isWhitespace(Src[I]))
475 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
476 // they are literal. This makes it much easier to read Windows file paths.
477 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
478 ++I; // Skip the escape.
479 Token.push_back(Src[I]);
483 // Consume a quoted string.
484 if (isQuote(Src[I])) {
485 char Quote = Src[I++];
486 while (I != E && Src[I] != Quote) {
487 // Backslashes are literal, unless they escape a special character.
488 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
490 Token.push_back(Src[I]);
497 // End the token if this is whitespace.
498 if (isWhitespace(Src[I])) {
500 NewArgv.push_back(Saver.SaveString(Token.c_str()));
505 // This is a normal character. Append it.
506 Token.push_back(Src[I]);
509 // Append the last token after hitting EOF with no whitespace.
511 NewArgv.push_back(Saver.SaveString(Token.c_str()));
514 /// Backslashes are interpreted in a rather complicated way in the Windows-style
515 /// command line, because backslashes are used both to separate path and to
516 /// escape double quote. This method consumes runs of backslashes as well as the
517 /// following double quote if it's escaped.
519 /// * If an even number of backslashes is followed by a double quote, one
520 /// backslash is output for every pair of backslashes, and the last double
521 /// quote remains unconsumed. The double quote will later be interpreted as
522 /// the start or end of a quoted string in the main loop outside of this
525 /// * If an odd number of backslashes is followed by a double quote, one
526 /// backslash is output for every pair of backslashes, and a double quote is
527 /// output for the last pair of backslash-double quote. The double quote is
528 /// consumed in this case.
530 /// * Otherwise, backslashes are interpreted literally.
531 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
532 size_t E = Src.size();
533 int BackslashCount = 0;
534 // Skip the backslashes.
538 } while (I != E && Src[I] == '\\');
540 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
541 if (FollowedByDoubleQuote) {
542 Token.append(BackslashCount / 2, '\\');
543 if (BackslashCount % 2 == 0)
545 Token.push_back('"');
548 Token.append(BackslashCount, '\\');
552 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
553 SmallVectorImpl<const char *> &NewArgv) {
554 SmallString<128> Token;
556 // This is a small state machine to consume characters until it reaches the
557 // end of the source string.
558 enum { INIT, UNQUOTED, QUOTED } State = INIT;
559 for (size_t I = 0, E = Src.size(); I != E; ++I) {
560 // INIT state indicates that the current input index is at the start of
561 // the string or between tokens.
563 if (isWhitespace(Src[I]))
569 if (Src[I] == '\\') {
570 I = parseBackslash(Src, I, Token);
574 Token.push_back(Src[I]);
579 // UNQUOTED state means that it's reading a token not quoted by double
581 if (State == UNQUOTED) {
582 // Whitespace means the end of the token.
583 if (isWhitespace(Src[I])) {
584 NewArgv.push_back(Saver.SaveString(Token.c_str()));
593 if (Src[I] == '\\') {
594 I = parseBackslash(Src, I, Token);
597 Token.push_back(Src[I]);
601 // QUOTED state means that it's reading a token quoted by double quotes.
602 if (State == QUOTED) {
607 if (Src[I] == '\\') {
608 I = parseBackslash(Src, I, Token);
611 Token.push_back(Src[I]);
614 // Append the last token after hitting EOF with no whitespace.
616 NewArgv.push_back(Saver.SaveString(Token.c_str()));
619 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
620 TokenizerCallback Tokenizer,
621 SmallVectorImpl<const char *> &NewArgv) {
622 std::unique_ptr<MemoryBuffer> MemBuf;
623 if (MemoryBuffer::getFile(FName, MemBuf))
625 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
627 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
628 ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd());
630 if (hasUTF16ByteOrderMark(BufRef)) {
631 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
633 Str = StringRef(UTF8Buf);
636 // Tokenize the contents into NewArgv.
637 Tokenizer(Str, Saver, NewArgv);
642 /// \brief Expand response files on a command line recursively using the given
643 /// StringSaver and tokenization strategy.
644 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
645 SmallVectorImpl<const char *> &Argv) {
646 unsigned RspFiles = 0;
647 bool AllExpanded = true;
649 // Don't cache Argv.size() because it can change.
650 for (unsigned I = 0; I != Argv.size(); ) {
651 const char *Arg = Argv[I];
657 // If we have too many response files, leave some unexpanded. This avoids
658 // crashing on self-referential response files.
662 // Replace this response file argument with the tokenization of its
663 // contents. Nested response files are expanded in subsequent iterations.
664 // FIXME: If a nested response file uses a relative path, is it relative to
665 // the cwd of the process or the response file?
666 SmallVector<const char *, 0> ExpandedArgv;
667 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
668 // We couldn't read this file, so we leave it in the argument stream and
674 Argv.erase(Argv.begin() + I);
675 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
681 class StrDupSaver : public StringSaver {
682 std::vector<char*> Dups;
685 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
691 const char *SaveString(const char *Str) override {
692 char *Dup = strdup(Str);
699 /// ParseEnvironmentOptions - An alternative entry point to the
700 /// CommandLine library, which allows you to read the program's name
701 /// from the caller (as PROGNAME) and its command-line arguments from
702 /// an environment variable (whose name is given in ENVVAR).
704 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
705 const char *Overview) {
707 assert(progName && "Program name not specified");
708 assert(envVar && "Environment variable name missing");
710 // Get the environment variable they want us to parse options out of.
711 const char *envValue = getenv(envVar);
715 // Get program's "name", which we wouldn't know without the caller
717 SmallVector<const char *, 20> newArgv;
719 newArgv.push_back(Saver.SaveString(progName));
721 // Parse the value of the environment variable into a "command line"
722 // and hand it off to ParseCommandLineOptions().
723 TokenizeGNUCommandLine(envValue, Saver, newArgv);
724 int newArgc = static_cast<int>(newArgv.size());
725 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
728 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
729 const char *Overview) {
730 // Process all registered options.
731 SmallVector<Option*, 4> PositionalOpts;
732 SmallVector<Option*, 4> SinkOpts;
733 StringMap<Option*> Opts;
734 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
736 assert((!Opts.empty() || !PositionalOpts.empty()) &&
737 "No options specified!");
739 // Expand response files.
740 SmallVector<const char *, 20> newArgv;
741 for (int i = 0; i != argc; ++i)
742 newArgv.push_back(argv[i]);
744 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
746 argc = static_cast<int>(newArgv.size());
748 // Copy the program name into ProgName, making sure not to overflow it.
749 std::string ProgName = sys::path::filename(argv[0]);
750 size_t Len = std::min(ProgName.size(), size_t(79));
751 memcpy(ProgramName, ProgName.data(), Len);
752 ProgramName[Len] = '\0';
754 ProgramOverview = Overview;
755 bool ErrorParsing = false;
757 // Check out the positional arguments to collect information about them.
758 unsigned NumPositionalRequired = 0;
760 // Determine whether or not there are an unlimited number of positionals
761 bool HasUnlimitedPositionals = false;
763 Option *ConsumeAfterOpt = 0;
764 if (!PositionalOpts.empty()) {
765 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
766 assert(PositionalOpts.size() > 1 &&
767 "Cannot specify cl::ConsumeAfter without a positional argument!");
768 ConsumeAfterOpt = PositionalOpts[0];
771 // Calculate how many positional values are _required_.
772 bool UnboundedFound = false;
773 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
775 Option *Opt = PositionalOpts[i];
776 if (RequiresValue(Opt))
777 ++NumPositionalRequired;
778 else if (ConsumeAfterOpt) {
779 // ConsumeAfter cannot be combined with "optional" positional options
780 // unless there is only one positional argument...
781 if (PositionalOpts.size() > 2)
783 Opt->error("error - this positional option will never be matched, "
784 "because it does not Require a value, and a "
785 "cl::ConsumeAfter option is active!");
786 } else if (UnboundedFound && !Opt->ArgStr[0]) {
787 // This option does not "require" a value... Make sure this option is
788 // not specified after an option that eats all extra arguments, or this
789 // one will never get any!
791 ErrorParsing |= Opt->error("error - option can never match, because "
792 "another positional argument will match an "
793 "unbounded number of values, and this option"
794 " does not require a value!");
796 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
798 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
801 // PositionalVals - A vector of "positional" arguments we accumulate into
802 // the process at the end.
804 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
806 // If the program has named positional arguments, and the name has been run
807 // across, keep track of which positional argument was named. Otherwise put
808 // the positional args into the PositionalVals list...
809 Option *ActivePositionalArg = 0;
811 // Loop over all of the arguments... processing them.
812 bool DashDashFound = false; // Have we read '--'?
813 for (int i = 1; i < argc; ++i) {
815 Option *NearestHandler = 0;
816 std::string NearestHandlerString;
818 StringRef ArgName = "";
820 // If the option list changed, this means that some command line
821 // option has just been registered or deregistered. This can occur in
822 // response to things like -load, etc. If this happens, rescan the options.
823 if (OptionListChanged) {
824 PositionalOpts.clear();
827 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
828 OptionListChanged = false;
831 // Check to see if this is a positional argument. This argument is
832 // considered to be positional if it doesn't start with '-', if it is "-"
833 // itself, or if we have seen "--" already.
835 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
836 // Positional argument!
837 if (ActivePositionalArg) {
838 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
839 continue; // We are done!
842 if (!PositionalOpts.empty()) {
843 PositionalVals.push_back(std::make_pair(argv[i],i));
845 // All of the positional arguments have been fulfulled, give the rest to
846 // the consume after option... if it's specified...
848 if (PositionalVals.size() >= NumPositionalRequired &&
849 ConsumeAfterOpt != 0) {
850 for (++i; i < argc; ++i)
851 PositionalVals.push_back(std::make_pair(argv[i],i));
852 break; // Handle outside of the argument processing loop...
855 // Delay processing positional arguments until the end...
858 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
860 DashDashFound = true; // This is the mythical "--"?
861 continue; // Don't try to process it as an argument itself.
862 } else if (ActivePositionalArg &&
863 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
864 // If there is a positional argument eating options, check to see if this
865 // option is another positional argument. If so, treat it as an argument,
866 // otherwise feed it to the eating positional.
868 // Eat leading dashes.
869 while (!ArgName.empty() && ArgName[0] == '-')
870 ArgName = ArgName.substr(1);
872 Handler = LookupOption(ArgName, Value, Opts);
873 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
874 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
875 continue; // We are done!
878 } else { // We start with a '-', must be an argument.
880 // Eat leading dashes.
881 while (!ArgName.empty() && ArgName[0] == '-')
882 ArgName = ArgName.substr(1);
884 Handler = LookupOption(ArgName, Value, Opts);
886 // Check to see if this "option" is really a prefixed or grouped argument.
888 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
891 // Otherwise, look for the closest available option to report to the user
892 // in the upcoming error.
893 if (Handler == 0 && SinkOpts.empty())
894 NearestHandler = LookupNearestOption(ArgName, Opts,
895 NearestHandlerString);
899 if (SinkOpts.empty()) {
900 errs() << ProgramName << ": Unknown command line argument '"
901 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
903 if (NearestHandler) {
904 // If we know a near match, report it as well.
905 errs() << ProgramName << ": Did you mean '-"
906 << NearestHandlerString << "'?\n";
911 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
912 E = SinkOpts.end(); I != E ; ++I)
913 (*I)->addOccurrence(i, "", argv[i]);
918 // If this is a named positional argument, just remember that it is the
920 if (Handler->getFormattingFlag() == cl::Positional)
921 ActivePositionalArg = Handler;
923 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
926 // Check and handle positional arguments now...
927 if (NumPositionalRequired > PositionalVals.size()) {
928 errs() << ProgramName
929 << ": Not enough positional command line arguments specified!\n"
930 << "Must specify at least " << NumPositionalRequired
931 << " positional arguments: See: " << argv[0] << " -help\n";
934 } else if (!HasUnlimitedPositionals &&
935 PositionalVals.size() > PositionalOpts.size()) {
936 errs() << ProgramName
937 << ": Too many positional arguments specified!\n"
938 << "Can specify at most " << PositionalOpts.size()
939 << " positional arguments: See: " << argv[0] << " -help\n";
942 } else if (ConsumeAfterOpt == 0) {
943 // Positional args have already been handled if ConsumeAfter is specified.
944 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
945 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
946 if (RequiresValue(PositionalOpts[i])) {
947 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
948 PositionalVals[ValNo].second);
950 --NumPositionalRequired; // We fulfilled our duty...
953 // If we _can_ give this option more arguments, do so now, as long as we
954 // do not give it values that others need. 'Done' controls whether the
955 // option even _WANTS_ any more.
957 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
958 while (NumVals-ValNo > NumPositionalRequired && !Done) {
959 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
961 Done = true; // Optional arguments want _at most_ one value
963 case cl::ZeroOrMore: // Zero or more will take all they can get...
964 case cl::OneOrMore: // One or more will take all they can get...
965 ProvidePositionalOption(PositionalOpts[i],
966 PositionalVals[ValNo].first,
967 PositionalVals[ValNo].second);
971 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
972 "positional argument processing!");
977 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
979 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
980 if (RequiresValue(PositionalOpts[j])) {
981 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
982 PositionalVals[ValNo].first,
983 PositionalVals[ValNo].second);
987 // Handle the case where there is just one positional option, and it's
988 // optional. In this case, we want to give JUST THE FIRST option to the
989 // positional option and keep the rest for the consume after. The above
990 // loop would have assigned no values to positional options in this case.
992 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
993 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
994 PositionalVals[ValNo].first,
995 PositionalVals[ValNo].second);
999 // Handle over all of the rest of the arguments to the
1000 // cl::ConsumeAfter command line option...
1001 for (; ValNo != PositionalVals.size(); ++ValNo)
1002 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
1003 PositionalVals[ValNo].first,
1004 PositionalVals[ValNo].second);
1007 // Loop over args and make sure all required args are specified!
1008 for (StringMap<Option*>::iterator I = Opts.begin(),
1009 E = Opts.end(); I != E; ++I) {
1010 switch (I->second->getNumOccurrencesFlag()) {
1013 if (I->second->getNumOccurrences() == 0) {
1014 I->second->error("must be specified at least once!");
1015 ErrorParsing = true;
1023 // Now that we know if -debug is specified, we can use it.
1024 // Note that if ReadResponseFiles == true, this must be done before the
1025 // memory allocated for the expanded command line is free()d below.
1026 DEBUG(dbgs() << "Args: ";
1027 for (int i = 0; i < argc; ++i)
1028 dbgs() << argv[i] << ' ';
1032 // Free all of the memory allocated to the map. Command line options may only
1033 // be processed once!
1035 PositionalOpts.clear();
1038 // If we had an error processing our arguments, don't let the program execute
1039 if (ErrorParsing) exit(1);
1042 //===----------------------------------------------------------------------===//
1043 // Option Base class implementation
1046 bool Option::error(const Twine &Message, StringRef ArgName) {
1047 if (ArgName.data() == 0) ArgName = ArgStr;
1048 if (ArgName.empty())
1049 errs() << HelpStr; // Be nice for positional arguments
1051 errs() << ProgramName << ": for the -" << ArgName;
1053 errs() << " option: " << Message << "\n";
1057 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
1058 StringRef Value, bool MultiArg) {
1060 NumOccurrences++; // Increment the number of times we have been seen
1062 switch (getNumOccurrencesFlag()) {
1064 if (NumOccurrences > 1)
1065 return error("may only occur zero or one times!", ArgName);
1068 if (NumOccurrences > 1)
1069 return error("must occur exactly one time!", ArgName);
1073 case ConsumeAfter: break;
1076 return handleOccurrence(pos, ArgName, Value);
1080 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1081 // has been specified yet.
1083 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1084 if (O.ValueStr[0] == 0) return DefaultMsg;
1088 //===----------------------------------------------------------------------===//
1089 // cl::alias class implementation
1092 // Return the width of the option tag for printing...
1093 size_t alias::getOptionWidth() const {
1094 return std::strlen(ArgStr)+6;
1097 static void printHelpStr(StringRef HelpStr, size_t Indent,
1098 size_t FirstLineIndentedBy) {
1099 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1100 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1101 while (!Split.second.empty()) {
1102 Split = Split.second.split('\n');
1103 outs().indent(Indent) << Split.first << "\n";
1107 // Print out the option for the alias.
1108 void alias::printOptionInfo(size_t GlobalWidth) const {
1109 outs() << " -" << ArgStr;
1110 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1113 //===----------------------------------------------------------------------===//
1114 // Parser Implementation code...
1117 // basic_parser implementation
1120 // Return the width of the option tag for printing...
1121 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1122 size_t Len = std::strlen(O.ArgStr);
1123 if (const char *ValName = getValueName())
1124 Len += std::strlen(getValueStr(O, ValName))+3;
1129 // printOptionInfo - Print out information about this option. The
1130 // to-be-maintained width is specified.
1132 void basic_parser_impl::printOptionInfo(const Option &O,
1133 size_t GlobalWidth) const {
1134 outs() << " -" << O.ArgStr;
1136 if (const char *ValName = getValueName())
1137 outs() << "=<" << getValueStr(O, ValName) << '>';
1139 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1142 void basic_parser_impl::printOptionName(const Option &O,
1143 size_t GlobalWidth) const {
1144 outs() << " -" << O.ArgStr;
1145 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1149 // parser<bool> implementation
1151 bool parser<bool>::parse(Option &O, StringRef ArgName,
1152 StringRef Arg, bool &Value) {
1153 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1159 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1163 return O.error("'" + Arg +
1164 "' is invalid value for boolean argument! Try 0 or 1");
1167 // parser<boolOrDefault> implementation
1169 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
1170 StringRef Arg, boolOrDefault &Value) {
1171 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1176 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1181 return O.error("'" + Arg +
1182 "' is invalid value for boolean argument! Try 0 or 1");
1185 // parser<int> implementation
1187 bool parser<int>::parse(Option &O, StringRef ArgName,
1188 StringRef Arg, int &Value) {
1189 if (Arg.getAsInteger(0, Value))
1190 return O.error("'" + Arg + "' value invalid for integer argument!");
1194 // parser<unsigned> implementation
1196 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1197 StringRef Arg, unsigned &Value) {
1199 if (Arg.getAsInteger(0, Value))
1200 return O.error("'" + Arg + "' value invalid for uint argument!");
1204 // parser<unsigned long long> implementation
1206 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1207 StringRef Arg, unsigned long long &Value){
1209 if (Arg.getAsInteger(0, Value))
1210 return O.error("'" + Arg + "' value invalid for uint argument!");
1214 // parser<double>/parser<float> implementation
1216 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1217 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1218 const char *ArgStart = TmpStr.c_str();
1220 Value = strtod(ArgStart, &End);
1222 return O.error("'" + Arg + "' value invalid for floating point argument!");
1226 bool parser<double>::parse(Option &O, StringRef ArgName,
1227 StringRef Arg, double &Val) {
1228 return parseDouble(O, Arg, Val);
1231 bool parser<float>::parse(Option &O, StringRef ArgName,
1232 StringRef Arg, float &Val) {
1234 if (parseDouble(O, Arg, dVal))
1242 // generic_parser_base implementation
1245 // findOption - Return the option number corresponding to the specified
1246 // argument string. If the option is not found, getNumOptions() is returned.
1248 unsigned generic_parser_base::findOption(const char *Name) {
1249 unsigned e = getNumOptions();
1251 for (unsigned i = 0; i != e; ++i) {
1252 if (strcmp(getOption(i), Name) == 0)
1259 // Return the width of the option tag for printing...
1260 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1261 if (O.hasArgStr()) {
1262 size_t Size = std::strlen(O.ArgStr)+6;
1263 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1264 Size = std::max(Size, std::strlen(getOption(i))+8);
1267 size_t BaseSize = 0;
1268 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1269 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1274 // printOptionInfo - Print out information about this option. The
1275 // to-be-maintained width is specified.
1277 void generic_parser_base::printOptionInfo(const Option &O,
1278 size_t GlobalWidth) const {
1279 if (O.hasArgStr()) {
1280 outs() << " -" << O.ArgStr;
1281 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1283 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1284 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1285 outs() << " =" << getOption(i);
1286 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1290 outs() << " " << O.HelpStr << '\n';
1291 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1292 const char *Option = getOption(i);
1293 outs() << " -" << Option;
1294 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1299 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1301 // printGenericOptionDiff - Print the value of this option and it's default.
1303 // "Generic" options have each value mapped to a name.
1304 void generic_parser_base::
1305 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1306 const GenericOptionValue &Default,
1307 size_t GlobalWidth) const {
1308 outs() << " -" << O.ArgStr;
1309 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1311 unsigned NumOpts = getNumOptions();
1312 for (unsigned i = 0; i != NumOpts; ++i) {
1313 if (Value.compare(getOptionValue(i)))
1316 outs() << "= " << getOption(i);
1317 size_t L = std::strlen(getOption(i));
1318 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1319 outs().indent(NumSpaces) << " (default: ";
1320 for (unsigned j = 0; j != NumOpts; ++j) {
1321 if (Default.compare(getOptionValue(j)))
1323 outs() << getOption(j);
1329 outs() << "= *unknown option value*\n";
1332 // printOptionDiff - Specializations for printing basic value types.
1334 #define PRINT_OPT_DIFF(T) \
1336 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1337 size_t GlobalWidth) const { \
1338 printOptionName(O, GlobalWidth); \
1341 raw_string_ostream SS(Str); \
1344 outs() << "= " << Str; \
1345 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1346 outs().indent(NumSpaces) << " (default: "; \
1348 outs() << D.getValue(); \
1350 outs() << "*no default*"; \
1354 PRINT_OPT_DIFF(bool)
1355 PRINT_OPT_DIFF(boolOrDefault)
1357 PRINT_OPT_DIFF(unsigned)
1358 PRINT_OPT_DIFF(unsigned long long)
1359 PRINT_OPT_DIFF(double)
1360 PRINT_OPT_DIFF(float)
1361 PRINT_OPT_DIFF(char)
1363 void parser<std::string>::
1364 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1365 size_t GlobalWidth) const {
1366 printOptionName(O, GlobalWidth);
1367 outs() << "= " << V;
1368 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1369 outs().indent(NumSpaces) << " (default: ";
1371 outs() << D.getValue();
1373 outs() << "*no default*";
1377 // Print a placeholder for options that don't yet support printOptionDiff().
1378 void basic_parser_impl::
1379 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1380 printOptionName(O, GlobalWidth);
1381 outs() << "= *cannot print option value*\n";
1384 //===----------------------------------------------------------------------===//
1385 // -help and -help-hidden option implementation
1388 static int OptNameCompare(const void *LHS, const void *RHS) {
1389 typedef std::pair<const char *, Option*> pair_ty;
1391 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1394 // Copy Options into a vector so we can sort them as we like.
1396 sortOpts(StringMap<Option*> &OptMap,
1397 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1399 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1401 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1403 // Ignore really-hidden options.
1404 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1407 // Unless showhidden is set, ignore hidden flags.
1408 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1411 // If we've already seen this option, don't add it to the list again.
1412 if (!OptionSet.insert(I->second))
1415 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1419 // Sort the options list alphabetically.
1420 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1427 const bool ShowHidden;
1428 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1429 // Print the options. Opts is assumed to be alphabetically sorted.
1430 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1431 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1432 Opts[i].second->printOptionInfo(MaxArgLen);
1436 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1437 virtual ~HelpPrinter() {}
1439 // Invoke the printer.
1440 void operator=(bool Value) {
1441 if (Value == false) return;
1443 // Get all the options.
1444 SmallVector<Option*, 4> PositionalOpts;
1445 SmallVector<Option*, 4> SinkOpts;
1446 StringMap<Option*> OptMap;
1447 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1449 StrOptionPairVector Opts;
1450 sortOpts(OptMap, Opts, ShowHidden);
1452 if (ProgramOverview)
1453 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1455 outs() << "USAGE: " << ProgramName << " [options]";
1457 // Print out the positional options.
1458 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
1459 if (!PositionalOpts.empty() &&
1460 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1461 CAOpt = PositionalOpts[0];
1463 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1464 if (PositionalOpts[i]->ArgStr[0])
1465 outs() << " --" << PositionalOpts[i]->ArgStr;
1466 outs() << " " << PositionalOpts[i]->HelpStr;
1469 // Print the consume after option info if it exists...
1470 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1474 // Compute the maximum argument length...
1475 size_t MaxArgLen = 0;
1476 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1477 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1479 outs() << "OPTIONS:\n";
1480 printOptions(Opts, MaxArgLen);
1482 // Print any extra help the user has declared.
1483 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1484 E = MoreHelp->end();
1489 // Halt the program since help information was printed
1494 class CategorizedHelpPrinter : public HelpPrinter {
1496 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1498 // Helper function for printOptions().
1499 // It shall return true if A's name should be lexographically
1500 // ordered before B's name. It returns false otherwise.
1501 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1502 return strcmp(A->getName(), B->getName()) < 0;
1505 // Make sure we inherit our base class's operator=()
1506 using HelpPrinter::operator= ;
1509 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1510 std::vector<OptionCategory *> SortedCategories;
1511 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1513 // Collect registered option categories into vector in preparation for
1515 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1516 E = RegisteredOptionCategories->end();
1518 SortedCategories.push_back(*I);
1521 // Sort the different option categories alphabetically.
1522 assert(SortedCategories.size() > 0 && "No option categories registered!");
1523 std::sort(SortedCategories.begin(), SortedCategories.end(),
1524 OptionCategoryCompare);
1526 // Create map to empty vectors.
1527 for (std::vector<OptionCategory *>::const_iterator
1528 I = SortedCategories.begin(),
1529 E = SortedCategories.end();
1531 CategorizedOptions[*I] = std::vector<Option *>();
1533 // Walk through pre-sorted options and assign into categories.
1534 // Because the options are already alphabetically sorted the
1535 // options within categories will also be alphabetically sorted.
1536 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1537 Option *Opt = Opts[I].second;
1538 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1539 "Option has an unregistered category");
1540 CategorizedOptions[Opt->Category].push_back(Opt);
1544 for (std::vector<OptionCategory *>::const_iterator
1545 Category = SortedCategories.begin(),
1546 E = SortedCategories.end();
1547 Category != E; ++Category) {
1548 // Hide empty categories for -help, but show for -help-hidden.
1549 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1550 if (!ShowHidden && IsEmptyCategory)
1553 // Print category information.
1555 outs() << (*Category)->getName() << ":\n";
1557 // Check if description is set.
1558 if ((*Category)->getDescription() != 0)
1559 outs() << (*Category)->getDescription() << "\n\n";
1563 // When using -help-hidden explicitly state if the category has no
1564 // options associated with it.
1565 if (IsEmptyCategory) {
1566 outs() << " This option category has no options.\n";
1569 // Loop over the options in the category and print.
1570 for (std::vector<Option *>::const_iterator
1571 Opt = CategorizedOptions[*Category].begin(),
1572 E = CategorizedOptions[*Category].end();
1574 (*Opt)->printOptionInfo(MaxArgLen);
1579 // This wraps the Uncategorizing and Categorizing printers and decides
1580 // at run time which should be invoked.
1581 class HelpPrinterWrapper {
1583 HelpPrinter &UncategorizedPrinter;
1584 CategorizedHelpPrinter &CategorizedPrinter;
1587 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1588 CategorizedHelpPrinter &CategorizedPrinter) :
1589 UncategorizedPrinter(UncategorizedPrinter),
1590 CategorizedPrinter(CategorizedPrinter) { }
1592 // Invoke the printer.
1593 void operator=(bool Value);
1596 } // End anonymous namespace
1598 // Declare the four HelpPrinter instances that are used to print out help, or
1599 // help-hidden as an uncategorized list or in categories.
1600 static HelpPrinter UncategorizedNormalPrinter(false);
1601 static HelpPrinter UncategorizedHiddenPrinter(true);
1602 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1603 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1606 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1607 // a categorizing help printer
1608 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1609 CategorizedNormalPrinter);
1610 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1611 CategorizedHiddenPrinter);
1613 // Define uncategorized help printers.
1614 // -help-list is hidden by default because if Option categories are being used
1615 // then -help behaves the same as -help-list.
1616 static cl::opt<HelpPrinter, true, parser<bool> >
1618 cl::desc("Display list of available options (-help-list-hidden for more)"),
1619 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1621 static cl::opt<HelpPrinter, true, parser<bool> >
1622 HLHOp("help-list-hidden",
1623 cl::desc("Display list of all available options"),
1624 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1626 // Define uncategorized/categorized help printers. These printers change their
1627 // behaviour at runtime depending on whether one or more Option categories have
1629 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1630 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1631 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1633 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1634 HHOp("help-hidden", cl::desc("Display all available options"),
1635 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1639 static cl::opt<bool>
1640 PrintOptions("print-options",
1641 cl::desc("Print non-default options after command line parsing"),
1642 cl::Hidden, cl::init(false));
1644 static cl::opt<bool>
1645 PrintAllOptions("print-all-options",
1646 cl::desc("Print all option values after command line parsing"),
1647 cl::Hidden, cl::init(false));
1649 void HelpPrinterWrapper::operator=(bool Value) {
1653 // Decide which printer to invoke. If more than one option category is
1654 // registered then it is useful to show the categorized help instead of
1655 // uncategorized help.
1656 if (RegisteredOptionCategories->size() > 1) {
1657 // unhide -help-list option so user can have uncategorized output if they
1659 HLOp.setHiddenFlag(NotHidden);
1661 CategorizedPrinter = true; // Invoke categorized printer
1664 UncategorizedPrinter = true; // Invoke uncategorized printer
1667 // Print the value of each option.
1668 void cl::PrintOptionValues() {
1669 if (!PrintOptions && !PrintAllOptions) return;
1671 // Get all the options.
1672 SmallVector<Option*, 4> PositionalOpts;
1673 SmallVector<Option*, 4> SinkOpts;
1674 StringMap<Option*> OptMap;
1675 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1677 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1678 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1680 // Compute the maximum argument length...
1681 size_t MaxArgLen = 0;
1682 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1683 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1685 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1686 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1689 static void (*OverrideVersionPrinter)() = 0;
1691 static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1694 class VersionPrinter {
1697 raw_ostream &OS = outs();
1698 OS << "LLVM (http://llvm.org/):\n"
1699 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1700 #ifdef LLVM_VERSION_INFO
1701 OS << LLVM_VERSION_INFO;
1704 #ifndef __OPTIMIZE__
1705 OS << "DEBUG build";
1707 OS << "Optimized build";
1710 OS << " with assertions";
1712 std::string CPU = sys::getHostCPUName();
1713 if (CPU == "generic") CPU = "(unknown)";
1715 #if (ENABLE_TIMESTAMPS == 1)
1716 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1718 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1719 << " Host CPU: " << CPU << '\n';
1721 void operator=(bool OptionWasSpecified) {
1722 if (!OptionWasSpecified) return;
1724 if (OverrideVersionPrinter != 0) {
1725 (*OverrideVersionPrinter)();
1730 // Iterate over any registered extra printers and call them to add further
1732 if (ExtraVersionPrinters != 0) {
1734 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1735 E = ExtraVersionPrinters->end();
1743 } // End anonymous namespace
1746 // Define the --version option that prints out the LLVM version for the tool
1747 static VersionPrinter VersionPrinterInstance;
1749 static cl::opt<VersionPrinter, true, parser<bool> >
1750 VersOp("version", cl::desc("Display the version of this program"),
1751 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1753 // Utility function for printing the help message.
1754 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1755 // This looks weird, but it actually prints the help message. The Printers are
1756 // types of HelpPrinter and the help gets printed when its operator= is
1757 // invoked. That's because the "normal" usages of the help printer is to be
1758 // assigned true/false depending on whether -help or -help-hidden was given or
1759 // not. Since we're circumventing that we have to make it look like -help or
1760 // -help-hidden were given, so we assign true.
1762 if (!Hidden && !Categorized)
1763 UncategorizedNormalPrinter = true;
1764 else if (!Hidden && Categorized)
1765 CategorizedNormalPrinter = true;
1766 else if (Hidden && !Categorized)
1767 UncategorizedHiddenPrinter = true;
1769 CategorizedHiddenPrinter = true;
1772 /// Utility function for printing version number.
1773 void cl::PrintVersionMessage() {
1774 VersionPrinterInstance.print();
1777 void cl::SetVersionPrinter(void (*func)()) {
1778 OverrideVersionPrinter = func;
1781 void cl::AddExtraVersionPrinter(void (*func)()) {
1782 if (ExtraVersionPrinters == 0)
1783 ExtraVersionPrinters = new std::vector<void (*)()>;
1785 ExtraVersionPrinters->push_back(func);
1788 void cl::getRegisteredOptions(StringMap<Option*> &Map)
1790 // Get all the options.
1791 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1792 SmallVector<Option*, 4> SinkOpts; //NOT USED
1793 assert(Map.size() == 0 && "StringMap must be empty");
1794 GetOptionInfo(PositionalOpts, SinkOpts, Map);