1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This class implements a command line argument processor that is useful when
10 // creating a tool. It provides a simple, minimalistic interface that is easily
11 // extensible and supports nonlocal (library) command line options.
13 // Note that rather than trying to figure out what this code does, you could try
14 // reading the library documentation located in docs/CommandLine.html
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm-c/Support.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/Triple.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 //===----------------------------------------------------------------------===//
49 // Template instantiations and anchors.
53 template class basic_parser<bool>;
54 template class basic_parser<boolOrDefault>;
55 template class basic_parser<int>;
56 template class basic_parser<unsigned>;
57 template class basic_parser<unsigned long long>;
58 template class basic_parser<double>;
59 template class basic_parser<float>;
60 template class basic_parser<std::string>;
61 template class basic_parser<char>;
63 template class opt<unsigned>;
64 template class opt<int>;
65 template class opt<std::string>;
66 template class opt<char>;
67 template class opt<bool>;
69 } // end namespace llvm::cl
71 // Pin the vtables to this file.
72 void GenericOptionValue::anchor() {}
73 void OptionValue<boolOrDefault>::anchor() {}
74 void OptionValue<std::string>::anchor() {}
75 void Option::anchor() {}
76 void basic_parser_impl::anchor() {}
77 void parser<bool>::anchor() {}
78 void parser<boolOrDefault>::anchor() {}
79 void parser<int>::anchor() {}
80 void parser<unsigned>::anchor() {}
81 void parser<unsigned long long>::anchor() {}
82 void parser<double>::anchor() {}
83 void parser<float>::anchor() {}
84 void parser<std::string>::anchor() {}
85 void parser<char>::anchor() {}
87 //===----------------------------------------------------------------------===//
91 class CommandLineParser {
93 // Globals for name and overview of program. Program name is not a string to
94 // avoid static ctor/dtor issues.
95 std::string ProgramName;
96 StringRef ProgramOverview;
98 // This collects additional help to be printed.
99 std::vector<StringRef> MoreHelp;
101 // This collects the different option categories that have been registered.
102 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
104 // This collects the different subcommands that have been registered.
105 SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
107 CommandLineParser() : ActiveSubCommand(nullptr) {
108 registerSubCommand(&*TopLevelSubCommand);
109 registerSubCommand(&*AllSubCommands);
112 void ResetAllOptionOccurrences();
114 bool ParseCommandLineOptions(int argc, const char *const *argv,
115 StringRef Overview, raw_ostream *Errs = nullptr);
117 void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
120 if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
121 errs() << ProgramName << ": CommandLine Error: Option '" << Name
122 << "' registered more than once!\n";
123 report_fatal_error("inconsistency in registered CommandLine options");
126 // If we're adding this to all sub-commands, add it to the ones that have
127 // already been registered.
128 if (SC == &*AllSubCommands) {
129 for (const auto &Sub : RegisteredSubCommands) {
132 addLiteralOption(Opt, Sub, Name);
137 void addLiteralOption(Option &Opt, StringRef Name) {
138 if (Opt.Subs.empty())
139 addLiteralOption(Opt, &*TopLevelSubCommand, Name);
141 for (auto SC : Opt.Subs)
142 addLiteralOption(Opt, SC, Name);
146 void addOption(Option *O, SubCommand *SC) {
147 bool HadErrors = false;
148 if (O->hasArgStr()) {
149 // Add argument to the argument map!
150 if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
151 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
152 << "' registered more than once!\n";
157 // Remember information about positional options.
158 if (O->getFormattingFlag() == cl::Positional)
159 SC->PositionalOpts.push_back(O);
160 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
161 SC->SinkOpts.push_back(O);
162 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
163 if (SC->ConsumeAfterOpt) {
164 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
167 SC->ConsumeAfterOpt = O;
170 // Fail hard if there were errors. These are strictly unrecoverable and
171 // indicate serious issues such as conflicting option names or an
173 // linked LLVM distribution.
175 report_fatal_error("inconsistency in registered CommandLine options");
177 // If we're adding this to all sub-commands, add it to the ones that have
178 // already been registered.
179 if (SC == &*AllSubCommands) {
180 for (const auto &Sub : RegisteredSubCommands) {
188 void addOption(Option *O) {
189 if (O->Subs.empty()) {
190 addOption(O, &*TopLevelSubCommand);
192 for (auto SC : O->Subs)
197 void removeOption(Option *O, SubCommand *SC) {
198 SmallVector<StringRef, 16> OptionNames;
199 O->getExtraOptionNames(OptionNames);
201 OptionNames.push_back(O->ArgStr);
203 SubCommand &Sub = *SC;
204 for (auto Name : OptionNames)
205 Sub.OptionsMap.erase(Name);
207 if (O->getFormattingFlag() == cl::Positional)
208 for (auto Opt = Sub.PositionalOpts.begin();
209 Opt != Sub.PositionalOpts.end(); ++Opt) {
211 Sub.PositionalOpts.erase(Opt);
215 else if (O->getMiscFlags() & cl::Sink)
216 for (auto Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
218 Sub.SinkOpts.erase(Opt);
222 else if (O == Sub.ConsumeAfterOpt)
223 Sub.ConsumeAfterOpt = nullptr;
226 void removeOption(Option *O) {
228 removeOption(O, &*TopLevelSubCommand);
230 if (O->isInAllSubCommands()) {
231 for (auto SC : RegisteredSubCommands)
234 for (auto SC : O->Subs)
240 bool hasOptions(const SubCommand &Sub) const {
241 return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
242 nullptr != Sub.ConsumeAfterOpt);
245 bool hasOptions() const {
246 for (const auto &S : RegisteredSubCommands) {
253 SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
255 void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
256 SubCommand &Sub = *SC;
257 if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
258 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
259 << "' registered more than once!\n";
260 report_fatal_error("inconsistency in registered CommandLine options");
262 Sub.OptionsMap.erase(O->ArgStr);
265 void updateArgStr(Option *O, StringRef NewName) {
267 updateArgStr(O, NewName, &*TopLevelSubCommand);
269 for (auto SC : O->Subs)
270 updateArgStr(O, NewName, SC);
274 void printOptionValues();
276 void registerCategory(OptionCategory *cat) {
277 assert(count_if(RegisteredOptionCategories,
278 [cat](const OptionCategory *Category) {
279 return cat->getName() == Category->getName();
281 "Duplicate option categories");
283 RegisteredOptionCategories.insert(cat);
286 void registerSubCommand(SubCommand *sub) {
287 assert(count_if(RegisteredSubCommands,
288 [sub](const SubCommand *Sub) {
289 return (!sub->getName().empty()) &&
290 (Sub->getName() == sub->getName());
292 "Duplicate subcommands");
293 RegisteredSubCommands.insert(sub);
295 // For all options that have been registered for all subcommands, add the
296 // option to this subcommand now.
297 if (sub != &*AllSubCommands) {
298 for (auto &E : AllSubCommands->OptionsMap) {
299 Option *O = E.second;
300 if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
304 addLiteralOption(*O, sub, E.first());
309 void unregisterSubCommand(SubCommand *sub) {
310 RegisteredSubCommands.erase(sub);
313 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
314 getRegisteredSubcommands() {
315 return make_range(RegisteredSubCommands.begin(),
316 RegisteredSubCommands.end());
320 ActiveSubCommand = nullptr;
322 ProgramOverview = StringRef();
325 RegisteredOptionCategories.clear();
327 ResetAllOptionOccurrences();
328 RegisteredSubCommands.clear();
330 TopLevelSubCommand->reset();
331 AllSubCommands->reset();
332 registerSubCommand(&*TopLevelSubCommand);
333 registerSubCommand(&*AllSubCommands);
337 SubCommand *ActiveSubCommand;
339 Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
340 SubCommand *LookupSubCommand(StringRef Name);
345 static ManagedStatic<CommandLineParser> GlobalParser;
347 void cl::AddLiteralOption(Option &O, StringRef Name) {
348 GlobalParser->addLiteralOption(O, Name);
351 extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
352 GlobalParser->MoreHelp.push_back(Help);
355 void Option::addArgument() {
356 GlobalParser->addOption(this);
357 FullyInitialized = true;
360 void Option::removeArgument() { GlobalParser->removeOption(this); }
362 void Option::setArgStr(StringRef S) {
363 if (FullyInitialized)
364 GlobalParser->updateArgStr(this, S);
365 assert((S.empty() || S[0] != '-') && "Option can't start with '-");
369 // Initialise the general option category.
370 OptionCategory llvm::cl::GeneralCategory("General options");
372 void OptionCategory::registerCategory() {
373 GlobalParser->registerCategory(this);
376 // A special subcommand representing no subcommand. It is particularly important
377 // that this ManagedStatic uses constant initailization and not dynamic
378 // initialization because it is referenced from cl::opt constructors, which run
379 // dynamically in an arbitrary order.
380 ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
382 // A special subcommand that can be used to put an option into all subcommands.
383 ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
385 void SubCommand::registerSubCommand() {
386 GlobalParser->registerSubCommand(this);
389 void SubCommand::unregisterSubCommand() {
390 GlobalParser->unregisterSubCommand(this);
393 void SubCommand::reset() {
394 PositionalOpts.clear();
398 ConsumeAfterOpt = nullptr;
401 SubCommand::operator bool() const {
402 return (GlobalParser->getActiveSubCommand() == this);
405 //===----------------------------------------------------------------------===//
406 // Basic, shared command line option processing machinery.
409 /// LookupOption - Lookup the option specified by the specified option on the
410 /// command line. If there is a value specified (after an equal sign) return
411 /// that as well. This assumes that leading dashes have already been stripped.
412 Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
414 // Reject all dashes.
417 assert(&Sub != &*AllSubCommands);
419 size_t EqualPos = Arg.find('=');
421 // If we have an equals sign, remember the value.
422 if (EqualPos == StringRef::npos) {
423 // Look up the option.
424 auto I = Sub.OptionsMap.find(Arg);
425 if (I == Sub.OptionsMap.end())
428 return I != Sub.OptionsMap.end() ? I->second : nullptr;
431 // If the argument before the = is a valid option name and the option allows
432 // non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match
433 // failure by returning nullptr.
434 auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
435 if (I == Sub.OptionsMap.end())
439 if (O->getFormattingFlag() == cl::AlwaysPrefix)
442 Value = Arg.substr(EqualPos + 1);
443 Arg = Arg.substr(0, EqualPos);
447 SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
449 return &*TopLevelSubCommand;
450 for (auto S : RegisteredSubCommands) {
451 if (S == &*AllSubCommands)
453 if (S->getName().empty())
456 if (StringRef(S->getName()) == StringRef(Name))
459 return &*TopLevelSubCommand;
462 /// LookupNearestOption - Lookup the closest match to the option specified by
463 /// the specified option on the command line. If there is a value specified
464 /// (after an equal sign) return that as well. This assumes that leading dashes
465 /// have already been stripped.
466 static Option *LookupNearestOption(StringRef Arg,
467 const StringMap<Option *> &OptionsMap,
468 std::string &NearestString) {
469 // Reject all dashes.
473 // Split on any equal sign.
474 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
475 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
476 StringRef &RHS = SplitArg.second;
478 // Find the closest match.
479 Option *Best = nullptr;
480 unsigned BestDistance = 0;
481 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
482 ie = OptionsMap.end();
484 Option *O = it->second;
485 SmallVector<StringRef, 16> OptionNames;
486 O->getExtraOptionNames(OptionNames);
488 OptionNames.push_back(O->ArgStr);
490 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
491 StringRef Flag = PermitValue ? LHS : Arg;
492 for (auto Name : OptionNames) {
493 unsigned Distance = StringRef(Name).edit_distance(
494 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
495 if (!Best || Distance < BestDistance) {
497 BestDistance = Distance;
498 if (RHS.empty() || !PermitValue)
499 NearestString = Name;
501 NearestString = (Twine(Name) + "=" + RHS).str();
509 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
510 /// that does special handling of cl::CommaSeparated options.
511 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
512 StringRef ArgName, StringRef Value,
513 bool MultiArg = false) {
514 // Check to see if this option accepts a comma separated list of values. If
515 // it does, we have to split up the value into multiple values.
516 if (Handler->getMiscFlags() & CommaSeparated) {
517 StringRef Val(Value);
518 StringRef::size_type Pos = Val.find(',');
520 while (Pos != StringRef::npos) {
521 // Process the portion before the comma.
522 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
524 // Erase the portion before the comma, AND the comma.
525 Val = Val.substr(Pos + 1);
526 // Check for another comma.
533 return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
536 /// ProvideOption - For Value, this differentiates between an empty value ("")
537 /// and a null value (StringRef()). The later is accepted for arguments that
538 /// don't allow a value (-foo) the former is rejected (-foo=).
539 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
540 StringRef Value, int argc,
541 const char *const *argv, int &i) {
542 // Is this a multi-argument option?
543 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
545 // Enforce value requirements
546 switch (Handler->getValueExpectedFlag()) {
548 if (!Value.data()) { // No value specified?
549 // If no other argument or the option only supports prefix form, we
550 // cannot look at the next argument.
551 if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
552 return Handler->error("requires a value!");
553 // Steal the next argument, like for '-o filename'
554 assert(argv && "null check");
555 Value = StringRef(argv[++i]);
558 case ValueDisallowed:
559 if (NumAdditionalVals > 0)
560 return Handler->error("multi-valued option specified"
561 " with ValueDisallowed modifier!");
564 return Handler->error("does not allow a value! '" + Twine(Value) +
571 // If this isn't a multi-arg option, just run the handler.
572 if (NumAdditionalVals == 0)
573 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
575 // If it is, run the handle several times.
576 bool MultiArg = false;
579 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
585 while (NumAdditionalVals > 0) {
587 return Handler->error("not enough values!");
588 assert(argv && "null check");
589 Value = StringRef(argv[++i]);
591 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
599 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
601 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
604 // Option predicates...
605 static inline bool isGrouping(const Option *O) {
606 return O->getMiscFlags() & cl::Grouping;
608 static inline bool isPrefixedOrGrouping(const Option *O) {
609 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
610 O->getFormattingFlag() == cl::AlwaysPrefix;
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);
658 StringRef MaybeValue =
659 (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
660 Arg = Arg.substr(0, Length);
661 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
663 // cl::Prefix options do not preserve '=' when used separately.
664 // The behavior for them with grouped options should be the same.
665 if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
666 (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
671 if (MaybeValue[0] == '=') {
672 Value = MaybeValue.substr(1);
676 // This must be a grouped option.
677 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
679 // Grouping options inside a group can't have values.
680 if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
681 ErrorParsing |= PGOpt->error("may not occur within a group!");
685 // Because the value for the option is not required, we don't need to pass
688 ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
690 // Get the next grouping option.
692 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
695 // We could not find a grouping option in the remainder of Arg.
699 static bool RequiresValue(const Option *O) {
700 return O->getNumOccurrencesFlag() == cl::Required ||
701 O->getNumOccurrencesFlag() == cl::OneOrMore;
704 static bool EatsUnboundedNumberOfValues(const Option *O) {
705 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
706 O->getNumOccurrencesFlag() == cl::OneOrMore;
709 static bool isWhitespace(char C) {
710 return C == ' ' || C == '\t' || C == '\r' || C == '\n';
713 static bool isWhitespaceOrNull(char C) {
714 return isWhitespace(C) || C == '\0';
717 static bool isQuote(char C) { return C == '\"' || C == '\''; }
719 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
720 SmallVectorImpl<const char *> &NewArgv,
722 SmallString<128> Token;
723 for (size_t I = 0, E = Src.size(); I != E; ++I) {
724 // Consume runs of whitespace.
726 while (I != E && isWhitespace(Src[I])) {
727 // Mark the end of lines in response files
728 if (MarkEOLs && Src[I] == '\n')
729 NewArgv.push_back(nullptr);
738 // Backslash escapes the next character.
739 if (I + 1 < E && C == '\\') {
740 ++I; // Skip the escape.
741 Token.push_back(Src[I]);
745 // Consume a quoted string.
748 while (I != E && Src[I] != C) {
749 // Backslash escapes the next character.
750 if (Src[I] == '\\' && I + 1 != E)
752 Token.push_back(Src[I]);
760 // End the token if this is whitespace.
761 if (isWhitespace(C)) {
763 NewArgv.push_back(Saver.save(StringRef(Token)).data());
768 // This is a normal character. Append it.
772 // Append the last token after hitting EOF with no whitespace.
774 NewArgv.push_back(Saver.save(StringRef(Token)).data());
775 // Mark the end of response files
777 NewArgv.push_back(nullptr);
780 /// Backslashes are interpreted in a rather complicated way in the Windows-style
781 /// command line, because backslashes are used both to separate path and to
782 /// escape double quote. This method consumes runs of backslashes as well as the
783 /// following double quote if it's escaped.
785 /// * If an even number of backslashes is followed by a double quote, one
786 /// backslash is output for every pair of backslashes, and the last double
787 /// quote remains unconsumed. The double quote will later be interpreted as
788 /// the start or end of a quoted string in the main loop outside of this
791 /// * If an odd number of backslashes is followed by a double quote, one
792 /// backslash is output for every pair of backslashes, and a double quote is
793 /// output for the last pair of backslash-double quote. The double quote is
794 /// consumed in this case.
796 /// * Otherwise, backslashes are interpreted literally.
797 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
798 size_t E = Src.size();
799 int BackslashCount = 0;
800 // Skip the backslashes.
804 } while (I != E && Src[I] == '\\');
806 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
807 if (FollowedByDoubleQuote) {
808 Token.append(BackslashCount / 2, '\\');
809 if (BackslashCount % 2 == 0)
811 Token.push_back('"');
814 Token.append(BackslashCount, '\\');
818 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
819 SmallVectorImpl<const char *> &NewArgv,
821 SmallString<128> Token;
823 // This is a small state machine to consume characters until it reaches the
824 // end of the source string.
825 enum { INIT, UNQUOTED, QUOTED } State = INIT;
826 for (size_t I = 0, E = Src.size(); I != E; ++I) {
829 // INIT state indicates that the current input index is at the start of
830 // the string or between tokens.
832 if (isWhitespaceOrNull(C)) {
833 // Mark the end of lines in response files
834 if (MarkEOLs && C == '\n')
835 NewArgv.push_back(nullptr);
843 I = parseBackslash(Src, I, Token);
852 // UNQUOTED state means that it's reading a token not quoted by double
854 if (State == UNQUOTED) {
855 // Whitespace means the end of the token.
856 if (isWhitespaceOrNull(C)) {
857 NewArgv.push_back(Saver.save(StringRef(Token)).data());
860 // Mark the end of lines in response files
861 if (MarkEOLs && C == '\n')
862 NewArgv.push_back(nullptr);
870 I = parseBackslash(Src, I, Token);
877 // QUOTED state means that it's reading a token quoted by double quotes.
878 if (State == QUOTED) {
880 if (I < (E - 1) && Src[I + 1] == '"') {
881 // Consecutive double-quotes inside a quoted string implies one
883 Token.push_back('"');
891 I = parseBackslash(Src, I, Token);
897 // Append the last token after hitting EOF with no whitespace.
899 NewArgv.push_back(Saver.save(StringRef(Token)).data());
900 // Mark the end of response files
902 NewArgv.push_back(nullptr);
905 void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
906 SmallVectorImpl<const char *> &NewArgv,
908 for (const char *Cur = Source.begin(); Cur != Source.end();) {
909 SmallString<128> Line;
910 // Check for comment line.
911 if (isWhitespace(*Cur)) {
912 while (Cur != Source.end() && isWhitespace(*Cur))
917 while (Cur != Source.end() && *Cur != '\n')
921 // Find end of the current line.
922 const char *Start = Cur;
923 for (const char *End = Source.end(); Cur != End; ++Cur) {
925 if (Cur + 1 != End) {
928 (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
929 Line.append(Start, Cur - 1);
935 } else if (*Cur == '\n')
939 Line.append(Start, Cur);
940 cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
944 // It is called byte order marker but the UTF-8 BOM is actually not affected
945 // by the host system's endianness.
946 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
947 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
950 static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
951 TokenizerCallback Tokenizer,
952 SmallVectorImpl<const char *> &NewArgv,
953 bool MarkEOLs, bool RelativeNames) {
954 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
955 MemoryBuffer::getFile(FName);
958 MemoryBuffer &MemBuf = *MemBufOrErr.get();
959 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
961 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
962 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
964 if (hasUTF16ByteOrderMark(BufRef)) {
965 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
967 Str = StringRef(UTF8Buf);
969 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
970 // these bytes before parsing.
971 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
972 else if (hasUTF8ByteOrderMark(BufRef))
973 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
975 // Tokenize the contents into NewArgv.
976 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
978 // If names of nested response files should be resolved relative to including
979 // file, replace the included response file names with their full paths
980 // obtained by required resolution.
982 for (unsigned I = 0; I < NewArgv.size(); ++I)
984 StringRef Arg = NewArgv[I];
985 if (Arg.front() == '@') {
986 StringRef FileName = Arg.drop_front();
987 if (llvm::sys::path::is_relative(FileName)) {
988 SmallString<128> ResponseFile;
989 ResponseFile.append(1, '@');
990 if (llvm::sys::path::is_relative(FName)) {
991 SmallString<128> curr_dir;
992 llvm::sys::fs::current_path(curr_dir);
993 ResponseFile.append(curr_dir.str());
995 llvm::sys::path::append(
996 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
997 NewArgv[I] = Saver.save(ResponseFile.c_str()).data();
1005 /// Expand response files on a command line recursively using the given
1006 /// StringSaver and tokenization strategy.
1007 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1008 SmallVectorImpl<const char *> &Argv,
1009 bool MarkEOLs, bool RelativeNames) {
1010 unsigned RspFiles = 0;
1011 bool AllExpanded = true;
1013 // Don't cache Argv.size() because it can change.
1014 for (unsigned I = 0; I != Argv.size();) {
1015 const char *Arg = Argv[I];
1016 // Check if it is an EOL marker
1017 if (Arg == nullptr) {
1021 if (Arg[0] != '@') {
1026 // If we have too many response files, leave some unexpanded. This avoids
1027 // crashing on self-referential response files.
1028 if (RspFiles++ > 20)
1031 // Replace this response file argument with the tokenization of its
1032 // contents. Nested response files are expanded in subsequent iterations.
1033 SmallVector<const char *, 0> ExpandedArgv;
1034 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
1035 MarkEOLs, RelativeNames)) {
1036 // We couldn't read this file, so we leave it in the argument stream and
1038 AllExpanded = false;
1042 Argv.erase(Argv.begin() + I);
1043 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1048 bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver,
1049 SmallVectorImpl<const char *> &Argv) {
1050 if (!ExpandResponseFile(CfgFile, Saver, cl::tokenizeConfigFile, Argv,
1051 /*MarkEOLs*/ false, /*RelativeNames*/ true))
1053 return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
1054 /*MarkEOLs*/ false, /*RelativeNames*/ true);
1057 /// ParseEnvironmentOptions - An alternative entry point to the
1058 /// CommandLine library, which allows you to read the program's name
1059 /// from the caller (as PROGNAME) and its command-line arguments from
1060 /// an environment variable (whose name is given in ENVVAR).
1062 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
1063 const char *Overview) {
1065 assert(progName && "Program name not specified");
1066 assert(envVar && "Environment variable name missing");
1068 // Get the environment variable they want us to parse options out of.
1069 llvm::Optional<std::string> envValue = sys::Process::GetEnv(StringRef(envVar));
1073 // Get program's "name", which we wouldn't know without the caller
1075 SmallVector<const char *, 20> newArgv;
1077 StringSaver Saver(A);
1078 newArgv.push_back(Saver.save(progName).data());
1080 // Parse the value of the environment variable into a "command line"
1081 // and hand it off to ParseCommandLineOptions().
1082 TokenizeGNUCommandLine(*envValue, Saver, newArgv);
1083 int newArgc = static_cast<int>(newArgv.size());
1084 ParseCommandLineOptions(newArgc, &newArgv[0], StringRef(Overview));
1087 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1088 StringRef Overview, raw_ostream *Errs,
1089 const char *EnvVar) {
1090 SmallVector<const char *, 20> NewArgv;
1092 StringSaver Saver(A);
1093 NewArgv.push_back(argv[0]);
1095 // Parse options from environment variable.
1097 if (llvm::Optional<std::string> EnvValue =
1098 sys::Process::GetEnv(StringRef(EnvVar)))
1099 TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1102 // Append options from command line.
1103 for (int I = 1; I < argc; ++I)
1104 NewArgv.push_back(argv[I]);
1105 int NewArgc = static_cast<int>(NewArgv.size());
1107 // Parse all options.
1108 return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1112 void CommandLineParser::ResetAllOptionOccurrences() {
1113 // So that we can parse different command lines multiple times in succession
1114 // we reset all option values to look like they have never been seen before.
1115 for (auto SC : RegisteredSubCommands) {
1116 for (auto &O : SC->OptionsMap)
1121 bool CommandLineParser::ParseCommandLineOptions(int argc,
1122 const char *const *argv,
1124 raw_ostream *Errs) {
1125 assert(hasOptions() && "No options specified!");
1127 // Expand response files.
1128 SmallVector<const char *, 20> newArgv(argv, argv + argc);
1130 StringSaver Saver(A);
1131 ExpandResponseFiles(Saver,
1132 Triple(sys::getProcessTriple()).isOSWindows() ?
1133 cl::TokenizeWindowsCommandLine : cl::TokenizeGNUCommandLine,
1136 argc = static_cast<int>(newArgv.size());
1138 // Copy the program name into ProgName, making sure not to overflow it.
1139 ProgramName = sys::path::filename(StringRef(argv[0]));
1141 ProgramOverview = Overview;
1142 bool IgnoreErrors = Errs;
1145 bool ErrorParsing = false;
1147 // Check out the positional arguments to collect information about them.
1148 unsigned NumPositionalRequired = 0;
1150 // Determine whether or not there are an unlimited number of positionals
1151 bool HasUnlimitedPositionals = false;
1154 SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1155 if (argc >= 2 && argv[FirstArg][0] != '-') {
1156 // If the first argument specifies a valid subcommand, start processing
1157 // options from the second argument.
1158 ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1159 if (ChosenSubCommand != &*TopLevelSubCommand)
1162 GlobalParser->ActiveSubCommand = ChosenSubCommand;
1164 assert(ChosenSubCommand);
1165 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1166 auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1167 auto &SinkOpts = ChosenSubCommand->SinkOpts;
1168 auto &OptionsMap = ChosenSubCommand->OptionsMap;
1170 if (ConsumeAfterOpt) {
1171 assert(PositionalOpts.size() > 0 &&
1172 "Cannot specify cl::ConsumeAfter without a positional argument!");
1174 if (!PositionalOpts.empty()) {
1176 // Calculate how many positional values are _required_.
1177 bool UnboundedFound = false;
1178 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1179 Option *Opt = PositionalOpts[i];
1180 if (RequiresValue(Opt))
1181 ++NumPositionalRequired;
1182 else if (ConsumeAfterOpt) {
1183 // ConsumeAfter cannot be combined with "optional" positional options
1184 // unless there is only one positional argument...
1185 if (PositionalOpts.size() > 1) {
1187 Opt->error("error - this positional option will never be matched, "
1188 "because it does not Require a value, and a "
1189 "cl::ConsumeAfter option is active!");
1190 ErrorParsing = true;
1192 } else if (UnboundedFound && !Opt->hasArgStr()) {
1193 // This option does not "require" a value... Make sure this option is
1194 // not specified after an option that eats all extra arguments, or this
1195 // one will never get any!
1198 Opt->error("error - option can never match, because "
1199 "another positional argument will match an "
1200 "unbounded number of values, and this option"
1201 " does not require a value!");
1202 *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1203 << "' is all messed up!\n";
1204 *Errs << PositionalOpts.size();
1205 ErrorParsing = true;
1207 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1209 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1212 // PositionalVals - A vector of "positional" arguments we accumulate into
1213 // the process at the end.
1215 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1217 // If the program has named positional arguments, and the name has been run
1218 // across, keep track of which positional argument was named. Otherwise put
1219 // the positional args into the PositionalVals list...
1220 Option *ActivePositionalArg = nullptr;
1222 // Loop over all of the arguments... processing them.
1223 bool DashDashFound = false; // Have we read '--'?
1224 for (int i = FirstArg; i < argc; ++i) {
1225 Option *Handler = nullptr;
1226 Option *NearestHandler = nullptr;
1227 std::string NearestHandlerString;
1229 StringRef ArgName = "";
1231 // Check to see if this is a positional argument. This argument is
1232 // considered to be positional if it doesn't start with '-', if it is "-"
1233 // itself, or if we have seen "--" already.
1235 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1236 // Positional argument!
1237 if (ActivePositionalArg) {
1238 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1239 continue; // We are done!
1242 if (!PositionalOpts.empty()) {
1243 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1245 // All of the positional arguments have been fulfulled, give the rest to
1246 // the consume after option... if it's specified...
1248 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1249 for (++i; i < argc; ++i)
1250 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1251 break; // Handle outside of the argument processing loop...
1254 // Delay processing positional arguments until the end...
1257 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1259 DashDashFound = true; // This is the mythical "--"?
1260 continue; // Don't try to process it as an argument itself.
1261 } else if (ActivePositionalArg &&
1262 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1263 // If there is a positional argument eating options, check to see if this
1264 // option is another positional argument. If so, treat it as an argument,
1265 // otherwise feed it to the eating positional.
1266 ArgName = StringRef(argv[i] + 1);
1267 // Eat leading dashes.
1268 while (!ArgName.empty() && ArgName[0] == '-')
1269 ArgName = ArgName.substr(1);
1271 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1272 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1273 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1274 continue; // We are done!
1277 } else { // We start with a '-', must be an argument.
1278 ArgName = StringRef(argv[i] + 1);
1279 // Eat leading dashes.
1280 while (!ArgName.empty() && ArgName[0] == '-')
1281 ArgName = ArgName.substr(1);
1283 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1285 // Check to see if this "option" is really a prefixed or grouped argument.
1287 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1290 // Otherwise, look for the closest available option to report to the user
1291 // in the upcoming error.
1292 if (!Handler && SinkOpts.empty())
1294 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1298 if (SinkOpts.empty()) {
1299 *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1300 << "'. Try: '" << argv[0] << " -help'\n";
1302 if (NearestHandler) {
1303 // If we know a near match, report it as well.
1304 *Errs << ProgramName << ": Did you mean '-" << NearestHandlerString
1308 ErrorParsing = true;
1310 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1313 (*I)->addOccurrence(i, "", StringRef(argv[i]));
1318 // If this is a named positional argument, just remember that it is the
1320 if (Handler->getFormattingFlag() == cl::Positional) {
1321 if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1322 Handler->error("This argument does not take a value.\n"
1323 "\tInstead, it consumes any positional arguments until "
1324 "the next recognized option.", *Errs);
1325 ErrorParsing = true;
1327 ActivePositionalArg = Handler;
1330 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1333 // Check and handle positional arguments now...
1334 if (NumPositionalRequired > PositionalVals.size()) {
1335 *Errs << ProgramName
1336 << ": Not enough positional command line arguments specified!\n"
1337 << "Must specify at least " << NumPositionalRequired
1338 << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1339 << ": See: " << argv[0] << " -help\n";
1341 ErrorParsing = true;
1342 } else if (!HasUnlimitedPositionals &&
1343 PositionalVals.size() > PositionalOpts.size()) {
1344 *Errs << ProgramName << ": Too many positional arguments specified!\n"
1345 << "Can specify at most " << PositionalOpts.size()
1346 << " positional arguments: See: " << argv[0] << " -help\n";
1347 ErrorParsing = true;
1349 } else if (!ConsumeAfterOpt) {
1350 // Positional args have already been handled if ConsumeAfter is specified.
1351 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1352 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1353 if (RequiresValue(PositionalOpts[i])) {
1354 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1355 PositionalVals[ValNo].second);
1357 --NumPositionalRequired; // We fulfilled our duty...
1360 // If we _can_ give this option more arguments, do so now, as long as we
1361 // do not give it values that others need. 'Done' controls whether the
1362 // option even _WANTS_ any more.
1364 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1365 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1366 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1368 Done = true; // Optional arguments want _at most_ one value
1370 case cl::ZeroOrMore: // Zero or more will take all they can get...
1371 case cl::OneOrMore: // One or more will take all they can get...
1372 ProvidePositionalOption(PositionalOpts[i],
1373 PositionalVals[ValNo].first,
1374 PositionalVals[ValNo].second);
1378 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1379 "positional argument processing!");
1384 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1386 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1387 if (RequiresValue(PositionalOpts[j])) {
1388 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1389 PositionalVals[ValNo].first,
1390 PositionalVals[ValNo].second);
1394 // Handle the case where there is just one positional option, and it's
1395 // optional. In this case, we want to give JUST THE FIRST option to the
1396 // positional option and keep the rest for the consume after. The above
1397 // loop would have assigned no values to positional options in this case.
1399 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1400 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1401 PositionalVals[ValNo].first,
1402 PositionalVals[ValNo].second);
1406 // Handle over all of the rest of the arguments to the
1407 // cl::ConsumeAfter command line option...
1408 for (; ValNo != PositionalVals.size(); ++ValNo)
1410 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1411 PositionalVals[ValNo].second);
1414 // Loop over args and make sure all required args are specified!
1415 for (const auto &Opt : OptionsMap) {
1416 switch (Opt.second->getNumOccurrencesFlag()) {
1419 if (Opt.second->getNumOccurrences() == 0) {
1420 Opt.second->error("must be specified at least once!");
1421 ErrorParsing = true;
1429 // Now that we know if -debug is specified, we can use it.
1430 // Note that if ReadResponseFiles == true, this must be done before the
1431 // memory allocated for the expanded command line is free()d below.
1432 LLVM_DEBUG(dbgs() << "Args: ";
1433 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1436 // Free all of the memory allocated to the map. Command line options may only
1437 // be processed once!
1440 // If we had an error processing our arguments, don't let the program execute
1449 //===----------------------------------------------------------------------===//
1450 // Option Base class implementation
1453 bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1454 if (!ArgName.data())
1456 if (ArgName.empty())
1457 Errs << HelpStr; // Be nice for positional arguments
1459 Errs << GlobalParser->ProgramName << ": for the -" << ArgName;
1461 Errs << " option: " << Message << "\n";
1465 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1468 NumOccurrences++; // Increment the number of times we have been seen
1470 switch (getNumOccurrencesFlag()) {
1472 if (NumOccurrences > 1)
1473 return error("may only occur zero or one times!", ArgName);
1476 if (NumOccurrences > 1)
1477 return error("must occur exactly one time!", ArgName);
1485 return handleOccurrence(pos, ArgName, Value);
1488 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1489 // has been specified yet.
1491 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1492 if (O.ValueStr.empty())
1497 static StringRef ArgPrefix = " -";
1498 static StringRef ArgHelpPrefix = " - ";
1499 static size_t ArgPrefixesSize = ArgPrefix.size() + ArgHelpPrefix.size();
1501 //===----------------------------------------------------------------------===//
1502 // cl::alias class implementation
1505 // Return the width of the option tag for printing...
1506 size_t alias::getOptionWidth() const { return ArgStr.size() + ArgPrefixesSize; }
1508 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1509 size_t FirstLineIndentedBy) {
1510 assert(Indent >= FirstLineIndentedBy);
1511 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1512 outs().indent(Indent - FirstLineIndentedBy)
1513 << ArgHelpPrefix << Split.first << "\n";
1514 while (!Split.second.empty()) {
1515 Split = Split.second.split('\n');
1516 outs().indent(Indent) << Split.first << "\n";
1520 // Print out the option for the alias.
1521 void alias::printOptionInfo(size_t GlobalWidth) const {
1522 outs() << ArgPrefix << ArgStr;
1523 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + ArgPrefixesSize);
1526 //===----------------------------------------------------------------------===//
1527 // Parser Implementation code...
1530 // basic_parser implementation
1533 // Return the width of the option tag for printing...
1534 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1535 size_t Len = O.ArgStr.size();
1536 auto ValName = getValueName();
1537 if (!ValName.empty()) {
1538 size_t FormattingLen = 3;
1539 if (O.getMiscFlags() & PositionalEatsArgs)
1541 Len += getValueStr(O, ValName).size() + FormattingLen;
1544 return Len + ArgPrefixesSize;
1547 // printOptionInfo - Print out information about this option. The
1548 // to-be-maintained width is specified.
1550 void basic_parser_impl::printOptionInfo(const Option &O,
1551 size_t GlobalWidth) const {
1552 outs() << ArgPrefix << O.ArgStr;
1554 auto ValName = getValueName();
1555 if (!ValName.empty()) {
1556 if (O.getMiscFlags() & PositionalEatsArgs) {
1557 outs() << " <" << getValueStr(O, ValName) << ">...";
1559 outs() << "=<" << getValueStr(O, ValName) << '>';
1563 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1566 void basic_parser_impl::printOptionName(const Option &O,
1567 size_t GlobalWidth) const {
1568 outs() << ArgPrefix << O.ArgStr;
1569 outs().indent(GlobalWidth - O.ArgStr.size());
1572 // parser<bool> implementation
1574 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1576 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1582 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1586 return O.error("'" + Arg +
1587 "' is invalid value for boolean argument! Try 0 or 1");
1590 // parser<boolOrDefault> implementation
1592 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1593 boolOrDefault &Value) {
1594 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1599 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1604 return O.error("'" + Arg +
1605 "' is invalid value for boolean argument! Try 0 or 1");
1608 // parser<int> implementation
1610 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1612 if (Arg.getAsInteger(0, Value))
1613 return O.error("'" + Arg + "' value invalid for integer argument!");
1617 // parser<unsigned> implementation
1619 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1622 if (Arg.getAsInteger(0, Value))
1623 return O.error("'" + Arg + "' value invalid for uint argument!");
1627 // parser<unsigned long long> implementation
1629 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1631 unsigned long long &Value) {
1633 if (Arg.getAsInteger(0, Value))
1634 return O.error("'" + Arg + "' value invalid for uint argument!");
1638 // parser<double>/parser<float> implementation
1640 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1641 if (to_float(Arg, Value))
1643 return O.error("'" + Arg + "' value invalid for floating point argument!");
1646 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1648 return parseDouble(O, Arg, Val);
1651 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1654 if (parseDouble(O, Arg, dVal))
1660 // generic_parser_base implementation
1663 // findOption - Return the option number corresponding to the specified
1664 // argument string. If the option is not found, getNumOptions() is returned.
1666 unsigned generic_parser_base::findOption(StringRef Name) {
1667 unsigned e = getNumOptions();
1669 for (unsigned i = 0; i != e; ++i) {
1670 if (getOption(i) == Name)
1676 static StringRef EqValue = "=<value>";
1677 static StringRef EmptyOption = "<empty>";
1678 static StringRef OptionPrefix = " =";
1679 static size_t OptionPrefixesSize = OptionPrefix.size() + ArgHelpPrefix.size();
1681 static bool shouldPrintOption(StringRef Name, StringRef Description,
1683 return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
1684 !Description.empty();
1687 // Return the width of the option tag for printing...
1688 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1689 if (O.hasArgStr()) {
1690 size_t Size = O.ArgStr.size() + ArgPrefixesSize + EqValue.size();
1691 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1692 StringRef Name = getOption(i);
1693 if (!shouldPrintOption(Name, getDescription(i), O))
1695 size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
1696 Size = std::max(Size, NameSize + OptionPrefixesSize);
1700 size_t BaseSize = 0;
1701 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1702 BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1707 // printOptionInfo - Print out information about this option. The
1708 // to-be-maintained width is specified.
1710 void generic_parser_base::printOptionInfo(const Option &O,
1711 size_t GlobalWidth) const {
1712 if (O.hasArgStr()) {
1713 // When the value is optional, first print a line just describing the
1714 // option without values.
1715 if (O.getValueExpectedFlag() == ValueOptional) {
1716 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1717 if (getOption(i).empty()) {
1718 outs() << ArgPrefix << O.ArgStr;
1719 Option::printHelpStr(O.HelpStr, GlobalWidth,
1720 O.ArgStr.size() + ArgPrefixesSize);
1726 outs() << ArgPrefix << O.ArgStr << EqValue;
1727 Option::printHelpStr(O.HelpStr, GlobalWidth,
1728 O.ArgStr.size() + EqValue.size() + ArgPrefixesSize);
1729 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1730 StringRef OptionName = getOption(i);
1731 StringRef Description = getDescription(i);
1732 if (!shouldPrintOption(OptionName, Description, O))
1734 assert(GlobalWidth >= OptionName.size() + OptionPrefixesSize);
1735 size_t NumSpaces = GlobalWidth - OptionName.size() - OptionPrefixesSize;
1736 outs() << OptionPrefix << OptionName;
1737 if (OptionName.empty()) {
1738 outs() << EmptyOption;
1739 assert(NumSpaces >= EmptyOption.size());
1740 NumSpaces -= EmptyOption.size();
1742 if (!Description.empty())
1743 outs().indent(NumSpaces) << ArgHelpPrefix << " " << Description;
1747 if (!O.HelpStr.empty())
1748 outs() << " " << O.HelpStr << '\n';
1749 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1750 auto Option = getOption(i);
1751 outs() << " -" << Option;
1752 Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
1757 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1759 // printGenericOptionDiff - Print the value of this option and it's default.
1761 // "Generic" options have each value mapped to a name.
1762 void generic_parser_base::printGenericOptionDiff(
1763 const Option &O, const GenericOptionValue &Value,
1764 const GenericOptionValue &Default, size_t GlobalWidth) const {
1765 outs() << " -" << O.ArgStr;
1766 outs().indent(GlobalWidth - O.ArgStr.size());
1768 unsigned NumOpts = getNumOptions();
1769 for (unsigned i = 0; i != NumOpts; ++i) {
1770 if (Value.compare(getOptionValue(i)))
1773 outs() << "= " << getOption(i);
1774 size_t L = getOption(i).size();
1775 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1776 outs().indent(NumSpaces) << " (default: ";
1777 for (unsigned j = 0; j != NumOpts; ++j) {
1778 if (Default.compare(getOptionValue(j)))
1780 outs() << getOption(j);
1786 outs() << "= *unknown option value*\n";
1789 // printOptionDiff - Specializations for printing basic value types.
1791 #define PRINT_OPT_DIFF(T) \
1792 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1793 size_t GlobalWidth) const { \
1794 printOptionName(O, GlobalWidth); \
1797 raw_string_ostream SS(Str); \
1800 outs() << "= " << Str; \
1801 size_t NumSpaces = \
1802 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1803 outs().indent(NumSpaces) << " (default: "; \
1805 outs() << D.getValue(); \
1807 outs() << "*no default*"; \
1811 PRINT_OPT_DIFF(bool)
1812 PRINT_OPT_DIFF(boolOrDefault)
1814 PRINT_OPT_DIFF(unsigned)
1815 PRINT_OPT_DIFF(unsigned long long)
1816 PRINT_OPT_DIFF(double)
1817 PRINT_OPT_DIFF(float)
1818 PRINT_OPT_DIFF(char)
1820 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1821 const OptionValue<std::string> &D,
1822 size_t GlobalWidth) const {
1823 printOptionName(O, GlobalWidth);
1824 outs() << "= " << V;
1825 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1826 outs().indent(NumSpaces) << " (default: ";
1828 outs() << D.getValue();
1830 outs() << "*no default*";
1834 // Print a placeholder for options that don't yet support printOptionDiff().
1835 void basic_parser_impl::printOptionNoValue(const Option &O,
1836 size_t GlobalWidth) const {
1837 printOptionName(O, GlobalWidth);
1838 outs() << "= *cannot print option value*\n";
1841 //===----------------------------------------------------------------------===//
1842 // -help and -help-hidden option implementation
1845 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1846 const std::pair<const char *, Option *> *RHS) {
1847 return strcmp(LHS->first, RHS->first);
1850 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
1851 const std::pair<const char *, SubCommand *> *RHS) {
1852 return strcmp(LHS->first, RHS->first);
1855 // Copy Options into a vector so we can sort them as we like.
1856 static void sortOpts(StringMap<Option *> &OptMap,
1857 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1859 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
1861 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1863 // Ignore really-hidden options.
1864 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1867 // Unless showhidden is set, ignore hidden flags.
1868 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1871 // If we've already seen this option, don't add it to the list again.
1872 if (!OptionSet.insert(I->second).second)
1876 std::pair<const char *, Option *>(I->getKey().data(), I->second));
1879 // Sort the options list alphabetically.
1880 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1884 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
1885 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
1886 for (const auto &S : SubMap) {
1887 if (S->getName().empty())
1889 Subs.push_back(std::make_pair(S->getName().data(), S));
1891 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
1898 const bool ShowHidden;
1899 typedef SmallVector<std::pair<const char *, Option *>, 128>
1900 StrOptionPairVector;
1901 typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
1902 StrSubCommandPairVector;
1903 // Print the options. Opts is assumed to be alphabetically sorted.
1904 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1905 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1906 Opts[i].second->printOptionInfo(MaxArgLen);
1909 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
1910 for (const auto &S : Subs) {
1911 outs() << " " << S.first;
1912 if (!S.second->getDescription().empty()) {
1913 outs().indent(MaxSubLen - strlen(S.first));
1914 outs() << " - " << S.second->getDescription();
1921 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1922 virtual ~HelpPrinter() {}
1924 // Invoke the printer.
1925 void operator=(bool Value) {
1930 // Halt the program since help information was printed
1935 SubCommand *Sub = GlobalParser->getActiveSubCommand();
1936 auto &OptionsMap = Sub->OptionsMap;
1937 auto &PositionalOpts = Sub->PositionalOpts;
1938 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
1940 StrOptionPairVector Opts;
1941 sortOpts(OptionsMap, Opts, ShowHidden);
1943 StrSubCommandPairVector Subs;
1944 sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
1946 if (!GlobalParser->ProgramOverview.empty())
1947 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1949 if (Sub == &*TopLevelSubCommand) {
1950 outs() << "USAGE: " << GlobalParser->ProgramName;
1951 if (Subs.size() > 2)
1952 outs() << " [subcommand]";
1953 outs() << " [options]";
1955 if (!Sub->getDescription().empty()) {
1956 outs() << "SUBCOMMAND '" << Sub->getName()
1957 << "': " << Sub->getDescription() << "\n\n";
1959 outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
1963 for (auto Opt : PositionalOpts) {
1964 if (Opt->hasArgStr())
1965 outs() << " --" << Opt->ArgStr;
1966 outs() << " " << Opt->HelpStr;
1969 // Print the consume after option info if it exists...
1970 if (ConsumeAfterOpt)
1971 outs() << " " << ConsumeAfterOpt->HelpStr;
1973 if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
1974 // Compute the maximum subcommand length...
1975 size_t MaxSubLen = 0;
1976 for (size_t i = 0, e = Subs.size(); i != e; ++i)
1977 MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
1980 outs() << "SUBCOMMANDS:\n\n";
1981 printSubCommands(Subs, MaxSubLen);
1983 outs() << " Type \"" << GlobalParser->ProgramName
1984 << " <subcommand> -help\" to get more help on a specific "
1990 // Compute the maximum argument length...
1991 size_t MaxArgLen = 0;
1992 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1993 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1995 outs() << "OPTIONS:\n";
1996 printOptions(Opts, MaxArgLen);
1998 // Print any extra help the user has declared.
1999 for (auto I : GlobalParser->MoreHelp)
2001 GlobalParser->MoreHelp.clear();
2005 class CategorizedHelpPrinter : public HelpPrinter {
2007 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2009 // Helper function for printOptions().
2010 // It shall return a negative value if A's name should be lexicographically
2011 // ordered before B's name. It returns a value greater than zero if B's name
2012 // should be ordered before A's name, and it returns 0 otherwise.
2013 static int OptionCategoryCompare(OptionCategory *const *A,
2014 OptionCategory *const *B) {
2015 return (*A)->getName().compare((*B)->getName());
2018 // Make sure we inherit our base class's operator=()
2019 using HelpPrinter::operator=;
2022 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2023 std::vector<OptionCategory *> SortedCategories;
2024 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2026 // Collect registered option categories into vector in preparation for
2028 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
2029 E = GlobalParser->RegisteredOptionCategories.end();
2031 SortedCategories.push_back(*I);
2034 // Sort the different option categories alphabetically.
2035 assert(SortedCategories.size() > 0 && "No option categories registered!");
2036 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2037 OptionCategoryCompare);
2039 // Create map to empty vectors.
2040 for (std::vector<OptionCategory *>::const_iterator
2041 I = SortedCategories.begin(),
2042 E = SortedCategories.end();
2044 CategorizedOptions[*I] = std::vector<Option *>();
2046 // Walk through pre-sorted options and assign into categories.
2047 // Because the options are already alphabetically sorted the
2048 // options within categories will also be alphabetically sorted.
2049 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
2050 Option *Opt = Opts[I].second;
2051 assert(CategorizedOptions.count(Opt->Category) > 0 &&
2052 "Option has an unregistered category");
2053 CategorizedOptions[Opt->Category].push_back(Opt);
2057 for (std::vector<OptionCategory *>::const_iterator
2058 Category = SortedCategories.begin(),
2059 E = SortedCategories.end();
2060 Category != E; ++Category) {
2061 // Hide empty categories for -help, but show for -help-hidden.
2062 const auto &CategoryOptions = CategorizedOptions[*Category];
2063 bool IsEmptyCategory = CategoryOptions.empty();
2064 if (!ShowHidden && IsEmptyCategory)
2067 // Print category information.
2069 outs() << (*Category)->getName() << ":\n";
2071 // Check if description is set.
2072 if (!(*Category)->getDescription().empty())
2073 outs() << (*Category)->getDescription() << "\n\n";
2077 // When using -help-hidden explicitly state if the category has no
2078 // options associated with it.
2079 if (IsEmptyCategory) {
2080 outs() << " This option category has no options.\n";
2083 // Loop over the options in the category and print.
2084 for (const Option *Opt : CategoryOptions)
2085 Opt->printOptionInfo(MaxArgLen);
2090 // This wraps the Uncategorizing and Categorizing printers and decides
2091 // at run time which should be invoked.
2092 class HelpPrinterWrapper {
2094 HelpPrinter &UncategorizedPrinter;
2095 CategorizedHelpPrinter &CategorizedPrinter;
2098 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2099 CategorizedHelpPrinter &CategorizedPrinter)
2100 : UncategorizedPrinter(UncategorizedPrinter),
2101 CategorizedPrinter(CategorizedPrinter) {}
2103 // Invoke the printer.
2104 void operator=(bool Value);
2107 } // End anonymous namespace
2109 // Declare the four HelpPrinter instances that are used to print out help, or
2110 // help-hidden as an uncategorized list or in categories.
2111 static HelpPrinter UncategorizedNormalPrinter(false);
2112 static HelpPrinter UncategorizedHiddenPrinter(true);
2113 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
2114 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
2116 // Declare HelpPrinter wrappers that will decide whether or not to invoke
2117 // a categorizing help printer
2118 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
2119 CategorizedNormalPrinter);
2120 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
2121 CategorizedHiddenPrinter);
2123 // Define a category for generic options that all tools should have.
2124 static cl::OptionCategory GenericCategory("Generic Options");
2126 // Define uncategorized help printers.
2127 // -help-list is hidden by default because if Option categories are being used
2128 // then -help behaves the same as -help-list.
2129 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
2131 cl::desc("Display list of available options (-help-list-hidden for more)"),
2132 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
2133 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2135 static cl::opt<HelpPrinter, true, parser<bool>>
2136 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
2137 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
2138 cl::ValueDisallowed, cl::cat(GenericCategory),
2139 cl::sub(*AllSubCommands));
2141 // Define uncategorized/categorized help printers. These printers change their
2142 // behaviour at runtime depending on whether one or more Option categories have
2144 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2145 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
2146 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
2147 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2149 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2150 HHOp("help-hidden", cl::desc("Display all available options"),
2151 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
2152 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2154 static cl::opt<bool> PrintOptions(
2156 cl::desc("Print non-default options after command line parsing"),
2157 cl::Hidden, cl::init(false), cl::cat(GenericCategory),
2158 cl::sub(*AllSubCommands));
2160 static cl::opt<bool> PrintAllOptions(
2161 "print-all-options",
2162 cl::desc("Print all option values after command line parsing"), cl::Hidden,
2163 cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2165 void HelpPrinterWrapper::operator=(bool Value) {
2169 // Decide which printer to invoke. If more than one option category is
2170 // registered then it is useful to show the categorized help instead of
2171 // uncategorized help.
2172 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2173 // unhide -help-list option so user can have uncategorized output if they
2175 HLOp.setHiddenFlag(NotHidden);
2177 CategorizedPrinter = true; // Invoke categorized printer
2179 UncategorizedPrinter = true; // Invoke uncategorized printer
2182 // Print the value of each option.
2183 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2185 void CommandLineParser::printOptionValues() {
2186 if (!PrintOptions && !PrintAllOptions)
2189 SmallVector<std::pair<const char *, Option *>, 128> Opts;
2190 sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2192 // Compute the maximum argument length...
2193 size_t MaxArgLen = 0;
2194 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2195 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2197 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2198 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2201 static VersionPrinterTy OverrideVersionPrinter = nullptr;
2203 static std::vector<VersionPrinterTy> *ExtraVersionPrinters = nullptr;
2206 class VersionPrinter {
2209 raw_ostream &OS = outs();
2210 #ifdef PACKAGE_VENDOR
2211 OS << PACKAGE_VENDOR << " ";
2213 OS << "LLVM (http://llvm.org/):\n ";
2215 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2216 #ifdef LLVM_VERSION_INFO
2217 OS << " " << LLVM_VERSION_INFO;
2220 #ifndef __OPTIMIZE__
2221 OS << "DEBUG build";
2223 OS << "Optimized build";
2226 OS << " with assertions";
2228 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2229 std::string CPU = sys::getHostCPUName();
2230 if (CPU == "generic")
2233 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
2234 << " Host CPU: " << CPU;
2238 void operator=(bool OptionWasSpecified) {
2239 if (!OptionWasSpecified)
2242 if (OverrideVersionPrinter != nullptr) {
2243 OverrideVersionPrinter(outs());
2248 // Iterate over any registered extra printers and call them to add further
2250 if (ExtraVersionPrinters != nullptr) {
2252 for (auto I : *ExtraVersionPrinters)
2259 } // End anonymous namespace
2261 // Define the --version option that prints out the LLVM version for the tool
2262 static VersionPrinter VersionPrinterInstance;
2264 static cl::opt<VersionPrinter, true, parser<bool>>
2265 VersOp("version", cl::desc("Display the version of this program"),
2266 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2267 cl::cat(GenericCategory));
2269 // Utility function for printing the help message.
2270 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2271 if (!Hidden && !Categorized)
2272 UncategorizedNormalPrinter.printHelp();
2273 else if (!Hidden && Categorized)
2274 CategorizedNormalPrinter.printHelp();
2275 else if (Hidden && !Categorized)
2276 UncategorizedHiddenPrinter.printHelp();
2278 CategorizedHiddenPrinter.printHelp();
2281 /// Utility function for printing version number.
2282 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
2284 void cl::SetVersionPrinter(VersionPrinterTy func) { OverrideVersionPrinter = func; }
2286 void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2287 if (!ExtraVersionPrinters)
2288 ExtraVersionPrinters = new std::vector<VersionPrinterTy>;
2290 ExtraVersionPrinters->push_back(func);
2293 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2294 auto &Subs = GlobalParser->RegisteredSubCommands;
2296 assert(is_contained(Subs, &Sub));
2297 return Sub.OptionsMap;
2300 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2301 cl::getRegisteredSubcommands() {
2302 return GlobalParser->getRegisteredSubcommands();
2305 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2306 for (auto &I : Sub.OptionsMap) {
2307 if (I.second->Category != &Category &&
2308 I.second->Category != &GenericCategory)
2309 I.second->setHiddenFlag(cl::ReallyHidden);
2313 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2315 auto CategoriesBegin = Categories.begin();
2316 auto CategoriesEnd = Categories.end();
2317 for (auto &I : Sub.OptionsMap) {
2318 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
2320 I.second->Category != &GenericCategory)
2321 I.second->setHiddenFlag(cl::ReallyHidden);
2325 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2326 void cl::ResetAllOptionOccurrences() {
2327 GlobalParser->ResetAllOptionOccurrences();
2330 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2331 const char *Overview) {
2332 llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),