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/DenseMap.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Config/config.h"
30 #include "llvm/Support/ConvertUTF.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Process.h"
39 #include "llvm/Support/StringSaver.h"
40 #include "llvm/Support/raw_ostream.h"
46 #define DEBUG_TYPE "commandline"
48 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
50 // If LLVM_ENABLE_ABI_BREAKING_CHECKS is set the flag -mllvm -reverse-iterate
51 // can be used to toggle forward/reverse iteration of unordered containers.
52 // This will help uncover differences in codegen caused due to undefined
54 static cl::opt<bool, true> ReverseIteration("reverse-iterate",
55 cl::location(ReverseIterate<bool>::value));
59 //===----------------------------------------------------------------------===//
60 // Template instantiations and anchors.
64 template class basic_parser<bool>;
65 template class basic_parser<boolOrDefault>;
66 template class basic_parser<int>;
67 template class basic_parser<unsigned>;
68 template class basic_parser<unsigned long long>;
69 template class basic_parser<double>;
70 template class basic_parser<float>;
71 template class basic_parser<std::string>;
72 template class basic_parser<char>;
74 template class opt<unsigned>;
75 template class opt<int>;
76 template class opt<std::string>;
77 template class opt<char>;
78 template class opt<bool>;
80 } // end namespace llvm::cl
82 // Pin the vtables to this file.
83 void GenericOptionValue::anchor() {}
84 void OptionValue<boolOrDefault>::anchor() {}
85 void OptionValue<std::string>::anchor() {}
86 void Option::anchor() {}
87 void basic_parser_impl::anchor() {}
88 void parser<bool>::anchor() {}
89 void parser<boolOrDefault>::anchor() {}
90 void parser<int>::anchor() {}
91 void parser<unsigned>::anchor() {}
92 void parser<unsigned long long>::anchor() {}
93 void parser<double>::anchor() {}
94 void parser<float>::anchor() {}
95 void parser<std::string>::anchor() {}
96 void parser<char>::anchor() {}
98 //===----------------------------------------------------------------------===//
102 class CommandLineParser {
104 // Globals for name and overview of program. Program name is not a string to
105 // avoid static ctor/dtor issues.
106 std::string ProgramName;
107 StringRef ProgramOverview;
109 // This collects additional help to be printed.
110 std::vector<StringRef> MoreHelp;
112 // This collects the different option categories that have been registered.
113 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
115 // This collects the different subcommands that have been registered.
116 SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
118 CommandLineParser() : ActiveSubCommand(nullptr) {
119 registerSubCommand(&*TopLevelSubCommand);
120 registerSubCommand(&*AllSubCommands);
123 void ResetAllOptionOccurrences();
125 bool ParseCommandLineOptions(int argc, const char *const *argv,
126 StringRef Overview, bool IgnoreErrors);
128 void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
131 if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
132 errs() << ProgramName << ": CommandLine Error: Option '" << Name
133 << "' registered more than once!\n";
134 report_fatal_error("inconsistency in registered CommandLine options");
137 // If we're adding this to all sub-commands, add it to the ones that have
138 // already been registered.
139 if (SC == &*AllSubCommands) {
140 for (const auto &Sub : RegisteredSubCommands) {
143 addLiteralOption(Opt, Sub, Name);
148 void addLiteralOption(Option &Opt, StringRef Name) {
149 if (Opt.Subs.empty())
150 addLiteralOption(Opt, &*TopLevelSubCommand, Name);
152 for (auto SC : Opt.Subs)
153 addLiteralOption(Opt, SC, Name);
157 void addOption(Option *O, SubCommand *SC) {
158 bool HadErrors = false;
159 if (O->hasArgStr()) {
160 // Add argument to the argument map!
161 if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
162 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
163 << "' registered more than once!\n";
168 // Remember information about positional options.
169 if (O->getFormattingFlag() == cl::Positional)
170 SC->PositionalOpts.push_back(O);
171 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
172 SC->SinkOpts.push_back(O);
173 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
174 if (SC->ConsumeAfterOpt) {
175 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
178 SC->ConsumeAfterOpt = O;
181 // Fail hard if there were errors. These are strictly unrecoverable and
182 // indicate serious issues such as conflicting option names or an
184 // linked LLVM distribution.
186 report_fatal_error("inconsistency in registered CommandLine options");
188 // If we're adding this to all sub-commands, add it to the ones that have
189 // already been registered.
190 if (SC == &*AllSubCommands) {
191 for (const auto &Sub : RegisteredSubCommands) {
199 void addOption(Option *O) {
200 if (O->Subs.empty()) {
201 addOption(O, &*TopLevelSubCommand);
203 for (auto SC : O->Subs)
208 void removeOption(Option *O, SubCommand *SC) {
209 SmallVector<StringRef, 16> OptionNames;
210 O->getExtraOptionNames(OptionNames);
212 OptionNames.push_back(O->ArgStr);
214 SubCommand &Sub = *SC;
215 for (auto Name : OptionNames)
216 Sub.OptionsMap.erase(Name);
218 if (O->getFormattingFlag() == cl::Positional)
219 for (auto Opt = Sub.PositionalOpts.begin();
220 Opt != Sub.PositionalOpts.end(); ++Opt) {
222 Sub.PositionalOpts.erase(Opt);
226 else if (O->getMiscFlags() & cl::Sink)
227 for (auto Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
229 Sub.SinkOpts.erase(Opt);
233 else if (O == Sub.ConsumeAfterOpt)
234 Sub.ConsumeAfterOpt = nullptr;
237 void removeOption(Option *O) {
239 removeOption(O, &*TopLevelSubCommand);
241 if (O->isInAllSubCommands()) {
242 for (auto SC : RegisteredSubCommands)
245 for (auto SC : O->Subs)
251 bool hasOptions(const SubCommand &Sub) const {
252 return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
253 nullptr != Sub.ConsumeAfterOpt);
256 bool hasOptions() const {
257 for (const auto &S : RegisteredSubCommands) {
264 SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
266 void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
267 SubCommand &Sub = *SC;
268 if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
269 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
270 << "' registered more than once!\n";
271 report_fatal_error("inconsistency in registered CommandLine options");
273 Sub.OptionsMap.erase(O->ArgStr);
276 void updateArgStr(Option *O, StringRef NewName) {
278 updateArgStr(O, NewName, &*TopLevelSubCommand);
280 for (auto SC : O->Subs)
281 updateArgStr(O, NewName, SC);
285 void printOptionValues();
287 void registerCategory(OptionCategory *cat) {
288 assert(count_if(RegisteredOptionCategories,
289 [cat](const OptionCategory *Category) {
290 return cat->getName() == Category->getName();
292 "Duplicate option categories");
294 RegisteredOptionCategories.insert(cat);
297 void registerSubCommand(SubCommand *sub) {
298 assert(count_if(RegisteredSubCommands,
299 [sub](const SubCommand *Sub) {
300 return (!sub->getName().empty()) &&
301 (Sub->getName() == sub->getName());
303 "Duplicate subcommands");
304 RegisteredSubCommands.insert(sub);
306 // For all options that have been registered for all subcommands, add the
307 // option to this subcommand now.
308 if (sub != &*AllSubCommands) {
309 for (auto &E : AllSubCommands->OptionsMap) {
310 Option *O = E.second;
311 if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
315 addLiteralOption(*O, sub, E.first());
320 void unregisterSubCommand(SubCommand *sub) {
321 RegisteredSubCommands.erase(sub);
324 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
325 getRegisteredSubcommands() {
326 return make_range(RegisteredSubCommands.begin(),
327 RegisteredSubCommands.end());
331 ActiveSubCommand = nullptr;
333 ProgramOverview = StringRef();
336 RegisteredOptionCategories.clear();
338 ResetAllOptionOccurrences();
339 RegisteredSubCommands.clear();
341 TopLevelSubCommand->reset();
342 AllSubCommands->reset();
343 registerSubCommand(&*TopLevelSubCommand);
344 registerSubCommand(&*AllSubCommands);
348 SubCommand *ActiveSubCommand;
350 Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
351 SubCommand *LookupSubCommand(StringRef Name);
356 static ManagedStatic<CommandLineParser> GlobalParser;
358 void cl::AddLiteralOption(Option &O, StringRef Name) {
359 GlobalParser->addLiteralOption(O, Name);
362 extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
363 GlobalParser->MoreHelp.push_back(Help);
366 void Option::addArgument() {
367 GlobalParser->addOption(this);
368 FullyInitialized = true;
371 void Option::removeArgument() { GlobalParser->removeOption(this); }
373 void Option::setArgStr(StringRef S) {
374 if (FullyInitialized)
375 GlobalParser->updateArgStr(this, S);
376 assert((S.empty() || S[0] != '-') && "Option can't start with '-");
380 // Initialise the general option category.
381 OptionCategory llvm::cl::GeneralCategory("General options");
383 void OptionCategory::registerCategory() {
384 GlobalParser->registerCategory(this);
387 // A special subcommand representing no subcommand
388 ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
390 // A special subcommand that can be used to put an option into all subcommands.
391 ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
393 void SubCommand::registerSubCommand() {
394 GlobalParser->registerSubCommand(this);
397 void SubCommand::unregisterSubCommand() {
398 GlobalParser->unregisterSubCommand(this);
401 void SubCommand::reset() {
402 PositionalOpts.clear();
406 ConsumeAfterOpt = nullptr;
409 SubCommand::operator bool() const {
410 return (GlobalParser->getActiveSubCommand() == this);
413 //===----------------------------------------------------------------------===//
414 // Basic, shared command line option processing machinery.
417 /// LookupOption - Lookup the option specified by the specified option on the
418 /// command line. If there is a value specified (after an equal sign) return
419 /// that as well. This assumes that leading dashes have already been stripped.
420 Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
422 // Reject all dashes.
425 assert(&Sub != &*AllSubCommands);
427 size_t EqualPos = Arg.find('=');
429 // If we have an equals sign, remember the value.
430 if (EqualPos == StringRef::npos) {
431 // Look up the option.
432 auto I = Sub.OptionsMap.find(Arg);
433 if (I == Sub.OptionsMap.end())
436 return I != Sub.OptionsMap.end() ? I->second : nullptr;
439 // If the argument before the = is a valid option name, we match. If not,
440 // return Arg unmolested.
441 auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
442 if (I == Sub.OptionsMap.end())
445 Value = Arg.substr(EqualPos + 1);
446 Arg = Arg.substr(0, EqualPos);
450 SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
452 return &*TopLevelSubCommand;
453 for (auto S : RegisteredSubCommands) {
454 if (S == &*AllSubCommands)
456 if (S->getName().empty())
459 if (StringRef(S->getName()) == StringRef(Name))
462 return &*TopLevelSubCommand;
465 /// LookupNearestOption - Lookup the closest match to the option specified by
466 /// the specified option on the command line. If there is a value specified
467 /// (after an equal sign) return that as well. This assumes that leading dashes
468 /// have already been stripped.
469 static Option *LookupNearestOption(StringRef Arg,
470 const StringMap<Option *> &OptionsMap,
471 std::string &NearestString) {
472 // Reject all dashes.
476 // Split on any equal sign.
477 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
478 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
479 StringRef &RHS = SplitArg.second;
481 // Find the closest match.
482 Option *Best = nullptr;
483 unsigned BestDistance = 0;
484 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
485 ie = OptionsMap.end();
487 Option *O = it->second;
488 SmallVector<StringRef, 16> OptionNames;
489 O->getExtraOptionNames(OptionNames);
491 OptionNames.push_back(O->ArgStr);
493 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
494 StringRef Flag = PermitValue ? LHS : Arg;
495 for (auto Name : OptionNames) {
496 unsigned Distance = StringRef(Name).edit_distance(
497 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
498 if (!Best || Distance < BestDistance) {
500 BestDistance = Distance;
501 if (RHS.empty() || !PermitValue)
502 NearestString = Name;
504 NearestString = (Twine(Name) + "=" + RHS).str();
512 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
513 /// that does special handling of cl::CommaSeparated options.
514 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
515 StringRef ArgName, StringRef Value,
516 bool MultiArg = false) {
517 // Check to see if this option accepts a comma separated list of values. If
518 // it does, we have to split up the value into multiple values.
519 if (Handler->getMiscFlags() & CommaSeparated) {
520 StringRef Val(Value);
521 StringRef::size_type Pos = Val.find(',');
523 while (Pos != StringRef::npos) {
524 // Process the portion before the comma.
525 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
527 // Erase the portion before the comma, AND the comma.
528 Val = Val.substr(Pos + 1);
529 // Check for another comma.
536 return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
539 /// ProvideOption - For Value, this differentiates between an empty value ("")
540 /// and a null value (StringRef()). The later is accepted for arguments that
541 /// don't allow a value (-foo) the former is rejected (-foo=).
542 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
543 StringRef Value, int argc,
544 const char *const *argv, int &i) {
545 // Is this a multi-argument option?
546 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
548 // Enforce value requirements
549 switch (Handler->getValueExpectedFlag()) {
551 if (!Value.data()) { // No value specified?
553 return Handler->error("requires a value!");
554 // Steal the next argument, like for '-o filename'
555 assert(argv && "null check");
556 Value = StringRef(argv[++i]);
559 case ValueDisallowed:
560 if (NumAdditionalVals > 0)
561 return Handler->error("multi-valued option specified"
562 " with ValueDisallowed modifier!");
565 return Handler->error("does not allow a value! '" + Twine(Value) +
572 // If this isn't a multi-arg option, just run the handler.
573 if (NumAdditionalVals == 0)
574 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
576 // If it is, run the handle several times.
577 bool MultiArg = false;
580 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
586 while (NumAdditionalVals > 0) {
588 return Handler->error("not enough values!");
589 assert(argv && "null check");
590 Value = StringRef(argv[++i]);
592 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
600 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
602 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
605 // Option predicates...
606 static inline bool isGrouping(const Option *O) {
607 return O->getFormattingFlag() == cl::Grouping;
609 static inline bool isPrefixedOrGrouping(const Option *O) {
610 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
613 // getOptionPred - Check to see if there are any options that satisfy the
614 // specified predicate with names that are the prefixes in Name. This is
615 // checked by progressively stripping characters off of the name, checking to
616 // see if there options that satisfy the predicate. If we find one, return it,
617 // otherwise return null.
619 static Option *getOptionPred(StringRef Name, size_t &Length,
620 bool (*Pred)(const Option *),
621 const StringMap<Option *> &OptionsMap) {
623 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
625 // Loop while we haven't found an option and Name still has at least two
626 // characters in it (so that the next iteration will not be the empty
628 while (OMI == OptionsMap.end() && Name.size() > 1) {
629 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
630 OMI = OptionsMap.find(Name);
633 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
634 Length = Name.size();
635 return OMI->second; // Found one!
637 return nullptr; // No option found!
640 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
641 /// with at least one '-') does not fully match an available option. Check to
642 /// see if this is a prefix or grouped option. If so, split arg into output an
643 /// Arg/Value pair and return the Option to parse it with.
645 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
647 const StringMap<Option *> &OptionsMap) {
653 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
657 // If the option is a prefixed option, then the value is simply the
658 // rest of the name... so fall through to later processing, by
659 // setting up the argument name flags and value fields.
660 if (PGOpt->getFormattingFlag() == cl::Prefix) {
661 Value = Arg.substr(Length);
662 Arg = Arg.substr(0, Length);
663 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
667 // This must be a grouped option... handle them now. Grouping options can't
669 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
672 // Move current arg name out of Arg into OneArgName.
673 StringRef OneArgName = Arg.substr(0, Length);
674 Arg = Arg.substr(Length);
676 // Because ValueRequired is an invalid flag for grouped arguments,
677 // we don't need to pass argc/argv in.
678 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
679 "Option can not be cl::Grouping AND cl::ValueRequired!");
682 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
684 // Get the next grouping option.
685 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
686 } while (PGOpt && Length != Arg.size());
688 // Return the last option with Arg cut down to just the last one.
692 static bool RequiresValue(const Option *O) {
693 return O->getNumOccurrencesFlag() == cl::Required ||
694 O->getNumOccurrencesFlag() == cl::OneOrMore;
697 static bool EatsUnboundedNumberOfValues(const Option *O) {
698 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
699 O->getNumOccurrencesFlag() == cl::OneOrMore;
702 static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
704 static bool isQuote(char C) { return C == '\"' || C == '\''; }
706 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
707 SmallVectorImpl<const char *> &NewArgv,
709 SmallString<128> Token;
710 for (size_t I = 0, E = Src.size(); I != E; ++I) {
711 // Consume runs of whitespace.
713 while (I != E && isWhitespace(Src[I])) {
714 // Mark the end of lines in response files
715 if (MarkEOLs && Src[I] == '\n')
716 NewArgv.push_back(nullptr);
723 // Backslash escapes the next character.
724 if (I + 1 < E && Src[I] == '\\') {
725 ++I; // Skip the escape.
726 Token.push_back(Src[I]);
730 // Consume a quoted string.
731 if (isQuote(Src[I])) {
732 char Quote = Src[I++];
733 while (I != E && Src[I] != Quote) {
734 // Backslash escapes the next character.
735 if (Src[I] == '\\' && I + 1 != E)
737 Token.push_back(Src[I]);
745 // End the token if this is whitespace.
746 if (isWhitespace(Src[I])) {
748 NewArgv.push_back(Saver.save(StringRef(Token)).data());
753 // This is a normal character. Append it.
754 Token.push_back(Src[I]);
757 // Append the last token after hitting EOF with no whitespace.
759 NewArgv.push_back(Saver.save(StringRef(Token)).data());
760 // Mark the end of response files
762 NewArgv.push_back(nullptr);
765 /// Backslashes are interpreted in a rather complicated way in the Windows-style
766 /// command line, because backslashes are used both to separate path and to
767 /// escape double quote. This method consumes runs of backslashes as well as the
768 /// following double quote if it's escaped.
770 /// * If an even number of backslashes is followed by a double quote, one
771 /// backslash is output for every pair of backslashes, and the last double
772 /// quote remains unconsumed. The double quote will later be interpreted as
773 /// the start or end of a quoted string in the main loop outside of this
776 /// * If an odd number of backslashes is followed by a double quote, one
777 /// backslash is output for every pair of backslashes, and a double quote is
778 /// output for the last pair of backslash-double quote. The double quote is
779 /// consumed in this case.
781 /// * Otherwise, backslashes are interpreted literally.
782 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
783 size_t E = Src.size();
784 int BackslashCount = 0;
785 // Skip the backslashes.
789 } while (I != E && Src[I] == '\\');
791 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
792 if (FollowedByDoubleQuote) {
793 Token.append(BackslashCount / 2, '\\');
794 if (BackslashCount % 2 == 0)
796 Token.push_back('"');
799 Token.append(BackslashCount, '\\');
803 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
804 SmallVectorImpl<const char *> &NewArgv,
806 SmallString<128> Token;
808 // This is a small state machine to consume characters until it reaches the
809 // end of the source string.
810 enum { INIT, UNQUOTED, QUOTED } State = INIT;
811 for (size_t I = 0, E = Src.size(); I != E; ++I) {
812 // INIT state indicates that the current input index is at the start of
813 // the string or between tokens.
815 if (isWhitespace(Src[I])) {
816 // Mark the end of lines in response files
817 if (MarkEOLs && Src[I] == '\n')
818 NewArgv.push_back(nullptr);
825 if (Src[I] == '\\') {
826 I = parseBackslash(Src, I, Token);
830 Token.push_back(Src[I]);
835 // UNQUOTED state means that it's reading a token not quoted by double
837 if (State == UNQUOTED) {
838 // Whitespace means the end of the token.
839 if (isWhitespace(Src[I])) {
840 NewArgv.push_back(Saver.save(StringRef(Token)).data());
843 // Mark the end of lines in response files
844 if (MarkEOLs && Src[I] == '\n')
845 NewArgv.push_back(nullptr);
852 if (Src[I] == '\\') {
853 I = parseBackslash(Src, I, Token);
856 Token.push_back(Src[I]);
860 // QUOTED state means that it's reading a token quoted by double quotes.
861 if (State == QUOTED) {
866 if (Src[I] == '\\') {
867 I = parseBackslash(Src, I, Token);
870 Token.push_back(Src[I]);
873 // Append the last token after hitting EOF with no whitespace.
875 NewArgv.push_back(Saver.save(StringRef(Token)).data());
876 // Mark the end of response files
878 NewArgv.push_back(nullptr);
881 // It is called byte order marker but the UTF-8 BOM is actually not affected
882 // by the host system's endianness.
883 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
884 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
887 static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
888 TokenizerCallback Tokenizer,
889 SmallVectorImpl<const char *> &NewArgv,
890 bool MarkEOLs, bool RelativeNames) {
891 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
892 MemoryBuffer::getFile(FName);
895 MemoryBuffer &MemBuf = *MemBufOrErr.get();
896 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
898 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
899 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
901 if (hasUTF16ByteOrderMark(BufRef)) {
902 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
904 Str = StringRef(UTF8Buf);
906 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
907 // these bytes before parsing.
908 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
909 else if (hasUTF8ByteOrderMark(BufRef))
910 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
912 // Tokenize the contents into NewArgv.
913 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
915 // If names of nested response files should be resolved relative to including
916 // file, replace the included response file names with their full paths
917 // obtained by required resolution.
919 for (unsigned I = 0; I < NewArgv.size(); ++I)
921 StringRef Arg = NewArgv[I];
922 if (Arg.front() == '@') {
923 StringRef FileName = Arg.drop_front();
924 if (llvm::sys::path::is_relative(FileName)) {
925 SmallString<128> ResponseFile;
926 ResponseFile.append(1, '@');
927 if (llvm::sys::path::is_relative(FName)) {
928 SmallString<128> curr_dir;
929 llvm::sys::fs::current_path(curr_dir);
930 ResponseFile.append(curr_dir.str());
932 llvm::sys::path::append(
933 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
934 NewArgv[I] = Saver.save(ResponseFile.c_str()).data();
942 /// \brief Expand response files on a command line recursively using the given
943 /// StringSaver and tokenization strategy.
944 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
945 SmallVectorImpl<const char *> &Argv,
946 bool MarkEOLs, bool RelativeNames) {
947 unsigned RspFiles = 0;
948 bool AllExpanded = true;
950 // Don't cache Argv.size() because it can change.
951 for (unsigned I = 0; I != Argv.size();) {
952 const char *Arg = Argv[I];
953 // Check if it is an EOL marker
954 if (Arg == nullptr) {
963 // If we have too many response files, leave some unexpanded. This avoids
964 // crashing on self-referential response files.
968 // Replace this response file argument with the tokenization of its
969 // contents. Nested response files are expanded in subsequent iterations.
970 SmallVector<const char *, 0> ExpandedArgv;
971 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
972 MarkEOLs, RelativeNames)) {
973 // We couldn't read this file, so we leave it in the argument stream and
979 Argv.erase(Argv.begin() + I);
980 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
985 /// ParseEnvironmentOptions - An alternative entry point to the
986 /// CommandLine library, which allows you to read the program's name
987 /// from the caller (as PROGNAME) and its command-line arguments from
988 /// an environment variable (whose name is given in ENVVAR).
990 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
991 const char *Overview) {
993 assert(progName && "Program name not specified");
994 assert(envVar && "Environment variable name missing");
996 // Get the environment variable they want us to parse options out of.
997 llvm::Optional<std::string> envValue = sys::Process::GetEnv(StringRef(envVar));
1001 // Get program's "name", which we wouldn't know without the caller
1003 SmallVector<const char *, 20> newArgv;
1005 StringSaver Saver(A);
1006 newArgv.push_back(Saver.save(progName).data());
1008 // Parse the value of the environment variable into a "command line"
1009 // and hand it off to ParseCommandLineOptions().
1010 TokenizeGNUCommandLine(*envValue, Saver, newArgv);
1011 int newArgc = static_cast<int>(newArgv.size());
1012 ParseCommandLineOptions(newArgc, &newArgv[0], StringRef(Overview));
1015 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1016 StringRef Overview, bool IgnoreErrors) {
1017 return GlobalParser->ParseCommandLineOptions(argc, argv, Overview,
1021 void CommandLineParser::ResetAllOptionOccurrences() {
1022 // So that we can parse different command lines multiple times in succession
1023 // we reset all option values to look like they have never been seen before.
1024 for (auto SC : RegisteredSubCommands) {
1025 for (auto &O : SC->OptionsMap)
1030 bool CommandLineParser::ParseCommandLineOptions(int argc,
1031 const char *const *argv,
1033 bool IgnoreErrors) {
1034 assert(hasOptions() && "No options specified!");
1036 // Expand response files.
1037 SmallVector<const char *, 20> newArgv(argv, argv + argc);
1039 StringSaver Saver(A);
1040 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
1042 argc = static_cast<int>(newArgv.size());
1044 // Copy the program name into ProgName, making sure not to overflow it.
1045 ProgramName = sys::path::filename(StringRef(argv[0]));
1047 ProgramOverview = Overview;
1048 bool ErrorParsing = false;
1050 // Check out the positional arguments to collect information about them.
1051 unsigned NumPositionalRequired = 0;
1053 // Determine whether or not there are an unlimited number of positionals
1054 bool HasUnlimitedPositionals = false;
1057 SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1058 if (argc >= 2 && argv[FirstArg][0] != '-') {
1059 // If the first argument specifies a valid subcommand, start processing
1060 // options from the second argument.
1061 ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1062 if (ChosenSubCommand != &*TopLevelSubCommand)
1065 GlobalParser->ActiveSubCommand = ChosenSubCommand;
1067 assert(ChosenSubCommand);
1068 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1069 auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1070 auto &SinkOpts = ChosenSubCommand->SinkOpts;
1071 auto &OptionsMap = ChosenSubCommand->OptionsMap;
1073 if (ConsumeAfterOpt) {
1074 assert(PositionalOpts.size() > 0 &&
1075 "Cannot specify cl::ConsumeAfter without a positional argument!");
1077 if (!PositionalOpts.empty()) {
1079 // Calculate how many positional values are _required_.
1080 bool UnboundedFound = false;
1081 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1082 Option *Opt = PositionalOpts[i];
1083 if (RequiresValue(Opt))
1084 ++NumPositionalRequired;
1085 else if (ConsumeAfterOpt) {
1086 // ConsumeAfter cannot be combined with "optional" positional options
1087 // unless there is only one positional argument...
1088 if (PositionalOpts.size() > 1) {
1090 Opt->error("error - this positional option will never be matched, "
1091 "because it does not Require a value, and a "
1092 "cl::ConsumeAfter option is active!");
1093 ErrorParsing = true;
1095 } else if (UnboundedFound && !Opt->hasArgStr()) {
1096 // This option does not "require" a value... Make sure this option is
1097 // not specified after an option that eats all extra arguments, or this
1098 // one will never get any!
1100 if (!IgnoreErrors) {
1101 Opt->error("error - option can never match, because "
1102 "another positional argument will match an "
1103 "unbounded number of values, and this option"
1104 " does not require a value!");
1105 errs() << ProgramName << ": CommandLine Error: Option '"
1106 << Opt->ArgStr << "' is all messed up!\n";
1107 errs() << PositionalOpts.size();
1109 ErrorParsing = true;
1111 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1113 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1116 // PositionalVals - A vector of "positional" arguments we accumulate into
1117 // the process at the end.
1119 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1121 // If the program has named positional arguments, and the name has been run
1122 // across, keep track of which positional argument was named. Otherwise put
1123 // the positional args into the PositionalVals list...
1124 Option *ActivePositionalArg = nullptr;
1126 // Loop over all of the arguments... processing them.
1127 bool DashDashFound = false; // Have we read '--'?
1128 for (int i = FirstArg; i < argc; ++i) {
1129 Option *Handler = nullptr;
1130 Option *NearestHandler = nullptr;
1131 std::string NearestHandlerString;
1133 StringRef ArgName = "";
1135 // Check to see if this is a positional argument. This argument is
1136 // considered to be positional if it doesn't start with '-', if it is "-"
1137 // itself, or if we have seen "--" already.
1139 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1140 // Positional argument!
1141 if (ActivePositionalArg) {
1142 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1143 continue; // We are done!
1146 if (!PositionalOpts.empty()) {
1147 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1149 // All of the positional arguments have been fulfulled, give the rest to
1150 // the consume after option... if it's specified...
1152 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1153 for (++i; i < argc; ++i)
1154 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1155 break; // Handle outside of the argument processing loop...
1158 // Delay processing positional arguments until the end...
1161 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1163 DashDashFound = true; // This is the mythical "--"?
1164 continue; // Don't try to process it as an argument itself.
1165 } else if (ActivePositionalArg &&
1166 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1167 // If there is a positional argument eating options, check to see if this
1168 // option is another positional argument. If so, treat it as an argument,
1169 // otherwise feed it to the eating positional.
1170 ArgName = StringRef(argv[i] + 1);
1171 // Eat leading dashes.
1172 while (!ArgName.empty() && ArgName[0] == '-')
1173 ArgName = ArgName.substr(1);
1175 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1176 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1177 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1178 continue; // We are done!
1181 } else { // We start with a '-', must be an argument.
1182 ArgName = StringRef(argv[i] + 1);
1183 // Eat leading dashes.
1184 while (!ArgName.empty() && ArgName[0] == '-')
1185 ArgName = ArgName.substr(1);
1187 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1189 // Check to see if this "option" is really a prefixed or grouped argument.
1191 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1194 // Otherwise, look for the closest available option to report to the user
1195 // in the upcoming error.
1196 if (!Handler && SinkOpts.empty())
1198 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1202 if (SinkOpts.empty()) {
1203 if (!IgnoreErrors) {
1204 errs() << ProgramName << ": Unknown command line argument '"
1205 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
1207 if (NearestHandler) {
1208 // If we know a near match, report it as well.
1209 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
1214 ErrorParsing = true;
1216 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1219 (*I)->addOccurrence(i, "", StringRef(argv[i]));
1224 // If this is a named positional argument, just remember that it is the
1226 if (Handler->getFormattingFlag() == cl::Positional)
1227 ActivePositionalArg = Handler;
1229 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1232 // Check and handle positional arguments now...
1233 if (NumPositionalRequired > PositionalVals.size()) {
1234 if (!IgnoreErrors) {
1235 errs() << ProgramName
1236 << ": Not enough positional command line arguments specified!\n"
1237 << "Must specify at least " << NumPositionalRequired
1238 << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1239 << ": See: " << argv[0] << " - help\n";
1242 ErrorParsing = true;
1243 } else if (!HasUnlimitedPositionals &&
1244 PositionalVals.size() > PositionalOpts.size()) {
1245 if (!IgnoreErrors) {
1246 errs() << ProgramName << ": Too many positional arguments specified!\n"
1247 << "Can specify at most " << PositionalOpts.size()
1248 << " positional arguments: See: " << argv[0] << " -help\n";
1250 ErrorParsing = true;
1252 } else if (!ConsumeAfterOpt) {
1253 // Positional args have already been handled if ConsumeAfter is specified.
1254 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1255 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1256 if (RequiresValue(PositionalOpts[i])) {
1257 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1258 PositionalVals[ValNo].second);
1260 --NumPositionalRequired; // We fulfilled our duty...
1263 // If we _can_ give this option more arguments, do so now, as long as we
1264 // do not give it values that others need. 'Done' controls whether the
1265 // option even _WANTS_ any more.
1267 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1268 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1269 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1271 Done = true; // Optional arguments want _at most_ one value
1273 case cl::ZeroOrMore: // Zero or more will take all they can get...
1274 case cl::OneOrMore: // One or more will take all they can get...
1275 ProvidePositionalOption(PositionalOpts[i],
1276 PositionalVals[ValNo].first,
1277 PositionalVals[ValNo].second);
1281 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1282 "positional argument processing!");
1287 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1289 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1290 if (RequiresValue(PositionalOpts[j])) {
1291 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1292 PositionalVals[ValNo].first,
1293 PositionalVals[ValNo].second);
1297 // Handle the case where there is just one positional option, and it's
1298 // optional. In this case, we want to give JUST THE FIRST option to the
1299 // positional option and keep the rest for the consume after. The above
1300 // loop would have assigned no values to positional options in this case.
1302 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1303 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1304 PositionalVals[ValNo].first,
1305 PositionalVals[ValNo].second);
1309 // Handle over all of the rest of the arguments to the
1310 // cl::ConsumeAfter command line option...
1311 for (; ValNo != PositionalVals.size(); ++ValNo)
1313 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1314 PositionalVals[ValNo].second);
1317 // Loop over args and make sure all required args are specified!
1318 for (const auto &Opt : OptionsMap) {
1319 switch (Opt.second->getNumOccurrencesFlag()) {
1322 if (Opt.second->getNumOccurrences() == 0) {
1323 Opt.second->error("must be specified at least once!");
1324 ErrorParsing = true;
1332 // Now that we know if -debug is specified, we can use it.
1333 // Note that if ReadResponseFiles == true, this must be done before the
1334 // memory allocated for the expanded command line is free()d below.
1335 DEBUG(dbgs() << "Args: ";
1336 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1339 // Free all of the memory allocated to the map. Command line options may only
1340 // be processed once!
1343 // If we had an error processing our arguments, don't let the program execute
1352 //===----------------------------------------------------------------------===//
1353 // Option Base class implementation
1356 bool Option::error(const Twine &Message, StringRef ArgName) {
1357 if (!ArgName.data())
1359 if (ArgName.empty())
1360 errs() << HelpStr; // Be nice for positional arguments
1362 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1364 errs() << " option: " << Message << "\n";
1368 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1371 NumOccurrences++; // Increment the number of times we have been seen
1373 switch (getNumOccurrencesFlag()) {
1375 if (NumOccurrences > 1)
1376 return error("may only occur zero or one times!", ArgName);
1379 if (NumOccurrences > 1)
1380 return error("must occur exactly one time!", ArgName);
1388 return handleOccurrence(pos, ArgName, Value);
1391 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1392 // has been specified yet.
1394 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1395 if (O.ValueStr.empty())
1400 //===----------------------------------------------------------------------===//
1401 // cl::alias class implementation
1404 // Return the width of the option tag for printing...
1405 size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
1407 static void printHelpStr(StringRef HelpStr, size_t Indent,
1408 size_t FirstLineIndentedBy) {
1409 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1410 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1411 while (!Split.second.empty()) {
1412 Split = Split.second.split('\n');
1413 outs().indent(Indent) << Split.first << "\n";
1417 // Print out the option for the alias.
1418 void alias::printOptionInfo(size_t GlobalWidth) const {
1419 outs() << " -" << ArgStr;
1420 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
1423 //===----------------------------------------------------------------------===//
1424 // Parser Implementation code...
1427 // basic_parser implementation
1430 // Return the width of the option tag for printing...
1431 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1432 size_t Len = O.ArgStr.size();
1433 auto ValName = getValueName();
1434 if (!ValName.empty())
1435 Len += getValueStr(O, ValName).size() + 3;
1440 // printOptionInfo - Print out information about this option. The
1441 // to-be-maintained width is specified.
1443 void basic_parser_impl::printOptionInfo(const Option &O,
1444 size_t GlobalWidth) const {
1445 outs() << " -" << O.ArgStr;
1447 auto ValName = getValueName();
1448 if (!ValName.empty())
1449 outs() << "=<" << getValueStr(O, ValName) << '>';
1451 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1454 void basic_parser_impl::printOptionName(const Option &O,
1455 size_t GlobalWidth) const {
1456 outs() << " -" << O.ArgStr;
1457 outs().indent(GlobalWidth - O.ArgStr.size());
1460 // parser<bool> implementation
1462 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1464 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1470 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1474 return O.error("'" + Arg +
1475 "' is invalid value for boolean argument! Try 0 or 1");
1478 // parser<boolOrDefault> implementation
1480 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1481 boolOrDefault &Value) {
1482 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1487 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1492 return O.error("'" + Arg +
1493 "' is invalid value for boolean argument! Try 0 or 1");
1496 // parser<int> implementation
1498 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1500 if (Arg.getAsInteger(0, Value))
1501 return O.error("'" + Arg + "' value invalid for integer argument!");
1505 // parser<unsigned> implementation
1507 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1510 if (Arg.getAsInteger(0, Value))
1511 return O.error("'" + Arg + "' value invalid for uint argument!");
1515 // parser<unsigned long long> implementation
1517 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1519 unsigned long long &Value) {
1521 if (Arg.getAsInteger(0, Value))
1522 return O.error("'" + Arg + "' value invalid for uint argument!");
1526 // parser<double>/parser<float> implementation
1528 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1529 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1530 const char *ArgStart = TmpStr.c_str();
1532 Value = strtod(ArgStart, &End);
1534 return O.error("'" + Arg + "' value invalid for floating point argument!");
1538 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1540 return parseDouble(O, Arg, Val);
1543 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1546 if (parseDouble(O, Arg, dVal))
1552 // generic_parser_base implementation
1555 // findOption - Return the option number corresponding to the specified
1556 // argument string. If the option is not found, getNumOptions() is returned.
1558 unsigned generic_parser_base::findOption(StringRef Name) {
1559 unsigned e = getNumOptions();
1561 for (unsigned i = 0; i != e; ++i) {
1562 if (getOption(i) == Name)
1568 // Return the width of the option tag for printing...
1569 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1570 if (O.hasArgStr()) {
1571 size_t Size = O.ArgStr.size() + 6;
1572 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1573 Size = std::max(Size, getOption(i).size() + 8);
1576 size_t BaseSize = 0;
1577 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1578 BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1583 // printOptionInfo - Print out information about this option. The
1584 // to-be-maintained width is specified.
1586 void generic_parser_base::printOptionInfo(const Option &O,
1587 size_t GlobalWidth) const {
1588 if (O.hasArgStr()) {
1589 outs() << " -" << O.ArgStr;
1590 printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
1592 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1593 size_t NumSpaces = GlobalWidth - getOption(i).size() - 8;
1594 outs() << " =" << getOption(i);
1595 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1598 if (!O.HelpStr.empty())
1599 outs() << " " << O.HelpStr << '\n';
1600 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1601 auto Option = getOption(i);
1602 outs() << " -" << Option;
1603 printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
1608 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1610 // printGenericOptionDiff - Print the value of this option and it's default.
1612 // "Generic" options have each value mapped to a name.
1613 void generic_parser_base::printGenericOptionDiff(
1614 const Option &O, const GenericOptionValue &Value,
1615 const GenericOptionValue &Default, size_t GlobalWidth) const {
1616 outs() << " -" << O.ArgStr;
1617 outs().indent(GlobalWidth - O.ArgStr.size());
1619 unsigned NumOpts = getNumOptions();
1620 for (unsigned i = 0; i != NumOpts; ++i) {
1621 if (Value.compare(getOptionValue(i)))
1624 outs() << "= " << getOption(i);
1625 size_t L = getOption(i).size();
1626 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1627 outs().indent(NumSpaces) << " (default: ";
1628 for (unsigned j = 0; j != NumOpts; ++j) {
1629 if (Default.compare(getOptionValue(j)))
1631 outs() << getOption(j);
1637 outs() << "= *unknown option value*\n";
1640 // printOptionDiff - Specializations for printing basic value types.
1642 #define PRINT_OPT_DIFF(T) \
1643 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1644 size_t GlobalWidth) const { \
1645 printOptionName(O, GlobalWidth); \
1648 raw_string_ostream SS(Str); \
1651 outs() << "= " << Str; \
1652 size_t NumSpaces = \
1653 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1654 outs().indent(NumSpaces) << " (default: "; \
1656 outs() << D.getValue(); \
1658 outs() << "*no default*"; \
1662 PRINT_OPT_DIFF(bool)
1663 PRINT_OPT_DIFF(boolOrDefault)
1665 PRINT_OPT_DIFF(unsigned)
1666 PRINT_OPT_DIFF(unsigned long long)
1667 PRINT_OPT_DIFF(double)
1668 PRINT_OPT_DIFF(float)
1669 PRINT_OPT_DIFF(char)
1671 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1672 const OptionValue<std::string> &D,
1673 size_t GlobalWidth) const {
1674 printOptionName(O, GlobalWidth);
1675 outs() << "= " << V;
1676 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1677 outs().indent(NumSpaces) << " (default: ";
1679 outs() << D.getValue();
1681 outs() << "*no default*";
1685 // Print a placeholder for options that don't yet support printOptionDiff().
1686 void basic_parser_impl::printOptionNoValue(const Option &O,
1687 size_t GlobalWidth) const {
1688 printOptionName(O, GlobalWidth);
1689 outs() << "= *cannot print option value*\n";
1692 //===----------------------------------------------------------------------===//
1693 // -help and -help-hidden option implementation
1696 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1697 const std::pair<const char *, Option *> *RHS) {
1698 return strcmp(LHS->first, RHS->first);
1701 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
1702 const std::pair<const char *, SubCommand *> *RHS) {
1703 return strcmp(LHS->first, RHS->first);
1706 // Copy Options into a vector so we can sort them as we like.
1707 static void sortOpts(StringMap<Option *> &OptMap,
1708 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1710 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
1712 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1714 // Ignore really-hidden options.
1715 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1718 // Unless showhidden is set, ignore hidden flags.
1719 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1722 // If we've already seen this option, don't add it to the list again.
1723 if (!OptionSet.insert(I->second).second)
1727 std::pair<const char *, Option *>(I->getKey().data(), I->second));
1730 // Sort the options list alphabetically.
1731 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1735 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
1736 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
1737 for (const auto &S : SubMap) {
1738 if (S->getName().empty())
1740 Subs.push_back(std::make_pair(S->getName().data(), S));
1742 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
1749 const bool ShowHidden;
1750 typedef SmallVector<std::pair<const char *, Option *>, 128>
1751 StrOptionPairVector;
1752 typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
1753 StrSubCommandPairVector;
1754 // Print the options. Opts is assumed to be alphabetically sorted.
1755 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1756 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1757 Opts[i].second->printOptionInfo(MaxArgLen);
1760 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
1761 for (const auto &S : Subs) {
1762 outs() << " " << S.first;
1763 if (!S.second->getDescription().empty()) {
1764 outs().indent(MaxSubLen - strlen(S.first));
1765 outs() << " - " << S.second->getDescription();
1772 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1773 virtual ~HelpPrinter() {}
1775 // Invoke the printer.
1776 void operator=(bool Value) {
1780 SubCommand *Sub = GlobalParser->getActiveSubCommand();
1781 auto &OptionsMap = Sub->OptionsMap;
1782 auto &PositionalOpts = Sub->PositionalOpts;
1783 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
1785 StrOptionPairVector Opts;
1786 sortOpts(OptionsMap, Opts, ShowHidden);
1788 StrSubCommandPairVector Subs;
1789 sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
1791 if (!GlobalParser->ProgramOverview.empty())
1792 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1794 if (Sub == &*TopLevelSubCommand) {
1795 outs() << "USAGE: " << GlobalParser->ProgramName;
1796 if (Subs.size() > 2)
1797 outs() << " [subcommand]";
1798 outs() << " [options]";
1800 if (!Sub->getDescription().empty()) {
1801 outs() << "SUBCOMMAND '" << Sub->getName()
1802 << "': " << Sub->getDescription() << "\n\n";
1804 outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
1808 for (auto Opt : PositionalOpts) {
1809 if (Opt->hasArgStr())
1810 outs() << " --" << Opt->ArgStr;
1811 outs() << " " << Opt->HelpStr;
1814 // Print the consume after option info if it exists...
1815 if (ConsumeAfterOpt)
1816 outs() << " " << ConsumeAfterOpt->HelpStr;
1818 if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
1819 // Compute the maximum subcommand length...
1820 size_t MaxSubLen = 0;
1821 for (size_t i = 0, e = Subs.size(); i != e; ++i)
1822 MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
1825 outs() << "SUBCOMMANDS:\n\n";
1826 printSubCommands(Subs, MaxSubLen);
1828 outs() << " Type \"" << GlobalParser->ProgramName
1829 << " <subcommand> -help\" to get more help on a specific "
1835 // Compute the maximum argument length...
1836 size_t MaxArgLen = 0;
1837 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1838 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1840 outs() << "OPTIONS:\n";
1841 printOptions(Opts, MaxArgLen);
1843 // Print any extra help the user has declared.
1844 for (auto I : GlobalParser->MoreHelp)
1846 GlobalParser->MoreHelp.clear();
1848 // Halt the program since help information was printed
1853 class CategorizedHelpPrinter : public HelpPrinter {
1855 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1857 // Helper function for printOptions().
1858 // It shall return a negative value if A's name should be lexicographically
1859 // ordered before B's name. It returns a value greater equal zero otherwise.
1860 static int OptionCategoryCompare(OptionCategory *const *A,
1861 OptionCategory *const *B) {
1862 return (*A)->getName() == (*B)->getName();
1865 // Make sure we inherit our base class's operator=()
1866 using HelpPrinter::operator=;
1869 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1870 std::vector<OptionCategory *> SortedCategories;
1871 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1873 // Collect registered option categories into vector in preparation for
1875 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1876 E = GlobalParser->RegisteredOptionCategories.end();
1878 SortedCategories.push_back(*I);
1881 // Sort the different option categories alphabetically.
1882 assert(SortedCategories.size() > 0 && "No option categories registered!");
1883 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1884 OptionCategoryCompare);
1886 // Create map to empty vectors.
1887 for (std::vector<OptionCategory *>::const_iterator
1888 I = SortedCategories.begin(),
1889 E = SortedCategories.end();
1891 CategorizedOptions[*I] = std::vector<Option *>();
1893 // Walk through pre-sorted options and assign into categories.
1894 // Because the options are already alphabetically sorted the
1895 // options within categories will also be alphabetically sorted.
1896 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1897 Option *Opt = Opts[I].second;
1898 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1899 "Option has an unregistered category");
1900 CategorizedOptions[Opt->Category].push_back(Opt);
1904 for (std::vector<OptionCategory *>::const_iterator
1905 Category = SortedCategories.begin(),
1906 E = SortedCategories.end();
1907 Category != E; ++Category) {
1908 // Hide empty categories for -help, but show for -help-hidden.
1909 const auto &CategoryOptions = CategorizedOptions[*Category];
1910 bool IsEmptyCategory = CategoryOptions.empty();
1911 if (!ShowHidden && IsEmptyCategory)
1914 // Print category information.
1916 outs() << (*Category)->getName() << ":\n";
1918 // Check if description is set.
1919 if (!(*Category)->getDescription().empty())
1920 outs() << (*Category)->getDescription() << "\n\n";
1924 // When using -help-hidden explicitly state if the category has no
1925 // options associated with it.
1926 if (IsEmptyCategory) {
1927 outs() << " This option category has no options.\n";
1930 // Loop over the options in the category and print.
1931 for (const Option *Opt : CategoryOptions)
1932 Opt->printOptionInfo(MaxArgLen);
1937 // This wraps the Uncategorizing and Categorizing printers and decides
1938 // at run time which should be invoked.
1939 class HelpPrinterWrapper {
1941 HelpPrinter &UncategorizedPrinter;
1942 CategorizedHelpPrinter &CategorizedPrinter;
1945 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1946 CategorizedHelpPrinter &CategorizedPrinter)
1947 : UncategorizedPrinter(UncategorizedPrinter),
1948 CategorizedPrinter(CategorizedPrinter) {}
1950 // Invoke the printer.
1951 void operator=(bool Value);
1954 } // End anonymous namespace
1956 // Declare the four HelpPrinter instances that are used to print out help, or
1957 // help-hidden as an uncategorized list or in categories.
1958 static HelpPrinter UncategorizedNormalPrinter(false);
1959 static HelpPrinter UncategorizedHiddenPrinter(true);
1960 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1961 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1963 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1964 // a categorizing help printer
1965 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1966 CategorizedNormalPrinter);
1967 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1968 CategorizedHiddenPrinter);
1970 // Define a category for generic options that all tools should have.
1971 static cl::OptionCategory GenericCategory("Generic Options");
1973 // Define uncategorized help printers.
1974 // -help-list is hidden by default because if Option categories are being used
1975 // then -help behaves the same as -help-list.
1976 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1978 cl::desc("Display list of available options (-help-list-hidden for more)"),
1979 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1980 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
1982 static cl::opt<HelpPrinter, true, parser<bool>>
1983 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1984 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1985 cl::ValueDisallowed, cl::cat(GenericCategory),
1986 cl::sub(*AllSubCommands));
1988 // Define uncategorized/categorized help printers. These printers change their
1989 // behaviour at runtime depending on whether one or more Option categories have
1991 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1992 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1993 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1994 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
1996 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1997 HHOp("help-hidden", cl::desc("Display all available options"),
1998 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1999 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2001 static cl::opt<bool> PrintOptions(
2003 cl::desc("Print non-default options after command line parsing"),
2004 cl::Hidden, cl::init(false), cl::cat(GenericCategory),
2005 cl::sub(*AllSubCommands));
2007 static cl::opt<bool> PrintAllOptions(
2008 "print-all-options",
2009 cl::desc("Print all option values after command line parsing"), cl::Hidden,
2010 cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2012 void HelpPrinterWrapper::operator=(bool Value) {
2016 // Decide which printer to invoke. If more than one option category is
2017 // registered then it is useful to show the categorized help instead of
2018 // uncategorized help.
2019 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2020 // unhide -help-list option so user can have uncategorized output if they
2022 HLOp.setHiddenFlag(NotHidden);
2024 CategorizedPrinter = true; // Invoke categorized printer
2026 UncategorizedPrinter = true; // Invoke uncategorized printer
2029 // Print the value of each option.
2030 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2032 void CommandLineParser::printOptionValues() {
2033 if (!PrintOptions && !PrintAllOptions)
2036 SmallVector<std::pair<const char *, Option *>, 128> Opts;
2037 sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2039 // Compute the maximum argument length...
2040 size_t MaxArgLen = 0;
2041 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2042 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2044 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2045 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2048 static void (*OverrideVersionPrinter)() = nullptr;
2050 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
2053 class VersionPrinter {
2056 raw_ostream &OS = outs();
2057 #ifdef PACKAGE_VENDOR
2058 OS << PACKAGE_VENDOR << " ";
2060 OS << "LLVM (http://llvm.org/):\n ";
2062 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2063 #ifdef LLVM_VERSION_INFO
2064 OS << " " << LLVM_VERSION_INFO;
2067 #ifndef __OPTIMIZE__
2068 OS << "DEBUG build";
2070 OS << "Optimized build";
2073 OS << " with assertions";
2075 std::string CPU = sys::getHostCPUName();
2076 if (CPU == "generic")
2079 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
2080 << " Host CPU: " << CPU << '\n';
2082 void operator=(bool OptionWasSpecified) {
2083 if (!OptionWasSpecified)
2086 if (OverrideVersionPrinter != nullptr) {
2087 (*OverrideVersionPrinter)();
2092 // Iterate over any registered extra printers and call them to add further
2094 if (ExtraVersionPrinters != nullptr) {
2096 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
2097 E = ExtraVersionPrinters->end();
2105 } // End anonymous namespace
2107 // Define the --version option that prints out the LLVM version for the tool
2108 static VersionPrinter VersionPrinterInstance;
2110 static cl::opt<VersionPrinter, true, parser<bool>>
2111 VersOp("version", cl::desc("Display the version of this program"),
2112 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2113 cl::cat(GenericCategory));
2115 // Utility function for printing the help message.
2116 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2117 // This looks weird, but it actually prints the help message. The Printers are
2118 // types of HelpPrinter and the help gets printed when its operator= is
2119 // invoked. That's because the "normal" usages of the help printer is to be
2120 // assigned true/false depending on whether -help or -help-hidden was given or
2121 // not. Since we're circumventing that we have to make it look like -help or
2122 // -help-hidden were given, so we assign true.
2124 if (!Hidden && !Categorized)
2125 UncategorizedNormalPrinter = true;
2126 else if (!Hidden && Categorized)
2127 CategorizedNormalPrinter = true;
2128 else if (Hidden && !Categorized)
2129 UncategorizedHiddenPrinter = true;
2131 CategorizedHiddenPrinter = true;
2134 /// Utility function for printing version number.
2135 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
2137 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
2139 void cl::AddExtraVersionPrinter(void (*func)()) {
2140 if (!ExtraVersionPrinters)
2141 ExtraVersionPrinters = new std::vector<void (*)()>;
2143 ExtraVersionPrinters->push_back(func);
2146 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2147 auto &Subs = GlobalParser->RegisteredSubCommands;
2149 assert(is_contained(Subs, &Sub));
2150 return Sub.OptionsMap;
2153 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2154 cl::getRegisteredSubcommands() {
2155 return GlobalParser->getRegisteredSubcommands();
2158 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2159 for (auto &I : Sub.OptionsMap) {
2160 if (I.second->Category != &Category &&
2161 I.second->Category != &GenericCategory)
2162 I.second->setHiddenFlag(cl::ReallyHidden);
2166 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2168 auto CategoriesBegin = Categories.begin();
2169 auto CategoriesEnd = Categories.end();
2170 for (auto &I : Sub.OptionsMap) {
2171 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
2173 I.second->Category != &GenericCategory)
2174 I.second->setHiddenFlag(cl::ReallyHidden);
2178 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2179 void cl::ResetAllOptionOccurrences() {
2180 GlobalParser->ResetAllOptionOccurrences();
2183 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2184 const char *Overview) {
2185 llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview), true);