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-c/Support.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Config/config.h"
28 #include "llvm/Support/ConvertUTF.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/StringSaver.h"
36 #include "llvm/Support/raw_ostream.h"
42 #define DEBUG_TYPE "commandline"
44 //===----------------------------------------------------------------------===//
45 // Template instantiations and anchors.
49 template class basic_parser<bool>;
50 template class basic_parser<boolOrDefault>;
51 template class basic_parser<int>;
52 template class basic_parser<unsigned>;
53 template class basic_parser<unsigned long long>;
54 template class basic_parser<double>;
55 template class basic_parser<float>;
56 template class basic_parser<std::string>;
57 template class basic_parser<char>;
59 template class opt<unsigned>;
60 template class opt<int>;
61 template class opt<std::string>;
62 template class opt<char>;
63 template class opt<bool>;
65 } // end namespace llvm::cl
67 // Pin the vtables to this file.
68 void GenericOptionValue::anchor() {}
69 void OptionValue<boolOrDefault>::anchor() {}
70 void OptionValue<std::string>::anchor() {}
71 void Option::anchor() {}
72 void basic_parser_impl::anchor() {}
73 void parser<bool>::anchor() {}
74 void parser<boolOrDefault>::anchor() {}
75 void parser<int>::anchor() {}
76 void parser<unsigned>::anchor() {}
77 void parser<unsigned long long>::anchor() {}
78 void parser<double>::anchor() {}
79 void parser<float>::anchor() {}
80 void parser<std::string>::anchor() {}
81 void parser<char>::anchor() {}
83 //===----------------------------------------------------------------------===//
87 class CommandLineParser {
89 // Globals for name and overview of program. Program name is not a string to
90 // avoid static ctor/dtor issues.
91 std::string ProgramName;
92 const char *ProgramOverview;
94 // This collects additional help to be printed.
95 std::vector<const char *> MoreHelp;
97 SmallVector<Option *, 4> PositionalOpts;
98 SmallVector<Option *, 4> SinkOpts;
99 StringMap<Option *> OptionsMap;
101 Option *ConsumeAfterOpt; // The ConsumeAfter option if it exists.
103 // This collects the different option categories that have been registered.
104 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
106 CommandLineParser() : ProgramOverview(nullptr), ConsumeAfterOpt(nullptr) {}
108 void ParseCommandLineOptions(int argc, const char *const *argv,
109 const char *Overview);
111 void addLiteralOption(Option &Opt, const char *Name) {
112 if (!Opt.hasArgStr()) {
113 if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
114 errs() << ProgramName << ": CommandLine Error: Option '" << Name
115 << "' registered more than once!\n";
116 report_fatal_error("inconsistency in registered CommandLine options");
121 void addOption(Option *O) {
122 bool HadErrors = false;
123 if (O->hasArgStr()) {
124 // Add argument to the argument map!
125 if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
126 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
127 << "' registered more than once!\n";
132 // Remember information about positional options.
133 if (O->getFormattingFlag() == cl::Positional)
134 PositionalOpts.push_back(O);
135 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
136 SinkOpts.push_back(O);
137 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
138 if (ConsumeAfterOpt) {
139 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
145 // Fail hard if there were errors. These are strictly unrecoverable and
146 // indicate serious issues such as conflicting option names or an
148 // linked LLVM distribution.
150 report_fatal_error("inconsistency in registered CommandLine options");
153 void removeOption(Option *O) {
154 SmallVector<StringRef, 16> OptionNames;
155 O->getExtraOptionNames(OptionNames);
157 OptionNames.push_back(O->ArgStr);
158 for (auto Name : OptionNames)
159 OptionsMap.erase(Name);
161 if (O->getFormattingFlag() == cl::Positional)
162 for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
165 PositionalOpts.erase(Opt);
169 else if (O->getMiscFlags() & cl::Sink)
170 for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
176 else if (O == ConsumeAfterOpt)
177 ConsumeAfterOpt = nullptr;
181 return (!OptionsMap.empty() || !PositionalOpts.empty() ||
182 nullptr != ConsumeAfterOpt);
185 void updateArgStr(Option *O, StringRef NewName) {
186 if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
187 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
188 << "' registered more than once!\n";
189 report_fatal_error("inconsistency in registered CommandLine options");
191 OptionsMap.erase(O->ArgStr);
194 void printOptionValues();
196 void registerCategory(OptionCategory *cat) {
197 assert(std::count_if(RegisteredOptionCategories.begin(),
198 RegisteredOptionCategories.end(),
199 [cat](const OptionCategory *Category) {
200 return cat->getName() == Category->getName();
202 "Duplicate option categories");
204 RegisteredOptionCategories.insert(cat);
208 Option *LookupOption(StringRef &Arg, StringRef &Value);
213 static ManagedStatic<CommandLineParser> GlobalParser;
215 void cl::AddLiteralOption(Option &O, const char *Name) {
216 GlobalParser->addLiteralOption(O, Name);
219 extrahelp::extrahelp(const char *Help) : morehelp(Help) {
220 GlobalParser->MoreHelp.push_back(Help);
223 void Option::addArgument() {
224 GlobalParser->addOption(this);
225 FullyInitialized = true;
228 void Option::removeArgument() { GlobalParser->removeOption(this); }
230 void Option::setArgStr(StringRef S) {
231 if (FullyInitialized)
232 GlobalParser->updateArgStr(this, S);
236 // Initialise the general option category.
237 OptionCategory llvm::cl::GeneralCategory("General options");
239 void OptionCategory::registerCategory() {
240 GlobalParser->registerCategory(this);
243 //===----------------------------------------------------------------------===//
244 // Basic, shared command line option processing machinery.
247 /// LookupOption - Lookup the option specified by the specified option on the
248 /// command line. If there is a value specified (after an equal sign) return
249 /// that as well. This assumes that leading dashes have already been stripped.
250 Option *CommandLineParser::LookupOption(StringRef &Arg, StringRef &Value) {
251 // Reject all dashes.
255 size_t EqualPos = Arg.find('=');
257 // If we have an equals sign, remember the value.
258 if (EqualPos == StringRef::npos) {
259 // Look up the option.
260 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
261 return I != OptionsMap.end() ? I->second : nullptr;
264 // If the argument before the = is a valid option name, we match. If not,
265 // return Arg unmolested.
266 StringMap<Option *>::const_iterator I =
267 OptionsMap.find(Arg.substr(0, EqualPos));
268 if (I == OptionsMap.end())
271 Value = Arg.substr(EqualPos + 1);
272 Arg = Arg.substr(0, EqualPos);
276 /// LookupNearestOption - Lookup the closest match to the option specified by
277 /// the specified option on the command line. If there is a value specified
278 /// (after an equal sign) return that as well. This assumes that leading dashes
279 /// have already been stripped.
280 static Option *LookupNearestOption(StringRef Arg,
281 const StringMap<Option *> &OptionsMap,
282 std::string &NearestString) {
283 // Reject all dashes.
287 // Split on any equal sign.
288 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
289 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
290 StringRef &RHS = SplitArg.second;
292 // Find the closest match.
293 Option *Best = nullptr;
294 unsigned BestDistance = 0;
295 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
296 ie = OptionsMap.end();
298 Option *O = it->second;
299 SmallVector<StringRef, 16> OptionNames;
300 O->getExtraOptionNames(OptionNames);
302 OptionNames.push_back(O->ArgStr);
304 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
305 StringRef Flag = PermitValue ? LHS : Arg;
306 for (auto Name : OptionNames) {
307 unsigned Distance = StringRef(Name).edit_distance(
308 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
309 if (!Best || Distance < BestDistance) {
311 BestDistance = Distance;
312 if (RHS.empty() || !PermitValue)
313 NearestString = Name;
315 NearestString = (Twine(Name) + "=" + RHS).str();
323 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
324 /// that does special handling of cl::CommaSeparated options.
325 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
326 StringRef ArgName, StringRef Value,
327 bool MultiArg = false) {
328 // Check to see if this option accepts a comma separated list of values. If
329 // it does, we have to split up the value into multiple values.
330 if (Handler->getMiscFlags() & CommaSeparated) {
331 StringRef Val(Value);
332 StringRef::size_type Pos = Val.find(',');
334 while (Pos != StringRef::npos) {
335 // Process the portion before the comma.
336 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
338 // Erase the portion before the comma, AND the comma.
339 Val = Val.substr(Pos + 1);
340 Value.substr(Pos + 1); // Increment the original value pointer as well.
341 // Check for another comma.
348 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
354 /// ProvideOption - For Value, this differentiates between an empty value ("")
355 /// and a null value (StringRef()). The later is accepted for arguments that
356 /// don't allow a value (-foo) the former is rejected (-foo=).
357 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
358 StringRef Value, int argc,
359 const char *const *argv, int &i) {
360 // Is this a multi-argument option?
361 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
363 // Enforce value requirements
364 switch (Handler->getValueExpectedFlag()) {
366 if (!Value.data()) { // No value specified?
368 return Handler->error("requires a value!");
369 // Steal the next argument, like for '-o filename'
370 assert(argv && "null check");
374 case ValueDisallowed:
375 if (NumAdditionalVals > 0)
376 return Handler->error("multi-valued option specified"
377 " with ValueDisallowed modifier!");
380 return Handler->error("does not allow a value! '" + Twine(Value) +
387 // If this isn't a multi-arg option, just run the handler.
388 if (NumAdditionalVals == 0)
389 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
391 // If it is, run the handle several times.
392 bool MultiArg = false;
395 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
401 while (NumAdditionalVals > 0) {
403 return Handler->error("not enough values!");
404 assert(argv && "null check");
407 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
415 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
417 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
420 // Option predicates...
421 static inline bool isGrouping(const Option *O) {
422 return O->getFormattingFlag() == cl::Grouping;
424 static inline bool isPrefixedOrGrouping(const Option *O) {
425 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
428 // getOptionPred - Check to see if there are any options that satisfy the
429 // specified predicate with names that are the prefixes in Name. This is
430 // checked by progressively stripping characters off of the name, checking to
431 // see if there options that satisfy the predicate. If we find one, return it,
432 // otherwise return null.
434 static Option *getOptionPred(StringRef Name, size_t &Length,
435 bool (*Pred)(const Option *),
436 const StringMap<Option *> &OptionsMap) {
438 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
440 // Loop while we haven't found an option and Name still has at least two
441 // characters in it (so that the next iteration will not be the empty
443 while (OMI == OptionsMap.end() && Name.size() > 1) {
444 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
445 OMI = OptionsMap.find(Name);
448 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
449 Length = Name.size();
450 return OMI->second; // Found one!
452 return nullptr; // No option found!
455 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
456 /// with at least one '-') does not fully match an available option. Check to
457 /// see if this is a prefix or grouped option. If so, split arg into output an
458 /// Arg/Value pair and return the Option to parse it with.
460 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
462 const StringMap<Option *> &OptionsMap) {
468 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
472 // If the option is a prefixed option, then the value is simply the
473 // rest of the name... so fall through to later processing, by
474 // setting up the argument name flags and value fields.
475 if (PGOpt->getFormattingFlag() == cl::Prefix) {
476 Value = Arg.substr(Length);
477 Arg = Arg.substr(0, Length);
478 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
482 // This must be a grouped option... handle them now. Grouping options can't
484 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
487 // Move current arg name out of Arg into OneArgName.
488 StringRef OneArgName = Arg.substr(0, Length);
489 Arg = Arg.substr(Length);
491 // Because ValueRequired is an invalid flag for grouped arguments,
492 // we don't need to pass argc/argv in.
493 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
494 "Option can not be cl::Grouping AND cl::ValueRequired!");
497 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
499 // Get the next grouping option.
500 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
501 } while (PGOpt && Length != Arg.size());
503 // Return the last option with Arg cut down to just the last one.
507 static bool RequiresValue(const Option *O) {
508 return O->getNumOccurrencesFlag() == cl::Required ||
509 O->getNumOccurrencesFlag() == cl::OneOrMore;
512 static bool EatsUnboundedNumberOfValues(const Option *O) {
513 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
514 O->getNumOccurrencesFlag() == cl::OneOrMore;
517 static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
519 static bool isQuote(char C) { return C == '\"' || C == '\''; }
521 static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
523 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
524 SmallVectorImpl<const char *> &NewArgv,
526 SmallString<128> Token;
527 for (size_t I = 0, E = Src.size(); I != E; ++I) {
528 // Consume runs of whitespace.
530 while (I != E && isWhitespace(Src[I])) {
531 // Mark the end of lines in response files
532 if (MarkEOLs && Src[I] == '\n')
533 NewArgv.push_back(nullptr);
540 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
541 // they are literal. This makes it much easier to read Windows file paths.
542 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
543 ++I; // Skip the escape.
544 Token.push_back(Src[I]);
548 // Consume a quoted string.
549 if (isQuote(Src[I])) {
550 char Quote = Src[I++];
551 while (I != E && Src[I] != Quote) {
552 // Backslashes are literal, unless they escape a special character.
553 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
555 Token.push_back(Src[I]);
563 // End the token if this is whitespace.
564 if (isWhitespace(Src[I])) {
566 NewArgv.push_back(Saver.save(Token.c_str()));
571 // This is a normal character. Append it.
572 Token.push_back(Src[I]);
575 // Append the last token after hitting EOF with no whitespace.
577 NewArgv.push_back(Saver.save(Token.c_str()));
578 // Mark the end of response files
580 NewArgv.push_back(nullptr);
583 /// Backslashes are interpreted in a rather complicated way in the Windows-style
584 /// command line, because backslashes are used both to separate path and to
585 /// escape double quote. This method consumes runs of backslashes as well as the
586 /// following double quote if it's escaped.
588 /// * If an even number of backslashes is followed by a double quote, one
589 /// backslash is output for every pair of backslashes, and the last double
590 /// quote remains unconsumed. The double quote will later be interpreted as
591 /// the start or end of a quoted string in the main loop outside of this
594 /// * If an odd number of backslashes is followed by a double quote, one
595 /// backslash is output for every pair of backslashes, and a double quote is
596 /// output for the last pair of backslash-double quote. The double quote is
597 /// consumed in this case.
599 /// * Otherwise, backslashes are interpreted literally.
600 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
601 size_t E = Src.size();
602 int BackslashCount = 0;
603 // Skip the backslashes.
607 } while (I != E && Src[I] == '\\');
609 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
610 if (FollowedByDoubleQuote) {
611 Token.append(BackslashCount / 2, '\\');
612 if (BackslashCount % 2 == 0)
614 Token.push_back('"');
617 Token.append(BackslashCount, '\\');
621 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
622 SmallVectorImpl<const char *> &NewArgv,
624 SmallString<128> Token;
626 // This is a small state machine to consume characters until it reaches the
627 // end of the source string.
628 enum { INIT, UNQUOTED, QUOTED } State = INIT;
629 for (size_t I = 0, E = Src.size(); I != E; ++I) {
630 // INIT state indicates that the current input index is at the start of
631 // the string or between tokens.
633 if (isWhitespace(Src[I])) {
634 // Mark the end of lines in response files
635 if (MarkEOLs && Src[I] == '\n')
636 NewArgv.push_back(nullptr);
643 if (Src[I] == '\\') {
644 I = parseBackslash(Src, I, Token);
648 Token.push_back(Src[I]);
653 // UNQUOTED state means that it's reading a token not quoted by double
655 if (State == UNQUOTED) {
656 // Whitespace means the end of the token.
657 if (isWhitespace(Src[I])) {
658 NewArgv.push_back(Saver.save(Token.c_str()));
661 // Mark the end of lines in response files
662 if (MarkEOLs && Src[I] == '\n')
663 NewArgv.push_back(nullptr);
670 if (Src[I] == '\\') {
671 I = parseBackslash(Src, I, Token);
674 Token.push_back(Src[I]);
678 // QUOTED state means that it's reading a token quoted by double quotes.
679 if (State == QUOTED) {
684 if (Src[I] == '\\') {
685 I = parseBackslash(Src, I, Token);
688 Token.push_back(Src[I]);
691 // Append the last token after hitting EOF with no whitespace.
693 NewArgv.push_back(Saver.save(Token.c_str()));
694 // Mark the end of response files
696 NewArgv.push_back(nullptr);
699 // It is called byte order marker but the UTF-8 BOM is actually not affected
700 // by the host system's endianness.
701 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
702 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
705 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
706 TokenizerCallback Tokenizer,
707 SmallVectorImpl<const char *> &NewArgv,
708 bool MarkEOLs = false) {
709 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
710 MemoryBuffer::getFile(FName);
713 MemoryBuffer &MemBuf = *MemBufOrErr.get();
714 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
716 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
717 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
719 if (hasUTF16ByteOrderMark(BufRef)) {
720 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
722 Str = StringRef(UTF8Buf);
724 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
725 // these bytes before parsing.
726 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
727 else if (hasUTF8ByteOrderMark(BufRef))
728 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
730 // Tokenize the contents into NewArgv.
731 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
736 /// \brief Expand response files on a command line recursively using the given
737 /// StringSaver and tokenization strategy.
738 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
739 SmallVectorImpl<const char *> &Argv,
741 unsigned RspFiles = 0;
742 bool AllExpanded = true;
744 // Don't cache Argv.size() because it can change.
745 for (unsigned I = 0; I != Argv.size();) {
746 const char *Arg = Argv[I];
747 // Check if it is an EOL marker
748 if (Arg == nullptr) {
757 // If we have too many response files, leave some unexpanded. This avoids
758 // crashing on self-referential response files.
762 // Replace this response file argument with the tokenization of its
763 // contents. Nested response files are expanded in subsequent iterations.
764 // FIXME: If a nested response file uses a relative path, is it relative to
765 // the cwd of the process or the response file?
766 SmallVector<const char *, 0> ExpandedArgv;
767 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
769 // We couldn't read this file, so we leave it in the argument stream and
775 Argv.erase(Argv.begin() + I);
776 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
781 /// ParseEnvironmentOptions - An alternative entry point to the
782 /// CommandLine library, which allows you to read the program's name
783 /// from the caller (as PROGNAME) and its command-line arguments from
784 /// an environment variable (whose name is given in ENVVAR).
786 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
787 const char *Overview) {
789 assert(progName && "Program name not specified");
790 assert(envVar && "Environment variable name missing");
792 // Get the environment variable they want us to parse options out of.
793 const char *envValue = getenv(envVar);
797 // Get program's "name", which we wouldn't know without the caller
799 SmallVector<const char *, 20> newArgv;
801 StringSaver Saver(A);
802 newArgv.push_back(Saver.save(progName));
804 // Parse the value of the environment variable into a "command line"
805 // and hand it off to ParseCommandLineOptions().
806 TokenizeGNUCommandLine(envValue, Saver, newArgv);
807 int newArgc = static_cast<int>(newArgv.size());
808 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
811 void cl::ParseCommandLineOptions(int argc, const char *const *argv,
812 const char *Overview) {
813 GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
816 void CommandLineParser::ParseCommandLineOptions(int argc,
817 const char *const *argv,
818 const char *Overview) {
819 assert(hasOptions() && "No options specified!");
821 // Expand response files.
822 SmallVector<const char *, 20> newArgv(argv, argv + argc);
824 StringSaver Saver(A);
825 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
827 argc = static_cast<int>(newArgv.size());
829 // Copy the program name into ProgName, making sure not to overflow it.
830 ProgramName = sys::path::filename(argv[0]);
832 ProgramOverview = Overview;
833 bool ErrorParsing = false;
835 // Check out the positional arguments to collect information about them.
836 unsigned NumPositionalRequired = 0;
838 // Determine whether or not there are an unlimited number of positionals
839 bool HasUnlimitedPositionals = false;
841 if (ConsumeAfterOpt) {
842 assert(PositionalOpts.size() > 0 &&
843 "Cannot specify cl::ConsumeAfter without a positional argument!");
845 if (!PositionalOpts.empty()) {
847 // Calculate how many positional values are _required_.
848 bool UnboundedFound = false;
849 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
850 Option *Opt = PositionalOpts[i];
851 if (RequiresValue(Opt))
852 ++NumPositionalRequired;
853 else if (ConsumeAfterOpt) {
854 // ConsumeAfter cannot be combined with "optional" positional options
855 // unless there is only one positional argument...
856 if (PositionalOpts.size() > 1)
857 ErrorParsing |= Opt->error(
858 "error - this positional option will never be matched, "
859 "because it does not Require a value, and a "
860 "cl::ConsumeAfter option is active!");
861 } else if (UnboundedFound && !Opt->hasArgStr()) {
862 // This option does not "require" a value... Make sure this option is
863 // not specified after an option that eats all extra arguments, or this
864 // one will never get any!
866 ErrorParsing |= Opt->error("error - option can never match, because "
867 "another positional argument will match an "
868 "unbounded number of values, and this option"
869 " does not require a value!");
870 errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
871 << "' is all messed up!\n";
872 errs() << PositionalOpts.size();
874 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
876 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
879 // PositionalVals - A vector of "positional" arguments we accumulate into
880 // the process at the end.
882 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
884 // If the program has named positional arguments, and the name has been run
885 // across, keep track of which positional argument was named. Otherwise put
886 // the positional args into the PositionalVals list...
887 Option *ActivePositionalArg = nullptr;
889 // Loop over all of the arguments... processing them.
890 bool DashDashFound = false; // Have we read '--'?
891 for (int i = 1; i < argc; ++i) {
892 Option *Handler = nullptr;
893 Option *NearestHandler = nullptr;
894 std::string NearestHandlerString;
896 StringRef ArgName = "";
898 // Check to see if this is a positional argument. This argument is
899 // considered to be positional if it doesn't start with '-', if it is "-"
900 // itself, or if we have seen "--" already.
902 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
903 // Positional argument!
904 if (ActivePositionalArg) {
905 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
906 continue; // We are done!
909 if (!PositionalOpts.empty()) {
910 PositionalVals.push_back(std::make_pair(argv[i], i));
912 // All of the positional arguments have been fulfulled, give the rest to
913 // the consume after option... if it's specified...
915 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
916 for (++i; i < argc; ++i)
917 PositionalVals.push_back(std::make_pair(argv[i], i));
918 break; // Handle outside of the argument processing loop...
921 // Delay processing positional arguments until the end...
924 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
926 DashDashFound = true; // This is the mythical "--"?
927 continue; // Don't try to process it as an argument itself.
928 } else if (ActivePositionalArg &&
929 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
930 // If there is a positional argument eating options, check to see if this
931 // option is another positional argument. If so, treat it as an argument,
932 // otherwise feed it to the eating positional.
933 ArgName = argv[i] + 1;
934 // Eat leading dashes.
935 while (!ArgName.empty() && ArgName[0] == '-')
936 ArgName = ArgName.substr(1);
938 Handler = LookupOption(ArgName, Value);
939 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
940 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
941 continue; // We are done!
944 } else { // We start with a '-', must be an argument.
945 ArgName = argv[i] + 1;
946 // Eat leading dashes.
947 while (!ArgName.empty() && ArgName[0] == '-')
948 ArgName = ArgName.substr(1);
950 Handler = LookupOption(ArgName, Value);
952 // Check to see if this "option" is really a prefixed or grouped argument.
954 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
957 // Otherwise, look for the closest available option to report to the user
958 // in the upcoming error.
959 if (!Handler && SinkOpts.empty())
961 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
965 if (SinkOpts.empty()) {
966 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
967 << "'. Try: '" << argv[0] << " -help'\n";
969 if (NearestHandler) {
970 // If we know a near match, report it as well.
971 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
977 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
980 (*I)->addOccurrence(i, "", argv[i]);
985 // If this is a named positional argument, just remember that it is the
987 if (Handler->getFormattingFlag() == cl::Positional)
988 ActivePositionalArg = Handler;
990 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
993 // Check and handle positional arguments now...
994 if (NumPositionalRequired > PositionalVals.size()) {
995 errs() << ProgramName
996 << ": Not enough positional command line arguments specified!\n"
997 << "Must specify at least " << NumPositionalRequired
998 << " positional arguments: See: " << argv[0] << " -help\n";
1000 ErrorParsing = true;
1001 } else if (!HasUnlimitedPositionals &&
1002 PositionalVals.size() > PositionalOpts.size()) {
1003 errs() << ProgramName << ": Too many positional arguments specified!\n"
1004 << "Can specify at most " << PositionalOpts.size()
1005 << " positional arguments: See: " << argv[0] << " -help\n";
1006 ErrorParsing = true;
1008 } else if (!ConsumeAfterOpt) {
1009 // Positional args have already been handled if ConsumeAfter is specified.
1010 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1011 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1012 if (RequiresValue(PositionalOpts[i])) {
1013 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1014 PositionalVals[ValNo].second);
1016 --NumPositionalRequired; // We fulfilled our duty...
1019 // If we _can_ give this option more arguments, do so now, as long as we
1020 // do not give it values that others need. 'Done' controls whether the
1021 // option even _WANTS_ any more.
1023 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1024 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1025 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1027 Done = true; // Optional arguments want _at most_ one value
1029 case cl::ZeroOrMore: // Zero or more will take all they can get...
1030 case cl::OneOrMore: // One or more will take all they can get...
1031 ProvidePositionalOption(PositionalOpts[i],
1032 PositionalVals[ValNo].first,
1033 PositionalVals[ValNo].second);
1037 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1038 "positional argument processing!");
1043 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1045 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1046 if (RequiresValue(PositionalOpts[j])) {
1047 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1048 PositionalVals[ValNo].first,
1049 PositionalVals[ValNo].second);
1053 // Handle the case where there is just one positional option, and it's
1054 // optional. In this case, we want to give JUST THE FIRST option to the
1055 // positional option and keep the rest for the consume after. The above
1056 // loop would have assigned no values to positional options in this case.
1058 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1059 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1060 PositionalVals[ValNo].first,
1061 PositionalVals[ValNo].second);
1065 // Handle over all of the rest of the arguments to the
1066 // cl::ConsumeAfter command line option...
1067 for (; ValNo != PositionalVals.size(); ++ValNo)
1069 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1070 PositionalVals[ValNo].second);
1073 // Loop over args and make sure all required args are specified!
1074 for (const auto &Opt : OptionsMap) {
1075 switch (Opt.second->getNumOccurrencesFlag()) {
1078 if (Opt.second->getNumOccurrences() == 0) {
1079 Opt.second->error("must be specified at least once!");
1080 ErrorParsing = true;
1088 // Now that we know if -debug is specified, we can use it.
1089 // Note that if ReadResponseFiles == true, this must be done before the
1090 // memory allocated for the expanded command line is free()d below.
1091 DEBUG(dbgs() << "Args: ";
1092 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1095 // Free all of the memory allocated to the map. Command line options may only
1096 // be processed once!
1099 // If we had an error processing our arguments, don't let the program execute
1104 //===----------------------------------------------------------------------===//
1105 // Option Base class implementation
1108 bool Option::error(const Twine &Message, StringRef ArgName) {
1109 if (!ArgName.data())
1111 if (ArgName.empty())
1112 errs() << HelpStr; // Be nice for positional arguments
1114 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1116 errs() << " option: " << Message << "\n";
1120 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1123 NumOccurrences++; // Increment the number of times we have been seen
1125 switch (getNumOccurrencesFlag()) {
1127 if (NumOccurrences > 1)
1128 return error("may only occur zero or one times!", ArgName);
1131 if (NumOccurrences > 1)
1132 return error("must occur exactly one time!", ArgName);
1140 return handleOccurrence(pos, ArgName, Value);
1143 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1144 // has been specified yet.
1146 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1147 if (O.ValueStr.empty())
1152 //===----------------------------------------------------------------------===//
1153 // cl::alias class implementation
1156 // Return the width of the option tag for printing...
1157 size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
1159 static void printHelpStr(StringRef HelpStr, size_t Indent,
1160 size_t FirstLineIndentedBy) {
1161 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1162 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1163 while (!Split.second.empty()) {
1164 Split = Split.second.split('\n');
1165 outs().indent(Indent) << Split.first << "\n";
1169 // Print out the option for the alias.
1170 void alias::printOptionInfo(size_t GlobalWidth) const {
1171 outs() << " -" << ArgStr;
1172 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
1175 //===----------------------------------------------------------------------===//
1176 // Parser Implementation code...
1179 // basic_parser implementation
1182 // Return the width of the option tag for printing...
1183 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1184 size_t Len = O.ArgStr.size();
1185 if (const char *ValName = getValueName())
1186 Len += getValueStr(O, ValName).size() + 3;
1191 // printOptionInfo - Print out information about this option. The
1192 // to-be-maintained width is specified.
1194 void basic_parser_impl::printOptionInfo(const Option &O,
1195 size_t GlobalWidth) const {
1196 outs() << " -" << O.ArgStr;
1198 if (const char *ValName = getValueName())
1199 outs() << "=<" << getValueStr(O, ValName) << '>';
1201 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1204 void basic_parser_impl::printOptionName(const Option &O,
1205 size_t GlobalWidth) const {
1206 outs() << " -" << O.ArgStr;
1207 outs().indent(GlobalWidth - O.ArgStr.size());
1210 // parser<bool> implementation
1212 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1214 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1220 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1224 return O.error("'" + Arg +
1225 "' is invalid value for boolean argument! Try 0 or 1");
1228 // parser<boolOrDefault> implementation
1230 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1231 boolOrDefault &Value) {
1232 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1237 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1242 return O.error("'" + Arg +
1243 "' is invalid value for boolean argument! Try 0 or 1");
1246 // parser<int> implementation
1248 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1250 if (Arg.getAsInteger(0, Value))
1251 return O.error("'" + Arg + "' value invalid for integer argument!");
1255 // parser<unsigned> implementation
1257 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1260 if (Arg.getAsInteger(0, Value))
1261 return O.error("'" + Arg + "' value invalid for uint argument!");
1265 // parser<unsigned long long> implementation
1267 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1269 unsigned long long &Value) {
1271 if (Arg.getAsInteger(0, Value))
1272 return O.error("'" + Arg + "' value invalid for uint argument!");
1276 // parser<double>/parser<float> implementation
1278 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1279 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1280 const char *ArgStart = TmpStr.c_str();
1282 Value = strtod(ArgStart, &End);
1284 return O.error("'" + Arg + "' value invalid for floating point argument!");
1288 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1290 return parseDouble(O, Arg, Val);
1293 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1296 if (parseDouble(O, Arg, dVal))
1302 // generic_parser_base implementation
1305 // findOption - Return the option number corresponding to the specified
1306 // argument string. If the option is not found, getNumOptions() is returned.
1308 unsigned generic_parser_base::findOption(const char *Name) {
1309 unsigned e = getNumOptions();
1311 for (unsigned i = 0; i != e; ++i) {
1312 if (strcmp(getOption(i), Name) == 0)
1318 // Return the width of the option tag for printing...
1319 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1320 if (O.hasArgStr()) {
1321 size_t Size = O.ArgStr.size() + 6;
1322 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1323 Size = std::max(Size, std::strlen(getOption(i)) + 8);
1326 size_t BaseSize = 0;
1327 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1328 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
1333 // printOptionInfo - Print out information about this option. The
1334 // to-be-maintained width is specified.
1336 void generic_parser_base::printOptionInfo(const Option &O,
1337 size_t GlobalWidth) const {
1338 if (O.hasArgStr()) {
1339 outs() << " -" << O.ArgStr;
1340 printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
1342 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1343 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
1344 outs() << " =" << getOption(i);
1345 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1348 if (!O.HelpStr.empty())
1349 outs() << " " << O.HelpStr << '\n';
1350 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1351 const char *Option = getOption(i);
1352 outs() << " -" << Option;
1353 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1358 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1360 // printGenericOptionDiff - Print the value of this option and it's default.
1362 // "Generic" options have each value mapped to a name.
1363 void generic_parser_base::printGenericOptionDiff(
1364 const Option &O, const GenericOptionValue &Value,
1365 const GenericOptionValue &Default, size_t GlobalWidth) const {
1366 outs() << " -" << O.ArgStr;
1367 outs().indent(GlobalWidth - O.ArgStr.size());
1369 unsigned NumOpts = getNumOptions();
1370 for (unsigned i = 0; i != NumOpts; ++i) {
1371 if (Value.compare(getOptionValue(i)))
1374 outs() << "= " << getOption(i);
1375 size_t L = std::strlen(getOption(i));
1376 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1377 outs().indent(NumSpaces) << " (default: ";
1378 for (unsigned j = 0; j != NumOpts; ++j) {
1379 if (Default.compare(getOptionValue(j)))
1381 outs() << getOption(j);
1387 outs() << "= *unknown option value*\n";
1390 // printOptionDiff - Specializations for printing basic value types.
1392 #define PRINT_OPT_DIFF(T) \
1393 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1394 size_t GlobalWidth) const { \
1395 printOptionName(O, GlobalWidth); \
1398 raw_string_ostream SS(Str); \
1401 outs() << "= " << Str; \
1402 size_t NumSpaces = \
1403 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1404 outs().indent(NumSpaces) << " (default: "; \
1406 outs() << D.getValue(); \
1408 outs() << "*no default*"; \
1412 PRINT_OPT_DIFF(bool)
1413 PRINT_OPT_DIFF(boolOrDefault)
1415 PRINT_OPT_DIFF(unsigned)
1416 PRINT_OPT_DIFF(unsigned long long)
1417 PRINT_OPT_DIFF(double)
1418 PRINT_OPT_DIFF(float)
1419 PRINT_OPT_DIFF(char)
1421 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1422 OptionValue<std::string> D,
1423 size_t GlobalWidth) const {
1424 printOptionName(O, GlobalWidth);
1425 outs() << "= " << V;
1426 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1427 outs().indent(NumSpaces) << " (default: ";
1429 outs() << D.getValue();
1431 outs() << "*no default*";
1435 // Print a placeholder for options that don't yet support printOptionDiff().
1436 void basic_parser_impl::printOptionNoValue(const Option &O,
1437 size_t GlobalWidth) const {
1438 printOptionName(O, GlobalWidth);
1439 outs() << "= *cannot print option value*\n";
1442 //===----------------------------------------------------------------------===//
1443 // -help and -help-hidden option implementation
1446 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1447 const std::pair<const char *, Option *> *RHS) {
1448 return strcmp(LHS->first, RHS->first);
1451 // Copy Options into a vector so we can sort them as we like.
1452 static void sortOpts(StringMap<Option *> &OptMap,
1453 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1455 SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
1457 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1459 // Ignore really-hidden options.
1460 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1463 // Unless showhidden is set, ignore hidden flags.
1464 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1467 // If we've already seen this option, don't add it to the list again.
1468 if (!OptionSet.insert(I->second).second)
1472 std::pair<const char *, Option *>(I->getKey().data(), I->second));
1475 // Sort the options list alphabetically.
1476 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1483 const bool ShowHidden;
1484 typedef SmallVector<std::pair<const char *, Option *>, 128>
1485 StrOptionPairVector;
1486 // Print the options. Opts is assumed to be alphabetically sorted.
1487 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1488 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1489 Opts[i].second->printOptionInfo(MaxArgLen);
1493 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1494 virtual ~HelpPrinter() {}
1496 // Invoke the printer.
1497 void operator=(bool Value) {
1501 StrOptionPairVector Opts;
1502 sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
1504 if (GlobalParser->ProgramOverview)
1505 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1507 outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
1509 for (auto Opt : GlobalParser->PositionalOpts) {
1510 if (Opt->hasArgStr())
1511 outs() << " --" << Opt->ArgStr;
1512 outs() << " " << Opt->HelpStr;
1515 // Print the consume after option info if it exists...
1516 if (GlobalParser->ConsumeAfterOpt)
1517 outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
1521 // Compute the maximum argument length...
1522 size_t MaxArgLen = 0;
1523 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1524 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1526 outs() << "OPTIONS:\n";
1527 printOptions(Opts, MaxArgLen);
1529 // Print any extra help the user has declared.
1530 for (auto I : GlobalParser->MoreHelp)
1532 GlobalParser->MoreHelp.clear();
1534 // Halt the program since help information was printed
1539 class CategorizedHelpPrinter : public HelpPrinter {
1541 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1543 // Helper function for printOptions().
1544 // It shall return a negative value if A's name should be lexicographically
1545 // ordered before B's name. It returns a value greater equal zero otherwise.
1546 static int OptionCategoryCompare(OptionCategory *const *A,
1547 OptionCategory *const *B) {
1548 return strcmp((*A)->getName(), (*B)->getName());
1551 // Make sure we inherit our base class's operator=()
1552 using HelpPrinter::operator=;
1555 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1556 std::vector<OptionCategory *> SortedCategories;
1557 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1559 // Collect registered option categories into vector in preparation for
1561 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1562 E = GlobalParser->RegisteredOptionCategories.end();
1564 SortedCategories.push_back(*I);
1567 // Sort the different option categories alphabetically.
1568 assert(SortedCategories.size() > 0 && "No option categories registered!");
1569 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1570 OptionCategoryCompare);
1572 // Create map to empty vectors.
1573 for (std::vector<OptionCategory *>::const_iterator
1574 I = SortedCategories.begin(),
1575 E = SortedCategories.end();
1577 CategorizedOptions[*I] = std::vector<Option *>();
1579 // Walk through pre-sorted options and assign into categories.
1580 // Because the options are already alphabetically sorted the
1581 // options within categories will also be alphabetically sorted.
1582 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1583 Option *Opt = Opts[I].second;
1584 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1585 "Option has an unregistered category");
1586 CategorizedOptions[Opt->Category].push_back(Opt);
1590 for (std::vector<OptionCategory *>::const_iterator
1591 Category = SortedCategories.begin(),
1592 E = SortedCategories.end();
1593 Category != E; ++Category) {
1594 // Hide empty categories for -help, but show for -help-hidden.
1595 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1596 if (!ShowHidden && IsEmptyCategory)
1599 // Print category information.
1601 outs() << (*Category)->getName() << ":\n";
1603 // Check if description is set.
1604 if ((*Category)->getDescription() != nullptr)
1605 outs() << (*Category)->getDescription() << "\n\n";
1609 // When using -help-hidden explicitly state if the category has no
1610 // options associated with it.
1611 if (IsEmptyCategory) {
1612 outs() << " This option category has no options.\n";
1615 // Loop over the options in the category and print.
1616 for (std::vector<Option *>::const_iterator
1617 Opt = CategorizedOptions[*Category].begin(),
1618 E = CategorizedOptions[*Category].end();
1620 (*Opt)->printOptionInfo(MaxArgLen);
1625 // This wraps the Uncategorizing and Categorizing printers and decides
1626 // at run time which should be invoked.
1627 class HelpPrinterWrapper {
1629 HelpPrinter &UncategorizedPrinter;
1630 CategorizedHelpPrinter &CategorizedPrinter;
1633 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1634 CategorizedHelpPrinter &CategorizedPrinter)
1635 : UncategorizedPrinter(UncategorizedPrinter),
1636 CategorizedPrinter(CategorizedPrinter) {}
1638 // Invoke the printer.
1639 void operator=(bool Value);
1642 } // End anonymous namespace
1644 // Declare the four HelpPrinter instances that are used to print out help, or
1645 // help-hidden as an uncategorized list or in categories.
1646 static HelpPrinter UncategorizedNormalPrinter(false);
1647 static HelpPrinter UncategorizedHiddenPrinter(true);
1648 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1649 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1651 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1652 // a categorizing help printer
1653 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1654 CategorizedNormalPrinter);
1655 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1656 CategorizedHiddenPrinter);
1658 // Define a category for generic options that all tools should have.
1659 static cl::OptionCategory GenericCategory("Generic Options");
1661 // Define uncategorized help printers.
1662 // -help-list is hidden by default because if Option categories are being used
1663 // then -help behaves the same as -help-list.
1664 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1666 cl::desc("Display list of available options (-help-list-hidden for more)"),
1667 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1668 cl::cat(GenericCategory));
1670 static cl::opt<HelpPrinter, true, parser<bool>>
1671 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1672 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1673 cl::ValueDisallowed, cl::cat(GenericCategory));
1675 // Define uncategorized/categorized help printers. These printers change their
1676 // behaviour at runtime depending on whether one or more Option categories have
1678 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1679 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1680 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1681 cl::cat(GenericCategory));
1683 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1684 HHOp("help-hidden", cl::desc("Display all available options"),
1685 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1686 cl::cat(GenericCategory));
1688 static cl::opt<bool> PrintOptions(
1690 cl::desc("Print non-default options after command line parsing"),
1691 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
1693 static cl::opt<bool> PrintAllOptions(
1694 "print-all-options",
1695 cl::desc("Print all option values after command line parsing"), cl::Hidden,
1696 cl::init(false), cl::cat(GenericCategory));
1698 void HelpPrinterWrapper::operator=(bool Value) {
1702 // Decide which printer to invoke. If more than one option category is
1703 // registered then it is useful to show the categorized help instead of
1704 // uncategorized help.
1705 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
1706 // unhide -help-list option so user can have uncategorized output if they
1708 HLOp.setHiddenFlag(NotHidden);
1710 CategorizedPrinter = true; // Invoke categorized printer
1712 UncategorizedPrinter = true; // Invoke uncategorized printer
1715 // Print the value of each option.
1716 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
1718 void CommandLineParser::printOptionValues() {
1719 if (!PrintOptions && !PrintAllOptions)
1722 SmallVector<std::pair<const char *, Option *>, 128> Opts;
1723 sortOpts(OptionsMap, Opts, /*ShowHidden*/ true);
1725 // Compute the maximum argument length...
1726 size_t MaxArgLen = 0;
1727 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1728 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1730 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1731 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1734 static void (*OverrideVersionPrinter)() = nullptr;
1736 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
1739 class VersionPrinter {
1742 raw_ostream &OS = outs();
1743 OS << "LLVM (http://llvm.org/):\n"
1744 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1745 #ifdef LLVM_VERSION_INFO
1746 OS << " " << LLVM_VERSION_INFO;
1749 #ifndef __OPTIMIZE__
1750 OS << "DEBUG build";
1752 OS << "Optimized build";
1755 OS << " with assertions";
1757 std::string CPU = sys::getHostCPUName();
1758 if (CPU == "generic")
1761 #if (ENABLE_TIMESTAMPS == 1)
1762 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1764 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1765 << " Host CPU: " << CPU << '\n';
1767 void operator=(bool OptionWasSpecified) {
1768 if (!OptionWasSpecified)
1771 if (OverrideVersionPrinter != nullptr) {
1772 (*OverrideVersionPrinter)();
1777 // Iterate over any registered extra printers and call them to add further
1779 if (ExtraVersionPrinters != nullptr) {
1781 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1782 E = ExtraVersionPrinters->end();
1790 } // End anonymous namespace
1792 // Define the --version option that prints out the LLVM version for the tool
1793 static VersionPrinter VersionPrinterInstance;
1795 static cl::opt<VersionPrinter, true, parser<bool>>
1796 VersOp("version", cl::desc("Display the version of this program"),
1797 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1798 cl::cat(GenericCategory));
1800 // Utility function for printing the help message.
1801 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1802 // This looks weird, but it actually prints the help message. The Printers are
1803 // types of HelpPrinter and the help gets printed when its operator= is
1804 // invoked. That's because the "normal" usages of the help printer is to be
1805 // assigned true/false depending on whether -help or -help-hidden was given or
1806 // not. Since we're circumventing that we have to make it look like -help or
1807 // -help-hidden were given, so we assign true.
1809 if (!Hidden && !Categorized)
1810 UncategorizedNormalPrinter = true;
1811 else if (!Hidden && Categorized)
1812 CategorizedNormalPrinter = true;
1813 else if (Hidden && !Categorized)
1814 UncategorizedHiddenPrinter = true;
1816 CategorizedHiddenPrinter = true;
1819 /// Utility function for printing version number.
1820 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
1822 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
1824 void cl::AddExtraVersionPrinter(void (*func)()) {
1825 if (!ExtraVersionPrinters)
1826 ExtraVersionPrinters = new std::vector<void (*)()>;
1828 ExtraVersionPrinters->push_back(func);
1831 StringMap<Option *> &cl::getRegisteredOptions() {
1832 return GlobalParser->OptionsMap;
1835 void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
1836 for (auto &I : GlobalParser->OptionsMap) {
1837 if (I.second->Category != &Category &&
1838 I.second->Category != &GenericCategory)
1839 I.second->setHiddenFlag(cl::ReallyHidden);
1843 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
1844 auto CategoriesBegin = Categories.begin();
1845 auto CategoriesEnd = Categories.end();
1846 for (auto &I : GlobalParser->OptionsMap) {
1847 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1849 I.second->Category != &GenericCategory)
1850 I.second->setHiddenFlag(cl::ReallyHidden);
1854 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1855 const char *Overview) {
1856 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);