30 #include "llvm/Config/config.h" 47 #define DEBUG_TYPE "commandline" 73 void GenericOptionValue::anchor() {}
76 void Option::anchor() {}
92 class CommandLineParser {
96 std::string ProgramName;
100 std::vector<StringRef> MoreHelp;
108 CommandLineParser() : ActiveSubCommand(
nullptr) {
121 if (!SC->
OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
122 errs() << ProgramName <<
": CommandLine Error: Option '" << Name
123 <<
"' registered more than once!\n";
130 for (
const auto &Sub : RegisteredSubCommands) {
133 addLiteralOption(Opt, Sub, Name);
139 if (Opt.
Subs.empty())
142 for (
auto SC : Opt.
Subs)
143 addLiteralOption(Opt, SC, Name);
148 bool HadErrors =
false;
152 errs() << ProgramName <<
": CommandLine Error: Option '" << O->
ArgStr 153 <<
"' registered more than once!\n";
165 O->
error(
"Cannot specify more than one option with cl::ConsumeAfter!");
181 for (
const auto &Sub : RegisteredSubCommands) {
189 void addOption(
Option *O) {
190 if (O->
Subs.empty()) {
193 for (
auto SC : O->
Subs)
205 for (
auto Name : OptionNames)
227 void removeOption(
Option *O) {
232 for (
auto SC : RegisteredSubCommands)
235 for (
auto SC : O->
Subs)
241 bool hasOptions(
const SubCommand &Sub)
const {
246 bool hasOptions()
const {
247 for (
const auto &S : RegisteredSubCommands) {
254 SubCommand *getActiveSubCommand() {
return ActiveSubCommand; }
258 if (!Sub.
OptionsMap.insert(std::make_pair(NewName, O)).second) {
259 errs() << ProgramName <<
": CommandLine Error: Option '" << O->
ArgStr 260 <<
"' registered more than once!\n";
270 for (
auto SC : O->
Subs)
271 updateArgStr(O, NewName, SC);
275 void printOptionValues();
282 "Duplicate option categories");
284 RegisteredOptionCategories.
insert(cat);
293 "Duplicate subcommands");
294 RegisteredSubCommands.
insert(sub);
305 addLiteralOption(*O, sub,
E.first());
311 RegisteredSubCommands.
erase(sub);
317 RegisteredSubCommands.
end());
321 ActiveSubCommand =
nullptr;
326 RegisteredOptionCategories.
clear();
329 RegisteredSubCommands.
clear();
349 GlobalParser->addLiteralOption(O, Name);
353 GlobalParser->MoreHelp.push_back(Help);
357 GlobalParser->addOption(
this);
358 FullyInitialized =
true;
364 if (FullyInitialized)
365 GlobalParser->updateArgStr(
this, S);
366 assert((S.
empty() || S[0] !=
'-') &&
"Option can't start with '-");
373 void OptionCategory::registerCategory() {
374 GlobalParser->registerCategory(
this);
384 GlobalParser->registerSubCommand(
this);
388 GlobalParser->unregisterSubCommand(
this);
392 PositionalOpts.clear();
396 ConsumeAfterOpt =
nullptr;
399 SubCommand::operator
bool()
const {
400 return (GlobalParser->getActiveSubCommand() ==
this);
417 size_t EqualPos = Arg.
find(
'=');
440 Value = Arg.
substr(EqualPos + 1);
441 Arg = Arg.
substr(0, EqualPos);
448 for (
auto S : RegisteredSubCommands) {
451 if (S->getName().empty())
466 std::string &NearestString) {
472 std::pair<StringRef, StringRef> SplitArg = Arg.
split(
'=');
478 unsigned BestDistance = 0;
480 ie = OptionsMap.
end();
490 for (
auto Name : OptionNames) {
492 Flag,
true, BestDistance);
493 if (!Best || Distance < BestDistance) {
495 BestDistance = Distance;
496 if (RHS.
empty() || !PermitValue)
497 NearestString = Name;
499 NearestString = (
Twine(Name) +
"=" + RHS).str();
511 bool MultiArg =
false) {
523 Val = Val.
substr(Pos + 1);
531 return Handler->
addOccurrence(pos, ArgName, Value, MultiArg);
539 const char *
const *argv,
int &i) {
550 return Handler->
error(
"requires a value!");
552 assert(argv &&
"null check");
557 if (NumAdditionalVals > 0)
558 return Handler->
error(
"multi-valued option specified" 559 " with ValueDisallowed modifier!");
562 return Handler->
error(
"does not allow a value! '" +
Twine(Value) +
570 if (NumAdditionalVals == 0)
574 bool MultiArg =
false;
583 while (NumAdditionalVals > 0) {
585 return Handler->
error(
"not enough values!");
586 assert(argv &&
"null check");
618 bool (*Pred)(
const Option *),
626 while (OMI == OptionsMap.
end() && Name.
size() > 1) {
628 OMI = OptionsMap.
find(Name);
631 if (OMI != OptionsMap.
end() && Pred(OMI->second)) {
632 Length = Name.
size();
660 Value = Arg.
substr(Length);
661 Arg = Arg.
substr(0, Length);
662 assert(OptionsMap.
count(Arg) && OptionsMap.
find(Arg)->second == PGOpt);
678 "Option can not be cl::Grouping AND cl::ValueRequired!");
685 }
while (PGOpt && Length != Arg.
size());
702 return C ==
' ' || C ==
'\t' || C ==
'\r' || C ==
'\n';
709 static bool isQuote(
char C) {
return C ==
'\"' || C ==
'\''; }
715 for (
size_t I = 0,
E = Src.
size();
I !=
E; ++
I) {
720 if (MarkEOLs && Src[I] ==
'\n')
731 if (
I + 1 <
E && C ==
'\\') {
740 while (
I !=
E && Src[
I] != C) {
742 if (Src[
I] ==
'\\' &&
I + 1 !=
E)
790 size_t E = Src.
size();
791 int BackslashCount = 0;
796 }
while (I != E && Src[I] ==
'\\');
798 bool FollowedByDoubleQuote = (I != E && Src[
I] ==
'"');
799 if (FollowedByDoubleQuote) {
800 Token.
append(BackslashCount / 2,
'\\');
801 if (BackslashCount % 2 == 0)
806 Token.
append(BackslashCount,
'\\');
817 enum {
INIT, UNQUOTED, QUOTED } State =
INIT;
818 for (
size_t I = 0,
E = Src.
size();
I !=
E; ++
I) {
826 if (MarkEOLs && C ==
'\n')
846 if (State == UNQUOTED) {
853 if (MarkEOLs && C ==
'\n')
870 if (State == QUOTED) {
893 for (
const char *Cur = Source.
begin(); Cur != Source.
end();) {
902 while (Cur != Source.
end() && *Cur !=
'\n')
907 const char *Start = Cur;
908 for (
const char *End = Source.
end(); Cur != End; ++Cur) {
910 if (Cur + 1 != End) {
913 (*Cur ==
'\r' && (Cur + 1 != End) && Cur[1] ==
'\n')) {
914 Line.
append(Start, Cur - 1);
920 }
else if (*Cur ==
'\n')
932 return (S.
size() >= 3 && S[0] ==
'\xef' && S[1] ==
'\xbb' && S[2] ==
'\xbf');
938 bool MarkEOLs,
bool RelativeNames) {
958 Str =
StringRef(BufRef.data() + 3, BufRef.size() - 3);
961 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
967 for (
unsigned I = 0;
I < NewArgv.
size(); ++
I)
970 if (Arg.
front() ==
'@') {
974 ResponseFile.
append(1,
'@');
982 NewArgv[
I] = Saver.
save(ResponseFile.
c_str()).data();
994 bool MarkEOLs,
bool RelativeNames) {
995 unsigned RspFiles = 0;
996 bool AllExpanded =
true;
999 for (
unsigned I = 0;
I != Argv.
size();) {
1000 const char *Arg = Argv[
I];
1002 if (Arg ==
nullptr) {
1006 if (Arg[0] !=
'@') {
1013 if (RspFiles++ > 20)
1020 MarkEOLs, RelativeNames)) {
1023 AllExpanded =
false;
1048 const char *Overview) {
1050 assert(progName &&
"Program name not specified");
1051 assert(envVar &&
"Environment variable name missing");
1068 int newArgc =
static_cast<int>(newArgv.
size());
1074 const char *EnvVar) {
1088 for (
int I = 1;
I < argc; ++
I)
1090 int NewArgc =
static_cast<int>(NewArgv.
size());
1093 return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1100 for (
auto SC : RegisteredSubCommands) {
1101 for (
auto &
O :
SC->OptionsMap)
1107 const char *
const *argv,
1110 assert(hasOptions() &&
"No options specified!");
1121 argc =
static_cast<int>(newArgv.
size());
1126 ProgramOverview = Overview;
1127 bool IgnoreErrors = Errs;
1130 bool ErrorParsing =
false;
1133 unsigned NumPositionalRequired = 0;
1136 bool HasUnlimitedPositionals =
false;
1140 if (argc >= 2 && argv[FirstArg][0] !=
'-') {
1143 ChosenSubCommand = LookupSubCommand(
StringRef(argv[FirstArg]));
1147 GlobalParser->ActiveSubCommand = ChosenSubCommand;
1149 assert(ChosenSubCommand);
1152 auto &SinkOpts = ChosenSubCommand->
SinkOpts;
1153 auto &OptionsMap = ChosenSubCommand->
OptionsMap;
1155 if (ConsumeAfterOpt) {
1156 assert(PositionalOpts.size() > 0 &&
1157 "Cannot specify cl::ConsumeAfter without a positional argument!");
1159 if (!PositionalOpts.empty()) {
1162 bool UnboundedFound =
false;
1163 for (
size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1164 Option *Opt = PositionalOpts[i];
1166 ++NumPositionalRequired;
1167 else if (ConsumeAfterOpt) {
1170 if (PositionalOpts.size() > 1) {
1172 Opt->
error(
"error - this positional option will never be matched, " 1173 "because it does not Require a value, and a " 1174 "cl::ConsumeAfter option is active!");
1175 ErrorParsing =
true;
1177 }
else if (UnboundedFound && !Opt->
hasArgStr()) {
1183 Opt->
error(
"error - option can never match, because " 1184 "another positional argument will match an " 1185 "unbounded number of values, and this option" 1186 " does not require a value!");
1187 *Errs << ProgramName <<
": CommandLine Error: Option '" << Opt->
ArgStr 1188 <<
"' is all messed up!\n";
1189 *Errs << PositionalOpts.size();
1190 ErrorParsing =
true;
1194 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1205 Option *ActivePositionalArg =
nullptr;
1208 bool DashDashFound =
false;
1209 for (
int i = FirstArg; i < argc; ++i) {
1210 Option *Handler =
nullptr;
1211 Option *NearestHandler =
nullptr;
1212 std::string NearestHandlerString;
1220 if (argv[i][0] !=
'-' || argv[i][1] == 0 || DashDashFound) {
1222 if (ActivePositionalArg) {
1227 if (!PositionalOpts.empty()) {
1233 if (PositionalVals.
size() >= NumPositionalRequired && ConsumeAfterOpt) {
1234 for (++i; i < argc; ++i)
1242 }
else if (argv[i][0] ==
'-' && argv[i][1] ==
'-' && argv[i][2] == 0 &&
1244 DashDashFound =
true;
1246 }
else if (ActivePositionalArg &&
1253 while (!ArgName.
empty() && ArgName[0] ==
'-')
1254 ArgName = ArgName.
substr(1);
1256 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1265 while (!ArgName.
empty() && ArgName[0] ==
'-')
1266 ArgName = ArgName.
substr(1);
1268 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1277 if (!Handler && SinkOpts.empty())
1283 if (SinkOpts.empty()) {
1284 *Errs << ProgramName <<
": Unknown command line argument '" << argv[i]
1285 <<
"'. Try: '" << argv[0] <<
" -help'\n";
1287 if (NearestHandler) {
1289 *Errs << ProgramName <<
": Did you mean '-" << NearestHandlerString
1293 ErrorParsing =
true;
1298 (*I)->addOccurrence(i,
"",
StringRef(argv[i]));
1307 Handler->
error(
"This argument does not take a value.\n" 1308 "\tInstead, it consumes any positional arguments until " 1309 "the next recognized option.", *Errs);
1310 ErrorParsing =
true;
1312 ActivePositionalArg = Handler;
1315 ErrorParsing |=
ProvideOption(Handler, ArgName, Value, argc, argv, i);
1319 if (NumPositionalRequired > PositionalVals.
size()) {
1320 *Errs << ProgramName
1321 <<
": Not enough positional command line arguments specified!\n" 1322 <<
"Must specify at least " << NumPositionalRequired
1323 <<
" positional argument" << (NumPositionalRequired > 1 ?
"s" :
"")
1324 <<
": See: " << argv[0] <<
" -help\n";
1326 ErrorParsing =
true;
1327 }
else if (!HasUnlimitedPositionals &&
1328 PositionalVals.
size() > PositionalOpts.size()) {
1329 *Errs << ProgramName <<
": Too many positional arguments specified!\n" 1330 <<
"Can specify at most " << PositionalOpts.size()
1331 <<
" positional arguments: See: " << argv[0] <<
" -help\n";
1332 ErrorParsing =
true;
1334 }
else if (!ConsumeAfterOpt) {
1336 unsigned ValNo = 0, NumVals =
static_cast<unsigned>(PositionalVals.
size());
1337 for (
size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1340 PositionalVals[ValNo].
second);
1342 --NumPositionalRequired;
1349 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() ==
cl::Required;
1350 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1351 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1358 PositionalVals[ValNo].
first,
1359 PositionalVals[ValNo].
second);
1364 "positional argument processing!");
1369 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.
size());
1371 for (
size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1374 PositionalVals[ValNo].
first,
1375 PositionalVals[ValNo].
second);
1384 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.
empty()) {
1386 PositionalVals[ValNo].
first,
1387 PositionalVals[ValNo].
second);
1393 for (; ValNo != PositionalVals.
size(); ++ValNo)
1396 PositionalVals[ValNo].
second);
1400 for (
const auto &Opt : OptionsMap) {
1401 switch (Opt.second->getNumOccurrencesFlag()) {
1404 if (Opt.second->getNumOccurrences() == 0) {
1405 Opt.second->error(
"must be specified at least once!");
1406 ErrorParsing =
true;
1418 for (
int i = 0; i < argc; ++i)
dbgs() << argv[i] <<
' ';
1439 if (!ArgName.
data())
1441 if (ArgName.
empty())
1444 Errs << GlobalParser->ProgramName <<
": for the -" << ArgName;
1446 Errs <<
" option: " << Message <<
"\n";
1455 switch (getNumOccurrencesFlag()) {
1457 if (NumOccurrences > 1)
1458 return error(
"may only occur zero or one times!", ArgName);
1461 if (NumOccurrences > 1)
1462 return error(
"must occur exactly one time!", ArgName);
1470 return handleOccurrence(pos, ArgName, Value);
1487 size_t alias::getOptionWidth()
const {
return ArgStr.
size() + 6; }
1490 size_t FirstLineIndentedBy) {
1491 std::pair<StringRef, StringRef>
Split = HelpStr.
split(
'\n');
1492 outs().
indent(Indent - FirstLineIndentedBy) <<
" - " << Split.first <<
"\n";
1493 while (!Split.second.empty()) {
1494 Split = Split.second.split(
'\n');
1495 outs().
indent(Indent) << Split.first <<
"\n";
1500 void alias::printOptionInfo(
size_t GlobalWidth)
const {
1501 outs() <<
" -" << ArgStr;
1502 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
1515 auto ValName = getValueName();
1516 if (!ValName.empty()) {
1517 size_t FormattingLen = 3;
1530 size_t GlobalWidth)
const {
1533 auto ValName = getValueName();
1534 if (!ValName.empty()) {
1546 size_t GlobalWidth)
const {
1555 if (Arg ==
"" || Arg ==
"true" || Arg ==
"TRUE" || Arg ==
"True" ||
1561 if (Arg ==
"false" || Arg ==
"FALSE" || Arg ==
"False" || Arg ==
"0") {
1565 return O.
error(
"'" + Arg +
1566 "' is invalid value for boolean argument! Try 0 or 1");
1573 if (Arg ==
"" || Arg ==
"true" || Arg ==
"TRUE" || Arg ==
"True" ||
1578 if (Arg ==
"false" || Arg ==
"FALSE" || Arg ==
"False" || Arg ==
"0") {
1583 return O.
error(
"'" + Arg +
1584 "' is invalid value for boolean argument! Try 0 or 1");
1592 return O.
error(
"'" + Arg +
"' value invalid for integer argument!");
1602 return O.
error(
"'" + Arg +
"' value invalid for uint argument!");
1610 unsigned long long &Value) {
1613 return O.
error(
"'" + Arg +
"' value invalid for uint argument!");
1622 return O.
error(
"'" + Arg +
"' value invalid for floating point argument!");
1646 unsigned e = getNumOptions();
1648 for (
unsigned i = 0; i != e; ++i) {
1649 if (getOption(i) == Name)
1659 for (
unsigned i = 0, e = getNumOptions(); i != e; ++i)
1663 size_t BaseSize = 0;
1664 for (
unsigned i = 0, e = getNumOptions(); i != e; ++i)
1665 BaseSize =
std::max(BaseSize, getOption(i).
size() + 8);
1674 size_t GlobalWidth)
const {
1679 for (
unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1680 size_t NumSpaces = GlobalWidth - getOption(i).size() - 8;
1681 outs() <<
" =" << getOption(i);
1687 for (
unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1688 auto Option = getOption(i);
1706 unsigned NumOpts = getNumOptions();
1707 for (
unsigned i = 0; i != NumOpts; ++i) {
1708 if (Value.
compare(getOptionValue(i)))
1711 outs() <<
"= " << getOption(i);
1712 size_t L = getOption(i).size();
1713 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1715 for (
unsigned j = 0; j != NumOpts; ++j) {
1716 if (Default.
compare(getOptionValue(j)))
1718 outs() << getOption(j);
1724 outs() <<
"= *unknown option value*\n";
1729 #define PRINT_OPT_DIFF(T) \ 1730 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \ 1731 size_t GlobalWidth) const { \ 1732 printOptionName(O, GlobalWidth); \ 1735 raw_string_ostream SS(Str); \ 1738 outs() << "= " << Str; \ 1739 size_t NumSpaces = \ 1740 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \ 1741 outs().indent(NumSpaces) << " (default: "; \ 1743 outs() << D.getValue(); \ 1745 outs() << "*no default*"; \ 1760 size_t GlobalWidth)
const {
1761 printOptionName(O, GlobalWidth);
1762 outs() <<
"= " << V;
1763 size_t NumSpaces = MaxOptWidth > V.
size() ? MaxOptWidth - V.
size() : 0;
1768 outs() <<
"*no default*";
1774 size_t GlobalWidth)
const {
1775 printOptionName(O, GlobalWidth);
1776 outs() <<
"= *cannot print option value*\n";
1784 const std::pair<const char *, Option *> *RHS) {
1785 return strcmp(LHS->first, RHS->first);
1789 const std::pair<const char *, SubCommand *> *RHS) {
1790 return strcmp(LHS->first, RHS->first);
1806 if (
I->second->getOptionHiddenFlag() ==
Hidden && !ShowHidden)
1810 if (!OptionSet.
insert(
I->second).second)
1814 std::pair<const char *, Option *>(
I->getKey().data(),
I->second));
1824 for (
const auto &S : SubMap) {
1825 if (S->getName().empty())
1827 Subs.push_back(std::make_pair(S->getName().data(), S));
1836 const bool ShowHidden;
1838 StrOptionPairVector;
1840 StrSubCommandPairVector;
1842 virtual void printOptions(StrOptionPairVector &Opts,
size_t MaxArgLen) {
1843 for (
size_t i = 0, e = Opts.size(); i != e; ++i)
1844 Opts[i].
second->printOptionInfo(MaxArgLen);
1847 void printSubCommands(StrSubCommandPairVector &Subs,
size_t MaxSubLen) {
1848 for (
const auto &S : Subs) {
1849 outs() <<
" " << S.first;
1850 if (!S.second->getDescription().empty()) {
1852 outs() <<
" - " << S.second->getDescription();
1859 explicit HelpPrinter(
bool showHidden) : ShowHidden(showHidden) {}
1860 virtual ~HelpPrinter() {}
1863 void operator=(
bool Value) {
1873 SubCommand *Sub = GlobalParser->getActiveSubCommand();
1878 StrOptionPairVector Opts;
1879 sortOpts(OptionsMap, Opts, ShowHidden);
1881 StrSubCommandPairVector Subs;
1884 if (!GlobalParser->ProgramOverview.empty())
1885 outs() <<
"OVERVIEW: " << GlobalParser->ProgramOverview <<
"\n";
1888 outs() <<
"USAGE: " << GlobalParser->ProgramName;
1889 if (Subs.size() > 2)
1890 outs() <<
" [subcommand]";
1891 outs() <<
" [options]";
1897 outs() <<
"USAGE: " << GlobalParser->ProgramName <<
" " << Sub->
getName()
1901 for (
auto Opt : PositionalOpts) {
1902 if (Opt->hasArgStr())
1903 outs() <<
" --" << Opt->ArgStr;
1904 outs() <<
" " << Opt->HelpStr;
1908 if (ConsumeAfterOpt)
1909 outs() <<
" " << ConsumeAfterOpt->HelpStr;
1913 size_t MaxSubLen = 0;
1914 for (
size_t i = 0, e = Subs.size(); i != e; ++i)
1918 outs() <<
"SUBCOMMANDS:\n\n";
1919 printSubCommands(Subs, MaxSubLen);
1921 outs() <<
" Type \"" << GlobalParser->ProgramName
1922 <<
" <subcommand> -help\" to get more help on a specific " 1929 size_t MaxArgLen = 0;
1930 for (
size_t i = 0, e = Opts.size(); i != e; ++i)
1931 MaxArgLen =
std::max(MaxArgLen, Opts[i].
second->getOptionWidth());
1933 outs() <<
"OPTIONS:\n";
1934 printOptions(Opts, MaxArgLen);
1937 for (
auto I : GlobalParser->MoreHelp)
1939 GlobalParser->MoreHelp.clear();
1943 class CategorizedHelpPrinter :
public HelpPrinter {
1945 explicit CategorizedHelpPrinter(
bool showHidden) : HelpPrinter(showHidden) {}
1953 return (*A)->getName().compare((*B)->getName());
1957 using HelpPrinter::operator=;
1960 void printOptions(StrOptionPairVector &Opts,
size_t MaxArgLen)
override {
1961 std::vector<OptionCategory *> SortedCategories;
1962 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1966 for (
auto I = GlobalParser->RegisteredOptionCategories.begin(),
1967 E = GlobalParser->RegisteredOptionCategories.end();
1969 SortedCategories.push_back(*
I);
1973 assert(SortedCategories.size() > 0 &&
"No option categories registered!");
1975 OptionCategoryCompare);
1978 for (std::vector<OptionCategory *>::const_iterator
1979 I = SortedCategories.begin(),
1980 E = SortedCategories.end();
1982 CategorizedOptions[*
I] = std::vector<Option *>();
1987 for (
size_t I = 0,
E = Opts.size();
I !=
E; ++
I) {
1990 "Option has an unregistered category");
1991 CategorizedOptions[Opt->
Category].push_back(Opt);
1995 for (std::vector<OptionCategory *>::const_iterator
1996 Category = SortedCategories.begin(),
1997 E = SortedCategories.end();
1998 Category !=
E; ++Category) {
2000 const auto &CategoryOptions = CategorizedOptions[*Category];
2001 bool IsEmptyCategory = CategoryOptions.empty();
2002 if (!ShowHidden && IsEmptyCategory)
2007 outs() << (*Category)->getName() <<
":\n";
2010 if (!(*Category)->getDescription().empty())
2011 outs() << (*Category)->getDescription() <<
"\n\n";
2017 if (IsEmptyCategory) {
2018 outs() <<
" This option category has no options.\n";
2022 for (
const Option *Opt : CategoryOptions)
2023 Opt->printOptionInfo(MaxArgLen);
2030 class HelpPrinterWrapper {
2032 HelpPrinter &UncategorizedPrinter;
2033 CategorizedHelpPrinter &CategorizedPrinter;
2036 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2037 CategorizedHelpPrinter &CategorizedPrinter)
2038 : UncategorizedPrinter(UncategorizedPrinter),
2039 CategorizedPrinter(CategorizedPrinter) {}
2042 void operator=(
bool Value);
2057 CategorizedNormalPrinter);
2059 CategorizedHiddenPrinter);
2069 cl::desc(
"Display list of available options (-help-list-hidden for more)"),
2074 HLHOp(
"help-list-hidden",
cl::desc(
"Display list of all available options"),
2083 HOp(
"help",
cl::desc(
"Display available options (-help-hidden for more)"),
2088 HHOp(
"help-hidden",
cl::desc(
"Display all available options"),
2094 cl::desc(
"Print non-default options after command line parsing"),
2099 "print-all-options",
2103 void HelpPrinterWrapper::operator=(
bool Value) {
2110 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2115 CategorizedPrinter =
true;
2117 UncategorizedPrinter =
true;
2123 void CommandLineParser::printOptionValues() {
2124 if (!PrintOptions && !PrintAllOptions)
2128 sortOpts(ActiveSubCommand->OptionsMap, Opts,
true);
2131 size_t MaxArgLen = 0;
2132 for (
size_t i = 0, e = Opts.
size(); i != e; ++i)
2133 MaxArgLen =
std::max(MaxArgLen, Opts[i].
second->getOptionWidth());
2135 for (
size_t i = 0, e = Opts.
size(); i != e; ++i)
2136 Opts[i].
second->printOptionValue(MaxArgLen, PrintAllOptions);
2144 class VersionPrinter {
2148 #ifdef PACKAGE_VENDOR 2149 OS << PACKAGE_VENDOR <<
" ";
2151 OS <<
"LLVM (http://llvm.org/):\n ";
2153 OS << PACKAGE_NAME <<
" version " << PACKAGE_VERSION;
2154 #ifdef LLVM_VERSION_INFO 2155 OS <<
" " << LLVM_VERSION_INFO;
2158 #ifndef __OPTIMIZE__ 2159 OS <<
"DEBUG build";
2161 OS <<
"Optimized build";
2164 OS <<
" with assertions";
2166 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO 2168 if (CPU ==
"generic")
2172 <<
" Host CPU: " << CPU;
2176 void operator=(
bool OptionWasSpecified) {
2177 if (!OptionWasSpecified)
2180 if (OverrideVersionPrinter !=
nullptr) {
2188 if (ExtraVersionPrinters !=
nullptr) {
2190 for (
auto I : *ExtraVersionPrinters)
2203 VersOp(
"version",
cl::desc(
"Display the version of this program"),
2209 if (!Hidden && !Categorized)
2210 UncategorizedNormalPrinter.printHelp();
2211 else if (!Hidden && Categorized)
2212 CategorizedNormalPrinter.printHelp();
2213 else if (Hidden && !Categorized)
2214 UncategorizedHiddenPrinter.printHelp();
2216 CategorizedHiddenPrinter.printHelp();
2225 if (!ExtraVersionPrinters)
2226 ExtraVersionPrinters =
new std::vector<VersionPrinterTy>;
2228 ExtraVersionPrinters->push_back(func);
2232 auto &Subs = GlobalParser->RegisteredSubCommands;
2240 return GlobalParser->getRegisteredSubcommands();
2245 if (
I.second->Category != &Category &&
2246 I.second->Category != &GenericCategory)
2253 auto CategoriesBegin = Categories.
begin();
2254 auto CategoriesEnd = Categories.
end();
2256 if (
std::find(CategoriesBegin, CategoriesEnd,
I.second->Category) ==
2258 I.second->Category != &GenericCategory)
2265 GlobalParser->ResetAllOptionOccurrences();
2269 const char *Overview) {
bool hasUTF16ByteOrderMark(ArrayRef< char > SrcBytes)
Returns true if a blob of text starts with a UTF-16 big or little endian byte order mark...
bool isPositional() const
void ResetCommandLineParser()
Reset the command line parser back to its initial state.
Represents either an error or a value T.
static bool isQuote(char C)
enum ValueExpected getValueExpectedFlag() const
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
OptionCategory GeneralCategory
static void sortOpts(StringMap< Option *> &OptMap, SmallVectorImpl< std::pair< const char *, Option *>> &Opts, bool ShowHidden)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
static void Help(ArrayRef< SubtargetFeatureKV > CPUTable, ArrayRef< SubtargetFeatureKV > FeatTable)
Display help for feature choices.
static bool isPrefixedOrGrouping(const Option *O)
static bool parseDouble(Option &O, StringRef Arg, double &Value)
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
static int OptNameCompare(const std::pair< const char *, Option *> *LHS, const std::pair< const char *, Option *> *RHS)
static bool isGrouping(const Option *O)
static cl::opt< bool > PrintAllOptions("print-all-options", cl::desc("Print all option values after command line parsing"), cl::Hidden, cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands))
static void printHelpStr(StringRef HelpStr, size_t Indent, size_t FirstLineIndentedBy)
bool isConsumeAfter() const
void setArgStr(StringRef S)
void PrintVersionMessage()
Utility function for printing version number.
static cl::opt< VersionPrinter, true, parser< bool > > VersOp("version", cl::desc("Display the version of this program"), cl::location(VersionPrinterInstance), cl::ValueDisallowed, cl::cat(GenericCategory))
void push_back(const T &Elt)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
std::string getDefaultTargetTriple()
getDefaultTargetTriple() - Return the default target triple the compiler has been configured to produ...
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
#define PRINT_OPT_DIFF(T)
void ResetAllOptionOccurrences()
Reset all command line options to a state that looks as if they have never appeared on the command li...
size_t getOptionWidth(const Option &O) const
iterator find(StringRef Key)
enum NumOccurrencesFlag getNumOccurrencesFlag() const
void tokenizeConfigFile(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char *> &NewArgv, bool MarkEOLs=false)
Tokenizes content of configuration file.
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
auto count_if(R &&Range, UnaryPredicate P) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
void unregisterSubCommand()
void ParseEnvironmentOptions(const char *progName, const char *envvar, const char *Overview="")
ParseEnvironmentOptions - An alternative entry point to the CommandLine library, which allows you to ...
size_t getBufferSize() const
SmallVector< Option *, 4 > SinkOpts
static HelpPrinter UncategorizedHiddenPrinter(true)
LLVM_NODISCARD unsigned edit_distance(StringRef Other, bool AllowReplacements=true, unsigned MaxEditDistance=0) const
Determine the edit distance between this string and another string.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
static cl::opt< HelpPrinter, true, parser< bool > > HLHOp("help-list-hidden", cl::desc("Display list of all available options"), cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed, cl::cat(GenericCategory), cl::sub(*AllSubCommands))
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
void printOptionInfo(const Option &O, size_t GlobalWidth) const
StringMap< Option * > & getRegisteredOptions(SubCommand &Sub= *TopLevelSubCommand)
Use this to get a StringMap to all registered named options (e.g.
bool readConfigFile(StringRef CfgFileName, StringSaver &Saver, SmallVectorImpl< const char *> &Argv)
Reads command line options from the given configuration file.
static StringRef getValueStr(const Option &O, StringRef DefaultMsg)
static cl::opt< HelpPrinter, true, parser< bool > > HLOp("help-list", cl::desc("Display list of available options (-help-list-hidden for more)"), cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed, cl::cat(GenericCategory), cl::sub(*AllSubCommands))
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
amdgpu Simplify well known AMD library false Value Value const Twine & Name
void LLVMParseCommandLineOptions(int argc, const char *const *argv, const char *Overview)
This function parses the given arguments using the LLVM command line parser.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const
static const size_t MaxOptWidth
static VersionPrinter VersionPrinterInstance
static cl::OptionCategory GenericCategory("Generic Options")
void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char *> &NewArgv, bool MarkEOLs=false)
Tokenizes a Windows command line which may contain quotes and escaped quotes.
virtual bool compare(const GenericOptionValue &V) const =0
static Option * LookupNearestOption(StringRef Arg, const StringMap< Option *> &OptionsMap, std::string &NearestString)
LookupNearestOption - Lookup the closest match to the option specified by the specified option on the...
virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value, bool MultiArg=false)
StringRef str() const
Explicit conversion to StringRef.
static cl::opt< bool > PrintOptions("print-options", cl::desc("Print non-default options after command line parsing"), cl::Hidden, cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands))
std::function< void(raw_ostream &)> VersionPrinterTy
static size_t parseBackslash(StringRef Src, size_t I, SmallString< 128 > &Token)
Backslashes are interpreted in a rather complicated way in the Windows-style command line...
static HelpPrinter UncategorizedNormalPrinter(false)
SmallVector< Option *, 4 > PositionalOpts
static ManagedStatic< CommandLineParser > GlobalParser
void printOptionNoValue(const Option &O, size_t GlobalWidth) const
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
bool to_float(const Twine &T, float &Num)
static bool ExpandResponseFile(StringRef FName, StringSaver &Saver, TokenizerCallback Tokenizer, SmallVectorImpl< const char *> &NewArgv, bool MarkEOLs, bool RelativeNames)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
void printGenericOptionDiff(const Option &O, const GenericOptionValue &V, const GenericOptionValue &Default, size_t GlobalWidth) const
StringRef getName() const
ManagedStatic< SubCommand > AllSubCommands
static std::vector< VersionPrinterTy > * ExtraVersionPrinters
static bool hasUTF8ByteOrderMark(ArrayRef< char > S)
Flag
These should be considered private to the implementation of the MCInstrDesc class.
StringMap< Option * > OptionsMap
ManagedStatic< SubCommand > TopLevelSubCommand
static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i)
void append(in_iter S, in_iter E)
Append from an iterator pair.
void HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub= *TopLevelSubCommand)
Mark all options not part of this category as cl::ReallyHidden.
raw_ostream & outs()
This returns a reference to a raw_ostream for standard output.
const DataType & getValue() const
static int SubNameCompare(const std::pair< const char *, SubCommand *> *LHS, const std::pair< const char *, SubCommand *> *RHS)
initializer< Ty > init(const Ty &Val)
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Allocate memory in an ever growing pool, as if by bump-pointer.
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
unsigned getNumAdditionalVals() const
void PrintHelpMessage(bool Hidden=false, bool Categorized=false)
This function just prints the help message, exactly the same way as if the -help or -help-hidden opti...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void registerSubCommand()
static Option * HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, bool &ErrorParsing, const StringMap< Option *> &OptionsMap)
HandlePrefixedOrGroupedOption - The specified argument string (which started with at least one '-') d...
void setHiddenFlag(enum OptionHidden Val)
static void sortSubCommands(const SmallPtrSetImpl< SubCommand *> &SubMap, SmallVectorImpl< std::pair< const char *, SubCommand *>> &Subs)
OptionCategory * Category
static bool EatsUnboundedNumberOfValues(const Option *O)
bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", raw_ostream *Errs=nullptr, const char *EnvVar=nullptr)
void SetVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// SetVersionPrinter - Over...
StringRef getDescription() const
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
bool isInAllSubCommands() const
static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos, StringRef ArgName, StringRef Value, bool MultiArg=false)
CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence() that does special handling ...
iterator erase(const_iterator CI)
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
std::string getProcessTriple()
getProcessTriple() - Return an appropriate target triple for generating code to be loaded into the cu...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Triple - Helper class for working with autoconf configuration names.
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter, CategorizedNormalPrinter)
static bool isWhitespaceOrNull(char C)
void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char *> &NewArgv, bool MarkEOLs=false)
Tokenizes a command line that can contain escapes and quotes.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
CHAIN = SC CHAIN, Imm128 - System call.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static VersionPrinterTy OverrideVersionPrinter
static bool ProvideOption(Option *Handler, StringRef ArgName, StringRef Value, int argc, const char *const *argv, int &i)
ProvideOption - For Value, this differentiates between an empty value ("") and a null value (StringRe...
void printOptionDiff(const Option &O, const AnyOptionValue &V, const AnyOptionValue &Default, size_t GlobalWidth) const
This interface provides simple read-only access to a block of memory, and provides simple methods for...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
A range adaptor for a pair of iterators.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
static bool isWhitespace(char C)
StringRef save(const char *S)
static std::string getDescription(const Module &M)
enum FormattingFlags getFormattingFlag() const
typename SuperClass::iterator iterator
void AddLiteralOption(Option &O, StringRef Name)
Adds a new option for parsing and provides the option it refers to.
static bool RequiresValue(const Option *O)
iterator insert(iterator I, T &&Elt)
bool convertUTF16ToUTF8String(ArrayRef< char > SrcBytes, std::string &Out)
Converts a stream of raw bytes assumed to be UTF16 into a UTF8 std::string.
amdgpu Simplify well known AMD library false Value Value * Arg
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
const char * getBufferEnd() const
Provides a library for accessing information about this process and other processes on the operating ...
StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
static CategorizedHelpPrinter CategorizedNormalPrinter(false)
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
static cl::opt< HelpPrinterWrapper, true, parser< bool > > HOp("help", cl::desc("Display available options (-help-hidden for more)"), cl::location(WrappedNormalPrinter), cl::ValueDisallowed, cl::cat(GenericCategory), cl::sub(*AllSubCommands))
LLVM_NODISCARD bool empty() const
void(*)(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs) TokenizerCallback
String tokenization function type.
virtual void getExtraOptionNames(SmallVectorImpl< StringRef > &)
void removeArgument()
Unregisters this option from the CommandLine system.
static Option * getOptionPred(StringRef Name, size_t &Length, bool(*Pred)(const Option *), const StringMap< Option *> &OptionsMap)
bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
SmallPtrSet< SubCommand *, 4 > Subs
bool error(const Twine &Message, StringRef ArgName=StringRef(), raw_ostream &Errs=llvm::errs())
const char * getBufferStart() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void printOptionName(const Option &O, size_t GlobalWidth) const
LLVM_NODISCARD char front() const
front - Get the first character in the string.
static cl::opt< HelpPrinterWrapper, true, parser< bool > > HHOp("help-hidden", cl::desc("Display all available options"), cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed, cl::cat(GenericCategory), cl::sub(*AllSubCommands))
LLVM Value Representation.
void AddExtraVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// AddExtraVersionPrinter -...
raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
This class implements an extremely fast bulk output stream that can only output to a stream...
static CategorizedHelpPrinter CategorizedHiddenPrinter(true)
bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, SmallVectorImpl< const char *> &Argv, bool MarkEOLs=false, bool RelativeNames=false)
Expand response files on a command line recursively using the given StringSaver and tokenization stra...
unsigned getMiscFlags() const
StringRef - Represent a constant reference to a string, i.e.
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
static void Split(std::vector< std::string > &V, StringRef S)
Splits a string of comma separated items in to a vector of strings.
virtual size_t getOptionWidth(const Option &O) const
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t find(char C, size_t From=0) const
Search for the first character C in the string.
unsigned findOption(StringRef Name)
iterator_range< typename SmallPtrSet< SubCommand *, 4 >::iterator > getRegisteredSubcommands()
Use this to get all registered SubCommands from the provided parser.
static Optional< std::string > GetEnv(StringRef name)
static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter, CategorizedHiddenPrinter)
LocationClass< Ty > location(Ty &L)
StringRef getName() const
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.