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/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Config/config.h"
30 #include "llvm/Support/ConvertUTF.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Process.h"
39 #include "llvm/Support/StringSaver.h"
40 #include "llvm/Support/raw_ostream.h"
46 #define DEBUG_TYPE "commandline"
48 //===----------------------------------------------------------------------===//
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
377 ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
379 // A special subcommand that can be used to put an option into all subcommands.
380 ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
382 void SubCommand::registerSubCommand() {
383 GlobalParser->registerSubCommand(this);
386 void SubCommand::unregisterSubCommand() {
387 GlobalParser->unregisterSubCommand(this);
390 void SubCommand::reset() {
391 PositionalOpts.clear();
395 ConsumeAfterOpt = nullptr;
398 SubCommand::operator bool() const {
399 return (GlobalParser->getActiveSubCommand() == this);
402 //===----------------------------------------------------------------------===//
403 // Basic, shared command line option processing machinery.
406 /// LookupOption - Lookup the option specified by the specified option on the
407 /// command line. If there is a value specified (after an equal sign) return
408 /// that as well. This assumes that leading dashes have already been stripped.
409 Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
411 // Reject all dashes.
414 assert(&Sub != &*AllSubCommands);
416 size_t EqualPos = Arg.find('=');
418 // If we have an equals sign, remember the value.
419 if (EqualPos == StringRef::npos) {
420 // Look up the option.
421 auto I = Sub.OptionsMap.find(Arg);
422 if (I == Sub.OptionsMap.end())
425 return I != Sub.OptionsMap.end() ? I->second : nullptr;
428 // If the argument before the = is a valid option name, we match. If not,
429 // return Arg unmolested.
430 auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
431 if (I == Sub.OptionsMap.end())
434 Value = Arg.substr(EqualPos + 1);
435 Arg = Arg.substr(0, EqualPos);
439 SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
441 return &*TopLevelSubCommand;
442 for (auto S : RegisteredSubCommands) {
443 if (S == &*AllSubCommands)
445 if (S->getName().empty())
448 if (StringRef(S->getName()) == StringRef(Name))
451 return &*TopLevelSubCommand;
454 /// LookupNearestOption - Lookup the closest match to the option specified by
455 /// the specified option on the command line. If there is a value specified
456 /// (after an equal sign) return that as well. This assumes that leading dashes
457 /// have already been stripped.
458 static Option *LookupNearestOption(StringRef Arg,
459 const StringMap<Option *> &OptionsMap,
460 std::string &NearestString) {
461 // Reject all dashes.
465 // Split on any equal sign.
466 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
467 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
468 StringRef &RHS = SplitArg.second;
470 // Find the closest match.
471 Option *Best = nullptr;
472 unsigned BestDistance = 0;
473 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
474 ie = OptionsMap.end();
476 Option *O = it->second;
477 SmallVector<StringRef, 16> OptionNames;
478 O->getExtraOptionNames(OptionNames);
480 OptionNames.push_back(O->ArgStr);
482 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
483 StringRef Flag = PermitValue ? LHS : Arg;
484 for (auto Name : OptionNames) {
485 unsigned Distance = StringRef(Name).edit_distance(
486 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
487 if (!Best || Distance < BestDistance) {
489 BestDistance = Distance;
490 if (RHS.empty() || !PermitValue)
491 NearestString = Name;
493 NearestString = (Twine(Name) + "=" + RHS).str();
501 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
502 /// that does special handling of cl::CommaSeparated options.
503 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
504 StringRef ArgName, StringRef Value,
505 bool MultiArg = false) {
506 // Check to see if this option accepts a comma separated list of values. If
507 // it does, we have to split up the value into multiple values.
508 if (Handler->getMiscFlags() & CommaSeparated) {
509 StringRef Val(Value);
510 StringRef::size_type Pos = Val.find(',');
512 while (Pos != StringRef::npos) {
513 // Process the portion before the comma.
514 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
516 // Erase the portion before the comma, AND the comma.
517 Val = Val.substr(Pos + 1);
518 // Check for another comma.
525 return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
528 /// ProvideOption - For Value, this differentiates between an empty value ("")
529 /// and a null value (StringRef()). The later is accepted for arguments that
530 /// don't allow a value (-foo) the former is rejected (-foo=).
531 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
532 StringRef Value, int argc,
533 const char *const *argv, int &i) {
534 // Is this a multi-argument option?
535 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
537 // Enforce value requirements
538 switch (Handler->getValueExpectedFlag()) {
540 if (!Value.data()) { // No value specified?
542 return Handler->error("requires a value!");
543 // Steal the next argument, like for '-o filename'
544 assert(argv && "null check");
545 Value = StringRef(argv[++i]);
548 case ValueDisallowed:
549 if (NumAdditionalVals > 0)
550 return Handler->error("multi-valued option specified"
551 " with ValueDisallowed modifier!");
554 return Handler->error("does not allow a value! '" + Twine(Value) +
561 // If this isn't a multi-arg option, just run the handler.
562 if (NumAdditionalVals == 0)
563 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
565 // If it is, run the handle several times.
566 bool MultiArg = false;
569 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
575 while (NumAdditionalVals > 0) {
577 return Handler->error("not enough values!");
578 assert(argv && "null check");
579 Value = StringRef(argv[++i]);
581 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
589 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
591 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
594 // Option predicates...
595 static inline bool isGrouping(const Option *O) {
596 return O->getFormattingFlag() == cl::Grouping;
598 static inline bool isPrefixedOrGrouping(const Option *O) {
599 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
602 // getOptionPred - Check to see if there are any options that satisfy the
603 // specified predicate with names that are the prefixes in Name. This is
604 // checked by progressively stripping characters off of the name, checking to
605 // see if there options that satisfy the predicate. If we find one, return it,
606 // otherwise return null.
608 static Option *getOptionPred(StringRef Name, size_t &Length,
609 bool (*Pred)(const Option *),
610 const StringMap<Option *> &OptionsMap) {
612 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
614 // Loop while we haven't found an option and Name still has at least two
615 // characters in it (so that the next iteration will not be the empty
617 while (OMI == OptionsMap.end() && Name.size() > 1) {
618 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
619 OMI = OptionsMap.find(Name);
622 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
623 Length = Name.size();
624 return OMI->second; // Found one!
626 return nullptr; // No option found!
629 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
630 /// with at least one '-') does not fully match an available option. Check to
631 /// see if this is a prefix or grouped option. If so, split arg into output an
632 /// Arg/Value pair and return the Option to parse it with.
634 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
636 const StringMap<Option *> &OptionsMap) {
642 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
646 // If the option is a prefixed option, then the value is simply the
647 // rest of the name... so fall through to later processing, by
648 // setting up the argument name flags and value fields.
649 if (PGOpt->getFormattingFlag() == cl::Prefix) {
650 Value = Arg.substr(Length);
651 Arg = Arg.substr(0, Length);
652 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
656 // This must be a grouped option... handle them now. Grouping options can't
658 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
661 // Move current arg name out of Arg into OneArgName.
662 StringRef OneArgName = Arg.substr(0, Length);
663 Arg = Arg.substr(Length);
665 // Because ValueRequired is an invalid flag for grouped arguments,
666 // we don't need to pass argc/argv in.
667 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
668 "Option can not be cl::Grouping AND cl::ValueRequired!");
671 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
673 // Get the next grouping option.
674 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
675 } while (PGOpt && Length != Arg.size());
677 // Return the last option with Arg cut down to just the last one.
681 static bool RequiresValue(const Option *O) {
682 return O->getNumOccurrencesFlag() == cl::Required ||
683 O->getNumOccurrencesFlag() == cl::OneOrMore;
686 static bool EatsUnboundedNumberOfValues(const Option *O) {
687 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
688 O->getNumOccurrencesFlag() == cl::OneOrMore;
691 static bool isWhitespace(char C) {
692 return C == ' ' || C == '\t' || C == '\r' || C == '\n';
695 static bool isQuote(char C) { return C == '\"' || C == '\''; }
697 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
698 SmallVectorImpl<const char *> &NewArgv,
700 SmallString<128> Token;
701 for (size_t I = 0, E = Src.size(); I != E; ++I) {
702 // Consume runs of whitespace.
704 while (I != E && isWhitespace(Src[I])) {
705 // Mark the end of lines in response files
706 if (MarkEOLs && Src[I] == '\n')
707 NewArgv.push_back(nullptr);
716 // Backslash escapes the next character.
717 if (I + 1 < E && C == '\\') {
718 ++I; // Skip the escape.
719 Token.push_back(Src[I]);
723 // Consume a quoted string.
726 while (I != E && Src[I] != C) {
727 // Backslash escapes the next character.
728 if (Src[I] == '\\' && I + 1 != E)
730 Token.push_back(Src[I]);
738 // End the token if this is whitespace.
739 if (isWhitespace(C)) {
741 NewArgv.push_back(Saver.save(StringRef(Token)).data());
746 // This is a normal character. Append it.
750 // Append the last token after hitting EOF with no whitespace.
752 NewArgv.push_back(Saver.save(StringRef(Token)).data());
753 // Mark the end of response files
755 NewArgv.push_back(nullptr);
758 /// Backslashes are interpreted in a rather complicated way in the Windows-style
759 /// command line, because backslashes are used both to separate path and to
760 /// escape double quote. This method consumes runs of backslashes as well as the
761 /// following double quote if it's escaped.
763 /// * If an even number of backslashes is followed by a double quote, one
764 /// backslash is output for every pair of backslashes, and the last double
765 /// quote remains unconsumed. The double quote will later be interpreted as
766 /// the start or end of a quoted string in the main loop outside of this
769 /// * If an odd number of backslashes is followed by a double quote, one
770 /// backslash is output for every pair of backslashes, and a double quote is
771 /// output for the last pair of backslash-double quote. The double quote is
772 /// consumed in this case.
774 /// * Otherwise, backslashes are interpreted literally.
775 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
776 size_t E = Src.size();
777 int BackslashCount = 0;
778 // Skip the backslashes.
782 } while (I != E && Src[I] == '\\');
784 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
785 if (FollowedByDoubleQuote) {
786 Token.append(BackslashCount / 2, '\\');
787 if (BackslashCount % 2 == 0)
789 Token.push_back('"');
792 Token.append(BackslashCount, '\\');
796 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
797 SmallVectorImpl<const char *> &NewArgv,
799 SmallString<128> Token;
801 // This is a small state machine to consume characters until it reaches the
802 // end of the source string.
803 enum { INIT, UNQUOTED, QUOTED } State = INIT;
804 for (size_t I = 0, E = Src.size(); I != E; ++I) {
807 // INIT state indicates that the current input index is at the start of
808 // the string or between tokens.
810 if (isWhitespace(C)) {
811 // Mark the end of lines in response files
812 if (MarkEOLs && C == '\n')
813 NewArgv.push_back(nullptr);
821 I = parseBackslash(Src, I, Token);
830 // UNQUOTED state means that it's reading a token not quoted by double
832 if (State == UNQUOTED) {
833 // Whitespace means the end of the token.
834 if (isWhitespace(C)) {
835 NewArgv.push_back(Saver.save(StringRef(Token)).data());
838 // Mark the end of lines in response files
839 if (MarkEOLs && C == '\n')
840 NewArgv.push_back(nullptr);
848 I = parseBackslash(Src, I, Token);
855 // QUOTED state means that it's reading a token quoted by double quotes.
856 if (State == QUOTED) {
862 I = parseBackslash(Src, I, Token);
868 // Append the last token after hitting EOF with no whitespace.
870 NewArgv.push_back(Saver.save(StringRef(Token)).data());
871 // Mark the end of response files
873 NewArgv.push_back(nullptr);
876 void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
877 SmallVectorImpl<const char *> &NewArgv,
879 for (const char *Cur = Source.begin(); Cur != Source.end();) {
880 SmallString<128> Line;
881 // Check for comment line.
882 if (isWhitespace(*Cur)) {
883 while (Cur != Source.end() && isWhitespace(*Cur))
888 while (Cur != Source.end() && *Cur != '\n')
892 // Find end of the current line.
893 const char *Start = Cur;
894 for (const char *End = Source.end(); Cur != End; ++Cur) {
896 if (Cur + 1 != End) {
899 (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
900 Line.append(Start, Cur - 1);
906 } else if (*Cur == '\n')
910 Line.append(Start, Cur);
911 cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
915 // It is called byte order marker but the UTF-8 BOM is actually not affected
916 // by the host system's endianness.
917 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
918 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
921 static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
922 TokenizerCallback Tokenizer,
923 SmallVectorImpl<const char *> &NewArgv,
924 bool MarkEOLs, bool RelativeNames) {
925 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
926 MemoryBuffer::getFile(FName);
929 MemoryBuffer &MemBuf = *MemBufOrErr.get();
930 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
932 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
933 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
935 if (hasUTF16ByteOrderMark(BufRef)) {
936 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
938 Str = StringRef(UTF8Buf);
940 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
941 // these bytes before parsing.
942 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
943 else if (hasUTF8ByteOrderMark(BufRef))
944 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
946 // Tokenize the contents into NewArgv.
947 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
949 // If names of nested response files should be resolved relative to including
950 // file, replace the included response file names with their full paths
951 // obtained by required resolution.
953 for (unsigned I = 0; I < NewArgv.size(); ++I)
955 StringRef Arg = NewArgv[I];
956 if (Arg.front() == '@') {
957 StringRef FileName = Arg.drop_front();
958 if (llvm::sys::path::is_relative(FileName)) {
959 SmallString<128> ResponseFile;
960 ResponseFile.append(1, '@');
961 if (llvm::sys::path::is_relative(FName)) {
962 SmallString<128> curr_dir;
963 llvm::sys::fs::current_path(curr_dir);
964 ResponseFile.append(curr_dir.str());
966 llvm::sys::path::append(
967 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
968 NewArgv[I] = Saver.save(ResponseFile.c_str()).data();
976 /// \brief Expand response files on a command line recursively using the given
977 /// StringSaver and tokenization strategy.
978 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
979 SmallVectorImpl<const char *> &Argv,
980 bool MarkEOLs, bool RelativeNames) {
981 unsigned RspFiles = 0;
982 bool AllExpanded = true;
984 // Don't cache Argv.size() because it can change.
985 for (unsigned I = 0; I != Argv.size();) {
986 const char *Arg = Argv[I];
987 // Check if it is an EOL marker
988 if (Arg == nullptr) {
997 // If we have too many response files, leave some unexpanded. This avoids
998 // crashing on self-referential response files.
1002 // Replace this response file argument with the tokenization of its
1003 // contents. Nested response files are expanded in subsequent iterations.
1004 SmallVector<const char *, 0> ExpandedArgv;
1005 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
1006 MarkEOLs, RelativeNames)) {
1007 // We couldn't read this file, so we leave it in the argument stream and
1009 AllExpanded = false;
1013 Argv.erase(Argv.begin() + I);
1014 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1019 bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver,
1020 SmallVectorImpl<const char *> &Argv) {
1021 if (!ExpandResponseFile(CfgFile, Saver, cl::tokenizeConfigFile, Argv,
1022 /*MarkEOLs*/ false, /*RelativeNames*/ true))
1024 return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
1025 /*MarkEOLs*/ false, /*RelativeNames*/ true);
1028 /// ParseEnvironmentOptions - An alternative entry point to the
1029 /// CommandLine library, which allows you to read the program's name
1030 /// from the caller (as PROGNAME) and its command-line arguments from
1031 /// an environment variable (whose name is given in ENVVAR).
1033 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
1034 const char *Overview) {
1036 assert(progName && "Program name not specified");
1037 assert(envVar && "Environment variable name missing");
1039 // Get the environment variable they want us to parse options out of.
1040 llvm::Optional<std::string> envValue = sys::Process::GetEnv(StringRef(envVar));
1044 // Get program's "name", which we wouldn't know without the caller
1046 SmallVector<const char *, 20> newArgv;
1048 StringSaver Saver(A);
1049 newArgv.push_back(Saver.save(progName).data());
1051 // Parse the value of the environment variable into a "command line"
1052 // and hand it off to ParseCommandLineOptions().
1053 TokenizeGNUCommandLine(*envValue, Saver, newArgv);
1054 int newArgc = static_cast<int>(newArgv.size());
1055 ParseCommandLineOptions(newArgc, &newArgv[0], StringRef(Overview));
1058 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1059 StringRef Overview, raw_ostream *Errs) {
1060 return GlobalParser->ParseCommandLineOptions(argc, argv, Overview,
1064 void CommandLineParser::ResetAllOptionOccurrences() {
1065 // So that we can parse different command lines multiple times in succession
1066 // we reset all option values to look like they have never been seen before.
1067 for (auto SC : RegisteredSubCommands) {
1068 for (auto &O : SC->OptionsMap)
1073 bool CommandLineParser::ParseCommandLineOptions(int argc,
1074 const char *const *argv,
1076 raw_ostream *Errs) {
1077 assert(hasOptions() && "No options specified!");
1079 // Expand response files.
1080 SmallVector<const char *, 20> newArgv(argv, argv + argc);
1082 StringSaver Saver(A);
1083 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
1085 argc = static_cast<int>(newArgv.size());
1087 // Copy the program name into ProgName, making sure not to overflow it.
1088 ProgramName = sys::path::filename(StringRef(argv[0]));
1090 ProgramOverview = Overview;
1091 bool IgnoreErrors = Errs;
1094 bool ErrorParsing = false;
1096 // Check out the positional arguments to collect information about them.
1097 unsigned NumPositionalRequired = 0;
1099 // Determine whether or not there are an unlimited number of positionals
1100 bool HasUnlimitedPositionals = false;
1103 SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1104 if (argc >= 2 && argv[FirstArg][0] != '-') {
1105 // If the first argument specifies a valid subcommand, start processing
1106 // options from the second argument.
1107 ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1108 if (ChosenSubCommand != &*TopLevelSubCommand)
1111 GlobalParser->ActiveSubCommand = ChosenSubCommand;
1113 assert(ChosenSubCommand);
1114 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1115 auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1116 auto &SinkOpts = ChosenSubCommand->SinkOpts;
1117 auto &OptionsMap = ChosenSubCommand->OptionsMap;
1119 if (ConsumeAfterOpt) {
1120 assert(PositionalOpts.size() > 0 &&
1121 "Cannot specify cl::ConsumeAfter without a positional argument!");
1123 if (!PositionalOpts.empty()) {
1125 // Calculate how many positional values are _required_.
1126 bool UnboundedFound = false;
1127 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1128 Option *Opt = PositionalOpts[i];
1129 if (RequiresValue(Opt))
1130 ++NumPositionalRequired;
1131 else if (ConsumeAfterOpt) {
1132 // ConsumeAfter cannot be combined with "optional" positional options
1133 // unless there is only one positional argument...
1134 if (PositionalOpts.size() > 1) {
1136 Opt->error("error - this positional option will never be matched, "
1137 "because it does not Require a value, and a "
1138 "cl::ConsumeAfter option is active!");
1139 ErrorParsing = true;
1141 } else if (UnboundedFound && !Opt->hasArgStr()) {
1142 // This option does not "require" a value... Make sure this option is
1143 // not specified after an option that eats all extra arguments, or this
1144 // one will never get any!
1147 Opt->error("error - option can never match, because "
1148 "another positional argument will match an "
1149 "unbounded number of values, and this option"
1150 " does not require a value!");
1151 *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1152 << "' is all messed up!\n";
1153 *Errs << PositionalOpts.size();
1154 ErrorParsing = true;
1156 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1158 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1161 // PositionalVals - A vector of "positional" arguments we accumulate into
1162 // the process at the end.
1164 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1166 // If the program has named positional arguments, and the name has been run
1167 // across, keep track of which positional argument was named. Otherwise put
1168 // the positional args into the PositionalVals list...
1169 Option *ActivePositionalArg = nullptr;
1171 // Loop over all of the arguments... processing them.
1172 bool DashDashFound = false; // Have we read '--'?
1173 for (int i = FirstArg; i < argc; ++i) {
1174 Option *Handler = nullptr;
1175 Option *NearestHandler = nullptr;
1176 std::string NearestHandlerString;
1178 StringRef ArgName = "";
1180 // Check to see if this is a positional argument. This argument is
1181 // considered to be positional if it doesn't start with '-', if it is "-"
1182 // itself, or if we have seen "--" already.
1184 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1185 // Positional argument!
1186 if (ActivePositionalArg) {
1187 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1188 continue; // We are done!
1191 if (!PositionalOpts.empty()) {
1192 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1194 // All of the positional arguments have been fulfulled, give the rest to
1195 // the consume after option... if it's specified...
1197 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1198 for (++i; i < argc; ++i)
1199 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1200 break; // Handle outside of the argument processing loop...
1203 // Delay processing positional arguments until the end...
1206 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1208 DashDashFound = true; // This is the mythical "--"?
1209 continue; // Don't try to process it as an argument itself.
1210 } else if (ActivePositionalArg &&
1211 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1212 // If there is a positional argument eating options, check to see if this
1213 // option is another positional argument. If so, treat it as an argument,
1214 // otherwise feed it to the eating positional.
1215 ArgName = StringRef(argv[i] + 1);
1216 // Eat leading dashes.
1217 while (!ArgName.empty() && ArgName[0] == '-')
1218 ArgName = ArgName.substr(1);
1220 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1221 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1222 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1223 continue; // We are done!
1226 } else { // We start with a '-', must be an argument.
1227 ArgName = StringRef(argv[i] + 1);
1228 // Eat leading dashes.
1229 while (!ArgName.empty() && ArgName[0] == '-')
1230 ArgName = ArgName.substr(1);
1232 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1234 // Check to see if this "option" is really a prefixed or grouped argument.
1236 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1239 // Otherwise, look for the closest available option to report to the user
1240 // in the upcoming error.
1241 if (!Handler && SinkOpts.empty())
1243 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1247 if (SinkOpts.empty()) {
1248 *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1249 << "'. Try: '" << argv[0] << " -help'\n";
1251 if (NearestHandler) {
1252 // If we know a near match, report it as well.
1253 *Errs << ProgramName << ": Did you mean '-" << NearestHandlerString
1257 ErrorParsing = true;
1259 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1262 (*I)->addOccurrence(i, "", StringRef(argv[i]));
1267 // If this is a named positional argument, just remember that it is the
1269 if (Handler->getFormattingFlag() == cl::Positional)
1270 ActivePositionalArg = Handler;
1272 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1275 // Check and handle positional arguments now...
1276 if (NumPositionalRequired > PositionalVals.size()) {
1277 *Errs << ProgramName
1278 << ": Not enough positional command line arguments specified!\n"
1279 << "Must specify at least " << NumPositionalRequired
1280 << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1281 << ": See: " << argv[0] << " -help\n";
1283 ErrorParsing = true;
1284 } else if (!HasUnlimitedPositionals &&
1285 PositionalVals.size() > PositionalOpts.size()) {
1286 *Errs << ProgramName << ": Too many positional arguments specified!\n"
1287 << "Can specify at most " << PositionalOpts.size()
1288 << " positional arguments: See: " << argv[0] << " -help\n";
1289 ErrorParsing = true;
1291 } else if (!ConsumeAfterOpt) {
1292 // Positional args have already been handled if ConsumeAfter is specified.
1293 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1294 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1295 if (RequiresValue(PositionalOpts[i])) {
1296 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1297 PositionalVals[ValNo].second);
1299 --NumPositionalRequired; // We fulfilled our duty...
1302 // If we _can_ give this option more arguments, do so now, as long as we
1303 // do not give it values that others need. 'Done' controls whether the
1304 // option even _WANTS_ any more.
1306 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1307 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1308 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1310 Done = true; // Optional arguments want _at most_ one value
1312 case cl::ZeroOrMore: // Zero or more will take all they can get...
1313 case cl::OneOrMore: // One or more will take all they can get...
1314 ProvidePositionalOption(PositionalOpts[i],
1315 PositionalVals[ValNo].first,
1316 PositionalVals[ValNo].second);
1320 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1321 "positional argument processing!");
1326 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1328 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1329 if (RequiresValue(PositionalOpts[j])) {
1330 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1331 PositionalVals[ValNo].first,
1332 PositionalVals[ValNo].second);
1336 // Handle the case where there is just one positional option, and it's
1337 // optional. In this case, we want to give JUST THE FIRST option to the
1338 // positional option and keep the rest for the consume after. The above
1339 // loop would have assigned no values to positional options in this case.
1341 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1342 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1343 PositionalVals[ValNo].first,
1344 PositionalVals[ValNo].second);
1348 // Handle over all of the rest of the arguments to the
1349 // cl::ConsumeAfter command line option...
1350 for (; ValNo != PositionalVals.size(); ++ValNo)
1352 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1353 PositionalVals[ValNo].second);
1356 // Loop over args and make sure all required args are specified!
1357 for (const auto &Opt : OptionsMap) {
1358 switch (Opt.second->getNumOccurrencesFlag()) {
1361 if (Opt.second->getNumOccurrences() == 0) {
1362 Opt.second->error("must be specified at least once!");
1363 ErrorParsing = true;
1371 // Now that we know if -debug is specified, we can use it.
1372 // Note that if ReadResponseFiles == true, this must be done before the
1373 // memory allocated for the expanded command line is free()d below.
1374 DEBUG(dbgs() << "Args: ";
1375 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1378 // Free all of the memory allocated to the map. Command line options may only
1379 // be processed once!
1382 // If we had an error processing our arguments, don't let the program execute
1391 //===----------------------------------------------------------------------===//
1392 // Option Base class implementation
1395 bool Option::error(const Twine &Message, StringRef ArgName) {
1396 if (!ArgName.data())
1398 if (ArgName.empty())
1399 errs() << HelpStr; // Be nice for positional arguments
1401 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1403 errs() << " option: " << Message << "\n";
1407 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1410 NumOccurrences++; // Increment the number of times we have been seen
1412 switch (getNumOccurrencesFlag()) {
1414 if (NumOccurrences > 1)
1415 return error("may only occur zero or one times!", ArgName);
1418 if (NumOccurrences > 1)
1419 return error("must occur exactly one time!", ArgName);
1427 return handleOccurrence(pos, ArgName, Value);
1430 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1431 // has been specified yet.
1433 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1434 if (O.ValueStr.empty())
1439 //===----------------------------------------------------------------------===//
1440 // cl::alias class implementation
1443 // Return the width of the option tag for printing...
1444 size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
1446 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1447 size_t FirstLineIndentedBy) {
1448 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1449 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1450 while (!Split.second.empty()) {
1451 Split = Split.second.split('\n');
1452 outs().indent(Indent) << Split.first << "\n";
1456 // Print out the option for the alias.
1457 void alias::printOptionInfo(size_t GlobalWidth) const {
1458 outs() << " -" << ArgStr;
1459 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
1462 //===----------------------------------------------------------------------===//
1463 // Parser Implementation code...
1466 // basic_parser implementation
1469 // Return the width of the option tag for printing...
1470 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1471 size_t Len = O.ArgStr.size();
1472 auto ValName = getValueName();
1473 if (!ValName.empty())
1474 Len += getValueStr(O, ValName).size() + 3;
1479 // printOptionInfo - Print out information about this option. The
1480 // to-be-maintained width is specified.
1482 void basic_parser_impl::printOptionInfo(const Option &O,
1483 size_t GlobalWidth) const {
1484 outs() << " -" << O.ArgStr;
1486 auto ValName = getValueName();
1487 if (!ValName.empty())
1488 outs() << "=<" << getValueStr(O, ValName) << '>';
1490 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1493 void basic_parser_impl::printOptionName(const Option &O,
1494 size_t GlobalWidth) const {
1495 outs() << " -" << O.ArgStr;
1496 outs().indent(GlobalWidth - O.ArgStr.size());
1499 // parser<bool> implementation
1501 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1503 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1509 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1513 return O.error("'" + Arg +
1514 "' is invalid value for boolean argument! Try 0 or 1");
1517 // parser<boolOrDefault> implementation
1519 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1520 boolOrDefault &Value) {
1521 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1526 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1531 return O.error("'" + Arg +
1532 "' is invalid value for boolean argument! Try 0 or 1");
1535 // parser<int> implementation
1537 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1539 if (Arg.getAsInteger(0, Value))
1540 return O.error("'" + Arg + "' value invalid for integer argument!");
1544 // parser<unsigned> implementation
1546 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1549 if (Arg.getAsInteger(0, Value))
1550 return O.error("'" + Arg + "' value invalid for uint argument!");
1554 // parser<unsigned long long> implementation
1556 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1558 unsigned long long &Value) {
1560 if (Arg.getAsInteger(0, Value))
1561 return O.error("'" + Arg + "' value invalid for uint argument!");
1565 // parser<double>/parser<float> implementation
1567 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1568 if (to_float(Arg, Value))
1570 return O.error("'" + Arg + "' value invalid for floating point argument!");
1573 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1575 return parseDouble(O, Arg, Val);
1578 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1581 if (parseDouble(O, Arg, dVal))
1587 // generic_parser_base implementation
1590 // findOption - Return the option number corresponding to the specified
1591 // argument string. If the option is not found, getNumOptions() is returned.
1593 unsigned generic_parser_base::findOption(StringRef Name) {
1594 unsigned e = getNumOptions();
1596 for (unsigned i = 0; i != e; ++i) {
1597 if (getOption(i) == Name)
1603 // Return the width of the option tag for printing...
1604 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1605 if (O.hasArgStr()) {
1606 size_t Size = O.ArgStr.size() + 6;
1607 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1608 Size = std::max(Size, getOption(i).size() + 8);
1611 size_t BaseSize = 0;
1612 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1613 BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1618 // printOptionInfo - Print out information about this option. The
1619 // to-be-maintained width is specified.
1621 void generic_parser_base::printOptionInfo(const Option &O,
1622 size_t GlobalWidth) const {
1623 if (O.hasArgStr()) {
1624 outs() << " -" << O.ArgStr;
1625 Option::printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
1627 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1628 size_t NumSpaces = GlobalWidth - getOption(i).size() - 8;
1629 outs() << " =" << getOption(i);
1630 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1633 if (!O.HelpStr.empty())
1634 outs() << " " << O.HelpStr << '\n';
1635 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1636 auto Option = getOption(i);
1637 outs() << " -" << Option;
1638 Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
1643 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1645 // printGenericOptionDiff - Print the value of this option and it's default.
1647 // "Generic" options have each value mapped to a name.
1648 void generic_parser_base::printGenericOptionDiff(
1649 const Option &O, const GenericOptionValue &Value,
1650 const GenericOptionValue &Default, size_t GlobalWidth) const {
1651 outs() << " -" << O.ArgStr;
1652 outs().indent(GlobalWidth - O.ArgStr.size());
1654 unsigned NumOpts = getNumOptions();
1655 for (unsigned i = 0; i != NumOpts; ++i) {
1656 if (Value.compare(getOptionValue(i)))
1659 outs() << "= " << getOption(i);
1660 size_t L = getOption(i).size();
1661 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1662 outs().indent(NumSpaces) << " (default: ";
1663 for (unsigned j = 0; j != NumOpts; ++j) {
1664 if (Default.compare(getOptionValue(j)))
1666 outs() << getOption(j);
1672 outs() << "= *unknown option value*\n";
1675 // printOptionDiff - Specializations for printing basic value types.
1677 #define PRINT_OPT_DIFF(T) \
1678 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1679 size_t GlobalWidth) const { \
1680 printOptionName(O, GlobalWidth); \
1683 raw_string_ostream SS(Str); \
1686 outs() << "= " << Str; \
1687 size_t NumSpaces = \
1688 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1689 outs().indent(NumSpaces) << " (default: "; \
1691 outs() << D.getValue(); \
1693 outs() << "*no default*"; \
1697 PRINT_OPT_DIFF(bool)
1698 PRINT_OPT_DIFF(boolOrDefault)
1700 PRINT_OPT_DIFF(unsigned)
1701 PRINT_OPT_DIFF(unsigned long long)
1702 PRINT_OPT_DIFF(double)
1703 PRINT_OPT_DIFF(float)
1704 PRINT_OPT_DIFF(char)
1706 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1707 const OptionValue<std::string> &D,
1708 size_t GlobalWidth) const {
1709 printOptionName(O, GlobalWidth);
1710 outs() << "= " << V;
1711 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1712 outs().indent(NumSpaces) << " (default: ";
1714 outs() << D.getValue();
1716 outs() << "*no default*";
1720 // Print a placeholder for options that don't yet support printOptionDiff().
1721 void basic_parser_impl::printOptionNoValue(const Option &O,
1722 size_t GlobalWidth) const {
1723 printOptionName(O, GlobalWidth);
1724 outs() << "= *cannot print option value*\n";
1727 //===----------------------------------------------------------------------===//
1728 // -help and -help-hidden option implementation
1731 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1732 const std::pair<const char *, Option *> *RHS) {
1733 return strcmp(LHS->first, RHS->first);
1736 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
1737 const std::pair<const char *, SubCommand *> *RHS) {
1738 return strcmp(LHS->first, RHS->first);
1741 // Copy Options into a vector so we can sort them as we like.
1742 static void sortOpts(StringMap<Option *> &OptMap,
1743 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1745 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
1747 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1749 // Ignore really-hidden options.
1750 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1753 // Unless showhidden is set, ignore hidden flags.
1754 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1757 // If we've already seen this option, don't add it to the list again.
1758 if (!OptionSet.insert(I->second).second)
1762 std::pair<const char *, Option *>(I->getKey().data(), I->second));
1765 // Sort the options list alphabetically.
1766 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1770 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
1771 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
1772 for (const auto &S : SubMap) {
1773 if (S->getName().empty())
1775 Subs.push_back(std::make_pair(S->getName().data(), S));
1777 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
1784 const bool ShowHidden;
1785 typedef SmallVector<std::pair<const char *, Option *>, 128>
1786 StrOptionPairVector;
1787 typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
1788 StrSubCommandPairVector;
1789 // Print the options. Opts is assumed to be alphabetically sorted.
1790 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1791 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1792 Opts[i].second->printOptionInfo(MaxArgLen);
1795 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
1796 for (const auto &S : Subs) {
1797 outs() << " " << S.first;
1798 if (!S.second->getDescription().empty()) {
1799 outs().indent(MaxSubLen - strlen(S.first));
1800 outs() << " - " << S.second->getDescription();
1807 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1808 virtual ~HelpPrinter() {}
1810 // Invoke the printer.
1811 void operator=(bool Value) {
1816 // Halt the program since help information was printed
1821 SubCommand *Sub = GlobalParser->getActiveSubCommand();
1822 auto &OptionsMap = Sub->OptionsMap;
1823 auto &PositionalOpts = Sub->PositionalOpts;
1824 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
1826 StrOptionPairVector Opts;
1827 sortOpts(OptionsMap, Opts, ShowHidden);
1829 StrSubCommandPairVector Subs;
1830 sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
1832 if (!GlobalParser->ProgramOverview.empty())
1833 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1835 if (Sub == &*TopLevelSubCommand) {
1836 outs() << "USAGE: " << GlobalParser->ProgramName;
1837 if (Subs.size() > 2)
1838 outs() << " [subcommand]";
1839 outs() << " [options]";
1841 if (!Sub->getDescription().empty()) {
1842 outs() << "SUBCOMMAND '" << Sub->getName()
1843 << "': " << Sub->getDescription() << "\n\n";
1845 outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
1849 for (auto Opt : PositionalOpts) {
1850 if (Opt->hasArgStr())
1851 outs() << " --" << Opt->ArgStr;
1852 outs() << " " << Opt->HelpStr;
1855 // Print the consume after option info if it exists...
1856 if (ConsumeAfterOpt)
1857 outs() << " " << ConsumeAfterOpt->HelpStr;
1859 if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
1860 // Compute the maximum subcommand length...
1861 size_t MaxSubLen = 0;
1862 for (size_t i = 0, e = Subs.size(); i != e; ++i)
1863 MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
1866 outs() << "SUBCOMMANDS:\n\n";
1867 printSubCommands(Subs, MaxSubLen);
1869 outs() << " Type \"" << GlobalParser->ProgramName
1870 << " <subcommand> -help\" to get more help on a specific "
1876 // Compute the maximum argument length...
1877 size_t MaxArgLen = 0;
1878 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1879 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1881 outs() << "OPTIONS:\n";
1882 printOptions(Opts, MaxArgLen);
1884 // Print any extra help the user has declared.
1885 for (auto I : GlobalParser->MoreHelp)
1887 GlobalParser->MoreHelp.clear();
1891 class CategorizedHelpPrinter : public HelpPrinter {
1893 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1895 // Helper function for printOptions().
1896 // It shall return a negative value if A's name should be lexicographically
1897 // ordered before B's name. It returns a value greater than zero if B's name
1898 // should be ordered before A's name, and it returns 0 otherwise.
1899 static int OptionCategoryCompare(OptionCategory *const *A,
1900 OptionCategory *const *B) {
1901 return (*A)->getName().compare((*B)->getName());
1904 // Make sure we inherit our base class's operator=()
1905 using HelpPrinter::operator=;
1908 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1909 std::vector<OptionCategory *> SortedCategories;
1910 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1912 // Collect registered option categories into vector in preparation for
1914 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1915 E = GlobalParser->RegisteredOptionCategories.end();
1917 SortedCategories.push_back(*I);
1920 // Sort the different option categories alphabetically.
1921 assert(SortedCategories.size() > 0 && "No option categories registered!");
1922 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1923 OptionCategoryCompare);
1925 // Create map to empty vectors.
1926 for (std::vector<OptionCategory *>::const_iterator
1927 I = SortedCategories.begin(),
1928 E = SortedCategories.end();
1930 CategorizedOptions[*I] = std::vector<Option *>();
1932 // Walk through pre-sorted options and assign into categories.
1933 // Because the options are already alphabetically sorted the
1934 // options within categories will also be alphabetically sorted.
1935 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1936 Option *Opt = Opts[I].second;
1937 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1938 "Option has an unregistered category");
1939 CategorizedOptions[Opt->Category].push_back(Opt);
1943 for (std::vector<OptionCategory *>::const_iterator
1944 Category = SortedCategories.begin(),
1945 E = SortedCategories.end();
1946 Category != E; ++Category) {
1947 // Hide empty categories for -help, but show for -help-hidden.
1948 const auto &CategoryOptions = CategorizedOptions[*Category];
1949 bool IsEmptyCategory = CategoryOptions.empty();
1950 if (!ShowHidden && IsEmptyCategory)
1953 // Print category information.
1955 outs() << (*Category)->getName() << ":\n";
1957 // Check if description is set.
1958 if (!(*Category)->getDescription().empty())
1959 outs() << (*Category)->getDescription() << "\n\n";
1963 // When using -help-hidden explicitly state if the category has no
1964 // options associated with it.
1965 if (IsEmptyCategory) {
1966 outs() << " This option category has no options.\n";
1969 // Loop over the options in the category and print.
1970 for (const Option *Opt : CategoryOptions)
1971 Opt->printOptionInfo(MaxArgLen);
1976 // This wraps the Uncategorizing and Categorizing printers and decides
1977 // at run time which should be invoked.
1978 class HelpPrinterWrapper {
1980 HelpPrinter &UncategorizedPrinter;
1981 CategorizedHelpPrinter &CategorizedPrinter;
1984 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1985 CategorizedHelpPrinter &CategorizedPrinter)
1986 : UncategorizedPrinter(UncategorizedPrinter),
1987 CategorizedPrinter(CategorizedPrinter) {}
1989 // Invoke the printer.
1990 void operator=(bool Value);
1993 } // End anonymous namespace
1995 // Declare the four HelpPrinter instances that are used to print out help, or
1996 // help-hidden as an uncategorized list or in categories.
1997 static HelpPrinter UncategorizedNormalPrinter(false);
1998 static HelpPrinter UncategorizedHiddenPrinter(true);
1999 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
2000 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
2002 // Declare HelpPrinter wrappers that will decide whether or not to invoke
2003 // a categorizing help printer
2004 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
2005 CategorizedNormalPrinter);
2006 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
2007 CategorizedHiddenPrinter);
2009 // Define a category for generic options that all tools should have.
2010 static cl::OptionCategory GenericCategory("Generic Options");
2012 // Define uncategorized help printers.
2013 // -help-list is hidden by default because if Option categories are being used
2014 // then -help behaves the same as -help-list.
2015 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
2017 cl::desc("Display list of available options (-help-list-hidden for more)"),
2018 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
2019 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2021 static cl::opt<HelpPrinter, true, parser<bool>>
2022 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
2023 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
2024 cl::ValueDisallowed, cl::cat(GenericCategory),
2025 cl::sub(*AllSubCommands));
2027 // Define uncategorized/categorized help printers. These printers change their
2028 // behaviour at runtime depending on whether one or more Option categories have
2030 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2031 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
2032 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
2033 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2035 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2036 HHOp("help-hidden", cl::desc("Display all available options"),
2037 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
2038 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2040 static cl::opt<bool> PrintOptions(
2042 cl::desc("Print non-default options after command line parsing"),
2043 cl::Hidden, cl::init(false), cl::cat(GenericCategory),
2044 cl::sub(*AllSubCommands));
2046 static cl::opt<bool> PrintAllOptions(
2047 "print-all-options",
2048 cl::desc("Print all option values after command line parsing"), cl::Hidden,
2049 cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2051 void HelpPrinterWrapper::operator=(bool Value) {
2055 // Decide which printer to invoke. If more than one option category is
2056 // registered then it is useful to show the categorized help instead of
2057 // uncategorized help.
2058 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2059 // unhide -help-list option so user can have uncategorized output if they
2061 HLOp.setHiddenFlag(NotHidden);
2063 CategorizedPrinter = true; // Invoke categorized printer
2065 UncategorizedPrinter = true; // Invoke uncategorized printer
2068 // Print the value of each option.
2069 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2071 void CommandLineParser::printOptionValues() {
2072 if (!PrintOptions && !PrintAllOptions)
2075 SmallVector<std::pair<const char *, Option *>, 128> Opts;
2076 sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2078 // Compute the maximum argument length...
2079 size_t MaxArgLen = 0;
2080 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2081 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2083 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2084 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2087 static VersionPrinterTy OverrideVersionPrinter = nullptr;
2089 static std::vector<VersionPrinterTy> *ExtraVersionPrinters = nullptr;
2092 class VersionPrinter {
2095 raw_ostream &OS = outs();
2096 #ifdef PACKAGE_VENDOR
2097 OS << PACKAGE_VENDOR << " ";
2099 OS << "LLVM (http://llvm.org/):\n ";
2101 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2102 #ifdef LLVM_VERSION_INFO
2103 OS << " " << LLVM_VERSION_INFO;
2106 #ifndef __OPTIMIZE__
2107 OS << "DEBUG build";
2109 OS << "Optimized build";
2112 OS << " with assertions";
2114 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2115 std::string CPU = sys::getHostCPUName();
2116 if (CPU == "generic")
2119 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
2120 << " Host CPU: " << CPU;
2124 void operator=(bool OptionWasSpecified) {
2125 if (!OptionWasSpecified)
2128 if (OverrideVersionPrinter != nullptr) {
2129 OverrideVersionPrinter(outs());
2134 // Iterate over any registered extra printers and call them to add further
2136 if (ExtraVersionPrinters != nullptr) {
2138 for (auto I : *ExtraVersionPrinters)
2145 } // End anonymous namespace
2147 // Define the --version option that prints out the LLVM version for the tool
2148 static VersionPrinter VersionPrinterInstance;
2150 static cl::opt<VersionPrinter, true, parser<bool>>
2151 VersOp("version", cl::desc("Display the version of this program"),
2152 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2153 cl::cat(GenericCategory));
2155 // Utility function for printing the help message.
2156 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2157 if (!Hidden && !Categorized)
2158 UncategorizedNormalPrinter.printHelp();
2159 else if (!Hidden && Categorized)
2160 CategorizedNormalPrinter.printHelp();
2161 else if (Hidden && !Categorized)
2162 UncategorizedHiddenPrinter.printHelp();
2164 CategorizedHiddenPrinter.printHelp();
2167 /// Utility function for printing version number.
2168 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
2170 void cl::SetVersionPrinter(VersionPrinterTy func) { OverrideVersionPrinter = func; }
2172 void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2173 if (!ExtraVersionPrinters)
2174 ExtraVersionPrinters = new std::vector<VersionPrinterTy>;
2176 ExtraVersionPrinters->push_back(func);
2179 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2180 auto &Subs = GlobalParser->RegisteredSubCommands;
2182 assert(is_contained(Subs, &Sub));
2183 return Sub.OptionsMap;
2186 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2187 cl::getRegisteredSubcommands() {
2188 return GlobalParser->getRegisteredSubcommands();
2191 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2192 for (auto &I : Sub.OptionsMap) {
2193 if (I.second->Category != &Category &&
2194 I.second->Category != &GenericCategory)
2195 I.second->setHiddenFlag(cl::ReallyHidden);
2199 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2201 auto CategoriesBegin = Categories.begin();
2202 auto CategoriesEnd = Categories.end();
2203 for (auto &I : Sub.OptionsMap) {
2204 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
2206 I.second->Category != &GenericCategory)
2207 I.second->setHiddenFlag(cl::ReallyHidden);
2211 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2212 void cl::ResetAllOptionOccurrences() {
2213 GlobalParser->ResetAllOptionOccurrences();
2216 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2217 const char *Overview) {
2218 llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),