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, raw_ostream *Errs = nullptr);
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, raw_ostream *Errs) {
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 raw_ostream *Errs) {
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 IgnoreErrors = Errs;
1051 bool ErrorParsing = false;
1053 // Check out the positional arguments to collect information about them.
1054 unsigned NumPositionalRequired = 0;
1056 // Determine whether or not there are an unlimited number of positionals
1057 bool HasUnlimitedPositionals = false;
1060 SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1061 if (argc >= 2 && argv[FirstArg][0] != '-') {
1062 // If the first argument specifies a valid subcommand, start processing
1063 // options from the second argument.
1064 ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1065 if (ChosenSubCommand != &*TopLevelSubCommand)
1068 GlobalParser->ActiveSubCommand = ChosenSubCommand;
1070 assert(ChosenSubCommand);
1071 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1072 auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1073 auto &SinkOpts = ChosenSubCommand->SinkOpts;
1074 auto &OptionsMap = ChosenSubCommand->OptionsMap;
1076 if (ConsumeAfterOpt) {
1077 assert(PositionalOpts.size() > 0 &&
1078 "Cannot specify cl::ConsumeAfter without a positional argument!");
1080 if (!PositionalOpts.empty()) {
1082 // Calculate how many positional values are _required_.
1083 bool UnboundedFound = false;
1084 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1085 Option *Opt = PositionalOpts[i];
1086 if (RequiresValue(Opt))
1087 ++NumPositionalRequired;
1088 else if (ConsumeAfterOpt) {
1089 // ConsumeAfter cannot be combined with "optional" positional options
1090 // unless there is only one positional argument...
1091 if (PositionalOpts.size() > 1) {
1093 Opt->error("error - this positional option will never be matched, "
1094 "because it does not Require a value, and a "
1095 "cl::ConsumeAfter option is active!");
1096 ErrorParsing = true;
1098 } else if (UnboundedFound && !Opt->hasArgStr()) {
1099 // This option does not "require" a value... Make sure this option is
1100 // not specified after an option that eats all extra arguments, or this
1101 // one will never get any!
1104 Opt->error("error - option can never match, because "
1105 "another positional argument will match an "
1106 "unbounded number of values, and this option"
1107 " does not require a value!");
1108 *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1109 << "' is all messed up!\n";
1110 *Errs << PositionalOpts.size();
1111 ErrorParsing = true;
1113 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1115 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1118 // PositionalVals - A vector of "positional" arguments we accumulate into
1119 // the process at the end.
1121 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1123 // If the program has named positional arguments, and the name has been run
1124 // across, keep track of which positional argument was named. Otherwise put
1125 // the positional args into the PositionalVals list...
1126 Option *ActivePositionalArg = nullptr;
1128 // Loop over all of the arguments... processing them.
1129 bool DashDashFound = false; // Have we read '--'?
1130 for (int i = FirstArg; i < argc; ++i) {
1131 Option *Handler = nullptr;
1132 Option *NearestHandler = nullptr;
1133 std::string NearestHandlerString;
1135 StringRef ArgName = "";
1137 // Check to see if this is a positional argument. This argument is
1138 // considered to be positional if it doesn't start with '-', if it is "-"
1139 // itself, or if we have seen "--" already.
1141 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1142 // Positional argument!
1143 if (ActivePositionalArg) {
1144 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1145 continue; // We are done!
1148 if (!PositionalOpts.empty()) {
1149 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1151 // All of the positional arguments have been fulfulled, give the rest to
1152 // the consume after option... if it's specified...
1154 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1155 for (++i; i < argc; ++i)
1156 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1157 break; // Handle outside of the argument processing loop...
1160 // Delay processing positional arguments until the end...
1163 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1165 DashDashFound = true; // This is the mythical "--"?
1166 continue; // Don't try to process it as an argument itself.
1167 } else if (ActivePositionalArg &&
1168 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1169 // If there is a positional argument eating options, check to see if this
1170 // option is another positional argument. If so, treat it as an argument,
1171 // otherwise feed it to the eating positional.
1172 ArgName = StringRef(argv[i] + 1);
1173 // Eat leading dashes.
1174 while (!ArgName.empty() && ArgName[0] == '-')
1175 ArgName = ArgName.substr(1);
1177 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1178 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1179 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1180 continue; // We are done!
1183 } else { // We start with a '-', must be an argument.
1184 ArgName = StringRef(argv[i] + 1);
1185 // Eat leading dashes.
1186 while (!ArgName.empty() && ArgName[0] == '-')
1187 ArgName = ArgName.substr(1);
1189 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1191 // Check to see if this "option" is really a prefixed or grouped argument.
1193 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1196 // Otherwise, look for the closest available option to report to the user
1197 // in the upcoming error.
1198 if (!Handler && SinkOpts.empty())
1200 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1204 if (SinkOpts.empty()) {
1205 *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1206 << "'. Try: '" << argv[0] << " -help'\n";
1208 if (NearestHandler) {
1209 // If we know a near match, report it as well.
1210 *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 *Errs << ProgramName
1235 << ": Not enough positional command line arguments specified!\n"
1236 << "Must specify at least " << NumPositionalRequired
1237 << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1238 << ": See: " << argv[0] << " - help\n";
1240 ErrorParsing = true;
1241 } else if (!HasUnlimitedPositionals &&
1242 PositionalVals.size() > PositionalOpts.size()) {
1243 *Errs << ProgramName << ": Too many positional arguments specified!\n"
1244 << "Can specify at most " << PositionalOpts.size()
1245 << " positional arguments: See: " << argv[0] << " -help\n";
1246 ErrorParsing = true;
1248 } else if (!ConsumeAfterOpt) {
1249 // Positional args have already been handled if ConsumeAfter is specified.
1250 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1251 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1252 if (RequiresValue(PositionalOpts[i])) {
1253 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1254 PositionalVals[ValNo].second);
1256 --NumPositionalRequired; // We fulfilled our duty...
1259 // If we _can_ give this option more arguments, do so now, as long as we
1260 // do not give it values that others need. 'Done' controls whether the
1261 // option even _WANTS_ any more.
1263 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1264 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1265 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1267 Done = true; // Optional arguments want _at most_ one value
1269 case cl::ZeroOrMore: // Zero or more will take all they can get...
1270 case cl::OneOrMore: // One or more will take all they can get...
1271 ProvidePositionalOption(PositionalOpts[i],
1272 PositionalVals[ValNo].first,
1273 PositionalVals[ValNo].second);
1277 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1278 "positional argument processing!");
1283 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1285 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1286 if (RequiresValue(PositionalOpts[j])) {
1287 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1288 PositionalVals[ValNo].first,
1289 PositionalVals[ValNo].second);
1293 // Handle the case where there is just one positional option, and it's
1294 // optional. In this case, we want to give JUST THE FIRST option to the
1295 // positional option and keep the rest for the consume after. The above
1296 // loop would have assigned no values to positional options in this case.
1298 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1299 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1300 PositionalVals[ValNo].first,
1301 PositionalVals[ValNo].second);
1305 // Handle over all of the rest of the arguments to the
1306 // cl::ConsumeAfter command line option...
1307 for (; ValNo != PositionalVals.size(); ++ValNo)
1309 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1310 PositionalVals[ValNo].second);
1313 // Loop over args and make sure all required args are specified!
1314 for (const auto &Opt : OptionsMap) {
1315 switch (Opt.second->getNumOccurrencesFlag()) {
1318 if (Opt.second->getNumOccurrences() == 0) {
1319 Opt.second->error("must be specified at least once!");
1320 ErrorParsing = true;
1328 // Now that we know if -debug is specified, we can use it.
1329 // Note that if ReadResponseFiles == true, this must be done before the
1330 // memory allocated for the expanded command line is free()d below.
1331 DEBUG(dbgs() << "Args: ";
1332 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1335 // Free all of the memory allocated to the map. Command line options may only
1336 // be processed once!
1339 // If we had an error processing our arguments, don't let the program execute
1348 //===----------------------------------------------------------------------===//
1349 // Option Base class implementation
1352 bool Option::error(const Twine &Message, StringRef ArgName) {
1353 if (!ArgName.data())
1355 if (ArgName.empty())
1356 errs() << HelpStr; // Be nice for positional arguments
1358 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1360 errs() << " option: " << Message << "\n";
1364 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1367 NumOccurrences++; // Increment the number of times we have been seen
1369 switch (getNumOccurrencesFlag()) {
1371 if (NumOccurrences > 1)
1372 return error("may only occur zero or one times!", ArgName);
1375 if (NumOccurrences > 1)
1376 return error("must occur exactly one time!", ArgName);
1384 return handleOccurrence(pos, ArgName, Value);
1387 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1388 // has been specified yet.
1390 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1391 if (O.ValueStr.empty())
1396 //===----------------------------------------------------------------------===//
1397 // cl::alias class implementation
1400 // Return the width of the option tag for printing...
1401 size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
1403 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1404 size_t FirstLineIndentedBy) {
1405 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1406 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1407 while (!Split.second.empty()) {
1408 Split = Split.second.split('\n');
1409 outs().indent(Indent) << Split.first << "\n";
1413 // Print out the option for the alias.
1414 void alias::printOptionInfo(size_t GlobalWidth) const {
1415 outs() << " -" << ArgStr;
1416 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
1419 //===----------------------------------------------------------------------===//
1420 // Parser Implementation code...
1423 // basic_parser implementation
1426 // Return the width of the option tag for printing...
1427 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1428 size_t Len = O.ArgStr.size();
1429 auto ValName = getValueName();
1430 if (!ValName.empty())
1431 Len += getValueStr(O, ValName).size() + 3;
1436 // printOptionInfo - Print out information about this option. The
1437 // to-be-maintained width is specified.
1439 void basic_parser_impl::printOptionInfo(const Option &O,
1440 size_t GlobalWidth) const {
1441 outs() << " -" << O.ArgStr;
1443 auto ValName = getValueName();
1444 if (!ValName.empty())
1445 outs() << "=<" << getValueStr(O, ValName) << '>';
1447 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1450 void basic_parser_impl::printOptionName(const Option &O,
1451 size_t GlobalWidth) const {
1452 outs() << " -" << O.ArgStr;
1453 outs().indent(GlobalWidth - O.ArgStr.size());
1456 // parser<bool> implementation
1458 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1460 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1466 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1470 return O.error("'" + Arg +
1471 "' is invalid value for boolean argument! Try 0 or 1");
1474 // parser<boolOrDefault> implementation
1476 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1477 boolOrDefault &Value) {
1478 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1483 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1488 return O.error("'" + Arg +
1489 "' is invalid value for boolean argument! Try 0 or 1");
1492 // parser<int> implementation
1494 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1496 if (Arg.getAsInteger(0, Value))
1497 return O.error("'" + Arg + "' value invalid for integer argument!");
1501 // parser<unsigned> implementation
1503 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1506 if (Arg.getAsInteger(0, Value))
1507 return O.error("'" + Arg + "' value invalid for uint argument!");
1511 // parser<unsigned long long> implementation
1513 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1515 unsigned long long &Value) {
1517 if (Arg.getAsInteger(0, Value))
1518 return O.error("'" + Arg + "' value invalid for uint argument!");
1522 // parser<double>/parser<float> implementation
1524 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1525 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1526 const char *ArgStart = TmpStr.c_str();
1528 Value = strtod(ArgStart, &End);
1530 return O.error("'" + Arg + "' value invalid for floating point argument!");
1534 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1536 return parseDouble(O, Arg, Val);
1539 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1542 if (parseDouble(O, Arg, dVal))
1548 // generic_parser_base implementation
1551 // findOption - Return the option number corresponding to the specified
1552 // argument string. If the option is not found, getNumOptions() is returned.
1554 unsigned generic_parser_base::findOption(StringRef Name) {
1555 unsigned e = getNumOptions();
1557 for (unsigned i = 0; i != e; ++i) {
1558 if (getOption(i) == Name)
1564 // Return the width of the option tag for printing...
1565 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1566 if (O.hasArgStr()) {
1567 size_t Size = O.ArgStr.size() + 6;
1568 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1569 Size = std::max(Size, getOption(i).size() + 8);
1572 size_t BaseSize = 0;
1573 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1574 BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1579 // printOptionInfo - Print out information about this option. The
1580 // to-be-maintained width is specified.
1582 void generic_parser_base::printOptionInfo(const Option &O,
1583 size_t GlobalWidth) const {
1584 if (O.hasArgStr()) {
1585 outs() << " -" << O.ArgStr;
1586 Option::printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
1588 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1589 size_t NumSpaces = GlobalWidth - getOption(i).size() - 8;
1590 outs() << " =" << getOption(i);
1591 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1594 if (!O.HelpStr.empty())
1595 outs() << " " << O.HelpStr << '\n';
1596 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1597 auto Option = getOption(i);
1598 outs() << " -" << Option;
1599 Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
1604 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1606 // printGenericOptionDiff - Print the value of this option and it's default.
1608 // "Generic" options have each value mapped to a name.
1609 void generic_parser_base::printGenericOptionDiff(
1610 const Option &O, const GenericOptionValue &Value,
1611 const GenericOptionValue &Default, size_t GlobalWidth) const {
1612 outs() << " -" << O.ArgStr;
1613 outs().indent(GlobalWidth - O.ArgStr.size());
1615 unsigned NumOpts = getNumOptions();
1616 for (unsigned i = 0; i != NumOpts; ++i) {
1617 if (Value.compare(getOptionValue(i)))
1620 outs() << "= " << getOption(i);
1621 size_t L = getOption(i).size();
1622 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1623 outs().indent(NumSpaces) << " (default: ";
1624 for (unsigned j = 0; j != NumOpts; ++j) {
1625 if (Default.compare(getOptionValue(j)))
1627 outs() << getOption(j);
1633 outs() << "= *unknown option value*\n";
1636 // printOptionDiff - Specializations for printing basic value types.
1638 #define PRINT_OPT_DIFF(T) \
1639 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1640 size_t GlobalWidth) const { \
1641 printOptionName(O, GlobalWidth); \
1644 raw_string_ostream SS(Str); \
1647 outs() << "= " << Str; \
1648 size_t NumSpaces = \
1649 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1650 outs().indent(NumSpaces) << " (default: "; \
1652 outs() << D.getValue(); \
1654 outs() << "*no default*"; \
1658 PRINT_OPT_DIFF(bool)
1659 PRINT_OPT_DIFF(boolOrDefault)
1661 PRINT_OPT_DIFF(unsigned)
1662 PRINT_OPT_DIFF(unsigned long long)
1663 PRINT_OPT_DIFF(double)
1664 PRINT_OPT_DIFF(float)
1665 PRINT_OPT_DIFF(char)
1667 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1668 const OptionValue<std::string> &D,
1669 size_t GlobalWidth) const {
1670 printOptionName(O, GlobalWidth);
1671 outs() << "= " << V;
1672 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1673 outs().indent(NumSpaces) << " (default: ";
1675 outs() << D.getValue();
1677 outs() << "*no default*";
1681 // Print a placeholder for options that don't yet support printOptionDiff().
1682 void basic_parser_impl::printOptionNoValue(const Option &O,
1683 size_t GlobalWidth) const {
1684 printOptionName(O, GlobalWidth);
1685 outs() << "= *cannot print option value*\n";
1688 //===----------------------------------------------------------------------===//
1689 // -help and -help-hidden option implementation
1692 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1693 const std::pair<const char *, Option *> *RHS) {
1694 return strcmp(LHS->first, RHS->first);
1697 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
1698 const std::pair<const char *, SubCommand *> *RHS) {
1699 return strcmp(LHS->first, RHS->first);
1702 // Copy Options into a vector so we can sort them as we like.
1703 static void sortOpts(StringMap<Option *> &OptMap,
1704 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1706 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
1708 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1710 // Ignore really-hidden options.
1711 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1714 // Unless showhidden is set, ignore hidden flags.
1715 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1718 // If we've already seen this option, don't add it to the list again.
1719 if (!OptionSet.insert(I->second).second)
1723 std::pair<const char *, Option *>(I->getKey().data(), I->second));
1726 // Sort the options list alphabetically.
1727 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1731 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
1732 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
1733 for (const auto &S : SubMap) {
1734 if (S->getName().empty())
1736 Subs.push_back(std::make_pair(S->getName().data(), S));
1738 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
1745 const bool ShowHidden;
1746 typedef SmallVector<std::pair<const char *, Option *>, 128>
1747 StrOptionPairVector;
1748 typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
1749 StrSubCommandPairVector;
1750 // Print the options. Opts is assumed to be alphabetically sorted.
1751 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1752 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1753 Opts[i].second->printOptionInfo(MaxArgLen);
1756 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
1757 for (const auto &S : Subs) {
1758 outs() << " " << S.first;
1759 if (!S.second->getDescription().empty()) {
1760 outs().indent(MaxSubLen - strlen(S.first));
1761 outs() << " - " << S.second->getDescription();
1768 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1769 virtual ~HelpPrinter() {}
1771 // Invoke the printer.
1772 void operator=(bool Value) {
1776 SubCommand *Sub = GlobalParser->getActiveSubCommand();
1777 auto &OptionsMap = Sub->OptionsMap;
1778 auto &PositionalOpts = Sub->PositionalOpts;
1779 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
1781 StrOptionPairVector Opts;
1782 sortOpts(OptionsMap, Opts, ShowHidden);
1784 StrSubCommandPairVector Subs;
1785 sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
1787 if (!GlobalParser->ProgramOverview.empty())
1788 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1790 if (Sub == &*TopLevelSubCommand) {
1791 outs() << "USAGE: " << GlobalParser->ProgramName;
1792 if (Subs.size() > 2)
1793 outs() << " [subcommand]";
1794 outs() << " [options]";
1796 if (!Sub->getDescription().empty()) {
1797 outs() << "SUBCOMMAND '" << Sub->getName()
1798 << "': " << Sub->getDescription() << "\n\n";
1800 outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
1804 for (auto Opt : PositionalOpts) {
1805 if (Opt->hasArgStr())
1806 outs() << " --" << Opt->ArgStr;
1807 outs() << " " << Opt->HelpStr;
1810 // Print the consume after option info if it exists...
1811 if (ConsumeAfterOpt)
1812 outs() << " " << ConsumeAfterOpt->HelpStr;
1814 if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
1815 // Compute the maximum subcommand length...
1816 size_t MaxSubLen = 0;
1817 for (size_t i = 0, e = Subs.size(); i != e; ++i)
1818 MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
1821 outs() << "SUBCOMMANDS:\n\n";
1822 printSubCommands(Subs, MaxSubLen);
1824 outs() << " Type \"" << GlobalParser->ProgramName
1825 << " <subcommand> -help\" to get more help on a specific "
1831 // Compute the maximum argument length...
1832 size_t MaxArgLen = 0;
1833 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1834 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1836 outs() << "OPTIONS:\n";
1837 printOptions(Opts, MaxArgLen);
1839 // Print any extra help the user has declared.
1840 for (auto I : GlobalParser->MoreHelp)
1842 GlobalParser->MoreHelp.clear();
1844 // Halt the program since help information was printed
1849 class CategorizedHelpPrinter : public HelpPrinter {
1851 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1853 // Helper function for printOptions().
1854 // It shall return a negative value if A's name should be lexicographically
1855 // ordered before B's name. It returns a value greater than zero if B's name
1856 // should be ordered before A's name, and it returns 0 otherwise.
1857 static int OptionCategoryCompare(OptionCategory *const *A,
1858 OptionCategory *const *B) {
1859 return (*A)->getName().compare((*B)->getName());
1862 // Make sure we inherit our base class's operator=()
1863 using HelpPrinter::operator=;
1866 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1867 std::vector<OptionCategory *> SortedCategories;
1868 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1870 // Collect registered option categories into vector in preparation for
1872 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1873 E = GlobalParser->RegisteredOptionCategories.end();
1875 SortedCategories.push_back(*I);
1878 // Sort the different option categories alphabetically.
1879 assert(SortedCategories.size() > 0 && "No option categories registered!");
1880 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1881 OptionCategoryCompare);
1883 // Create map to empty vectors.
1884 for (std::vector<OptionCategory *>::const_iterator
1885 I = SortedCategories.begin(),
1886 E = SortedCategories.end();
1888 CategorizedOptions[*I] = std::vector<Option *>();
1890 // Walk through pre-sorted options and assign into categories.
1891 // Because the options are already alphabetically sorted the
1892 // options within categories will also be alphabetically sorted.
1893 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1894 Option *Opt = Opts[I].second;
1895 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1896 "Option has an unregistered category");
1897 CategorizedOptions[Opt->Category].push_back(Opt);
1901 for (std::vector<OptionCategory *>::const_iterator
1902 Category = SortedCategories.begin(),
1903 E = SortedCategories.end();
1904 Category != E; ++Category) {
1905 // Hide empty categories for -help, but show for -help-hidden.
1906 const auto &CategoryOptions = CategorizedOptions[*Category];
1907 bool IsEmptyCategory = CategoryOptions.empty();
1908 if (!ShowHidden && IsEmptyCategory)
1911 // Print category information.
1913 outs() << (*Category)->getName() << ":\n";
1915 // Check if description is set.
1916 if (!(*Category)->getDescription().empty())
1917 outs() << (*Category)->getDescription() << "\n\n";
1921 // When using -help-hidden explicitly state if the category has no
1922 // options associated with it.
1923 if (IsEmptyCategory) {
1924 outs() << " This option category has no options.\n";
1927 // Loop over the options in the category and print.
1928 for (const Option *Opt : CategoryOptions)
1929 Opt->printOptionInfo(MaxArgLen);
1934 // This wraps the Uncategorizing and Categorizing printers and decides
1935 // at run time which should be invoked.
1936 class HelpPrinterWrapper {
1938 HelpPrinter &UncategorizedPrinter;
1939 CategorizedHelpPrinter &CategorizedPrinter;
1942 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1943 CategorizedHelpPrinter &CategorizedPrinter)
1944 : UncategorizedPrinter(UncategorizedPrinter),
1945 CategorizedPrinter(CategorizedPrinter) {}
1947 // Invoke the printer.
1948 void operator=(bool Value);
1951 } // End anonymous namespace
1953 // Declare the four HelpPrinter instances that are used to print out help, or
1954 // help-hidden as an uncategorized list or in categories.
1955 static HelpPrinter UncategorizedNormalPrinter(false);
1956 static HelpPrinter UncategorizedHiddenPrinter(true);
1957 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1958 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1960 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1961 // a categorizing help printer
1962 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1963 CategorizedNormalPrinter);
1964 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1965 CategorizedHiddenPrinter);
1967 // Define a category for generic options that all tools should have.
1968 static cl::OptionCategory GenericCategory("Generic Options");
1970 // Define uncategorized help printers.
1971 // -help-list is hidden by default because if Option categories are being used
1972 // then -help behaves the same as -help-list.
1973 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1975 cl::desc("Display list of available options (-help-list-hidden for more)"),
1976 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1977 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
1979 static cl::opt<HelpPrinter, true, parser<bool>>
1980 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1981 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1982 cl::ValueDisallowed, cl::cat(GenericCategory),
1983 cl::sub(*AllSubCommands));
1985 // Define uncategorized/categorized help printers. These printers change their
1986 // behaviour at runtime depending on whether one or more Option categories have
1988 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1989 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1990 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1991 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
1993 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1994 HHOp("help-hidden", cl::desc("Display all available options"),
1995 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1996 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
1998 static cl::opt<bool> PrintOptions(
2000 cl::desc("Print non-default options after command line parsing"),
2001 cl::Hidden, cl::init(false), cl::cat(GenericCategory),
2002 cl::sub(*AllSubCommands));
2004 static cl::opt<bool> PrintAllOptions(
2005 "print-all-options",
2006 cl::desc("Print all option values after command line parsing"), cl::Hidden,
2007 cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2009 void HelpPrinterWrapper::operator=(bool Value) {
2013 // Decide which printer to invoke. If more than one option category is
2014 // registered then it is useful to show the categorized help instead of
2015 // uncategorized help.
2016 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2017 // unhide -help-list option so user can have uncategorized output if they
2019 HLOp.setHiddenFlag(NotHidden);
2021 CategorizedPrinter = true; // Invoke categorized printer
2023 UncategorizedPrinter = true; // Invoke uncategorized printer
2026 // Print the value of each option.
2027 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2029 void CommandLineParser::printOptionValues() {
2030 if (!PrintOptions && !PrintAllOptions)
2033 SmallVector<std::pair<const char *, Option *>, 128> Opts;
2034 sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2036 // Compute the maximum argument length...
2037 size_t MaxArgLen = 0;
2038 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2039 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2041 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2042 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2045 static void (*OverrideVersionPrinter)() = nullptr;
2047 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
2050 class VersionPrinter {
2053 raw_ostream &OS = outs();
2054 #ifdef PACKAGE_VENDOR
2055 OS << PACKAGE_VENDOR << " ";
2057 OS << "LLVM (http://llvm.org/):\n ";
2059 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2060 #ifdef LLVM_VERSION_INFO
2061 OS << " " << LLVM_VERSION_INFO;
2064 #ifndef __OPTIMIZE__
2065 OS << "DEBUG build";
2067 OS << "Optimized build";
2070 OS << " with assertions";
2072 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2073 std::string CPU = sys::getHostCPUName();
2074 if (CPU == "generic")
2077 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
2078 << " Host CPU: " << CPU;
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),