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(
'=');
435 Value = Arg.
substr(EqualPos + 1);
436 Arg = Arg.
substr(0, EqualPos);
443 for (
auto S : RegisteredSubCommands) {
446 if (S->getName().empty())
461 std::string &NearestString) {
467 std::pair<StringRef, StringRef> SplitArg = Arg.
split(
'=');
473 unsigned BestDistance = 0;
475 ie = OptionsMap.
end();
485 for (
auto Name : OptionNames) {
487 Flag,
true, BestDistance);
488 if (!Best || Distance < BestDistance) {
490 BestDistance = Distance;
491 if (RHS.
empty() || !PermitValue)
492 NearestString = Name;
494 NearestString = (
Twine(Name) +
"=" + RHS).str();
506 bool MultiArg =
false) {
518 Val = Val.
substr(Pos + 1);
526 return Handler->
addOccurrence(pos, ArgName, Value, MultiArg);
534 const char *
const *argv,
int &i) {
543 return Handler->
error(
"requires a value!");
545 assert(argv &&
"null check");
550 if (NumAdditionalVals > 0)
551 return Handler->
error(
"multi-valued option specified" 552 " with ValueDisallowed modifier!");
555 return Handler->
error(
"does not allow a value! '" +
Twine(Value) +
563 if (NumAdditionalVals == 0)
567 bool MultiArg =
false;
576 while (NumAdditionalVals > 0) {
578 return Handler->
error(
"not enough values!");
579 assert(argv &&
"null check");
610 bool (*Pred)(
const Option *),
618 while (OMI == OptionsMap.
end() && Name.
size() > 1) {
620 OMI = OptionsMap.
find(Name);
623 if (OMI != OptionsMap.
end() && Pred(OMI->second)) {
624 Length = Name.
size();
651 Value = Arg.
substr(Length);
652 Arg = Arg.
substr(0, Length);
653 assert(OptionsMap.
count(Arg) && OptionsMap.
find(Arg)->second == PGOpt);
669 "Option can not be cl::Grouping AND cl::ValueRequired!");
676 }
while (PGOpt && Length != Arg.
size());
693 return C ==
' ' || C ==
'\t' || C ==
'\r' || C ==
'\n';
696 static bool isQuote(
char C) {
return C ==
'\"' || C ==
'\''; }
702 for (
size_t I = 0,
E = Src.
size();
I !=
E; ++
I) {
707 if (MarkEOLs && Src[I] ==
'\n')
718 if (
I + 1 <
E && C ==
'\\') {
727 while (
I !=
E && Src[
I] != C) {
729 if (Src[
I] ==
'\\' &&
I + 1 !=
E)
777 size_t E = Src.
size();
778 int BackslashCount = 0;
783 }
while (I != E && Src[I] ==
'\\');
785 bool FollowedByDoubleQuote = (I != E && Src[
I] ==
'"');
786 if (FollowedByDoubleQuote) {
787 Token.
append(BackslashCount / 2,
'\\');
788 if (BackslashCount % 2 == 0)
793 Token.
append(BackslashCount,
'\\');
804 enum {
INIT, UNQUOTED, QUOTED } State =
INIT;
805 for (
size_t I = 0,
E = Src.
size();
I !=
E; ++
I) {
813 if (MarkEOLs && C ==
'\n')
833 if (State == UNQUOTED) {
840 if (MarkEOLs && C ==
'\n')
857 if (State == QUOTED) {
880 for (
const char *Cur = Source.
begin(); Cur != Source.
end();) {
889 while (Cur != Source.
end() && *Cur !=
'\n')
894 const char *Start = Cur;
895 for (
const char *End = Source.
end(); Cur != End; ++Cur) {
897 if (Cur + 1 != End) {
900 (*Cur ==
'\r' && (Cur + 1 != End) && Cur[1] ==
'\n')) {
901 Line.
append(Start, Cur - 1);
907 }
else if (*Cur ==
'\n')
919 return (S.
size() >= 3 && S[0] ==
'\xef' && S[1] ==
'\xbb' && S[2] ==
'\xbf');
925 bool MarkEOLs,
bool RelativeNames) {
945 Str =
StringRef(BufRef.data() + 3, BufRef.size() - 3);
948 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
954 for (
unsigned I = 0;
I < NewArgv.
size(); ++
I)
957 if (Arg.
front() ==
'@') {
961 ResponseFile.
append(1,
'@');
969 NewArgv[
I] = Saver.
save(ResponseFile.
c_str()).data();
981 bool MarkEOLs,
bool RelativeNames) {
982 unsigned RspFiles = 0;
983 bool AllExpanded =
true;
986 for (
unsigned I = 0;
I != Argv.
size();) {
987 const char *Arg = Argv[
I];
989 if (Arg ==
nullptr) {
1000 if (RspFiles++ > 20)
1007 MarkEOLs, RelativeNames)) {
1010 AllExpanded =
false;
1035 const char *Overview) {
1037 assert(progName &&
"Program name not specified");
1038 assert(envVar &&
"Environment variable name missing");
1055 int newArgc =
static_cast<int>(newArgv.
size());
1061 return GlobalParser->ParseCommandLineOptions(argc, argv, Overview,
1068 for (
auto SC : RegisteredSubCommands) {
1069 for (
auto &
O :
SC->OptionsMap)
1075 const char *
const *argv,
1078 assert(hasOptions() &&
"No options specified!");
1089 argc =
static_cast<int>(newArgv.
size());
1094 ProgramOverview = Overview;
1095 bool IgnoreErrors = Errs;
1098 bool ErrorParsing =
false;
1101 unsigned NumPositionalRequired = 0;
1104 bool HasUnlimitedPositionals =
false;
1108 if (argc >= 2 && argv[FirstArg][0] !=
'-') {
1111 ChosenSubCommand = LookupSubCommand(
StringRef(argv[FirstArg]));
1115 GlobalParser->ActiveSubCommand = ChosenSubCommand;
1117 assert(ChosenSubCommand);
1120 auto &SinkOpts = ChosenSubCommand->
SinkOpts;
1121 auto &OptionsMap = ChosenSubCommand->
OptionsMap;
1123 if (ConsumeAfterOpt) {
1124 assert(PositionalOpts.size() > 0 &&
1125 "Cannot specify cl::ConsumeAfter without a positional argument!");
1127 if (!PositionalOpts.empty()) {
1130 bool UnboundedFound =
false;
1131 for (
size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1132 Option *Opt = PositionalOpts[i];
1134 ++NumPositionalRequired;
1135 else if (ConsumeAfterOpt) {
1138 if (PositionalOpts.size() > 1) {
1140 Opt->
error(
"error - this positional option will never be matched, " 1141 "because it does not Require a value, and a " 1142 "cl::ConsumeAfter option is active!");
1143 ErrorParsing =
true;
1145 }
else if (UnboundedFound && !Opt->
hasArgStr()) {
1151 Opt->
error(
"error - option can never match, because " 1152 "another positional argument will match an " 1153 "unbounded number of values, and this option" 1154 " does not require a value!");
1155 *Errs << ProgramName <<
": CommandLine Error: Option '" << Opt->
ArgStr 1156 <<
"' is all messed up!\n";
1157 *Errs << PositionalOpts.size();
1158 ErrorParsing =
true;
1162 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1173 Option *ActivePositionalArg =
nullptr;
1176 bool DashDashFound =
false;
1177 for (
int i = FirstArg; i < argc; ++i) {
1178 Option *Handler =
nullptr;
1179 Option *NearestHandler =
nullptr;
1180 std::string NearestHandlerString;
1188 if (argv[i][0] !=
'-' || argv[i][1] == 0 || DashDashFound) {
1190 if (ActivePositionalArg) {
1195 if (!PositionalOpts.empty()) {
1201 if (PositionalVals.
size() >= NumPositionalRequired && ConsumeAfterOpt) {
1202 for (++i; i < argc; ++i)
1210 }
else if (argv[i][0] ==
'-' && argv[i][1] ==
'-' && argv[i][2] == 0 &&
1212 DashDashFound =
true;
1214 }
else if (ActivePositionalArg &&
1221 while (!ArgName.
empty() && ArgName[0] ==
'-')
1222 ArgName = ArgName.
substr(1);
1224 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1233 while (!ArgName.
empty() && ArgName[0] ==
'-')
1234 ArgName = ArgName.
substr(1);
1236 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1245 if (!Handler && SinkOpts.empty())
1251 if (SinkOpts.empty()) {
1252 *Errs << ProgramName <<
": Unknown command line argument '" << argv[i]
1253 <<
"'. Try: '" << argv[0] <<
" -help'\n";
1255 if (NearestHandler) {
1257 *Errs << ProgramName <<
": Did you mean '-" << NearestHandlerString
1261 ErrorParsing =
true;
1266 (*I)->addOccurrence(i,
"",
StringRef(argv[i]));
1275 Handler->
error(
"This argument does not take a value.\n" 1276 "\tInstead, it consumes any positional arguments until " 1277 "the next recognized option.", *Errs);
1278 ErrorParsing =
true;
1280 ActivePositionalArg = Handler;
1283 ErrorParsing |=
ProvideOption(Handler, ArgName, Value, argc, argv, i);
1287 if (NumPositionalRequired > PositionalVals.
size()) {
1288 *Errs << ProgramName
1289 <<
": Not enough positional command line arguments specified!\n" 1290 <<
"Must specify at least " << NumPositionalRequired
1291 <<
" positional argument" << (NumPositionalRequired > 1 ?
"s" :
"")
1292 <<
": See: " << argv[0] <<
" -help\n";
1294 ErrorParsing =
true;
1295 }
else if (!HasUnlimitedPositionals &&
1296 PositionalVals.
size() > PositionalOpts.size()) {
1297 *Errs << ProgramName <<
": Too many positional arguments specified!\n" 1298 <<
"Can specify at most " << PositionalOpts.size()
1299 <<
" positional arguments: See: " << argv[0] <<
" -help\n";
1300 ErrorParsing =
true;
1302 }
else if (!ConsumeAfterOpt) {
1304 unsigned ValNo = 0, NumVals =
static_cast<unsigned>(PositionalVals.
size());
1305 for (
size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1308 PositionalVals[ValNo].
second);
1310 --NumPositionalRequired;
1317 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() ==
cl::Required;
1318 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1319 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1326 PositionalVals[ValNo].
first,
1327 PositionalVals[ValNo].
second);
1332 "positional argument processing!");
1337 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.
size());
1339 for (
size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1342 PositionalVals[ValNo].
first,
1343 PositionalVals[ValNo].
second);
1352 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.
empty()) {
1354 PositionalVals[ValNo].
first,
1355 PositionalVals[ValNo].
second);
1361 for (; ValNo != PositionalVals.
size(); ++ValNo)
1364 PositionalVals[ValNo].
second);
1368 for (
const auto &Opt : OptionsMap) {
1369 switch (Opt.second->getNumOccurrencesFlag()) {
1372 if (Opt.second->getNumOccurrences() == 0) {
1373 Opt.second->error(
"must be specified at least once!");
1374 ErrorParsing =
true;
1386 for (
int i = 0; i < argc; ++i)
dbgs() << argv[i] <<
' ';
1407 if (!ArgName.
data())
1409 if (ArgName.
empty())
1412 Errs << GlobalParser->ProgramName <<
": for the -" << ArgName;
1414 Errs <<
" option: " << Message <<
"\n";
1423 switch (getNumOccurrencesFlag()) {
1425 if (NumOccurrences > 1)
1426 return error(
"may only occur zero or one times!", ArgName);
1429 if (NumOccurrences > 1)
1430 return error(
"must occur exactly one time!", ArgName);
1438 return handleOccurrence(pos, ArgName, Value);
1455 size_t alias::getOptionWidth()
const {
return ArgStr.
size() + 6; }
1458 size_t FirstLineIndentedBy) {
1459 std::pair<StringRef, StringRef>
Split = HelpStr.
split(
'\n');
1460 outs().
indent(Indent - FirstLineIndentedBy) <<
" - " << Split.first <<
"\n";
1461 while (!Split.second.empty()) {
1462 Split = Split.second.split(
'\n');
1463 outs().
indent(Indent) << Split.first <<
"\n";
1468 void alias::printOptionInfo(
size_t GlobalWidth)
const {
1469 outs() <<
" -" << ArgStr;
1470 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
1483 auto ValName = getValueName();
1484 if (!ValName.empty()) {
1485 size_t FormattingLen = 3;
1498 size_t GlobalWidth)
const {
1501 auto ValName = getValueName();
1502 if (!ValName.empty()) {
1514 size_t GlobalWidth)
const {
1523 if (Arg ==
"" || Arg ==
"true" || Arg ==
"TRUE" || Arg ==
"True" ||
1529 if (Arg ==
"false" || Arg ==
"FALSE" || Arg ==
"False" || Arg ==
"0") {
1533 return O.
error(
"'" + Arg +
1534 "' is invalid value for boolean argument! Try 0 or 1");
1541 if (Arg ==
"" || Arg ==
"true" || Arg ==
"TRUE" || Arg ==
"True" ||
1546 if (Arg ==
"false" || Arg ==
"FALSE" || Arg ==
"False" || Arg ==
"0") {
1551 return O.
error(
"'" + Arg +
1552 "' is invalid value for boolean argument! Try 0 or 1");
1560 return O.
error(
"'" + Arg +
"' value invalid for integer argument!");
1570 return O.
error(
"'" + Arg +
"' value invalid for uint argument!");
1578 unsigned long long &Value) {
1581 return O.
error(
"'" + Arg +
"' value invalid for uint argument!");
1590 return O.
error(
"'" + Arg +
"' value invalid for floating point argument!");
1614 unsigned e = getNumOptions();
1616 for (
unsigned i = 0; i != e; ++i) {
1617 if (getOption(i) == Name)
1627 for (
unsigned i = 0, e = getNumOptions(); i != e; ++i)
1631 size_t BaseSize = 0;
1632 for (
unsigned i = 0, e = getNumOptions(); i != e; ++i)
1633 BaseSize =
std::max(BaseSize, getOption(i).
size() + 8);
1642 size_t GlobalWidth)
const {
1647 for (
unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1648 size_t NumSpaces = GlobalWidth - getOption(i).size() - 8;
1649 outs() <<
" =" << getOption(i);
1655 for (
unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1656 auto Option = getOption(i);
1674 unsigned NumOpts = getNumOptions();
1675 for (
unsigned i = 0; i != NumOpts; ++i) {
1676 if (Value.
compare(getOptionValue(i)))
1679 outs() <<
"= " << getOption(i);
1680 size_t L = getOption(i).size();
1681 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1683 for (
unsigned j = 0; j != NumOpts; ++j) {
1684 if (Default.
compare(getOptionValue(j)))
1686 outs() << getOption(j);
1692 outs() <<
"= *unknown option value*\n";
1697 #define PRINT_OPT_DIFF(T) \ 1698 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \ 1699 size_t GlobalWidth) const { \ 1700 printOptionName(O, GlobalWidth); \ 1703 raw_string_ostream SS(Str); \ 1706 outs() << "= " << Str; \ 1707 size_t NumSpaces = \ 1708 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \ 1709 outs().indent(NumSpaces) << " (default: "; \ 1711 outs() << D.getValue(); \ 1713 outs() << "*no default*"; \ 1728 size_t GlobalWidth)
const {
1729 printOptionName(O, GlobalWidth);
1730 outs() <<
"= " << V;
1731 size_t NumSpaces = MaxOptWidth > V.
size() ? MaxOptWidth - V.
size() : 0;
1736 outs() <<
"*no default*";
1742 size_t GlobalWidth)
const {
1743 printOptionName(O, GlobalWidth);
1744 outs() <<
"= *cannot print option value*\n";
1752 const std::pair<const char *, Option *> *RHS) {
1753 return strcmp(LHS->first, RHS->first);
1757 const std::pair<const char *, SubCommand *> *RHS) {
1758 return strcmp(LHS->first, RHS->first);
1774 if (
I->second->getOptionHiddenFlag() ==
Hidden && !ShowHidden)
1778 if (!OptionSet.
insert(
I->second).second)
1782 std::pair<const char *, Option *>(
I->getKey().data(),
I->second));
1792 for (
const auto &S : SubMap) {
1793 if (S->getName().empty())
1795 Subs.push_back(std::make_pair(S->getName().data(), S));
1804 const bool ShowHidden;
1806 StrOptionPairVector;
1808 StrSubCommandPairVector;
1810 virtual void printOptions(StrOptionPairVector &Opts,
size_t MaxArgLen) {
1811 for (
size_t i = 0, e = Opts.size(); i != e; ++i)
1812 Opts[i].
second->printOptionInfo(MaxArgLen);
1815 void printSubCommands(StrSubCommandPairVector &Subs,
size_t MaxSubLen) {
1816 for (
const auto &S : Subs) {
1817 outs() <<
" " << S.first;
1818 if (!S.second->getDescription().empty()) {
1820 outs() <<
" - " << S.second->getDescription();
1827 explicit HelpPrinter(
bool showHidden) : ShowHidden(showHidden) {}
1828 virtual ~HelpPrinter() {}
1831 void operator=(
bool Value) {
1841 SubCommand *Sub = GlobalParser->getActiveSubCommand();
1846 StrOptionPairVector Opts;
1847 sortOpts(OptionsMap, Opts, ShowHidden);
1849 StrSubCommandPairVector Subs;
1852 if (!GlobalParser->ProgramOverview.empty())
1853 outs() <<
"OVERVIEW: " << GlobalParser->ProgramOverview <<
"\n";
1856 outs() <<
"USAGE: " << GlobalParser->ProgramName;
1857 if (Subs.size() > 2)
1858 outs() <<
" [subcommand]";
1859 outs() <<
" [options]";
1865 outs() <<
"USAGE: " << GlobalParser->ProgramName <<
" " << Sub->
getName()
1869 for (
auto Opt : PositionalOpts) {
1870 if (Opt->hasArgStr())
1871 outs() <<
" --" << Opt->ArgStr;
1872 outs() <<
" " << Opt->HelpStr;
1876 if (ConsumeAfterOpt)
1877 outs() <<
" " << ConsumeAfterOpt->HelpStr;
1881 size_t MaxSubLen = 0;
1882 for (
size_t i = 0, e = Subs.size(); i != e; ++i)
1886 outs() <<
"SUBCOMMANDS:\n\n";
1887 printSubCommands(Subs, MaxSubLen);
1889 outs() <<
" Type \"" << GlobalParser->ProgramName
1890 <<
" <subcommand> -help\" to get more help on a specific " 1897 size_t MaxArgLen = 0;
1898 for (
size_t i = 0, e = Opts.size(); i != e; ++i)
1899 MaxArgLen =
std::max(MaxArgLen, Opts[i].
second->getOptionWidth());
1901 outs() <<
"OPTIONS:\n";
1902 printOptions(Opts, MaxArgLen);
1905 for (
auto I : GlobalParser->MoreHelp)
1907 GlobalParser->MoreHelp.clear();
1911 class CategorizedHelpPrinter :
public HelpPrinter {
1913 explicit CategorizedHelpPrinter(
bool showHidden) : HelpPrinter(showHidden) {}
1921 return (*A)->getName().compare((*B)->getName());
1925 using HelpPrinter::operator=;
1928 void printOptions(StrOptionPairVector &Opts,
size_t MaxArgLen)
override {
1929 std::vector<OptionCategory *> SortedCategories;
1930 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1934 for (
auto I = GlobalParser->RegisteredOptionCategories.begin(),
1935 E = GlobalParser->RegisteredOptionCategories.end();
1937 SortedCategories.push_back(*
I);
1941 assert(SortedCategories.size() > 0 &&
"No option categories registered!");
1943 OptionCategoryCompare);
1946 for (std::vector<OptionCategory *>::const_iterator
1947 I = SortedCategories.begin(),
1948 E = SortedCategories.end();
1950 CategorizedOptions[*
I] = std::vector<Option *>();
1955 for (
size_t I = 0,
E = Opts.size();
I !=
E; ++
I) {
1958 "Option has an unregistered category");
1959 CategorizedOptions[Opt->
Category].push_back(Opt);
1963 for (std::vector<OptionCategory *>::const_iterator
1964 Category = SortedCategories.begin(),
1965 E = SortedCategories.end();
1968 const auto &CategoryOptions = CategorizedOptions[*
Category];
1969 bool IsEmptyCategory = CategoryOptions.empty();
1970 if (!ShowHidden && IsEmptyCategory)
1975 outs() << (*Category)->getName() <<
":\n";
1978 if (!(*Category)->getDescription().empty())
1979 outs() << (*Category)->getDescription() <<
"\n\n";
1985 if (IsEmptyCategory) {
1986 outs() <<
" This option category has no options.\n";
1990 for (
const Option *Opt : CategoryOptions)
1991 Opt->printOptionInfo(MaxArgLen);
1998 class HelpPrinterWrapper {
2000 HelpPrinter &UncategorizedPrinter;
2001 CategorizedHelpPrinter &CategorizedPrinter;
2004 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2005 CategorizedHelpPrinter &CategorizedPrinter)
2006 : UncategorizedPrinter(UncategorizedPrinter),
2007 CategorizedPrinter(CategorizedPrinter) {}
2010 void operator=(
bool Value);
2025 CategorizedNormalPrinter);
2027 CategorizedHiddenPrinter);
2037 cl::desc(
"Display list of available options (-help-list-hidden for more)"),
2042 HLHOp(
"help-list-hidden",
cl::desc(
"Display list of all available options"),
2051 HOp(
"help",
cl::desc(
"Display available options (-help-hidden for more)"),
2056 HHOp(
"help-hidden",
cl::desc(
"Display all available options"),
2062 cl::desc(
"Print non-default options after command line parsing"),
2067 "print-all-options",
2071 void HelpPrinterWrapper::operator=(
bool Value) {
2078 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2083 CategorizedPrinter =
true;
2085 UncategorizedPrinter =
true;
2091 void CommandLineParser::printOptionValues() {
2092 if (!PrintOptions && !PrintAllOptions)
2096 sortOpts(ActiveSubCommand->OptionsMap, Opts,
true);
2099 size_t MaxArgLen = 0;
2100 for (
size_t i = 0, e = Opts.
size(); i != e; ++i)
2101 MaxArgLen =
std::max(MaxArgLen, Opts[i].
second->getOptionWidth());
2103 for (
size_t i = 0, e = Opts.
size(); i != e; ++i)
2104 Opts[i].
second->printOptionValue(MaxArgLen, PrintAllOptions);
2112 class VersionPrinter {
2116 #ifdef PACKAGE_VENDOR 2117 OS << PACKAGE_VENDOR <<
" ";
2119 OS <<
"LLVM (http://llvm.org/):\n ";
2121 OS << PACKAGE_NAME <<
" version " << PACKAGE_VERSION;
2122 #ifdef LLVM_VERSION_INFO 2123 OS <<
" " << LLVM_VERSION_INFO;
2126 #ifndef __OPTIMIZE__ 2127 OS <<
"DEBUG build";
2129 OS <<
"Optimized build";
2132 OS <<
" with assertions";
2134 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO 2136 if (CPU ==
"generic")
2140 <<
" Host CPU: " << CPU;
2144 void operator=(
bool OptionWasSpecified) {
2145 if (!OptionWasSpecified)
2148 if (OverrideVersionPrinter !=
nullptr) {
2156 if (ExtraVersionPrinters !=
nullptr) {
2158 for (
auto I : *ExtraVersionPrinters)
2171 VersOp(
"version",
cl::desc(
"Display the version of this program"),
2177 if (!Hidden && !Categorized)
2178 UncategorizedNormalPrinter.printHelp();
2179 else if (!Hidden && Categorized)
2180 CategorizedNormalPrinter.printHelp();
2181 else if (Hidden && !Categorized)
2182 UncategorizedHiddenPrinter.printHelp();
2184 CategorizedHiddenPrinter.printHelp();
2193 if (!ExtraVersionPrinters)
2194 ExtraVersionPrinters =
new std::vector<VersionPrinterTy>;
2196 ExtraVersionPrinters->push_back(func);
2200 auto &Subs = GlobalParser->RegisteredSubCommands;
2208 return GlobalParser->getRegisteredSubcommands();
2213 if (
I.second->Category != &Category &&
2214 I.second->Category != &GenericCategory)
2221 auto CategoriesBegin = Categories.
begin();
2222 auto CategoriesEnd = Categories.
end();
2224 if (
std::find(CategoriesBegin, CategoriesEnd,
I.second->Category) ==
2226 I.second->Category != &GenericCategory)
2233 GlobalParser->ResetAllOptionOccurrences();
2237 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 push_back(const T &Elt)
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.
Compute iterated dominance frontiers using a linear time algorithm.
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))
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.
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)
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
bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", raw_ostream *Errs=nullptr)
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)
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.
static ManagedStatic< CodeViewErrorCategory > Category
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 -...
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
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...
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
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.