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/raw_ostream.h"
39 #include <system_error>
43 #define DEBUG_TYPE "commandline"
45 //===----------------------------------------------------------------------===//
46 // Template instantiations and anchors.
50 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
51 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
52 TEMPLATE_INSTANTIATION(class basic_parser<int>);
53 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
54 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
55 TEMPLATE_INSTANTIATION(class basic_parser<double>);
56 TEMPLATE_INSTANTIATION(class basic_parser<float>);
57 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
58 TEMPLATE_INSTANTIATION(class basic_parser<char>);
60 TEMPLATE_INSTANTIATION(class opt<unsigned>);
61 TEMPLATE_INSTANTIATION(class opt<int>);
62 TEMPLATE_INSTANTIATION(class opt<std::string>);
63 TEMPLATE_INSTANTIATION(class opt<char>);
64 TEMPLATE_INSTANTIATION(class opt<bool>);
66 } // end namespace llvm::cl
68 // Pin the vtables to this file.
69 void GenericOptionValue::anchor() {}
70 void OptionValue<boolOrDefault>::anchor() {}
71 void OptionValue<std::string>::anchor() {}
72 void Option::anchor() {}
73 void basic_parser_impl::anchor() {}
74 void parser<bool>::anchor() {}
75 void parser<boolOrDefault>::anchor() {}
76 void parser<int>::anchor() {}
77 void parser<unsigned>::anchor() {}
78 void parser<unsigned long long>::anchor() {}
79 void parser<double>::anchor() {}
80 void parser<float>::anchor() {}
81 void parser<std::string>::anchor() {}
82 void parser<char>::anchor() {}
83 void StringSaver::anchor() {}
85 //===----------------------------------------------------------------------===//
89 class CommandLineParser {
91 // Globals for name and overview of program. Program name is not a string to
92 // avoid static ctor/dtor issues.
93 std::string ProgramName;
94 const char *ProgramOverview;
96 // This collects additional help to be printed.
97 std::vector<const char *> MoreHelp;
99 SmallVector<Option *, 4> PositionalOpts;
100 SmallVector<Option *, 4> SinkOpts;
101 StringMap<Option *> OptionsMap;
103 Option *ConsumeAfterOpt; // The ConsumeAfter option if it exists.
105 // This collects the different option categories that have been registered.
106 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
108 CommandLineParser() : ProgramOverview(nullptr), ConsumeAfterOpt(nullptr) {}
110 void ParseCommandLineOptions(int argc, const char *const *argv,
111 const char *Overview);
113 void addLiteralOption(Option &Opt, const char *Name) {
114 if (!Opt.hasArgStr()) {
115 if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
116 errs() << ProgramName << ": CommandLine Error: Option '" << Name
117 << "' registered more than once!\n";
118 report_fatal_error("inconsistency in registered CommandLine options");
123 void addOption(Option *O) {
124 bool HadErrors = false;
126 // Add argument to the argument map!
127 if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
128 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
129 << "' registered more than once!\n";
134 // Remember information about positional options.
135 if (O->getFormattingFlag() == cl::Positional)
136 PositionalOpts.push_back(O);
137 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
138 SinkOpts.push_back(O);
139 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
140 if (ConsumeAfterOpt) {
141 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
147 // Fail hard if there were errors. These are strictly unrecoverable and
148 // indicate serious issues such as conflicting option names or an
150 // linked LLVM distribution.
152 report_fatal_error("inconsistency in registered CommandLine options");
155 void removeOption(Option *O) {
156 SmallVector<const char *, 16> OptionNames;
157 O->getExtraOptionNames(OptionNames);
159 OptionNames.push_back(O->ArgStr);
160 for (auto Name : OptionNames)
161 OptionsMap.erase(StringRef(Name));
163 if (O->getFormattingFlag() == cl::Positional)
164 for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
167 PositionalOpts.erase(Opt);
171 else if (O->getMiscFlags() & cl::Sink)
172 for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
178 else if (O == ConsumeAfterOpt)
179 ConsumeAfterOpt = nullptr;
183 return (!OptionsMap.empty() || !PositionalOpts.empty() ||
184 nullptr != ConsumeAfterOpt);
187 void updateArgStr(Option *O, const char *NewName) {
188 if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
189 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
190 << "' registered more than once!\n";
191 report_fatal_error("inconsistency in registered CommandLine options");
193 OptionsMap.erase(StringRef(O->ArgStr));
196 void printOptionValues();
198 void registerCategory(OptionCategory *cat) {
199 assert(std::count_if(RegisteredOptionCategories.begin(),
200 RegisteredOptionCategories.end(),
201 [cat](const OptionCategory *Category) {
202 return cat->getName() == Category->getName();
204 "Duplicate option categories");
206 RegisteredOptionCategories.insert(cat);
210 Option *LookupOption(StringRef &Arg, StringRef &Value);
215 static ManagedStatic<CommandLineParser> GlobalParser;
217 void cl::AddLiteralOption(Option &O, const char *Name) {
218 GlobalParser->addLiteralOption(O, Name);
221 extrahelp::extrahelp(const char *Help) : morehelp(Help) {
222 GlobalParser->MoreHelp.push_back(Help);
225 void Option::addArgument() {
226 GlobalParser->addOption(this);
227 FullyInitialized = true;
230 void Option::removeArgument() { GlobalParser->removeOption(this); }
232 void Option::setArgStr(const char *S) {
233 if (FullyInitialized)
234 GlobalParser->updateArgStr(this, S);
238 // Initialise the general option category.
239 OptionCategory llvm::cl::GeneralCategory("General options");
241 void OptionCategory::registerCategory() {
242 GlobalParser->registerCategory(this);
245 //===----------------------------------------------------------------------===//
246 // Basic, shared command line option processing machinery.
249 /// LookupOption - Lookup the option specified by the specified option on the
250 /// command line. If there is a value specified (after an equal sign) return
251 /// that as well. This assumes that leading dashes have already been stripped.
252 Option *CommandLineParser::LookupOption(StringRef &Arg, StringRef &Value) {
253 // Reject all dashes.
257 size_t EqualPos = Arg.find('=');
259 // If we have an equals sign, remember the value.
260 if (EqualPos == StringRef::npos) {
261 // Look up the option.
262 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
263 return I != OptionsMap.end() ? I->second : nullptr;
266 // If the argument before the = is a valid option name, we match. If not,
267 // return Arg unmolested.
268 StringMap<Option *>::const_iterator I =
269 OptionsMap.find(Arg.substr(0, EqualPos));
270 if (I == OptionsMap.end())
273 Value = Arg.substr(EqualPos + 1);
274 Arg = Arg.substr(0, EqualPos);
278 /// LookupNearestOption - Lookup the closest match to the option specified by
279 /// the specified option on the command line. If there is a value specified
280 /// (after an equal sign) return that as well. This assumes that leading dashes
281 /// have already been stripped.
282 static Option *LookupNearestOption(StringRef Arg,
283 const StringMap<Option *> &OptionsMap,
284 std::string &NearestString) {
285 // Reject all dashes.
289 // Split on any equal sign.
290 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
291 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
292 StringRef &RHS = SplitArg.second;
294 // Find the closest match.
295 Option *Best = nullptr;
296 unsigned BestDistance = 0;
297 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
298 ie = OptionsMap.end();
300 Option *O = it->second;
301 SmallVector<const char *, 16> OptionNames;
302 O->getExtraOptionNames(OptionNames);
304 OptionNames.push_back(O->ArgStr);
306 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
307 StringRef Flag = PermitValue ? LHS : Arg;
308 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
309 StringRef Name = OptionNames[i];
310 unsigned Distance = StringRef(Name).edit_distance(
311 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
312 if (!Best || Distance < BestDistance) {
314 BestDistance = Distance;
315 if (RHS.empty() || !PermitValue)
316 NearestString = OptionNames[i];
318 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
326 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
327 /// that does special handling of cl::CommaSeparated options.
328 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
329 StringRef ArgName, StringRef Value,
330 bool MultiArg = false) {
331 // Check to see if this option accepts a comma separated list of values. If
332 // it does, we have to split up the value into multiple values.
333 if (Handler->getMiscFlags() & CommaSeparated) {
334 StringRef Val(Value);
335 StringRef::size_type Pos = Val.find(',');
337 while (Pos != StringRef::npos) {
338 // Process the portion before the comma.
339 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
341 // Erase the portion before the comma, AND the comma.
342 Val = Val.substr(Pos + 1);
343 Value.substr(Pos + 1); // Increment the original value pointer as well.
344 // Check for another comma.
351 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
357 /// ProvideOption - For Value, this differentiates between an empty value ("")
358 /// and a null value (StringRef()). The later is accepted for arguments that
359 /// don't allow a value (-foo) the former is rejected (-foo=).
360 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
361 StringRef Value, int argc,
362 const char *const *argv, int &i) {
363 // Is this a multi-argument option?
364 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
366 // Enforce value requirements
367 switch (Handler->getValueExpectedFlag()) {
369 if (!Value.data()) { // No value specified?
371 return Handler->error("requires a value!");
372 // Steal the next argument, like for '-o filename'
373 assert(argv && "null check");
377 case ValueDisallowed:
378 if (NumAdditionalVals > 0)
379 return Handler->error("multi-valued option specified"
380 " with ValueDisallowed modifier!");
383 return Handler->error("does not allow a value! '" + Twine(Value) +
390 // If this isn't a multi-arg option, just run the handler.
391 if (NumAdditionalVals == 0)
392 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
394 // If it is, run the handle several times.
395 bool MultiArg = false;
398 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
404 while (NumAdditionalVals > 0) {
406 return Handler->error("not enough values!");
407 assert(argv && "null check");
410 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
418 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
420 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
423 // Option predicates...
424 static inline bool isGrouping(const Option *O) {
425 return O->getFormattingFlag() == cl::Grouping;
427 static inline bool isPrefixedOrGrouping(const Option *O) {
428 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
431 // getOptionPred - Check to see if there are any options that satisfy the
432 // specified predicate with names that are the prefixes in Name. This is
433 // checked by progressively stripping characters off of the name, checking to
434 // see if there options that satisfy the predicate. If we find one, return it,
435 // otherwise return null.
437 static Option *getOptionPred(StringRef Name, size_t &Length,
438 bool (*Pred)(const Option *),
439 const StringMap<Option *> &OptionsMap) {
441 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
443 // Loop while we haven't found an option and Name still has at least two
444 // characters in it (so that the next iteration will not be the empty
446 while (OMI == OptionsMap.end() && Name.size() > 1) {
447 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
448 OMI = OptionsMap.find(Name);
451 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
452 Length = Name.size();
453 return OMI->second; // Found one!
455 return nullptr; // No option found!
458 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
459 /// with at least one '-') does not fully match an available option. Check to
460 /// see if this is a prefix or grouped option. If so, split arg into output an
461 /// Arg/Value pair and return the Option to parse it with.
463 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
465 const StringMap<Option *> &OptionsMap) {
471 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
475 // If the option is a prefixed option, then the value is simply the
476 // rest of the name... so fall through to later processing, by
477 // setting up the argument name flags and value fields.
478 if (PGOpt->getFormattingFlag() == cl::Prefix) {
479 Value = Arg.substr(Length);
480 Arg = Arg.substr(0, Length);
481 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
485 // This must be a grouped option... handle them now. Grouping options can't
487 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
490 // Move current arg name out of Arg into OneArgName.
491 StringRef OneArgName = Arg.substr(0, Length);
492 Arg = Arg.substr(Length);
494 // Because ValueRequired is an invalid flag for grouped arguments,
495 // we don't need to pass argc/argv in.
496 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
497 "Option can not be cl::Grouping AND cl::ValueRequired!");
500 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
502 // Get the next grouping option.
503 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
504 } while (PGOpt && Length != Arg.size());
506 // Return the last option with Arg cut down to just the last one.
510 static bool RequiresValue(const Option *O) {
511 return O->getNumOccurrencesFlag() == cl::Required ||
512 O->getNumOccurrencesFlag() == cl::OneOrMore;
515 static bool EatsUnboundedNumberOfValues(const Option *O) {
516 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
517 O->getNumOccurrencesFlag() == cl::OneOrMore;
520 static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
522 static bool isQuote(char C) { return C == '\"' || C == '\''; }
524 static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
526 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
527 SmallVectorImpl<const char *> &NewArgv,
529 SmallString<128> Token;
530 for (size_t I = 0, E = Src.size(); I != E; ++I) {
531 // Consume runs of whitespace.
533 while (I != E && isWhitespace(Src[I])) {
534 // Mark the end of lines in response files
535 if (MarkEOLs && Src[I] == '\n')
536 NewArgv.push_back(nullptr);
543 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
544 // they are literal. This makes it much easier to read Windows file paths.
545 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
546 ++I; // Skip the escape.
547 Token.push_back(Src[I]);
551 // Consume a quoted string.
552 if (isQuote(Src[I])) {
553 char Quote = Src[I++];
554 while (I != E && Src[I] != Quote) {
555 // Backslashes are literal, unless they escape a special character.
556 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
558 Token.push_back(Src[I]);
566 // End the token if this is whitespace.
567 if (isWhitespace(Src[I])) {
569 NewArgv.push_back(Saver.SaveString(Token.c_str()));
574 // This is a normal character. Append it.
575 Token.push_back(Src[I]);
578 // Append the last token after hitting EOF with no whitespace.
580 NewArgv.push_back(Saver.SaveString(Token.c_str()));
581 // Mark the end of response files
583 NewArgv.push_back(nullptr);
586 /// Backslashes are interpreted in a rather complicated way in the Windows-style
587 /// command line, because backslashes are used both to separate path and to
588 /// escape double quote. This method consumes runs of backslashes as well as the
589 /// following double quote if it's escaped.
591 /// * If an even number of backslashes is followed by a double quote, one
592 /// backslash is output for every pair of backslashes, and the last double
593 /// quote remains unconsumed. The double quote will later be interpreted as
594 /// the start or end of a quoted string in the main loop outside of this
597 /// * If an odd number of backslashes is followed by a double quote, one
598 /// backslash is output for every pair of backslashes, and a double quote is
599 /// output for the last pair of backslash-double quote. The double quote is
600 /// consumed in this case.
602 /// * Otherwise, backslashes are interpreted literally.
603 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
604 size_t E = Src.size();
605 int BackslashCount = 0;
606 // Skip the backslashes.
610 } while (I != E && Src[I] == '\\');
612 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
613 if (FollowedByDoubleQuote) {
614 Token.append(BackslashCount / 2, '\\');
615 if (BackslashCount % 2 == 0)
617 Token.push_back('"');
620 Token.append(BackslashCount, '\\');
624 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
625 SmallVectorImpl<const char *> &NewArgv,
627 SmallString<128> Token;
629 // This is a small state machine to consume characters until it reaches the
630 // end of the source string.
631 enum { INIT, UNQUOTED, QUOTED } State = INIT;
632 for (size_t I = 0, E = Src.size(); I != E; ++I) {
633 // INIT state indicates that the current input index is at the start of
634 // the string or between tokens.
636 if (isWhitespace(Src[I])) {
637 // Mark the end of lines in response files
638 if (MarkEOLs && Src[I] == '\n')
639 NewArgv.push_back(nullptr);
646 if (Src[I] == '\\') {
647 I = parseBackslash(Src, I, Token);
651 Token.push_back(Src[I]);
656 // UNQUOTED state means that it's reading a token not quoted by double
658 if (State == UNQUOTED) {
659 // Whitespace means the end of the token.
660 if (isWhitespace(Src[I])) {
661 NewArgv.push_back(Saver.SaveString(Token.c_str()));
664 // Mark the end of lines in response files
665 if (MarkEOLs && Src[I] == '\n')
666 NewArgv.push_back(nullptr);
673 if (Src[I] == '\\') {
674 I = parseBackslash(Src, I, Token);
677 Token.push_back(Src[I]);
681 // QUOTED state means that it's reading a token quoted by double quotes.
682 if (State == QUOTED) {
687 if (Src[I] == '\\') {
688 I = parseBackslash(Src, I, Token);
691 Token.push_back(Src[I]);
694 // Append the last token after hitting EOF with no whitespace.
696 NewArgv.push_back(Saver.SaveString(Token.c_str()));
697 // Mark the end of response files
699 NewArgv.push_back(nullptr);
702 // It is called byte order marker but the UTF-8 BOM is actually not affected
703 // by the host system's endianness.
704 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
705 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
708 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
709 TokenizerCallback Tokenizer,
710 SmallVectorImpl<const char *> &NewArgv,
711 bool MarkEOLs = false) {
712 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
713 MemoryBuffer::getFile(FName);
716 MemoryBuffer &MemBuf = *MemBufOrErr.get();
717 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
719 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
720 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
722 if (hasUTF16ByteOrderMark(BufRef)) {
723 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
725 Str = StringRef(UTF8Buf);
727 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
728 // these bytes before parsing.
729 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
730 else if (hasUTF8ByteOrderMark(BufRef))
731 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
733 // Tokenize the contents into NewArgv.
734 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
739 /// \brief Expand response files on a command line recursively using the given
740 /// StringSaver and tokenization strategy.
741 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
742 SmallVectorImpl<const char *> &Argv,
744 unsigned RspFiles = 0;
745 bool AllExpanded = true;
747 // Don't cache Argv.size() because it can change.
748 for (unsigned I = 0; I != Argv.size();) {
749 const char *Arg = Argv[I];
750 // Check if it is an EOL marker
751 if (Arg == nullptr) {
760 // If we have too many response files, leave some unexpanded. This avoids
761 // crashing on self-referential response files.
765 // Replace this response file argument with the tokenization of its
766 // contents. Nested response files are expanded in subsequent iterations.
767 // FIXME: If a nested response file uses a relative path, is it relative to
768 // the cwd of the process or the response file?
769 SmallVector<const char *, 0> ExpandedArgv;
770 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
772 // We couldn't read this file, so we leave it in the argument stream and
778 Argv.erase(Argv.begin() + I);
779 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
785 class StrDupSaver : public StringSaver {
786 std::vector<char *> Dups;
790 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); I != E;
796 const char *SaveString(const char *Str) override {
797 char *Dup = strdup(Str);
804 /// ParseEnvironmentOptions - An alternative entry point to the
805 /// CommandLine library, which allows you to read the program's name
806 /// from the caller (as PROGNAME) and its command-line arguments from
807 /// an environment variable (whose name is given in ENVVAR).
809 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
810 const char *Overview) {
812 assert(progName && "Program name not specified");
813 assert(envVar && "Environment variable name missing");
815 // Get the environment variable they want us to parse options out of.
816 const char *envValue = getenv(envVar);
820 // Get program's "name", which we wouldn't know without the caller
822 SmallVector<const char *, 20> newArgv;
824 newArgv.push_back(Saver.SaveString(progName));
826 // Parse the value of the environment variable into a "command line"
827 // and hand it off to ParseCommandLineOptions().
828 TokenizeGNUCommandLine(envValue, Saver, newArgv);
829 int newArgc = static_cast<int>(newArgv.size());
830 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
833 void cl::ParseCommandLineOptions(int argc, const char *const *argv,
834 const char *Overview) {
835 GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
838 void CommandLineParser::ParseCommandLineOptions(int argc,
839 const char *const *argv,
840 const char *Overview) {
841 assert(hasOptions() && "No options specified!");
843 // Expand response files.
844 SmallVector<const char *, 20> newArgv(argv, argv + argc);
846 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
848 argc = static_cast<int>(newArgv.size());
850 // Copy the program name into ProgName, making sure not to overflow it.
851 ProgramName = sys::path::filename(argv[0]);
853 ProgramOverview = Overview;
854 bool ErrorParsing = false;
856 // Check out the positional arguments to collect information about them.
857 unsigned NumPositionalRequired = 0;
859 // Determine whether or not there are an unlimited number of positionals
860 bool HasUnlimitedPositionals = false;
862 if (ConsumeAfterOpt) {
863 assert(PositionalOpts.size() > 0 &&
864 "Cannot specify cl::ConsumeAfter without a positional argument!");
866 if (!PositionalOpts.empty()) {
868 // Calculate how many positional values are _required_.
869 bool UnboundedFound = false;
870 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
871 Option *Opt = PositionalOpts[i];
872 if (RequiresValue(Opt))
873 ++NumPositionalRequired;
874 else if (ConsumeAfterOpt) {
875 // ConsumeAfter cannot be combined with "optional" positional options
876 // unless there is only one positional argument...
877 if (PositionalOpts.size() > 1)
878 ErrorParsing |= Opt->error(
879 "error - this positional option will never be matched, "
880 "because it does not Require a value, and a "
881 "cl::ConsumeAfter option is active!");
882 } else if (UnboundedFound && !Opt->ArgStr[0]) {
883 // This option does not "require" a value... Make sure this option is
884 // not specified after an option that eats all extra arguments, or this
885 // one will never get any!
887 ErrorParsing |= Opt->error("error - option can never match, because "
888 "another positional argument will match an "
889 "unbounded number of values, and this option"
890 " does not require a value!");
891 errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
892 << "' is all messed up!\n";
893 errs() << PositionalOpts.size();
895 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
897 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
900 // PositionalVals - A vector of "positional" arguments we accumulate into
901 // the process at the end.
903 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
905 // If the program has named positional arguments, and the name has been run
906 // across, keep track of which positional argument was named. Otherwise put
907 // the positional args into the PositionalVals list...
908 Option *ActivePositionalArg = nullptr;
910 // Loop over all of the arguments... processing them.
911 bool DashDashFound = false; // Have we read '--'?
912 for (int i = 1; i < argc; ++i) {
913 Option *Handler = nullptr;
914 Option *NearestHandler = nullptr;
915 std::string NearestHandlerString;
917 StringRef ArgName = "";
919 // Check to see if this is a positional argument. This argument is
920 // considered to be positional if it doesn't start with '-', if it is "-"
921 // itself, or if we have seen "--" already.
923 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
924 // Positional argument!
925 if (ActivePositionalArg) {
926 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
927 continue; // We are done!
930 if (!PositionalOpts.empty()) {
931 PositionalVals.push_back(std::make_pair(argv[i], i));
933 // All of the positional arguments have been fulfulled, give the rest to
934 // the consume after option... if it's specified...
936 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
937 for (++i; i < argc; ++i)
938 PositionalVals.push_back(std::make_pair(argv[i], i));
939 break; // Handle outside of the argument processing loop...
942 // Delay processing positional arguments until the end...
945 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
947 DashDashFound = true; // This is the mythical "--"?
948 continue; // Don't try to process it as an argument itself.
949 } else if (ActivePositionalArg &&
950 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
951 // If there is a positional argument eating options, check to see if this
952 // option is another positional argument. If so, treat it as an argument,
953 // otherwise feed it to the eating positional.
954 ArgName = argv[i] + 1;
955 // Eat leading dashes.
956 while (!ArgName.empty() && ArgName[0] == '-')
957 ArgName = ArgName.substr(1);
959 Handler = LookupOption(ArgName, Value);
960 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
961 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
962 continue; // We are done!
965 } else { // We start with a '-', must be an argument.
966 ArgName = argv[i] + 1;
967 // Eat leading dashes.
968 while (!ArgName.empty() && ArgName[0] == '-')
969 ArgName = ArgName.substr(1);
971 Handler = LookupOption(ArgName, Value);
973 // Check to see if this "option" is really a prefixed or grouped argument.
975 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
978 // Otherwise, look for the closest available option to report to the user
979 // in the upcoming error.
980 if (!Handler && SinkOpts.empty())
982 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
986 if (SinkOpts.empty()) {
987 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
988 << "'. Try: '" << argv[0] << " -help'\n";
990 if (NearestHandler) {
991 // If we know a near match, report it as well.
992 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
998 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1001 (*I)->addOccurrence(i, "", argv[i]);
1006 // If this is a named positional argument, just remember that it is the
1008 if (Handler->getFormattingFlag() == cl::Positional)
1009 ActivePositionalArg = Handler;
1011 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1014 // Check and handle positional arguments now...
1015 if (NumPositionalRequired > PositionalVals.size()) {
1016 errs() << ProgramName
1017 << ": Not enough positional command line arguments specified!\n"
1018 << "Must specify at least " << NumPositionalRequired
1019 << " positional arguments: See: " << argv[0] << " -help\n";
1021 ErrorParsing = true;
1022 } else if (!HasUnlimitedPositionals &&
1023 PositionalVals.size() > PositionalOpts.size()) {
1024 errs() << ProgramName << ": Too many positional arguments specified!\n"
1025 << "Can specify at most " << PositionalOpts.size()
1026 << " positional arguments: See: " << argv[0] << " -help\n";
1027 ErrorParsing = true;
1029 } else if (!ConsumeAfterOpt) {
1030 // Positional args have already been handled if ConsumeAfter is specified.
1031 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1032 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1033 if (RequiresValue(PositionalOpts[i])) {
1034 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1035 PositionalVals[ValNo].second);
1037 --NumPositionalRequired; // We fulfilled our duty...
1040 // If we _can_ give this option more arguments, do so now, as long as we
1041 // do not give it values that others need. 'Done' controls whether the
1042 // option even _WANTS_ any more.
1044 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1045 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1046 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1048 Done = true; // Optional arguments want _at most_ one value
1050 case cl::ZeroOrMore: // Zero or more will take all they can get...
1051 case cl::OneOrMore: // One or more will take all they can get...
1052 ProvidePositionalOption(PositionalOpts[i],
1053 PositionalVals[ValNo].first,
1054 PositionalVals[ValNo].second);
1058 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1059 "positional argument processing!");
1064 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1066 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1067 if (RequiresValue(PositionalOpts[j])) {
1068 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1069 PositionalVals[ValNo].first,
1070 PositionalVals[ValNo].second);
1074 // Handle the case where there is just one positional option, and it's
1075 // optional. In this case, we want to give JUST THE FIRST option to the
1076 // positional option and keep the rest for the consume after. The above
1077 // loop would have assigned no values to positional options in this case.
1079 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1080 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1081 PositionalVals[ValNo].first,
1082 PositionalVals[ValNo].second);
1086 // Handle over all of the rest of the arguments to the
1087 // cl::ConsumeAfter command line option...
1088 for (; ValNo != PositionalVals.size(); ++ValNo)
1090 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1091 PositionalVals[ValNo].second);
1094 // Loop over args and make sure all required args are specified!
1095 for (const auto &Opt : OptionsMap) {
1096 switch (Opt.second->getNumOccurrencesFlag()) {
1099 if (Opt.second->getNumOccurrences() == 0) {
1100 Opt.second->error("must be specified at least once!");
1101 ErrorParsing = true;
1109 // Now that we know if -debug is specified, we can use it.
1110 // Note that if ReadResponseFiles == true, this must be done before the
1111 // memory allocated for the expanded command line is free()d below.
1112 DEBUG(dbgs() << "Args: ";
1113 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1116 // Free all of the memory allocated to the map. Command line options may only
1117 // be processed once!
1120 // If we had an error processing our arguments, don't let the program execute
1125 //===----------------------------------------------------------------------===//
1126 // Option Base class implementation
1129 bool Option::error(const Twine &Message, StringRef ArgName) {
1130 if (!ArgName.data())
1132 if (ArgName.empty())
1133 errs() << HelpStr; // Be nice for positional arguments
1135 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1137 errs() << " option: " << Message << "\n";
1141 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1144 NumOccurrences++; // Increment the number of times we have been seen
1146 switch (getNumOccurrencesFlag()) {
1148 if (NumOccurrences > 1)
1149 return error("may only occur zero or one times!", ArgName);
1152 if (NumOccurrences > 1)
1153 return error("must occur exactly one time!", ArgName);
1161 return handleOccurrence(pos, ArgName, Value);
1164 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1165 // has been specified yet.
1167 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1168 if (O.ValueStr[0] == 0)
1173 //===----------------------------------------------------------------------===//
1174 // cl::alias class implementation
1177 // Return the width of the option tag for printing...
1178 size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; }
1180 static void printHelpStr(StringRef HelpStr, size_t Indent,
1181 size_t FirstLineIndentedBy) {
1182 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1183 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1184 while (!Split.second.empty()) {
1185 Split = Split.second.split('\n');
1186 outs().indent(Indent) << Split.first << "\n";
1190 // Print out the option for the alias.
1191 void alias::printOptionInfo(size_t GlobalWidth) const {
1192 outs() << " -" << ArgStr;
1193 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1196 //===----------------------------------------------------------------------===//
1197 // Parser Implementation code...
1200 // basic_parser implementation
1203 // Return the width of the option tag for printing...
1204 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1205 size_t Len = std::strlen(O.ArgStr);
1206 if (const char *ValName = getValueName())
1207 Len += std::strlen(getValueStr(O, ValName)) + 3;
1212 // printOptionInfo - Print out information about this option. The
1213 // to-be-maintained width is specified.
1215 void basic_parser_impl::printOptionInfo(const Option &O,
1216 size_t GlobalWidth) const {
1217 outs() << " -" << O.ArgStr;
1219 if (const char *ValName = getValueName())
1220 outs() << "=<" << getValueStr(O, ValName) << '>';
1222 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1225 void basic_parser_impl::printOptionName(const Option &O,
1226 size_t GlobalWidth) const {
1227 outs() << " -" << O.ArgStr;
1228 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1231 // parser<bool> implementation
1233 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1235 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1241 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1245 return O.error("'" + Arg +
1246 "' is invalid value for boolean argument! Try 0 or 1");
1249 // parser<boolOrDefault> implementation
1251 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1252 boolOrDefault &Value) {
1253 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1258 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1263 return O.error("'" + Arg +
1264 "' is invalid value for boolean argument! Try 0 or 1");
1267 // parser<int> implementation
1269 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1271 if (Arg.getAsInteger(0, Value))
1272 return O.error("'" + Arg + "' value invalid for integer argument!");
1276 // parser<unsigned> implementation
1278 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1281 if (Arg.getAsInteger(0, Value))
1282 return O.error("'" + Arg + "' value invalid for uint argument!");
1286 // parser<unsigned long long> implementation
1288 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1290 unsigned long long &Value) {
1292 if (Arg.getAsInteger(0, Value))
1293 return O.error("'" + Arg + "' value invalid for uint argument!");
1297 // parser<double>/parser<float> implementation
1299 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1300 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1301 const char *ArgStart = TmpStr.c_str();
1303 Value = strtod(ArgStart, &End);
1305 return O.error("'" + Arg + "' value invalid for floating point argument!");
1309 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1311 return parseDouble(O, Arg, Val);
1314 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1317 if (parseDouble(O, Arg, dVal))
1323 // generic_parser_base implementation
1326 // findOption - Return the option number corresponding to the specified
1327 // argument string. If the option is not found, getNumOptions() is returned.
1329 unsigned generic_parser_base::findOption(const char *Name) {
1330 unsigned e = getNumOptions();
1332 for (unsigned i = 0; i != e; ++i) {
1333 if (strcmp(getOption(i), Name) == 0)
1339 // Return the width of the option tag for printing...
1340 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1341 if (O.hasArgStr()) {
1342 size_t Size = std::strlen(O.ArgStr) + 6;
1343 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1344 Size = std::max(Size, std::strlen(getOption(i)) + 8);
1347 size_t BaseSize = 0;
1348 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1349 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
1354 // printOptionInfo - Print out information about this option. The
1355 // to-be-maintained width is specified.
1357 void generic_parser_base::printOptionInfo(const Option &O,
1358 size_t GlobalWidth) const {
1359 if (O.hasArgStr()) {
1360 outs() << " -" << O.ArgStr;
1361 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1363 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1364 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
1365 outs() << " =" << getOption(i);
1366 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1370 outs() << " " << O.HelpStr << '\n';
1371 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1372 const char *Option = getOption(i);
1373 outs() << " -" << Option;
1374 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1379 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1381 // printGenericOptionDiff - Print the value of this option and it's default.
1383 // "Generic" options have each value mapped to a name.
1384 void generic_parser_base::printGenericOptionDiff(
1385 const Option &O, const GenericOptionValue &Value,
1386 const GenericOptionValue &Default, size_t GlobalWidth) const {
1387 outs() << " -" << O.ArgStr;
1388 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1390 unsigned NumOpts = getNumOptions();
1391 for (unsigned i = 0; i != NumOpts; ++i) {
1392 if (Value.compare(getOptionValue(i)))
1395 outs() << "= " << getOption(i);
1396 size_t L = std::strlen(getOption(i));
1397 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1398 outs().indent(NumSpaces) << " (default: ";
1399 for (unsigned j = 0; j != NumOpts; ++j) {
1400 if (Default.compare(getOptionValue(j)))
1402 outs() << getOption(j);
1408 outs() << "= *unknown option value*\n";
1411 // printOptionDiff - Specializations for printing basic value types.
1413 #define PRINT_OPT_DIFF(T) \
1414 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1415 size_t GlobalWidth) const { \
1416 printOptionName(O, GlobalWidth); \
1419 raw_string_ostream SS(Str); \
1422 outs() << "= " << Str; \
1423 size_t NumSpaces = \
1424 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1425 outs().indent(NumSpaces) << " (default: "; \
1427 outs() << D.getValue(); \
1429 outs() << "*no default*"; \
1433 PRINT_OPT_DIFF(bool)
1434 PRINT_OPT_DIFF(boolOrDefault)
1436 PRINT_OPT_DIFF(unsigned)
1437 PRINT_OPT_DIFF(unsigned long long)
1438 PRINT_OPT_DIFF(double)
1439 PRINT_OPT_DIFF(float)
1440 PRINT_OPT_DIFF(char)
1442 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1443 OptionValue<std::string> D,
1444 size_t GlobalWidth) const {
1445 printOptionName(O, GlobalWidth);
1446 outs() << "= " << V;
1447 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1448 outs().indent(NumSpaces) << " (default: ";
1450 outs() << D.getValue();
1452 outs() << "*no default*";
1456 // Print a placeholder for options that don't yet support printOptionDiff().
1457 void basic_parser_impl::printOptionNoValue(const Option &O,
1458 size_t GlobalWidth) const {
1459 printOptionName(O, GlobalWidth);
1460 outs() << "= *cannot print option value*\n";
1463 //===----------------------------------------------------------------------===//
1464 // -help and -help-hidden option implementation
1467 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1468 const std::pair<const char *, Option *> *RHS) {
1469 return strcmp(LHS->first, RHS->first);
1472 // Copy Options into a vector so we can sort them as we like.
1473 static void sortOpts(StringMap<Option *> &OptMap,
1474 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1476 SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
1478 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1480 // Ignore really-hidden options.
1481 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1484 // Unless showhidden is set, ignore hidden flags.
1485 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1488 // If we've already seen this option, don't add it to the list again.
1489 if (!OptionSet.insert(I->second).second)
1493 std::pair<const char *, Option *>(I->getKey().data(), I->second));
1496 // Sort the options list alphabetically.
1497 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1504 const bool ShowHidden;
1505 typedef SmallVector<std::pair<const char *, Option *>, 128>
1506 StrOptionPairVector;
1507 // Print the options. Opts is assumed to be alphabetically sorted.
1508 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1509 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1510 Opts[i].second->printOptionInfo(MaxArgLen);
1514 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1515 virtual ~HelpPrinter() {}
1517 // Invoke the printer.
1518 void operator=(bool Value) {
1522 StrOptionPairVector Opts;
1523 sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
1525 if (GlobalParser->ProgramOverview)
1526 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1528 outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
1530 for (auto Opt : GlobalParser->PositionalOpts) {
1532 outs() << " --" << Opt->ArgStr;
1533 outs() << " " << Opt->HelpStr;
1536 // Print the consume after option info if it exists...
1537 if (GlobalParser->ConsumeAfterOpt)
1538 outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
1542 // Compute the maximum argument length...
1543 size_t MaxArgLen = 0;
1544 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1545 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1547 outs() << "OPTIONS:\n";
1548 printOptions(Opts, MaxArgLen);
1550 // Print any extra help the user has declared.
1551 for (auto I : GlobalParser->MoreHelp)
1553 GlobalParser->MoreHelp.clear();
1555 // Halt the program since help information was printed
1560 class CategorizedHelpPrinter : public HelpPrinter {
1562 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1564 // Helper function for printOptions().
1565 // It shall return a negative value if A's name should be lexicographically
1566 // ordered before B's name. It returns a value greater equal zero otherwise.
1567 static int OptionCategoryCompare(OptionCategory *const *A,
1568 OptionCategory *const *B) {
1569 return strcmp((*A)->getName(), (*B)->getName());
1572 // Make sure we inherit our base class's operator=()
1573 using HelpPrinter::operator=;
1576 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1577 std::vector<OptionCategory *> SortedCategories;
1578 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1580 // Collect registered option categories into vector in preparation for
1582 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1583 E = GlobalParser->RegisteredOptionCategories.end();
1585 SortedCategories.push_back(*I);
1588 // Sort the different option categories alphabetically.
1589 assert(SortedCategories.size() > 0 && "No option categories registered!");
1590 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1591 OptionCategoryCompare);
1593 // Create map to empty vectors.
1594 for (std::vector<OptionCategory *>::const_iterator
1595 I = SortedCategories.begin(),
1596 E = SortedCategories.end();
1598 CategorizedOptions[*I] = std::vector<Option *>();
1600 // Walk through pre-sorted options and assign into categories.
1601 // Because the options are already alphabetically sorted the
1602 // options within categories will also be alphabetically sorted.
1603 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1604 Option *Opt = Opts[I].second;
1605 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1606 "Option has an unregistered category");
1607 CategorizedOptions[Opt->Category].push_back(Opt);
1611 for (std::vector<OptionCategory *>::const_iterator
1612 Category = SortedCategories.begin(),
1613 E = SortedCategories.end();
1614 Category != E; ++Category) {
1615 // Hide empty categories for -help, but show for -help-hidden.
1616 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1617 if (!ShowHidden && IsEmptyCategory)
1620 // Print category information.
1622 outs() << (*Category)->getName() << ":\n";
1624 // Check if description is set.
1625 if ((*Category)->getDescription() != nullptr)
1626 outs() << (*Category)->getDescription() << "\n\n";
1630 // When using -help-hidden explicitly state if the category has no
1631 // options associated with it.
1632 if (IsEmptyCategory) {
1633 outs() << " This option category has no options.\n";
1636 // Loop over the options in the category and print.
1637 for (std::vector<Option *>::const_iterator
1638 Opt = CategorizedOptions[*Category].begin(),
1639 E = CategorizedOptions[*Category].end();
1641 (*Opt)->printOptionInfo(MaxArgLen);
1646 // This wraps the Uncategorizing and Categorizing printers and decides
1647 // at run time which should be invoked.
1648 class HelpPrinterWrapper {
1650 HelpPrinter &UncategorizedPrinter;
1651 CategorizedHelpPrinter &CategorizedPrinter;
1654 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1655 CategorizedHelpPrinter &CategorizedPrinter)
1656 : UncategorizedPrinter(UncategorizedPrinter),
1657 CategorizedPrinter(CategorizedPrinter) {}
1659 // Invoke the printer.
1660 void operator=(bool Value);
1663 } // End anonymous namespace
1665 // Declare the four HelpPrinter instances that are used to print out help, or
1666 // help-hidden as an uncategorized list or in categories.
1667 static HelpPrinter UncategorizedNormalPrinter(false);
1668 static HelpPrinter UncategorizedHiddenPrinter(true);
1669 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1670 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1672 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1673 // a categorizing help printer
1674 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1675 CategorizedNormalPrinter);
1676 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1677 CategorizedHiddenPrinter);
1679 // Define a category for generic options that all tools should have.
1680 static cl::OptionCategory GenericCategory("Generic Options");
1682 // Define uncategorized help printers.
1683 // -help-list is hidden by default because if Option categories are being used
1684 // then -help behaves the same as -help-list.
1685 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1687 cl::desc("Display list of available options (-help-list-hidden for more)"),
1688 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1689 cl::cat(GenericCategory));
1691 static cl::opt<HelpPrinter, true, parser<bool>>
1692 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1693 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1694 cl::ValueDisallowed, cl::cat(GenericCategory));
1696 // Define uncategorized/categorized help printers. These printers change their
1697 // behaviour at runtime depending on whether one or more Option categories have
1699 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1700 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1701 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1702 cl::cat(GenericCategory));
1704 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1705 HHOp("help-hidden", cl::desc("Display all available options"),
1706 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1707 cl::cat(GenericCategory));
1709 static cl::opt<bool> PrintOptions(
1711 cl::desc("Print non-default options after command line parsing"),
1712 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
1714 static cl::opt<bool> PrintAllOptions(
1715 "print-all-options",
1716 cl::desc("Print all option values after command line parsing"), cl::Hidden,
1717 cl::init(false), cl::cat(GenericCategory));
1719 void HelpPrinterWrapper::operator=(bool Value) {
1723 // Decide which printer to invoke. If more than one option category is
1724 // registered then it is useful to show the categorized help instead of
1725 // uncategorized help.
1726 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
1727 // unhide -help-list option so user can have uncategorized output if they
1729 HLOp.setHiddenFlag(NotHidden);
1731 CategorizedPrinter = true; // Invoke categorized printer
1733 UncategorizedPrinter = true; // Invoke uncategorized printer
1736 // Print the value of each option.
1737 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
1739 void CommandLineParser::printOptionValues() {
1740 if (!PrintOptions && !PrintAllOptions)
1743 SmallVector<std::pair<const char *, Option *>, 128> Opts;
1744 sortOpts(OptionsMap, Opts, /*ShowHidden*/ true);
1746 // Compute the maximum argument length...
1747 size_t MaxArgLen = 0;
1748 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1749 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1751 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1752 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1755 static void (*OverrideVersionPrinter)() = nullptr;
1757 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
1760 class VersionPrinter {
1763 raw_ostream &OS = outs();
1764 OS << "LLVM (http://llvm.org/):\n"
1765 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1766 #ifdef LLVM_VERSION_INFO
1767 OS << " " << LLVM_VERSION_INFO;
1770 #ifndef __OPTIMIZE__
1771 OS << "DEBUG build";
1773 OS << "Optimized build";
1776 OS << " with assertions";
1778 std::string CPU = sys::getHostCPUName();
1779 if (CPU == "generic")
1782 #if (ENABLE_TIMESTAMPS == 1)
1783 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1785 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1786 << " Host CPU: " << CPU << '\n';
1788 void operator=(bool OptionWasSpecified) {
1789 if (!OptionWasSpecified)
1792 if (OverrideVersionPrinter != nullptr) {
1793 (*OverrideVersionPrinter)();
1798 // Iterate over any registered extra printers and call them to add further
1800 if (ExtraVersionPrinters != nullptr) {
1802 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1803 E = ExtraVersionPrinters->end();
1811 } // End anonymous namespace
1813 // Define the --version option that prints out the LLVM version for the tool
1814 static VersionPrinter VersionPrinterInstance;
1816 static cl::opt<VersionPrinter, true, parser<bool>>
1817 VersOp("version", cl::desc("Display the version of this program"),
1818 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1819 cl::cat(GenericCategory));
1821 // Utility function for printing the help message.
1822 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1823 // This looks weird, but it actually prints the help message. The Printers are
1824 // types of HelpPrinter and the help gets printed when its operator= is
1825 // invoked. That's because the "normal" usages of the help printer is to be
1826 // assigned true/false depending on whether -help or -help-hidden was given or
1827 // not. Since we're circumventing that we have to make it look like -help or
1828 // -help-hidden were given, so we assign true.
1830 if (!Hidden && !Categorized)
1831 UncategorizedNormalPrinter = true;
1832 else if (!Hidden && Categorized)
1833 CategorizedNormalPrinter = true;
1834 else if (Hidden && !Categorized)
1835 UncategorizedHiddenPrinter = true;
1837 CategorizedHiddenPrinter = true;
1840 /// Utility function for printing version number.
1841 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
1843 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
1845 void cl::AddExtraVersionPrinter(void (*func)()) {
1846 if (!ExtraVersionPrinters)
1847 ExtraVersionPrinters = new std::vector<void (*)()>;
1849 ExtraVersionPrinters->push_back(func);
1852 StringMap<Option *> &cl::getRegisteredOptions() {
1853 return GlobalParser->OptionsMap;
1856 void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
1857 for (auto &I : GlobalParser->OptionsMap) {
1858 if (I.second->Category != &Category &&
1859 I.second->Category != &GenericCategory)
1860 I.second->setHiddenFlag(cl::ReallyHidden);
1864 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
1865 auto CategoriesBegin = Categories.begin();
1866 auto CategoriesEnd = Categories.end();
1867 for (auto &I : GlobalParser->OptionsMap) {
1868 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1870 I.second->Category != &GenericCategory)
1871 I.second->setHiddenFlag(cl::ReallyHidden);
1875 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1876 const char *Overview) {
1877 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);