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/StringExtras.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Config/config.h"
31 #include "llvm/Support/ConvertUTF.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/Process.h"
40 #include "llvm/Support/StringSaver.h"
41 #include "llvm/Support/raw_ostream.h"
47 #define DEBUG_TYPE "commandline"
49 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
51 // If LLVM_ENABLE_ABI_BREAKING_CHECKS is set the flag -mllvm -reverse-iterate
52 // can be used to toggle forward/reverse iteration of unordered containers.
53 // This will help uncover differences in codegen caused due to undefined
55 static cl::opt<bool, true> ReverseIteration("reverse-iterate",
56 cl::location(ReverseIterate<bool>::value));
60 //===----------------------------------------------------------------------===//
61 // Template instantiations and anchors.
65 template class basic_parser<bool>;
66 template class basic_parser<boolOrDefault>;
67 template class basic_parser<int>;
68 template class basic_parser<unsigned>;
69 template class basic_parser<unsigned long long>;
70 template class basic_parser<double>;
71 template class basic_parser<float>;
72 template class basic_parser<std::string>;
73 template class basic_parser<char>;
75 template class opt<unsigned>;
76 template class opt<int>;
77 template class opt<std::string>;
78 template class opt<char>;
79 template class opt<bool>;
81 } // end namespace llvm::cl
83 // Pin the vtables to this file.
84 void GenericOptionValue::anchor() {}
85 void OptionValue<boolOrDefault>::anchor() {}
86 void OptionValue<std::string>::anchor() {}
87 void Option::anchor() {}
88 void basic_parser_impl::anchor() {}
89 void parser<bool>::anchor() {}
90 void parser<boolOrDefault>::anchor() {}
91 void parser<int>::anchor() {}
92 void parser<unsigned>::anchor() {}
93 void parser<unsigned long long>::anchor() {}
94 void parser<double>::anchor() {}
95 void parser<float>::anchor() {}
96 void parser<std::string>::anchor() {}
97 void parser<char>::anchor() {}
99 //===----------------------------------------------------------------------===//
103 class CommandLineParser {
105 // Globals for name and overview of program. Program name is not a string to
106 // avoid static ctor/dtor issues.
107 std::string ProgramName;
108 StringRef ProgramOverview;
110 // This collects additional help to be printed.
111 std::vector<StringRef> MoreHelp;
113 // This collects the different option categories that have been registered.
114 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
116 // This collects the different subcommands that have been registered.
117 SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
119 CommandLineParser() : ActiveSubCommand(nullptr) {
120 registerSubCommand(&*TopLevelSubCommand);
121 registerSubCommand(&*AllSubCommands);
124 void ResetAllOptionOccurrences();
126 bool ParseCommandLineOptions(int argc, const char *const *argv,
127 StringRef Overview, raw_ostream *Errs = nullptr);
129 void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
132 if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
133 errs() << ProgramName << ": CommandLine Error: Option '" << Name
134 << "' registered more than once!\n";
135 report_fatal_error("inconsistency in registered CommandLine options");
138 // If we're adding this to all sub-commands, add it to the ones that have
139 // already been registered.
140 if (SC == &*AllSubCommands) {
141 for (const auto &Sub : RegisteredSubCommands) {
144 addLiteralOption(Opt, Sub, Name);
149 void addLiteralOption(Option &Opt, StringRef Name) {
150 if (Opt.Subs.empty())
151 addLiteralOption(Opt, &*TopLevelSubCommand, Name);
153 for (auto SC : Opt.Subs)
154 addLiteralOption(Opt, SC, Name);
158 void addOption(Option *O, SubCommand *SC) {
159 bool HadErrors = false;
160 if (O->hasArgStr()) {
161 // Add argument to the argument map!
162 if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
163 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
164 << "' registered more than once!\n";
169 // Remember information about positional options.
170 if (O->getFormattingFlag() == cl::Positional)
171 SC->PositionalOpts.push_back(O);
172 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
173 SC->SinkOpts.push_back(O);
174 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
175 if (SC->ConsumeAfterOpt) {
176 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
179 SC->ConsumeAfterOpt = O;
182 // Fail hard if there were errors. These are strictly unrecoverable and
183 // indicate serious issues such as conflicting option names or an
185 // linked LLVM distribution.
187 report_fatal_error("inconsistency in registered CommandLine options");
189 // If we're adding this to all sub-commands, add it to the ones that have
190 // already been registered.
191 if (SC == &*AllSubCommands) {
192 for (const auto &Sub : RegisteredSubCommands) {
200 void addOption(Option *O) {
201 if (O->Subs.empty()) {
202 addOption(O, &*TopLevelSubCommand);
204 for (auto SC : O->Subs)
209 void removeOption(Option *O, SubCommand *SC) {
210 SmallVector<StringRef, 16> OptionNames;
211 O->getExtraOptionNames(OptionNames);
213 OptionNames.push_back(O->ArgStr);
215 SubCommand &Sub = *SC;
216 for (auto Name : OptionNames)
217 Sub.OptionsMap.erase(Name);
219 if (O->getFormattingFlag() == cl::Positional)
220 for (auto Opt = Sub.PositionalOpts.begin();
221 Opt != Sub.PositionalOpts.end(); ++Opt) {
223 Sub.PositionalOpts.erase(Opt);
227 else if (O->getMiscFlags() & cl::Sink)
228 for (auto Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
230 Sub.SinkOpts.erase(Opt);
234 else if (O == Sub.ConsumeAfterOpt)
235 Sub.ConsumeAfterOpt = nullptr;
238 void removeOption(Option *O) {
240 removeOption(O, &*TopLevelSubCommand);
242 if (O->isInAllSubCommands()) {
243 for (auto SC : RegisteredSubCommands)
246 for (auto SC : O->Subs)
252 bool hasOptions(const SubCommand &Sub) const {
253 return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
254 nullptr != Sub.ConsumeAfterOpt);
257 bool hasOptions() const {
258 for (const auto &S : RegisteredSubCommands) {
265 SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
267 void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
268 SubCommand &Sub = *SC;
269 if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
270 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
271 << "' registered more than once!\n";
272 report_fatal_error("inconsistency in registered CommandLine options");
274 Sub.OptionsMap.erase(O->ArgStr);
277 void updateArgStr(Option *O, StringRef NewName) {
279 updateArgStr(O, NewName, &*TopLevelSubCommand);
281 for (auto SC : O->Subs)
282 updateArgStr(O, NewName, SC);
286 void printOptionValues();
288 void registerCategory(OptionCategory *cat) {
289 assert(count_if(RegisteredOptionCategories,
290 [cat](const OptionCategory *Category) {
291 return cat->getName() == Category->getName();
293 "Duplicate option categories");
295 RegisteredOptionCategories.insert(cat);
298 void registerSubCommand(SubCommand *sub) {
299 assert(count_if(RegisteredSubCommands,
300 [sub](const SubCommand *Sub) {
301 return (!sub->getName().empty()) &&
302 (Sub->getName() == sub->getName());
304 "Duplicate subcommands");
305 RegisteredSubCommands.insert(sub);
307 // For all options that have been registered for all subcommands, add the
308 // option to this subcommand now.
309 if (sub != &*AllSubCommands) {
310 for (auto &E : AllSubCommands->OptionsMap) {
311 Option *O = E.second;
312 if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
316 addLiteralOption(*O, sub, E.first());
321 void unregisterSubCommand(SubCommand *sub) {
322 RegisteredSubCommands.erase(sub);
325 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
326 getRegisteredSubcommands() {
327 return make_range(RegisteredSubCommands.begin(),
328 RegisteredSubCommands.end());
332 ActiveSubCommand = nullptr;
334 ProgramOverview = StringRef();
337 RegisteredOptionCategories.clear();
339 ResetAllOptionOccurrences();
340 RegisteredSubCommands.clear();
342 TopLevelSubCommand->reset();
343 AllSubCommands->reset();
344 registerSubCommand(&*TopLevelSubCommand);
345 registerSubCommand(&*AllSubCommands);
349 SubCommand *ActiveSubCommand;
351 Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
352 SubCommand *LookupSubCommand(StringRef Name);
357 static ManagedStatic<CommandLineParser> GlobalParser;
359 void cl::AddLiteralOption(Option &O, StringRef Name) {
360 GlobalParser->addLiteralOption(O, Name);
363 extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
364 GlobalParser->MoreHelp.push_back(Help);
367 void Option::addArgument() {
368 GlobalParser->addOption(this);
369 FullyInitialized = true;
372 void Option::removeArgument() { GlobalParser->removeOption(this); }
374 void Option::setArgStr(StringRef S) {
375 if (FullyInitialized)
376 GlobalParser->updateArgStr(this, S);
377 assert((S.empty() || S[0] != '-') && "Option can't start with '-");
381 // Initialise the general option category.
382 OptionCategory llvm::cl::GeneralCategory("General options");
384 void OptionCategory::registerCategory() {
385 GlobalParser->registerCategory(this);
388 // A special subcommand representing no subcommand
389 ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
391 // A special subcommand that can be used to put an option into all subcommands.
392 ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
394 void SubCommand::registerSubCommand() {
395 GlobalParser->registerSubCommand(this);
398 void SubCommand::unregisterSubCommand() {
399 GlobalParser->unregisterSubCommand(this);
402 void SubCommand::reset() {
403 PositionalOpts.clear();
407 ConsumeAfterOpt = nullptr;
410 SubCommand::operator bool() const {
411 return (GlobalParser->getActiveSubCommand() == this);
414 //===----------------------------------------------------------------------===//
415 // Basic, shared command line option processing machinery.
418 /// LookupOption - Lookup the option specified by the specified option on the
419 /// command line. If there is a value specified (after an equal sign) return
420 /// that as well. This assumes that leading dashes have already been stripped.
421 Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
423 // Reject all dashes.
426 assert(&Sub != &*AllSubCommands);
428 size_t EqualPos = Arg.find('=');
430 // If we have an equals sign, remember the value.
431 if (EqualPos == StringRef::npos) {
432 // Look up the option.
433 auto I = Sub.OptionsMap.find(Arg);
434 if (I == Sub.OptionsMap.end())
437 return I != Sub.OptionsMap.end() ? I->second : nullptr;
440 // If the argument before the = is a valid option name, we match. If not,
441 // return Arg unmolested.
442 auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
443 if (I == Sub.OptionsMap.end())
446 Value = Arg.substr(EqualPos + 1);
447 Arg = Arg.substr(0, EqualPos);
451 SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
453 return &*TopLevelSubCommand;
454 for (auto S : RegisteredSubCommands) {
455 if (S == &*AllSubCommands)
457 if (S->getName().empty())
460 if (StringRef(S->getName()) == StringRef(Name))
463 return &*TopLevelSubCommand;
466 /// LookupNearestOption - Lookup the closest match to the option specified by
467 /// the specified option on the command line. If there is a value specified
468 /// (after an equal sign) return that as well. This assumes that leading dashes
469 /// have already been stripped.
470 static Option *LookupNearestOption(StringRef Arg,
471 const StringMap<Option *> &OptionsMap,
472 std::string &NearestString) {
473 // Reject all dashes.
477 // Split on any equal sign.
478 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
479 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
480 StringRef &RHS = SplitArg.second;
482 // Find the closest match.
483 Option *Best = nullptr;
484 unsigned BestDistance = 0;
485 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
486 ie = OptionsMap.end();
488 Option *O = it->second;
489 SmallVector<StringRef, 16> OptionNames;
490 O->getExtraOptionNames(OptionNames);
492 OptionNames.push_back(O->ArgStr);
494 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
495 StringRef Flag = PermitValue ? LHS : Arg;
496 for (auto Name : OptionNames) {
497 unsigned Distance = StringRef(Name).edit_distance(
498 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
499 if (!Best || Distance < BestDistance) {
501 BestDistance = Distance;
502 if (RHS.empty() || !PermitValue)
503 NearestString = Name;
505 NearestString = (Twine(Name) + "=" + RHS).str();
513 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
514 /// that does special handling of cl::CommaSeparated options.
515 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
516 StringRef ArgName, StringRef Value,
517 bool MultiArg = false) {
518 // Check to see if this option accepts a comma separated list of values. If
519 // it does, we have to split up the value into multiple values.
520 if (Handler->getMiscFlags() & CommaSeparated) {
521 StringRef Val(Value);
522 StringRef::size_type Pos = Val.find(',');
524 while (Pos != StringRef::npos) {
525 // Process the portion before the comma.
526 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
528 // Erase the portion before the comma, AND the comma.
529 Val = Val.substr(Pos + 1);
530 // Check for another comma.
537 return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
540 /// ProvideOption - For Value, this differentiates between an empty value ("")
541 /// and a null value (StringRef()). The later is accepted for arguments that
542 /// don't allow a value (-foo) the former is rejected (-foo=).
543 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
544 StringRef Value, int argc,
545 const char *const *argv, int &i) {
546 // Is this a multi-argument option?
547 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
549 // Enforce value requirements
550 switch (Handler->getValueExpectedFlag()) {
552 if (!Value.data()) { // No value specified?
554 return Handler->error("requires a value!");
555 // Steal the next argument, like for '-o filename'
556 assert(argv && "null check");
557 Value = StringRef(argv[++i]);
560 case ValueDisallowed:
561 if (NumAdditionalVals > 0)
562 return Handler->error("multi-valued option specified"
563 " with ValueDisallowed modifier!");
566 return Handler->error("does not allow a value! '" + Twine(Value) +
573 // If this isn't a multi-arg option, just run the handler.
574 if (NumAdditionalVals == 0)
575 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
577 // If it is, run the handle several times.
578 bool MultiArg = false;
581 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
587 while (NumAdditionalVals > 0) {
589 return Handler->error("not enough values!");
590 assert(argv && "null check");
591 Value = StringRef(argv[++i]);
593 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
601 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
603 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
606 // Option predicates...
607 static inline bool isGrouping(const Option *O) {
608 return O->getFormattingFlag() == cl::Grouping;
610 static inline bool isPrefixedOrGrouping(const Option *O) {
611 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
614 // getOptionPred - Check to see if there are any options that satisfy the
615 // specified predicate with names that are the prefixes in Name. This is
616 // checked by progressively stripping characters off of the name, checking to
617 // see if there options that satisfy the predicate. If we find one, return it,
618 // otherwise return null.
620 static Option *getOptionPred(StringRef Name, size_t &Length,
621 bool (*Pred)(const Option *),
622 const StringMap<Option *> &OptionsMap) {
624 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
626 // Loop while we haven't found an option and Name still has at least two
627 // characters in it (so that the next iteration will not be the empty
629 while (OMI == OptionsMap.end() && Name.size() > 1) {
630 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
631 OMI = OptionsMap.find(Name);
634 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
635 Length = Name.size();
636 return OMI->second; // Found one!
638 return nullptr; // No option found!
641 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
642 /// with at least one '-') does not fully match an available option. Check to
643 /// see if this is a prefix or grouped option. If so, split arg into output an
644 /// Arg/Value pair and return the Option to parse it with.
646 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
648 const StringMap<Option *> &OptionsMap) {
654 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
658 // If the option is a prefixed option, then the value is simply the
659 // rest of the name... so fall through to later processing, by
660 // setting up the argument name flags and value fields.
661 if (PGOpt->getFormattingFlag() == cl::Prefix) {
662 Value = Arg.substr(Length);
663 Arg = Arg.substr(0, Length);
664 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
668 // This must be a grouped option... handle them now. Grouping options can't
670 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
673 // Move current arg name out of Arg into OneArgName.
674 StringRef OneArgName = Arg.substr(0, Length);
675 Arg = Arg.substr(Length);
677 // Because ValueRequired is an invalid flag for grouped arguments,
678 // we don't need to pass argc/argv in.
679 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
680 "Option can not be cl::Grouping AND cl::ValueRequired!");
683 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
685 // Get the next grouping option.
686 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
687 } while (PGOpt && Length != Arg.size());
689 // Return the last option with Arg cut down to just the last one.
693 static bool RequiresValue(const Option *O) {
694 return O->getNumOccurrencesFlag() == cl::Required ||
695 O->getNumOccurrencesFlag() == cl::OneOrMore;
698 static bool EatsUnboundedNumberOfValues(const Option *O) {
699 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
700 O->getNumOccurrencesFlag() == cl::OneOrMore;
703 static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
705 static bool isQuote(char C) { return C == '\"' || C == '\''; }
707 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
708 SmallVectorImpl<const char *> &NewArgv,
710 SmallString<128> Token;
711 for (size_t I = 0, E = Src.size(); I != E; ++I) {
712 // Consume runs of whitespace.
714 while (I != E && isWhitespace(Src[I])) {
715 // Mark the end of lines in response files
716 if (MarkEOLs && Src[I] == '\n')
717 NewArgv.push_back(nullptr);
724 // Backslash escapes the next character.
725 if (I + 1 < E && Src[I] == '\\') {
726 ++I; // Skip the escape.
727 Token.push_back(Src[I]);
731 // Consume a quoted string.
732 if (isQuote(Src[I])) {
733 char Quote = Src[I++];
734 while (I != E && Src[I] != Quote) {
735 // Backslash escapes the next character.
736 if (Src[I] == '\\' && I + 1 != E)
738 Token.push_back(Src[I]);
746 // End the token if this is whitespace.
747 if (isWhitespace(Src[I])) {
749 NewArgv.push_back(Saver.save(StringRef(Token)).data());
754 // This is a normal character. Append it.
755 Token.push_back(Src[I]);
758 // Append the last token after hitting EOF with no whitespace.
760 NewArgv.push_back(Saver.save(StringRef(Token)).data());
761 // Mark the end of response files
763 NewArgv.push_back(nullptr);
766 /// Backslashes are interpreted in a rather complicated way in the Windows-style
767 /// command line, because backslashes are used both to separate path and to
768 /// escape double quote. This method consumes runs of backslashes as well as the
769 /// following double quote if it's escaped.
771 /// * If an even number of backslashes is followed by a double quote, one
772 /// backslash is output for every pair of backslashes, and the last double
773 /// quote remains unconsumed. The double quote will later be interpreted as
774 /// the start or end of a quoted string in the main loop outside of this
777 /// * If an odd number of backslashes is followed by a double quote, one
778 /// backslash is output for every pair of backslashes, and a double quote is
779 /// output for the last pair of backslash-double quote. The double quote is
780 /// consumed in this case.
782 /// * Otherwise, backslashes are interpreted literally.
783 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
784 size_t E = Src.size();
785 int BackslashCount = 0;
786 // Skip the backslashes.
790 } while (I != E && Src[I] == '\\');
792 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
793 if (FollowedByDoubleQuote) {
794 Token.append(BackslashCount / 2, '\\');
795 if (BackslashCount % 2 == 0)
797 Token.push_back('"');
800 Token.append(BackslashCount, '\\');
804 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
805 SmallVectorImpl<const char *> &NewArgv,
807 SmallString<128> Token;
809 // This is a small state machine to consume characters until it reaches the
810 // end of the source string.
811 enum { INIT, UNQUOTED, QUOTED } State = INIT;
812 for (size_t I = 0, E = Src.size(); I != E; ++I) {
813 // INIT state indicates that the current input index is at the start of
814 // the string or between tokens.
816 if (isWhitespace(Src[I])) {
817 // Mark the end of lines in response files
818 if (MarkEOLs && Src[I] == '\n')
819 NewArgv.push_back(nullptr);
826 if (Src[I] == '\\') {
827 I = parseBackslash(Src, I, Token);
831 Token.push_back(Src[I]);
836 // UNQUOTED state means that it's reading a token not quoted by double
838 if (State == UNQUOTED) {
839 // Whitespace means the end of the token.
840 if (isWhitespace(Src[I])) {
841 NewArgv.push_back(Saver.save(StringRef(Token)).data());
844 // Mark the end of lines in response files
845 if (MarkEOLs && Src[I] == '\n')
846 NewArgv.push_back(nullptr);
853 if (Src[I] == '\\') {
854 I = parseBackslash(Src, I, Token);
857 Token.push_back(Src[I]);
861 // QUOTED state means that it's reading a token quoted by double quotes.
862 if (State == QUOTED) {
867 if (Src[I] == '\\') {
868 I = parseBackslash(Src, I, Token);
871 Token.push_back(Src[I]);
874 // Append the last token after hitting EOF with no whitespace.
876 NewArgv.push_back(Saver.save(StringRef(Token)).data());
877 // Mark the end of response files
879 NewArgv.push_back(nullptr);
882 // It is called byte order marker but the UTF-8 BOM is actually not affected
883 // by the host system's endianness.
884 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
885 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
888 static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
889 TokenizerCallback Tokenizer,
890 SmallVectorImpl<const char *> &NewArgv,
891 bool MarkEOLs, bool RelativeNames) {
892 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
893 MemoryBuffer::getFile(FName);
896 MemoryBuffer &MemBuf = *MemBufOrErr.get();
897 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
899 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
900 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
902 if (hasUTF16ByteOrderMark(BufRef)) {
903 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
905 Str = StringRef(UTF8Buf);
907 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
908 // these bytes before parsing.
909 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
910 else if (hasUTF8ByteOrderMark(BufRef))
911 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
913 // Tokenize the contents into NewArgv.
914 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
916 // If names of nested response files should be resolved relative to including
917 // file, replace the included response file names with their full paths
918 // obtained by required resolution.
920 for (unsigned I = 0; I < NewArgv.size(); ++I)
922 StringRef Arg = NewArgv[I];
923 if (Arg.front() == '@') {
924 StringRef FileName = Arg.drop_front();
925 if (llvm::sys::path::is_relative(FileName)) {
926 SmallString<128> ResponseFile;
927 ResponseFile.append(1, '@');
928 if (llvm::sys::path::is_relative(FName)) {
929 SmallString<128> curr_dir;
930 llvm::sys::fs::current_path(curr_dir);
931 ResponseFile.append(curr_dir.str());
933 llvm::sys::path::append(
934 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
935 NewArgv[I] = Saver.save(ResponseFile.c_str()).data();
943 /// \brief Expand response files on a command line recursively using the given
944 /// StringSaver and tokenization strategy.
945 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
946 SmallVectorImpl<const char *> &Argv,
947 bool MarkEOLs, bool RelativeNames) {
948 unsigned RspFiles = 0;
949 bool AllExpanded = true;
951 // Don't cache Argv.size() because it can change.
952 for (unsigned I = 0; I != Argv.size();) {
953 const char *Arg = Argv[I];
954 // Check if it is an EOL marker
955 if (Arg == nullptr) {
964 // If we have too many response files, leave some unexpanded. This avoids
965 // crashing on self-referential response files.
969 // Replace this response file argument with the tokenization of its
970 // contents. Nested response files are expanded in subsequent iterations.
971 SmallVector<const char *, 0> ExpandedArgv;
972 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
973 MarkEOLs, RelativeNames)) {
974 // We couldn't read this file, so we leave it in the argument stream and
980 Argv.erase(Argv.begin() + I);
981 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
986 /// ParseEnvironmentOptions - An alternative entry point to the
987 /// CommandLine library, which allows you to read the program's name
988 /// from the caller (as PROGNAME) and its command-line arguments from
989 /// an environment variable (whose name is given in ENVVAR).
991 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
992 const char *Overview) {
994 assert(progName && "Program name not specified");
995 assert(envVar && "Environment variable name missing");
997 // Get the environment variable they want us to parse options out of.
998 llvm::Optional<std::string> envValue = sys::Process::GetEnv(StringRef(envVar));
1002 // Get program's "name", which we wouldn't know without the caller
1004 SmallVector<const char *, 20> newArgv;
1006 StringSaver Saver(A);
1007 newArgv.push_back(Saver.save(progName).data());
1009 // Parse the value of the environment variable into a "command line"
1010 // and hand it off to ParseCommandLineOptions().
1011 TokenizeGNUCommandLine(*envValue, Saver, newArgv);
1012 int newArgc = static_cast<int>(newArgv.size());
1013 ParseCommandLineOptions(newArgc, &newArgv[0], StringRef(Overview));
1016 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1017 StringRef Overview, raw_ostream *Errs) {
1018 return GlobalParser->ParseCommandLineOptions(argc, argv, Overview,
1022 void CommandLineParser::ResetAllOptionOccurrences() {
1023 // So that we can parse different command lines multiple times in succession
1024 // we reset all option values to look like they have never been seen before.
1025 for (auto SC : RegisteredSubCommands) {
1026 for (auto &O : SC->OptionsMap)
1031 bool CommandLineParser::ParseCommandLineOptions(int argc,
1032 const char *const *argv,
1034 raw_ostream *Errs) {
1035 assert(hasOptions() && "No options specified!");
1037 // Expand response files.
1038 SmallVector<const char *, 20> newArgv(argv, argv + argc);
1040 StringSaver Saver(A);
1041 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
1043 argc = static_cast<int>(newArgv.size());
1045 // Copy the program name into ProgName, making sure not to overflow it.
1046 ProgramName = sys::path::filename(StringRef(argv[0]));
1048 ProgramOverview = Overview;
1049 bool IgnoreErrors = Errs;
1052 bool ErrorParsing = false;
1054 // Check out the positional arguments to collect information about them.
1055 unsigned NumPositionalRequired = 0;
1057 // Determine whether or not there are an unlimited number of positionals
1058 bool HasUnlimitedPositionals = false;
1061 SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1062 if (argc >= 2 && argv[FirstArg][0] != '-') {
1063 // If the first argument specifies a valid subcommand, start processing
1064 // options from the second argument.
1065 ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1066 if (ChosenSubCommand != &*TopLevelSubCommand)
1069 GlobalParser->ActiveSubCommand = ChosenSubCommand;
1071 assert(ChosenSubCommand);
1072 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1073 auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1074 auto &SinkOpts = ChosenSubCommand->SinkOpts;
1075 auto &OptionsMap = ChosenSubCommand->OptionsMap;
1077 if (ConsumeAfterOpt) {
1078 assert(PositionalOpts.size() > 0 &&
1079 "Cannot specify cl::ConsumeAfter without a positional argument!");
1081 if (!PositionalOpts.empty()) {
1083 // Calculate how many positional values are _required_.
1084 bool UnboundedFound = false;
1085 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1086 Option *Opt = PositionalOpts[i];
1087 if (RequiresValue(Opt))
1088 ++NumPositionalRequired;
1089 else if (ConsumeAfterOpt) {
1090 // ConsumeAfter cannot be combined with "optional" positional options
1091 // unless there is only one positional argument...
1092 if (PositionalOpts.size() > 1) {
1094 Opt->error("error - this positional option will never be matched, "
1095 "because it does not Require a value, and a "
1096 "cl::ConsumeAfter option is active!");
1097 ErrorParsing = true;
1099 } else if (UnboundedFound && !Opt->hasArgStr()) {
1100 // This option does not "require" a value... Make sure this option is
1101 // not specified after an option that eats all extra arguments, or this
1102 // one will never get any!
1105 Opt->error("error - option can never match, because "
1106 "another positional argument will match an "
1107 "unbounded number of values, and this option"
1108 " does not require a value!");
1109 *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1110 << "' is all messed up!\n";
1111 *Errs << PositionalOpts.size();
1112 ErrorParsing = true;
1114 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1116 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1119 // PositionalVals - A vector of "positional" arguments we accumulate into
1120 // the process at the end.
1122 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1124 // If the program has named positional arguments, and the name has been run
1125 // across, keep track of which positional argument was named. Otherwise put
1126 // the positional args into the PositionalVals list...
1127 Option *ActivePositionalArg = nullptr;
1129 // Loop over all of the arguments... processing them.
1130 bool DashDashFound = false; // Have we read '--'?
1131 for (int i = FirstArg; i < argc; ++i) {
1132 Option *Handler = nullptr;
1133 Option *NearestHandler = nullptr;
1134 std::string NearestHandlerString;
1136 StringRef ArgName = "";
1138 // Check to see if this is a positional argument. This argument is
1139 // considered to be positional if it doesn't start with '-', if it is "-"
1140 // itself, or if we have seen "--" already.
1142 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1143 // Positional argument!
1144 if (ActivePositionalArg) {
1145 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1146 continue; // We are done!
1149 if (!PositionalOpts.empty()) {
1150 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1152 // All of the positional arguments have been fulfulled, give the rest to
1153 // the consume after option... if it's specified...
1155 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1156 for (++i; i < argc; ++i)
1157 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1158 break; // Handle outside of the argument processing loop...
1161 // Delay processing positional arguments until the end...
1164 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1166 DashDashFound = true; // This is the mythical "--"?
1167 continue; // Don't try to process it as an argument itself.
1168 } else if (ActivePositionalArg &&
1169 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1170 // If there is a positional argument eating options, check to see if this
1171 // option is another positional argument. If so, treat it as an argument,
1172 // otherwise feed it to the eating positional.
1173 ArgName = StringRef(argv[i] + 1);
1174 // Eat leading dashes.
1175 while (!ArgName.empty() && ArgName[0] == '-')
1176 ArgName = ArgName.substr(1);
1178 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1179 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1180 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1181 continue; // We are done!
1184 } else { // We start with a '-', must be an argument.
1185 ArgName = StringRef(argv[i] + 1);
1186 // Eat leading dashes.
1187 while (!ArgName.empty() && ArgName[0] == '-')
1188 ArgName = ArgName.substr(1);
1190 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1192 // Check to see if this "option" is really a prefixed or grouped argument.
1194 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1197 // Otherwise, look for the closest available option to report to the user
1198 // in the upcoming error.
1199 if (!Handler && SinkOpts.empty())
1201 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1205 if (SinkOpts.empty()) {
1206 *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1207 << "'. Try: '" << argv[0] << " -help'\n";
1209 if (NearestHandler) {
1210 // If we know a near match, report it as well.
1211 *Errs << ProgramName << ": Did you mean '-" << NearestHandlerString
1215 ErrorParsing = true;
1217 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1220 (*I)->addOccurrence(i, "", StringRef(argv[i]));
1225 // If this is a named positional argument, just remember that it is the
1227 if (Handler->getFormattingFlag() == cl::Positional)
1228 ActivePositionalArg = Handler;
1230 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1233 // Check and handle positional arguments now...
1234 if (NumPositionalRequired > PositionalVals.size()) {
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";
1241 ErrorParsing = true;
1242 } else if (!HasUnlimitedPositionals &&
1243 PositionalVals.size() > PositionalOpts.size()) {
1244 *Errs << ProgramName << ": Too many positional arguments specified!\n"
1245 << "Can specify at most " << PositionalOpts.size()
1246 << " positional arguments: See: " << argv[0] << " -help\n";
1247 ErrorParsing = true;
1249 } else if (!ConsumeAfterOpt) {
1250 // Positional args have already been handled if ConsumeAfter is specified.
1251 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1252 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1253 if (RequiresValue(PositionalOpts[i])) {
1254 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1255 PositionalVals[ValNo].second);
1257 --NumPositionalRequired; // We fulfilled our duty...
1260 // If we _can_ give this option more arguments, do so now, as long as we
1261 // do not give it values that others need. 'Done' controls whether the
1262 // option even _WANTS_ any more.
1264 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1265 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1266 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1268 Done = true; // Optional arguments want _at most_ one value
1270 case cl::ZeroOrMore: // Zero or more will take all they can get...
1271 case cl::OneOrMore: // One or more will take all they can get...
1272 ProvidePositionalOption(PositionalOpts[i],
1273 PositionalVals[ValNo].first,
1274 PositionalVals[ValNo].second);
1278 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1279 "positional argument processing!");
1284 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1286 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1287 if (RequiresValue(PositionalOpts[j])) {
1288 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1289 PositionalVals[ValNo].first,
1290 PositionalVals[ValNo].second);
1294 // Handle the case where there is just one positional option, and it's
1295 // optional. In this case, we want to give JUST THE FIRST option to the
1296 // positional option and keep the rest for the consume after. The above
1297 // loop would have assigned no values to positional options in this case.
1299 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1300 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1301 PositionalVals[ValNo].first,
1302 PositionalVals[ValNo].second);
1306 // Handle over all of the rest of the arguments to the
1307 // cl::ConsumeAfter command line option...
1308 for (; ValNo != PositionalVals.size(); ++ValNo)
1310 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1311 PositionalVals[ValNo].second);
1314 // Loop over args and make sure all required args are specified!
1315 for (const auto &Opt : OptionsMap) {
1316 switch (Opt.second->getNumOccurrencesFlag()) {
1319 if (Opt.second->getNumOccurrences() == 0) {
1320 Opt.second->error("must be specified at least once!");
1321 ErrorParsing = true;
1329 // Now that we know if -debug is specified, we can use it.
1330 // Note that if ReadResponseFiles == true, this must be done before the
1331 // memory allocated for the expanded command line is free()d below.
1332 DEBUG(dbgs() << "Args: ";
1333 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1336 // Free all of the memory allocated to the map. Command line options may only
1337 // be processed once!
1340 // If we had an error processing our arguments, don't let the program execute
1349 //===----------------------------------------------------------------------===//
1350 // Option Base class implementation
1353 bool Option::error(const Twine &Message, StringRef ArgName) {
1354 if (!ArgName.data())
1356 if (ArgName.empty())
1357 errs() << HelpStr; // Be nice for positional arguments
1359 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1361 errs() << " option: " << Message << "\n";
1365 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1368 NumOccurrences++; // Increment the number of times we have been seen
1370 switch (getNumOccurrencesFlag()) {
1372 if (NumOccurrences > 1)
1373 return error("may only occur zero or one times!", ArgName);
1376 if (NumOccurrences > 1)
1377 return error("must occur exactly one time!", ArgName);
1385 return handleOccurrence(pos, ArgName, Value);
1388 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1389 // has been specified yet.
1391 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1392 if (O.ValueStr.empty())
1397 //===----------------------------------------------------------------------===//
1398 // cl::alias class implementation
1401 // Return the width of the option tag for printing...
1402 size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
1404 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1405 size_t FirstLineIndentedBy) {
1406 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1407 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1408 while (!Split.second.empty()) {
1409 Split = Split.second.split('\n');
1410 outs().indent(Indent) << Split.first << "\n";
1414 // Print out the option for the alias.
1415 void alias::printOptionInfo(size_t GlobalWidth) const {
1416 outs() << " -" << ArgStr;
1417 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
1420 //===----------------------------------------------------------------------===//
1421 // Parser Implementation code...
1424 // basic_parser implementation
1427 // Return the width of the option tag for printing...
1428 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1429 size_t Len = O.ArgStr.size();
1430 auto ValName = getValueName();
1431 if (!ValName.empty())
1432 Len += getValueStr(O, ValName).size() + 3;
1437 // printOptionInfo - Print out information about this option. The
1438 // to-be-maintained width is specified.
1440 void basic_parser_impl::printOptionInfo(const Option &O,
1441 size_t GlobalWidth) const {
1442 outs() << " -" << O.ArgStr;
1444 auto ValName = getValueName();
1445 if (!ValName.empty())
1446 outs() << "=<" << getValueStr(O, ValName) << '>';
1448 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1451 void basic_parser_impl::printOptionName(const Option &O,
1452 size_t GlobalWidth) const {
1453 outs() << " -" << O.ArgStr;
1454 outs().indent(GlobalWidth - O.ArgStr.size());
1457 // parser<bool> implementation
1459 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1461 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1467 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1471 return O.error("'" + Arg +
1472 "' is invalid value for boolean argument! Try 0 or 1");
1475 // parser<boolOrDefault> implementation
1477 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1478 boolOrDefault &Value) {
1479 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1484 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1489 return O.error("'" + Arg +
1490 "' is invalid value for boolean argument! Try 0 or 1");
1493 // parser<int> implementation
1495 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1497 if (Arg.getAsInteger(0, Value))
1498 return O.error("'" + Arg + "' value invalid for integer argument!");
1502 // parser<unsigned> implementation
1504 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1507 if (Arg.getAsInteger(0, Value))
1508 return O.error("'" + Arg + "' value invalid for uint argument!");
1512 // parser<unsigned long long> implementation
1514 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1516 unsigned long long &Value) {
1518 if (Arg.getAsInteger(0, Value))
1519 return O.error("'" + Arg + "' value invalid for uint argument!");
1523 // parser<double>/parser<float> implementation
1525 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1526 if (to_float(Arg, Value))
1528 return O.error("'" + Arg + "' value invalid for floating point argument!");
1531 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1533 return parseDouble(O, Arg, Val);
1536 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1539 if (parseDouble(O, Arg, dVal))
1545 // generic_parser_base implementation
1548 // findOption - Return the option number corresponding to the specified
1549 // argument string. If the option is not found, getNumOptions() is returned.
1551 unsigned generic_parser_base::findOption(StringRef Name) {
1552 unsigned e = getNumOptions();
1554 for (unsigned i = 0; i != e; ++i) {
1555 if (getOption(i) == Name)
1561 // Return the width of the option tag for printing...
1562 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1563 if (O.hasArgStr()) {
1564 size_t Size = O.ArgStr.size() + 6;
1565 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1566 Size = std::max(Size, getOption(i).size() + 8);
1569 size_t BaseSize = 0;
1570 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1571 BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1576 // printOptionInfo - Print out information about this option. The
1577 // to-be-maintained width is specified.
1579 void generic_parser_base::printOptionInfo(const Option &O,
1580 size_t GlobalWidth) const {
1581 if (O.hasArgStr()) {
1582 outs() << " -" << O.ArgStr;
1583 Option::printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
1585 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1586 size_t NumSpaces = GlobalWidth - getOption(i).size() - 8;
1587 outs() << " =" << getOption(i);
1588 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1591 if (!O.HelpStr.empty())
1592 outs() << " " << O.HelpStr << '\n';
1593 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1594 auto Option = getOption(i);
1595 outs() << " -" << Option;
1596 Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
1601 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1603 // printGenericOptionDiff - Print the value of this option and it's default.
1605 // "Generic" options have each value mapped to a name.
1606 void generic_parser_base::printGenericOptionDiff(
1607 const Option &O, const GenericOptionValue &Value,
1608 const GenericOptionValue &Default, size_t GlobalWidth) const {
1609 outs() << " -" << O.ArgStr;
1610 outs().indent(GlobalWidth - O.ArgStr.size());
1612 unsigned NumOpts = getNumOptions();
1613 for (unsigned i = 0; i != NumOpts; ++i) {
1614 if (Value.compare(getOptionValue(i)))
1617 outs() << "= " << getOption(i);
1618 size_t L = getOption(i).size();
1619 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1620 outs().indent(NumSpaces) << " (default: ";
1621 for (unsigned j = 0; j != NumOpts; ++j) {
1622 if (Default.compare(getOptionValue(j)))
1624 outs() << getOption(j);
1630 outs() << "= *unknown option value*\n";
1633 // printOptionDiff - Specializations for printing basic value types.
1635 #define PRINT_OPT_DIFF(T) \
1636 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1637 size_t GlobalWidth) const { \
1638 printOptionName(O, GlobalWidth); \
1641 raw_string_ostream SS(Str); \
1644 outs() << "= " << Str; \
1645 size_t NumSpaces = \
1646 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1647 outs().indent(NumSpaces) << " (default: "; \
1649 outs() << D.getValue(); \
1651 outs() << "*no default*"; \
1655 PRINT_OPT_DIFF(bool)
1656 PRINT_OPT_DIFF(boolOrDefault)
1658 PRINT_OPT_DIFF(unsigned)
1659 PRINT_OPT_DIFF(unsigned long long)
1660 PRINT_OPT_DIFF(double)
1661 PRINT_OPT_DIFF(float)
1662 PRINT_OPT_DIFF(char)
1664 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1665 const OptionValue<std::string> &D,
1666 size_t GlobalWidth) const {
1667 printOptionName(O, GlobalWidth);
1668 outs() << "= " << V;
1669 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1670 outs().indent(NumSpaces) << " (default: ";
1672 outs() << D.getValue();
1674 outs() << "*no default*";
1678 // Print a placeholder for options that don't yet support printOptionDiff().
1679 void basic_parser_impl::printOptionNoValue(const Option &O,
1680 size_t GlobalWidth) const {
1681 printOptionName(O, GlobalWidth);
1682 outs() << "= *cannot print option value*\n";
1685 //===----------------------------------------------------------------------===//
1686 // -help and -help-hidden option implementation
1689 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1690 const std::pair<const char *, Option *> *RHS) {
1691 return strcmp(LHS->first, RHS->first);
1694 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
1695 const std::pair<const char *, SubCommand *> *RHS) {
1696 return strcmp(LHS->first, RHS->first);
1699 // Copy Options into a vector so we can sort them as we like.
1700 static void sortOpts(StringMap<Option *> &OptMap,
1701 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1703 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
1705 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1707 // Ignore really-hidden options.
1708 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1711 // Unless showhidden is set, ignore hidden flags.
1712 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1715 // If we've already seen this option, don't add it to the list again.
1716 if (!OptionSet.insert(I->second).second)
1720 std::pair<const char *, Option *>(I->getKey().data(), I->second));
1723 // Sort the options list alphabetically.
1724 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1728 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
1729 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
1730 for (const auto &S : SubMap) {
1731 if (S->getName().empty())
1733 Subs.push_back(std::make_pair(S->getName().data(), S));
1735 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
1742 const bool ShowHidden;
1743 typedef SmallVector<std::pair<const char *, Option *>, 128>
1744 StrOptionPairVector;
1745 typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
1746 StrSubCommandPairVector;
1747 // Print the options. Opts is assumed to be alphabetically sorted.
1748 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1749 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1750 Opts[i].second->printOptionInfo(MaxArgLen);
1753 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
1754 for (const auto &S : Subs) {
1755 outs() << " " << S.first;
1756 if (!S.second->getDescription().empty()) {
1757 outs().indent(MaxSubLen - strlen(S.first));
1758 outs() << " - " << S.second->getDescription();
1765 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1766 virtual ~HelpPrinter() {}
1768 // Invoke the printer.
1769 void operator=(bool Value) {
1773 SubCommand *Sub = GlobalParser->getActiveSubCommand();
1774 auto &OptionsMap = Sub->OptionsMap;
1775 auto &PositionalOpts = Sub->PositionalOpts;
1776 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
1778 StrOptionPairVector Opts;
1779 sortOpts(OptionsMap, Opts, ShowHidden);
1781 StrSubCommandPairVector Subs;
1782 sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
1784 if (!GlobalParser->ProgramOverview.empty())
1785 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1787 if (Sub == &*TopLevelSubCommand) {
1788 outs() << "USAGE: " << GlobalParser->ProgramName;
1789 if (Subs.size() > 2)
1790 outs() << " [subcommand]";
1791 outs() << " [options]";
1793 if (!Sub->getDescription().empty()) {
1794 outs() << "SUBCOMMAND '" << Sub->getName()
1795 << "': " << Sub->getDescription() << "\n\n";
1797 outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
1801 for (auto Opt : PositionalOpts) {
1802 if (Opt->hasArgStr())
1803 outs() << " --" << Opt->ArgStr;
1804 outs() << " " << Opt->HelpStr;
1807 // Print the consume after option info if it exists...
1808 if (ConsumeAfterOpt)
1809 outs() << " " << ConsumeAfterOpt->HelpStr;
1811 if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
1812 // Compute the maximum subcommand length...
1813 size_t MaxSubLen = 0;
1814 for (size_t i = 0, e = Subs.size(); i != e; ++i)
1815 MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
1818 outs() << "SUBCOMMANDS:\n\n";
1819 printSubCommands(Subs, MaxSubLen);
1821 outs() << " Type \"" << GlobalParser->ProgramName
1822 << " <subcommand> -help\" to get more help on a specific "
1828 // Compute the maximum argument length...
1829 size_t MaxArgLen = 0;
1830 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1831 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1833 outs() << "OPTIONS:\n";
1834 printOptions(Opts, MaxArgLen);
1836 // Print any extra help the user has declared.
1837 for (auto I : GlobalParser->MoreHelp)
1839 GlobalParser->MoreHelp.clear();
1841 // Halt the program since help information was printed
1846 class CategorizedHelpPrinter : public HelpPrinter {
1848 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1850 // Helper function for printOptions().
1851 // It shall return a negative value if A's name should be lexicographically
1852 // ordered before B's name. It returns a value greater than zero if B's name
1853 // should be ordered before A's name, and it returns 0 otherwise.
1854 static int OptionCategoryCompare(OptionCategory *const *A,
1855 OptionCategory *const *B) {
1856 return (*A)->getName().compare((*B)->getName());
1859 // Make sure we inherit our base class's operator=()
1860 using HelpPrinter::operator=;
1863 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1864 std::vector<OptionCategory *> SortedCategories;
1865 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1867 // Collect registered option categories into vector in preparation for
1869 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1870 E = GlobalParser->RegisteredOptionCategories.end();
1872 SortedCategories.push_back(*I);
1875 // Sort the different option categories alphabetically.
1876 assert(SortedCategories.size() > 0 && "No option categories registered!");
1877 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1878 OptionCategoryCompare);
1880 // Create map to empty vectors.
1881 for (std::vector<OptionCategory *>::const_iterator
1882 I = SortedCategories.begin(),
1883 E = SortedCategories.end();
1885 CategorizedOptions[*I] = std::vector<Option *>();
1887 // Walk through pre-sorted options and assign into categories.
1888 // Because the options are already alphabetically sorted the
1889 // options within categories will also be alphabetically sorted.
1890 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1891 Option *Opt = Opts[I].second;
1892 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1893 "Option has an unregistered category");
1894 CategorizedOptions[Opt->Category].push_back(Opt);
1898 for (std::vector<OptionCategory *>::const_iterator
1899 Category = SortedCategories.begin(),
1900 E = SortedCategories.end();
1901 Category != E; ++Category) {
1902 // Hide empty categories for -help, but show for -help-hidden.
1903 const auto &CategoryOptions = CategorizedOptions[*Category];
1904 bool IsEmptyCategory = CategoryOptions.empty();
1905 if (!ShowHidden && IsEmptyCategory)
1908 // Print category information.
1910 outs() << (*Category)->getName() << ":\n";
1912 // Check if description is set.
1913 if (!(*Category)->getDescription().empty())
1914 outs() << (*Category)->getDescription() << "\n\n";
1918 // When using -help-hidden explicitly state if the category has no
1919 // options associated with it.
1920 if (IsEmptyCategory) {
1921 outs() << " This option category has no options.\n";
1924 // Loop over the options in the category and print.
1925 for (const Option *Opt : CategoryOptions)
1926 Opt->printOptionInfo(MaxArgLen);
1931 // This wraps the Uncategorizing and Categorizing printers and decides
1932 // at run time which should be invoked.
1933 class HelpPrinterWrapper {
1935 HelpPrinter &UncategorizedPrinter;
1936 CategorizedHelpPrinter &CategorizedPrinter;
1939 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1940 CategorizedHelpPrinter &CategorizedPrinter)
1941 : UncategorizedPrinter(UncategorizedPrinter),
1942 CategorizedPrinter(CategorizedPrinter) {}
1944 // Invoke the printer.
1945 void operator=(bool Value);
1948 } // End anonymous namespace
1950 // Declare the four HelpPrinter instances that are used to print out help, or
1951 // help-hidden as an uncategorized list or in categories.
1952 static HelpPrinter UncategorizedNormalPrinter(false);
1953 static HelpPrinter UncategorizedHiddenPrinter(true);
1954 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1955 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1957 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1958 // a categorizing help printer
1959 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1960 CategorizedNormalPrinter);
1961 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1962 CategorizedHiddenPrinter);
1964 // Define a category for generic options that all tools should have.
1965 static cl::OptionCategory GenericCategory("Generic Options");
1967 // Define uncategorized help printers.
1968 // -help-list is hidden by default because if Option categories are being used
1969 // then -help behaves the same as -help-list.
1970 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1972 cl::desc("Display list of available options (-help-list-hidden for more)"),
1973 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1974 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
1976 static cl::opt<HelpPrinter, true, parser<bool>>
1977 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1978 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1979 cl::ValueDisallowed, cl::cat(GenericCategory),
1980 cl::sub(*AllSubCommands));
1982 // Define uncategorized/categorized help printers. These printers change their
1983 // behaviour at runtime depending on whether one or more Option categories have
1985 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1986 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1987 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1988 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
1990 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1991 HHOp("help-hidden", cl::desc("Display all available options"),
1992 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1993 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
1995 static cl::opt<bool> PrintOptions(
1997 cl::desc("Print non-default options after command line parsing"),
1998 cl::Hidden, cl::init(false), cl::cat(GenericCategory),
1999 cl::sub(*AllSubCommands));
2001 static cl::opt<bool> PrintAllOptions(
2002 "print-all-options",
2003 cl::desc("Print all option values after command line parsing"), cl::Hidden,
2004 cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2006 void HelpPrinterWrapper::operator=(bool Value) {
2010 // Decide which printer to invoke. If more than one option category is
2011 // registered then it is useful to show the categorized help instead of
2012 // uncategorized help.
2013 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2014 // unhide -help-list option so user can have uncategorized output if they
2016 HLOp.setHiddenFlag(NotHidden);
2018 CategorizedPrinter = true; // Invoke categorized printer
2020 UncategorizedPrinter = true; // Invoke uncategorized printer
2023 // Print the value of each option.
2024 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2026 void CommandLineParser::printOptionValues() {
2027 if (!PrintOptions && !PrintAllOptions)
2030 SmallVector<std::pair<const char *, Option *>, 128> Opts;
2031 sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2033 // Compute the maximum argument length...
2034 size_t MaxArgLen = 0;
2035 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2036 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2038 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2039 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2042 static void (*OverrideVersionPrinter)() = nullptr;
2044 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
2047 class VersionPrinter {
2050 raw_ostream &OS = outs();
2051 #ifdef PACKAGE_VENDOR
2052 OS << PACKAGE_VENDOR << " ";
2054 OS << "LLVM (http://llvm.org/):\n ";
2056 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2057 #ifdef LLVM_VERSION_INFO
2058 OS << " " << LLVM_VERSION_INFO;
2061 #ifndef __OPTIMIZE__
2062 OS << "DEBUG build";
2064 OS << "Optimized build";
2067 OS << " with assertions";
2069 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2070 std::string CPU = sys::getHostCPUName();
2071 if (CPU == "generic")
2074 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
2075 << " Host CPU: " << CPU;
2079 void operator=(bool OptionWasSpecified) {
2080 if (!OptionWasSpecified)
2083 if (OverrideVersionPrinter != nullptr) {
2084 (*OverrideVersionPrinter)();
2089 // Iterate over any registered extra printers and call them to add further
2091 if (ExtraVersionPrinters != nullptr) {
2093 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
2094 E = ExtraVersionPrinters->end();
2102 } // End anonymous namespace
2104 // Define the --version option that prints out the LLVM version for the tool
2105 static VersionPrinter VersionPrinterInstance;
2107 static cl::opt<VersionPrinter, true, parser<bool>>
2108 VersOp("version", cl::desc("Display the version of this program"),
2109 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2110 cl::cat(GenericCategory));
2112 // Utility function for printing the help message.
2113 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2114 // This looks weird, but it actually prints the help message. The Printers are
2115 // types of HelpPrinter and the help gets printed when its operator= is
2116 // invoked. That's because the "normal" usages of the help printer is to be
2117 // assigned true/false depending on whether -help or -help-hidden was given or
2118 // not. Since we're circumventing that we have to make it look like -help or
2119 // -help-hidden were given, so we assign true.
2121 if (!Hidden && !Categorized)
2122 UncategorizedNormalPrinter = true;
2123 else if (!Hidden && Categorized)
2124 CategorizedNormalPrinter = true;
2125 else if (Hidden && !Categorized)
2126 UncategorizedHiddenPrinter = true;
2128 CategorizedHiddenPrinter = true;
2131 /// Utility function for printing version number.
2132 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
2134 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
2136 void cl::AddExtraVersionPrinter(void (*func)()) {
2137 if (!ExtraVersionPrinters)
2138 ExtraVersionPrinters = new std::vector<void (*)()>;
2140 ExtraVersionPrinters->push_back(func);
2143 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2144 auto &Subs = GlobalParser->RegisteredSubCommands;
2146 assert(is_contained(Subs, &Sub));
2147 return Sub.OptionsMap;
2150 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2151 cl::getRegisteredSubcommands() {
2152 return GlobalParser->getRegisteredSubcommands();
2155 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2156 for (auto &I : Sub.OptionsMap) {
2157 if (I.second->Category != &Category &&
2158 I.second->Category != &GenericCategory)
2159 I.second->setHiddenFlag(cl::ReallyHidden);
2163 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2165 auto CategoriesBegin = Categories.begin();
2166 auto CategoriesEnd = Categories.end();
2167 for (auto &I : Sub.OptionsMap) {
2168 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
2170 I.second->Category != &GenericCategory)
2171 I.second->setHiddenFlag(cl::ReallyHidden);
2175 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2176 void cl::ResetAllOptionOccurrences() {
2177 GlobalParser->ResetAllOptionOccurrences();
2180 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2181 const char *Overview) {
2182 llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),