#include "llvm/Support/CommandLine.h"
#include "DebugOptions.h"
#include "llvm-c/Support.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLFunctionalExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Config/config.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/StringSaver.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdlib>
#include <string>
using namespace llvm;
using namespace cl;
#define DEBUG_TYPE "commandline"
namespace llvm {
namespace cl {
template class basic_parser<bool>;
template class basic_parser<boolOrDefault>;
template class basic_parser<int>;
template class basic_parser<long>;
template class basic_parser<long long>;
template class basic_parser<unsigned>;
template class basic_parser<unsigned long>;
template class basic_parser<unsigned long long>;
template class basic_parser<double>;
template class basic_parser<float>;
template class basic_parser<std::string>;
template class basic_parser<char>;
template class opt<unsigned>;
template class opt<int>;
template class opt<std::string>;
template class opt<char>;
template class opt<bool>;
} }
void GenericOptionValue::anchor() {}
void OptionValue<boolOrDefault>::anchor() {}
void OptionValue<std::string>::anchor() {}
void Option::anchor() {}
void basic_parser_impl::anchor() {}
void parser<bool>::anchor() {}
void parser<boolOrDefault>::anchor() {}
void parser<int>::anchor() {}
void parser<long>::anchor() {}
void parser<long long>::anchor() {}
void parser<unsigned>::anchor() {}
void parser<unsigned long>::anchor() {}
void parser<unsigned long long>::anchor() {}
void parser<double>::anchor() {}
void parser<float>::anchor() {}
void parser<std::string>::anchor() {}
void parser<char>::anchor() {}
const static size_t DefaultPad = 2;
static StringRef ArgPrefix = "-";
static StringRef ArgPrefixLong = "--";
static StringRef ArgHelpPrefix = " - ";
static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad = DefaultPad) {
size_t Len = ArgName.size();
if (Len == 1)
return Len + Pad + ArgPrefix.size() + ArgHelpPrefix.size();
return Len + Pad + ArgPrefixLong.size() + ArgHelpPrefix.size();
}
static SmallString<8> argPrefix(StringRef ArgName, size_t Pad = DefaultPad) {
SmallString<8> Prefix;
for (size_t I = 0; I < Pad; ++I) {
Prefix.push_back(' ');
}
Prefix.append(ArgName.size() > 1 ? ArgPrefixLong : ArgPrefix);
return Prefix;
}
static inline bool isGrouping(const Option *O) {
return O->getMiscFlags() & cl::Grouping;
}
static inline bool isPrefixedOrGrouping(const Option *O) {
return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
O->getFormattingFlag() == cl::AlwaysPrefix;
}
namespace {
class PrintArg {
StringRef ArgName;
size_t Pad;
public:
PrintArg(StringRef ArgName, size_t Pad = DefaultPad) : ArgName(ArgName), Pad(Pad) {}
friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg &);
};
raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
OS << argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
return OS;
}
class CommandLineParser {
public:
std::string ProgramName;
StringRef ProgramOverview;
std::vector<StringRef> MoreHelp;
SmallVector<Option*, 4> DefaultOptions;
SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
CommandLineParser() {
registerSubCommand(&*TopLevelSubCommand);
registerSubCommand(&*AllSubCommands);
}
void ResetAllOptionOccurrences();
bool ParseCommandLineOptions(int argc, const char *const *argv,
StringRef Overview, raw_ostream *Errs = nullptr,
bool LongOptionsUseDoubleDash = false);
void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
if (Opt.hasArgStr())
return;
if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
errs() << ProgramName << ": CommandLine Error: Option '" << Name
<< "' registered more than once!\n";
report_fatal_error("inconsistency in registered CommandLine options");
}
if (SC == &*AllSubCommands) {
for (auto *Sub : RegisteredSubCommands) {
if (SC == Sub)
continue;
addLiteralOption(Opt, Sub, Name);
}
}
}
void addLiteralOption(Option &Opt, StringRef Name) {
if (Opt.Subs.empty())
addLiteralOption(Opt, &*TopLevelSubCommand, Name);
else {
for (auto *SC : Opt.Subs)
addLiteralOption(Opt, SC, Name);
}
}
void addOption(Option *O, SubCommand *SC) {
bool HadErrors = false;
if (O->hasArgStr()) {
if (O->isDefaultOption() &&
SC->OptionsMap.find(O->ArgStr) != SC->OptionsMap.end())
return;
if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
<< "' registered more than once!\n";
HadErrors = true;
}
}
if (O->getFormattingFlag() == cl::Positional)
SC->PositionalOpts.push_back(O);
else if (O->getMiscFlags() & cl::Sink) SC->SinkOpts.push_back(O);
else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
if (SC->ConsumeAfterOpt) {
O->error("Cannot specify more than one option with cl::ConsumeAfter!");
HadErrors = true;
}
SC->ConsumeAfterOpt = O;
}
if (HadErrors)
report_fatal_error("inconsistency in registered CommandLine options");
if (SC == &*AllSubCommands) {
for (auto *Sub : RegisteredSubCommands) {
if (SC == Sub)
continue;
addOption(O, Sub);
}
}
}
void addOption(Option *O, bool ProcessDefaultOption = false) {
if (!ProcessDefaultOption && O->isDefaultOption()) {
DefaultOptions.push_back(O);
return;
}
if (O->Subs.empty()) {
addOption(O, &*TopLevelSubCommand);
} else {
for (auto *SC : O->Subs)
addOption(O, SC);
}
}
void removeOption(Option *O, SubCommand *SC) {
SmallVector<StringRef, 16> OptionNames;
O->getExtraOptionNames(OptionNames);
if (O->hasArgStr())
OptionNames.push_back(O->ArgStr);
SubCommand &Sub = *SC;
auto End = Sub.OptionsMap.end();
for (auto Name : OptionNames) {
auto I = Sub.OptionsMap.find(Name);
if (I != End && I->getValue() == O)
Sub.OptionsMap.erase(I);
}
if (O->getFormattingFlag() == cl::Positional)
for (auto *Opt = Sub.PositionalOpts.begin();
Opt != Sub.PositionalOpts.end(); ++Opt) {
if (*Opt == O) {
Sub.PositionalOpts.erase(Opt);
break;
}
}
else if (O->getMiscFlags() & cl::Sink)
for (auto *Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
if (*Opt == O) {
Sub.SinkOpts.erase(Opt);
break;
}
}
else if (O == Sub.ConsumeAfterOpt)
Sub.ConsumeAfterOpt = nullptr;
}
void removeOption(Option *O) {
if (O->Subs.empty())
removeOption(O, &*TopLevelSubCommand);
else {
if (O->isInAllSubCommands()) {
for (auto *SC : RegisteredSubCommands)
removeOption(O, SC);
} else {
for (auto *SC : O->Subs)
removeOption(O, SC);
}
}
}
bool hasOptions(const SubCommand &Sub) const {
return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
nullptr != Sub.ConsumeAfterOpt);
}
bool hasOptions() const {
for (const auto *S : RegisteredSubCommands) {
if (hasOptions(*S))
return true;
}
return false;
}
SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
SubCommand &Sub = *SC;
if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
<< "' registered more than once!\n";
report_fatal_error("inconsistency in registered CommandLine options");
}
Sub.OptionsMap.erase(O->ArgStr);
}
void updateArgStr(Option *O, StringRef NewName) {
if (O->Subs.empty())
updateArgStr(O, NewName, &*TopLevelSubCommand);
else {
if (O->isInAllSubCommands()) {
for (auto *SC : RegisteredSubCommands)
updateArgStr(O, NewName, SC);
} else {
for (auto *SC : O->Subs)
updateArgStr(O, NewName, SC);
}
}
}
void printOptionValues();
void registerCategory(OptionCategory *cat) {
assert(count_if(RegisteredOptionCategories,
[cat](const OptionCategory *Category) {
return cat->getName() == Category->getName();
}) == 0 &&
"Duplicate option categories");
RegisteredOptionCategories.insert(cat);
}
void registerSubCommand(SubCommand *sub) {
assert(count_if(RegisteredSubCommands,
[sub](const SubCommand *Sub) {
return (!sub->getName().empty()) &&
(Sub->getName() == sub->getName());
}) == 0 &&
"Duplicate subcommands");
RegisteredSubCommands.insert(sub);
if (sub != &*AllSubCommands) {
for (auto &E : AllSubCommands->OptionsMap) {
Option *O = E.second;
if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
O->hasArgStr())
addOption(O, sub);
else
addLiteralOption(*O, sub, E.first());
}
}
}
void unregisterSubCommand(SubCommand *sub) {
RegisteredSubCommands.erase(sub);
}
iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
getRegisteredSubcommands() {
return make_range(RegisteredSubCommands.begin(),
RegisteredSubCommands.end());
}
void reset() {
ActiveSubCommand = nullptr;
ProgramName.clear();
ProgramOverview = StringRef();
MoreHelp.clear();
RegisteredOptionCategories.clear();
ResetAllOptionOccurrences();
RegisteredSubCommands.clear();
TopLevelSubCommand->reset();
AllSubCommands->reset();
registerSubCommand(&*TopLevelSubCommand);
registerSubCommand(&*AllSubCommands);
DefaultOptions.clear();
}
private:
SubCommand *ActiveSubCommand = nullptr;
Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
Option *Opt = LookupOption(Sub, Arg, Value);
if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(Opt))
return nullptr;
return Opt;
}
SubCommand *LookupSubCommand(StringRef Name);
};
}
static ManagedStatic<CommandLineParser> GlobalParser;
void cl::AddLiteralOption(Option &O, StringRef Name) {
GlobalParser->addLiteralOption(O, Name);
}
extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
GlobalParser->MoreHelp.push_back(Help);
}
void Option::addArgument() {
GlobalParser->addOption(this);
FullyInitialized = true;
}
void Option::removeArgument() { GlobalParser->removeOption(this); }
void Option::setArgStr(StringRef S) {
if (FullyInitialized)
GlobalParser->updateArgStr(this, S);
assert((S.empty() || S[0] != '-') && "Option can't start with '-");
ArgStr = S;
if (ArgStr.size() == 1)
setMiscFlag(Grouping);
}
void Option::addCategory(OptionCategory &C) {
assert(!Categories.empty() && "Categories cannot be empty.");
if (&C != &getGeneralCategory() && Categories[0] == &getGeneralCategory())
Categories[0] = &C;
else if (!is_contained(Categories, &C))
Categories.push_back(&C);
}
void Option::reset() {
NumOccurrences = 0;
setDefault();
if (isDefaultOption())
removeArgument();
}
void OptionCategory::registerCategory() {
GlobalParser->registerCategory(this);
}
LLVM_REQUIRE_CONSTANT_INITIALIZATION
ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
void SubCommand::registerSubCommand() {
GlobalParser->registerSubCommand(this);
}
void SubCommand::unregisterSubCommand() {
GlobalParser->unregisterSubCommand(this);
}
void SubCommand::reset() {
PositionalOpts.clear();
SinkOpts.clear();
OptionsMap.clear();
ConsumeAfterOpt = nullptr;
}
SubCommand::operator bool() const {
return (GlobalParser->getActiveSubCommand() == this);
}
Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
StringRef &Value) {
if (Arg.empty())
return nullptr;
assert(&Sub != &*AllSubCommands);
size_t EqualPos = Arg.find('=');
if (EqualPos == StringRef::npos) {
return Sub.OptionsMap.lookup(Arg);
}
auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
if (I == Sub.OptionsMap.end())
return nullptr;
auto *O = I->second;
if (O->getFormattingFlag() == cl::AlwaysPrefix)
return nullptr;
Value = Arg.substr(EqualPos + 1);
Arg = Arg.substr(0, EqualPos);
return I->second;
}
SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
if (Name.empty())
return &*TopLevelSubCommand;
for (auto *S : RegisteredSubCommands) {
if (S == &*AllSubCommands)
continue;
if (S->getName().empty())
continue;
if (StringRef(S->getName()) == StringRef(Name))
return S;
}
return &*TopLevelSubCommand;
}
static Option *LookupNearestOption(StringRef Arg,
const StringMap<Option *> &OptionsMap,
std::string &NearestString) {
if (Arg.empty())
return nullptr;
std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
StringRef &LHS = SplitArg.first; StringRef &RHS = SplitArg.second;
Option *Best = nullptr;
unsigned BestDistance = 0;
for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
ie = OptionsMap.end();
it != ie; ++it) {
Option *O = it->second;
if (O->getOptionHiddenFlag() == ReallyHidden)
continue;
SmallVector<StringRef, 16> OptionNames;
O->getExtraOptionNames(OptionNames);
if (O->hasArgStr())
OptionNames.push_back(O->ArgStr);
bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
StringRef Flag = PermitValue ? LHS : Arg;
for (const auto &Name : OptionNames) {
unsigned Distance = StringRef(Name).edit_distance(
Flag, true, BestDistance);
if (!Best || Distance < BestDistance) {
Best = O;
BestDistance = Distance;
if (RHS.empty() || !PermitValue)
NearestString = std::string(Name);
else
NearestString = (Twine(Name) + "=" + RHS).str();
}
}
}
return Best;
}
static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
StringRef ArgName, StringRef Value,
bool MultiArg = false) {
if (Handler->getMiscFlags() & CommaSeparated) {
StringRef Val(Value);
StringRef::size_type Pos = Val.find(',');
while (Pos != StringRef::npos) {
if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
return true;
Val = Val.substr(Pos + 1);
Pos = Val.find(',');
}
Value = Val;
}
return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
}
static inline bool ProvideOption(Option *Handler, StringRef ArgName,
StringRef Value, int argc,
const char *const *argv, int &i) {
unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
switch (Handler->getValueExpectedFlag()) {
case ValueRequired:
if (!Value.data()) { if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
return Handler->error("requires a value!");
assert(argv && "null check");
Value = StringRef(argv[++i]);
}
break;
case ValueDisallowed:
if (NumAdditionalVals > 0)
return Handler->error("multi-valued option specified"
" with ValueDisallowed modifier!");
if (Value.data())
return Handler->error("does not allow a value! '" + Twine(Value) +
"' specified.");
break;
case ValueOptional:
break;
}
if (NumAdditionalVals == 0)
return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
bool MultiArg = false;
if (Value.data()) {
if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
return true;
--NumAdditionalVals;
MultiArg = true;
}
while (NumAdditionalVals > 0) {
if (i + 1 >= argc)
return Handler->error("not enough values!");
assert(argv && "null check");
Value = StringRef(argv[++i]);
if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
return true;
MultiArg = true;
--NumAdditionalVals;
}
return false;
}
bool llvm::cl::ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
int Dummy = i;
return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
}
static Option *getOptionPred(StringRef Name, size_t &Length,
bool (*Pred)(const Option *),
const StringMap<Option *> &OptionsMap) {
StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
OMI = OptionsMap.end();
while (OMI == OptionsMap.end() && Name.size() > 1) {
Name = Name.substr(0, Name.size() - 1); OMI = OptionsMap.find(Name);
if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
OMI = OptionsMap.end();
}
if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Length = Name.size();
return OMI->second; }
return nullptr; }
static Option *
HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
bool &ErrorParsing,
const StringMap<Option *> &OptionsMap) {
if (Arg.size() == 1)
return nullptr;
size_t Length = 0;
Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
if (!PGOpt)
return nullptr;
do {
StringRef MaybeValue =
(Length < Arg.size()) ? Arg.substr(Length) : StringRef();
Arg = Arg.substr(0, Length);
assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
(PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
Value = MaybeValue;
return PGOpt;
}
if (MaybeValue[0] == '=') {
Value = MaybeValue.substr(1);
return PGOpt;
}
assert(isGrouping(PGOpt) && "Broken getOptionPred!");
if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
ErrorParsing |= PGOpt->error("may not occur within a group!");
return nullptr;
}
int Dummy = 0;
ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
Arg = MaybeValue;
PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
} while (PGOpt);
return nullptr;
}
static bool RequiresValue(const Option *O) {
return O->getNumOccurrencesFlag() == cl::Required ||
O->getNumOccurrencesFlag() == cl::OneOrMore;
}
static bool EatsUnboundedNumberOfValues(const Option *O) {
return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
O->getNumOccurrencesFlag() == cl::OneOrMore;
}
static bool isWhitespace(char C) {
return C == ' ' || C == '\t' || C == '\r' || C == '\n';
}
static bool isWhitespaceOrNull(char C) {
return isWhitespace(C) || C == '\0';
}
static bool isQuote(char C) { return C == '\"' || C == '\''; }
void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
SmallVectorImpl<const char *> &NewArgv,
bool MarkEOLs) {
SmallString<128> Token;
for (size_t I = 0, E = Src.size(); I != E; ++I) {
if (Token.empty()) {
while (I != E && isWhitespace(Src[I])) {
if (MarkEOLs && Src[I] == '\n')
NewArgv.push_back(nullptr);
++I;
}
if (I == E)
break;
}
char C = Src[I];
if (I + 1 < E && C == '\\') {
++I; Token.push_back(Src[I]);
continue;
}
if (isQuote(C)) {
++I;
while (I != E && Src[I] != C) {
if (Src[I] == '\\' && I + 1 != E)
++I;
Token.push_back(Src[I]);
++I;
}
if (I == E)
break;
continue;
}
if (isWhitespace(C)) {
if (!Token.empty())
NewArgv.push_back(Saver.save(Token.str()).data());
if (MarkEOLs && C == '\n')
NewArgv.push_back(nullptr);
Token.clear();
continue;
}
Token.push_back(C);
}
if (!Token.empty())
NewArgv.push_back(Saver.save(Token.str()).data());
}
static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
size_t E = Src.size();
int BackslashCount = 0;
do {
++I;
++BackslashCount;
} while (I != E && Src[I] == '\\');
bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
if (FollowedByDoubleQuote) {
Token.append(BackslashCount / 2, '\\');
if (BackslashCount % 2 == 0)
return I - 1;
Token.push_back('"');
return I;
}
Token.append(BackslashCount, '\\');
return I - 1;
}
static bool isWindowsSpecialChar(char C) {
return isWhitespaceOrNull(C) || C == '\\' || C == '\"';
}
static bool isWindowsSpecialCharInCommandName(char C) {
return isWhitespaceOrNull(C) || C == '\"';
}
static inline void tokenizeWindowsCommandLineImpl(
StringRef Src, StringSaver &Saver, function_ref<void(StringRef)> AddToken,
bool AlwaysCopy, function_ref<void()> MarkEOL, bool InitialCommandName) {
SmallString<128> Token;
bool CommandName = InitialCommandName;
enum { INIT, UNQUOTED, QUOTED } State = INIT;
for (size_t I = 0, E = Src.size(); I < E; ++I) {
switch (State) {
case INIT: {
assert(Token.empty() && "token should be empty in initial state");
while (I < E && isWhitespaceOrNull(Src[I])) {
if (Src[I] == '\n')
MarkEOL();
++I;
}
if (I >= E)
break;
size_t Start = I;
if (CommandName) {
while (I < E && !isWindowsSpecialCharInCommandName(Src[I]))
++I;
} else {
while (I < E && !isWindowsSpecialChar(Src[I]))
++I;
}
StringRef NormalChars = Src.slice(Start, I);
if (I >= E || isWhitespaceOrNull(Src[I])) {
AddToken(AlwaysCopy ? Saver.save(NormalChars) : NormalChars);
if (I < E && Src[I] == '\n') {
MarkEOL();
CommandName = InitialCommandName;
} else {
CommandName = false;
}
} else if (Src[I] == '\"') {
Token += NormalChars;
State = QUOTED;
} else if (Src[I] == '\\') {
assert(!CommandName && "or else we'd have treated it as a normal char");
Token += NormalChars;
I = parseBackslash(Src, I, Token);
State = UNQUOTED;
} else {
llvm_unreachable("unexpected special character");
}
break;
}
case UNQUOTED:
if (isWhitespaceOrNull(Src[I])) {
AddToken(Saver.save(Token.str()));
Token.clear();
if (Src[I] == '\n') {
CommandName = InitialCommandName;
MarkEOL();
} else {
CommandName = false;
}
State = INIT;
} else if (Src[I] == '\"') {
State = QUOTED;
} else if (Src[I] == '\\' && !CommandName) {
I = parseBackslash(Src, I, Token);
} else {
Token.push_back(Src[I]);
}
break;
case QUOTED:
if (Src[I] == '\"') {
if (I < (E - 1) && Src[I + 1] == '"') {
Token.push_back('"');
++I;
} else {
State = UNQUOTED;
}
} else if (Src[I] == '\\' && !CommandName) {
I = parseBackslash(Src, I, Token);
} else {
Token.push_back(Src[I]);
}
break;
}
}
if (State != INIT)
AddToken(Saver.save(Token.str()));
}
void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
SmallVectorImpl<const char *> &NewArgv,
bool MarkEOLs) {
auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
auto OnEOL = [&]() {
if (MarkEOLs)
NewArgv.push_back(nullptr);
};
tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
true, OnEOL, false);
}
void cl::TokenizeWindowsCommandLineNoCopy(StringRef Src, StringSaver &Saver,
SmallVectorImpl<StringRef> &NewArgv) {
auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok); };
auto OnEOL = []() {};
tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, false,
OnEOL, false);
}
void cl::TokenizeWindowsCommandLineFull(StringRef Src, StringSaver &Saver,
SmallVectorImpl<const char *> &NewArgv,
bool MarkEOLs) {
auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
auto OnEOL = [&]() {
if (MarkEOLs)
NewArgv.push_back(nullptr);
};
tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
true, OnEOL, true);
}
void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
SmallVectorImpl<const char *> &NewArgv,
bool MarkEOLs) {
for (const char *Cur = Source.begin(); Cur != Source.end();) {
SmallString<128> Line;
if (isWhitespace(*Cur)) {
while (Cur != Source.end() && isWhitespace(*Cur))
++Cur;
continue;
}
if (*Cur == '#') {
while (Cur != Source.end() && *Cur != '\n')
++Cur;
continue;
}
const char *Start = Cur;
for (const char *End = Source.end(); Cur != End; ++Cur) {
if (*Cur == '\\') {
if (Cur + 1 != End) {
++Cur;
if (*Cur == '\n' ||
(*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
Line.append(Start, Cur - 1);
if (*Cur == '\r')
++Cur;
Start = Cur + 1;
}
}
} else if (*Cur == '\n')
break;
}
Line.append(Start, Cur);
cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
}
}
static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
}
static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver,
const char *&Arg) {
assert(sys::path::is_absolute(BasePath));
constexpr StringLiteral Token("<CFGDIR>");
const StringRef ArgString(Arg);
SmallString<128> ResponseFile;
StringRef::size_type StartPos = 0;
for (StringRef::size_type TokenPos = ArgString.find(Token);
TokenPos != StringRef::npos;
TokenPos = ArgString.find(Token, StartPos)) {
const StringRef LHS = ArgString.substr(StartPos, TokenPos - StartPos);
if (ResponseFile.empty())
ResponseFile = LHS;
else
llvm::sys::path::append(ResponseFile, LHS);
ResponseFile.append(BasePath);
StartPos = TokenPos + Token.size();
}
if (!ResponseFile.empty()) {
const StringRef Remaining = ArgString.substr(StartPos);
if (!Remaining.empty())
llvm::sys::path::append(ResponseFile, Remaining);
Arg = Saver.save(ResponseFile.str()).data();
}
}
static llvm::Error ExpandResponseFile(StringRef FName, StringSaver &Saver,
TokenizerCallback Tokenizer,
SmallVectorImpl<const char *> &NewArgv,
bool MarkEOLs, bool RelativeNames,
bool ExpandBasePath,
llvm::vfs::FileSystem &FS) {
assert(sys::path::is_absolute(FName));
llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
FS.getBufferForFile(FName);
if (!MemBufOrErr)
return llvm::errorCodeToError(MemBufOrErr.getError());
MemoryBuffer &MemBuf = *MemBufOrErr.get();
StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
std::string UTF8Buf;
if (hasUTF16ByteOrderMark(BufRef)) {
if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
return llvm::createStringError(std::errc::illegal_byte_sequence,
"Could not convert UTF16 to UTF8");
Str = StringRef(UTF8Buf);
}
else if (hasUTF8ByteOrderMark(BufRef))
Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
Tokenizer(Str, Saver, NewArgv, MarkEOLs);
if (!RelativeNames)
return Error::success();
llvm::StringRef BasePath = llvm::sys::path::parent_path(FName);
for (auto &Arg : NewArgv) {
if (!Arg)
continue;
if (ExpandBasePath)
ExpandBasePaths(BasePath, Saver, Arg);
if (Arg[0] != '@')
continue;
StringRef FileName(Arg + 1);
if (!llvm::sys::path::is_relative(FileName))
continue;
SmallString<128> ResponseFile;
ResponseFile.push_back('@');
ResponseFile.append(BasePath);
llvm::sys::path::append(ResponseFile, FileName);
Arg = Saver.save(ResponseFile.str()).data();
}
return Error::success();
}
bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
SmallVectorImpl<const char *> &Argv, bool MarkEOLs,
bool RelativeNames, bool ExpandBasePath,
llvm::Optional<llvm::StringRef> CurrentDir,
llvm::vfs::FileSystem &FS) {
bool AllExpanded = true;
struct ResponseFileRecord {
std::string File;
size_t End;
};
SmallVector<ResponseFileRecord, 3> FileStack;
FileStack.push_back({"", Argv.size()});
for (unsigned I = 0; I != Argv.size();) {
while (I == FileStack.back().End) {
FileStack.pop_back();
}
const char *Arg = Argv[I];
if (Arg == nullptr) {
++I;
continue;
}
if (Arg[0] != '@') {
++I;
continue;
}
const char *FName = Arg + 1;
SmallString<128> CurrDir;
if (llvm::sys::path::is_relative(FName)) {
if (!CurrentDir)
llvm::sys::fs::current_path(CurrDir);
else
CurrDir = *CurrentDir;
llvm::sys::path::append(CurrDir, FName);
FName = CurrDir.c_str();
}
auto IsEquivalent = [FName, &FS](const ResponseFileRecord &RFile) {
llvm::ErrorOr<llvm::vfs::Status> LHS = FS.status(FName);
if (!LHS) {
llvm::consumeError(llvm::errorCodeToError(LHS.getError()));
return false;
}
llvm::ErrorOr<llvm::vfs::Status> RHS = FS.status(RFile.File);
if (!RHS) {
llvm::consumeError(llvm::errorCodeToError(RHS.getError()));
return false;
}
return LHS->equivalent(*RHS);
};
if (any_of(drop_begin(FileStack), IsEquivalent)) {
AllExpanded = false;
++I;
continue;
}
SmallVector<const char *, 0> ExpandedArgv;
if (llvm::Error Err =
ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
RelativeNames, ExpandBasePath, FS)) {
llvm::consumeError(std::move(Err));
AllExpanded = false;
++I;
continue;
}
for (ResponseFileRecord &Record : FileStack) {
Record.End += ExpandedArgv.size() - 1;
}
FileStack.push_back({FName, I + ExpandedArgv.size()});
Argv.erase(Argv.begin() + I);
Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
}
assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
return AllExpanded;
}
bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
SmallVectorImpl<const char *> &Argv, bool MarkEOLs,
bool RelativeNames, bool ExpandBasePath,
llvm::Optional<StringRef> CurrentDir) {
return ExpandResponseFiles(Saver, std::move(Tokenizer), Argv, MarkEOLs,
RelativeNames, ExpandBasePath,
std::move(CurrentDir), *vfs::getRealFileSystem());
}
bool cl::expandResponseFiles(int Argc, const char *const *Argv,
const char *EnvVar, StringSaver &Saver,
SmallVectorImpl<const char *> &NewArgv) {
auto Tokenize = Triple(sys::getProcessTriple()).isOSWindows()
? cl::TokenizeWindowsCommandLine
: cl::TokenizeGNUCommandLine;
if (EnvVar)
if (llvm::Optional<std::string> EnvValue = sys::Process::GetEnv(EnvVar))
Tokenize(*EnvValue, Saver, NewArgv, false);
NewArgv.append(Argv + 1, Argv + Argc);
return ExpandResponseFiles(Saver, Tokenize, NewArgv);
}
bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver,
SmallVectorImpl<const char *> &Argv) {
SmallString<128> AbsPath;
if (sys::path::is_relative(CfgFile)) {
llvm::sys::fs::current_path(AbsPath);
llvm::sys::path::append(AbsPath, CfgFile);
CfgFile = AbsPath.str();
}
if (llvm::Error Err = ExpandResponseFile(
CfgFile, Saver, cl::tokenizeConfigFile, Argv,
false, true, true,
*llvm::vfs::getRealFileSystem())) {
llvm::consumeError(std::move(Err));
return false;
}
return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
false, true,
true, llvm::None);
}
static void initCommonOptions();
bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
StringRef Overview, raw_ostream *Errs,
const char *EnvVar,
bool LongOptionsUseDoubleDash) {
initCommonOptions();
SmallVector<const char *, 20> NewArgv;
BumpPtrAllocator A;
StringSaver Saver(A);
NewArgv.push_back(argv[0]);
if (EnvVar) {
if (llvm::Optional<std::string> EnvValue =
sys::Process::GetEnv(StringRef(EnvVar)))
TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
}
for (int I = 1; I < argc; ++I)
NewArgv.push_back(argv[I]);
int NewArgc = static_cast<int>(NewArgv.size());
return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
Errs, LongOptionsUseDoubleDash);
}
void CommandLineParser::ResetAllOptionOccurrences() {
for (auto *SC : RegisteredSubCommands) {
for (auto &O : SC->OptionsMap)
O.second->reset();
for (Option *O : SC->PositionalOpts)
O->reset();
for (Option *O : SC->SinkOpts)
O->reset();
if (SC->ConsumeAfterOpt)
SC->ConsumeAfterOpt->reset();
}
}
bool CommandLineParser::ParseCommandLineOptions(int argc,
const char *const *argv,
StringRef Overview,
raw_ostream *Errs,
bool LongOptionsUseDoubleDash) {
assert(hasOptions() && "No options specified!");
SmallVector<const char *, 20> newArgv(argv, argv + argc);
BumpPtrAllocator A;
StringSaver Saver(A);
ExpandResponseFiles(Saver,
Triple(sys::getProcessTriple()).isOSWindows() ?
cl::TokenizeWindowsCommandLine : cl::TokenizeGNUCommandLine,
newArgv);
argv = &newArgv[0];
argc = static_cast<int>(newArgv.size());
ProgramName = std::string(sys::path::filename(StringRef(argv[0])));
ProgramOverview = Overview;
bool IgnoreErrors = Errs;
if (!Errs)
Errs = &errs();
bool ErrorParsing = false;
unsigned NumPositionalRequired = 0;
bool HasUnlimitedPositionals = false;
int FirstArg = 1;
SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
if (argc >= 2 && argv[FirstArg][0] != '-') {
ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
if (ChosenSubCommand != &*TopLevelSubCommand)
FirstArg = 2;
}
GlobalParser->ActiveSubCommand = ChosenSubCommand;
assert(ChosenSubCommand);
auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
auto &SinkOpts = ChosenSubCommand->SinkOpts;
auto &OptionsMap = ChosenSubCommand->OptionsMap;
for (auto *O: DefaultOptions) {
addOption(O, true);
}
if (ConsumeAfterOpt) {
assert(PositionalOpts.size() > 0 &&
"Cannot specify cl::ConsumeAfter without a positional argument!");
}
if (!PositionalOpts.empty()) {
bool UnboundedFound = false;
for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Option *Opt = PositionalOpts[i];
if (RequiresValue(Opt))
++NumPositionalRequired;
else if (ConsumeAfterOpt) {
if (PositionalOpts.size() > 1) {
if (!IgnoreErrors)
Opt->error("error - this positional option will never be matched, "
"because it does not Require a value, and a "
"cl::ConsumeAfter option is active!");
ErrorParsing = true;
}
} else if (UnboundedFound && !Opt->hasArgStr()) {
if (!IgnoreErrors)
Opt->error("error - option can never match, because "
"another positional argument will match an "
"unbounded number of values, and this option"
" does not require a value!");
*Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
<< "' is all messed up!\n";
*Errs << PositionalOpts.size();
ErrorParsing = true;
}
UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
}
HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
}
SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
Option *ActivePositionalArg = nullptr;
bool DashDashFound = false; for (int i = FirstArg; i < argc; ++i) {
Option *Handler = nullptr;
Option *NearestHandler = nullptr;
std::string NearestHandlerString;
StringRef Value;
StringRef ArgName = "";
bool HaveDoubleDash = false;
if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
if (ActivePositionalArg) {
ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
continue; }
if (!PositionalOpts.empty()) {
PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
for (++i; i < argc; ++i)
PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
break; }
continue;
}
} else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
!DashDashFound) {
DashDashFound = true; continue; } else if (ActivePositionalArg &&
(ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
ArgName = StringRef(argv[i] + 1);
if (!ArgName.empty() && ArgName[0] == '-') {
HaveDoubleDash = true;
ArgName = ArgName.substr(1);
}
Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
LongOptionsUseDoubleDash, HaveDoubleDash);
if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
continue; }
} else { ArgName = StringRef(argv[i] + 1);
if (!ArgName.empty() && ArgName[0] == '-') {
HaveDoubleDash = true;
ArgName = ArgName.substr(1);
}
Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
LongOptionsUseDoubleDash, HaveDoubleDash);
if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
OptionsMap);
if (!Handler && SinkOpts.empty())
NearestHandler =
LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
}
if (!Handler) {
if (SinkOpts.empty()) {
*Errs << ProgramName << ": Unknown command line argument '" << argv[i]
<< "'. Try: '" << argv[0] << " --help'\n";
if (NearestHandler) {
*Errs << ProgramName << ": Did you mean '"
<< PrintArg(NearestHandlerString, 0) << "'?\n";
}
ErrorParsing = true;
} else {
for (Option *SinkOpt : SinkOpts)
SinkOpt->addOccurrence(i, "", StringRef(argv[i]));
}
continue;
}
if (Handler->getFormattingFlag() == cl::Positional) {
if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
Handler->error("This argument does not take a value.\n"
"\tInstead, it consumes any positional arguments until "
"the next recognized option.", *Errs);
ErrorParsing = true;
}
ActivePositionalArg = Handler;
}
else
ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
}
if (NumPositionalRequired > PositionalVals.size()) {
*Errs << ProgramName
<< ": Not enough positional command line arguments specified!\n"
<< "Must specify at least " << NumPositionalRequired
<< " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
<< ": See: " << argv[0] << " --help\n";
ErrorParsing = true;
} else if (!HasUnlimitedPositionals &&
PositionalVals.size() > PositionalOpts.size()) {
*Errs << ProgramName << ": Too many positional arguments specified!\n"
<< "Can specify at most " << PositionalOpts.size()
<< " positional arguments: See: " << argv[0] << " --help\n";
ErrorParsing = true;
} else if (!ConsumeAfterOpt) {
unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
if (RequiresValue(PositionalOpts[i])) {
ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
PositionalVals[ValNo].second);
ValNo++;
--NumPositionalRequired; }
bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
while (NumVals - ValNo > NumPositionalRequired && !Done) {
switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
case cl::Optional:
Done = true; LLVM_FALLTHROUGH;
case cl::ZeroOrMore: case cl::OneOrMore: ProvidePositionalOption(PositionalOpts[i],
PositionalVals[ValNo].first,
PositionalVals[ValNo].second);
ValNo++;
break;
default:
llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
"positional argument processing!");
}
}
}
} else {
assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
unsigned ValNo = 0;
for (size_t J = 0, E = PositionalOpts.size(); J != E; ++J)
if (RequiresValue(PositionalOpts[J])) {
ErrorParsing |= ProvidePositionalOption(PositionalOpts[J],
PositionalVals[ValNo].first,
PositionalVals[ValNo].second);
ValNo++;
}
if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
PositionalVals[ValNo].first,
PositionalVals[ValNo].second);
ValNo++;
}
for (; ValNo != PositionalVals.size(); ++ValNo)
ErrorParsing |=
ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
PositionalVals[ValNo].second);
}
for (const auto &Opt : OptionsMap) {
switch (Opt.second->getNumOccurrencesFlag()) {
case Required:
case OneOrMore:
if (Opt.second->getNumOccurrences() == 0) {
Opt.second->error("must be specified at least once!");
ErrorParsing = true;
}
LLVM_FALLTHROUGH;
default:
break;
}
}
LLVM_DEBUG(dbgs() << "Args: ";
for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
dbgs() << '\n';);
MoreHelp.clear();
if (ErrorParsing) {
if (!IgnoreErrors)
exit(1);
return false;
}
return true;
}
bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
if (!ArgName.data())
ArgName = ArgStr;
if (ArgName.empty())
Errs << HelpStr; else
Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0);
Errs << " option: " << Message << "\n";
return true;
}
bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
bool MultiArg) {
if (!MultiArg)
NumOccurrences++;
return handleOccurrence(pos, ArgName, Value);
}
static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
if (O.ValueStr.empty())
return DefaultMsg;
return O.ValueStr;
}
size_t alias::getOptionWidth() const {
return argPlusPrefixesSize(ArgStr);
}
void Option::printHelpStr(StringRef HelpStr, size_t Indent,
size_t FirstLineIndentedBy) {
assert(Indent >= FirstLineIndentedBy);
std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
outs().indent(Indent - FirstLineIndentedBy)
<< ArgHelpPrefix << Split.first << "\n";
while (!Split.second.empty()) {
Split = Split.second.split('\n');
outs().indent(Indent) << Split.first << "\n";
}
}
void Option::printEnumValHelpStr(StringRef HelpStr, size_t BaseIndent,
size_t FirstLineIndentedBy) {
const StringRef ValHelpPrefix = " ";
assert(BaseIndent >= FirstLineIndentedBy);
std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
outs().indent(BaseIndent - FirstLineIndentedBy)
<< ArgHelpPrefix << ValHelpPrefix << Split.first << "\n";
while (!Split.second.empty()) {
Split = Split.second.split('\n');
outs().indent(BaseIndent + ValHelpPrefix.size()) << Split.first << "\n";
}
}
void alias::printOptionInfo(size_t GlobalWidth) const {
outs() << PrintArg(ArgStr);
printHelpStr(HelpStr, GlobalWidth, argPlusPrefixesSize(ArgStr));
}
size_t basic_parser_impl::getOptionWidth(const Option &O) const {
size_t Len = argPlusPrefixesSize(O.ArgStr);
auto ValName = getValueName();
if (!ValName.empty()) {
size_t FormattingLen = 3;
if (O.getMiscFlags() & PositionalEatsArgs)
FormattingLen = 6;
Len += getValueStr(O, ValName).size() + FormattingLen;
}
return Len;
}
void basic_parser_impl::printOptionInfo(const Option &O,
size_t GlobalWidth) const {
outs() << PrintArg(O.ArgStr);
auto ValName = getValueName();
if (!ValName.empty()) {
if (O.getMiscFlags() & PositionalEatsArgs) {
outs() << " <" << getValueStr(O, ValName) << ">...";
} else if (O.getValueExpectedFlag() == ValueOptional)
outs() << "[=<" << getValueStr(O, ValName) << ">]";
else {
outs() << (O.ArgStr.size() == 1 ? " <" : "=<") << getValueStr(O, ValName)
<< '>';
}
}
Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
}
void basic_parser_impl::printOptionName(const Option &O,
size_t GlobalWidth) const {
outs() << PrintArg(O.ArgStr);
outs().indent(GlobalWidth - O.ArgStr.size());
}
bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
bool &Value) {
if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Arg == "1") {
Value = true;
return false;
}
if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
Value = false;
return false;
}
return O.error("'" + Arg +
"' is invalid value for boolean argument! Try 0 or 1");
}
bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
boolOrDefault &Value) {
if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Arg == "1") {
Value = BOU_TRUE;
return false;
}
if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
Value = BOU_FALSE;
return false;
}
return O.error("'" + Arg +
"' is invalid value for boolean argument! Try 0 or 1");
}
bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
int &Value) {
if (Arg.getAsInteger(0, Value))
return O.error("'" + Arg + "' value invalid for integer argument!");
return false;
}
bool parser<long>::parse(Option &O, StringRef ArgName, StringRef Arg,
long &Value) {
if (Arg.getAsInteger(0, Value))
return O.error("'" + Arg + "' value invalid for long argument!");
return false;
}
bool parser<long long>::parse(Option &O, StringRef ArgName, StringRef Arg,
long long &Value) {
if (Arg.getAsInteger(0, Value))
return O.error("'" + Arg + "' value invalid for llong argument!");
return false;
}
bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
unsigned &Value) {
if (Arg.getAsInteger(0, Value))
return O.error("'" + Arg + "' value invalid for uint argument!");
return false;
}
bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
unsigned long &Value) {
if (Arg.getAsInteger(0, Value))
return O.error("'" + Arg + "' value invalid for ulong argument!");
return false;
}
bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
StringRef Arg,
unsigned long long &Value) {
if (Arg.getAsInteger(0, Value))
return O.error("'" + Arg + "' value invalid for ullong argument!");
return false;
}
static bool parseDouble(Option &O, StringRef Arg, double &Value) {
if (to_float(Arg, Value))
return false;
return O.error("'" + Arg + "' value invalid for floating point argument!");
}
bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
double &Val) {
return parseDouble(O, Arg, Val);
}
bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
float &Val) {
double dVal;
if (parseDouble(O, Arg, dVal))
return true;
Val = (float)dVal;
return false;
}
unsigned generic_parser_base::findOption(StringRef Name) {
unsigned e = getNumOptions();
for (unsigned i = 0; i != e; ++i) {
if (getOption(i) == Name)
return i;
}
return e;
}
static StringRef EqValue = "=<value>";
static StringRef EmptyOption = "<empty>";
static StringRef OptionPrefix = " =";
static size_t getOptionPrefixesSize() {
return OptionPrefix.size() + ArgHelpPrefix.size();
}
static bool shouldPrintOption(StringRef Name, StringRef Description,
const Option &O) {
return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
!Description.empty();
}
size_t generic_parser_base::getOptionWidth(const Option &O) const {
if (O.hasArgStr()) {
size_t Size =
argPlusPrefixesSize(O.ArgStr) + EqValue.size();
for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
StringRef Name = getOption(i);
if (!shouldPrintOption(Name, getDescription(i), O))
continue;
size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
Size = std::max(Size, NameSize + getOptionPrefixesSize());
}
return Size;
} else {
size_t BaseSize = 0;
for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
BaseSize = std::max(BaseSize, getOption(i).size() + 8);
return BaseSize;
}
}
void generic_parser_base::printOptionInfo(const Option &O,
size_t GlobalWidth) const {
if (O.hasArgStr()) {
if (O.getValueExpectedFlag() == ValueOptional) {
for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
if (getOption(i).empty()) {
outs() << PrintArg(O.ArgStr);
Option::printHelpStr(O.HelpStr, GlobalWidth,
argPlusPrefixesSize(O.ArgStr));
break;
}
}
}
outs() << PrintArg(O.ArgStr) << EqValue;
Option::printHelpStr(O.HelpStr, GlobalWidth,
EqValue.size() +
argPlusPrefixesSize(O.ArgStr));
for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
StringRef OptionName = getOption(i);
StringRef Description = getDescription(i);
if (!shouldPrintOption(OptionName, Description, O))
continue;
size_t FirstLineIndent = OptionName.size() + getOptionPrefixesSize();
outs() << OptionPrefix << OptionName;
if (OptionName.empty()) {
outs() << EmptyOption;
assert(FirstLineIndent >= EmptyOption.size());
FirstLineIndent += EmptyOption.size();
}
if (!Description.empty())
Option::printEnumValHelpStr(Description, GlobalWidth, FirstLineIndent);
else
outs() << '\n';
}
} else {
if (!O.HelpStr.empty())
outs() << " " << O.HelpStr << '\n';
for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
StringRef Option = getOption(i);
outs() << " " << PrintArg(Option);
Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
}
}
}
static const size_t MaxOptWidth = 8;
void generic_parser_base::printGenericOptionDiff(
const Option &O, const GenericOptionValue &Value,
const GenericOptionValue &Default, size_t GlobalWidth) const {
outs() << " " << PrintArg(O.ArgStr);
outs().indent(GlobalWidth - O.ArgStr.size());
unsigned NumOpts = getNumOptions();
for (unsigned i = 0; i != NumOpts; ++i) {
if (Value.compare(getOptionValue(i)))
continue;
outs() << "= " << getOption(i);
size_t L = getOption(i).size();
size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
outs().indent(NumSpaces) << " (default: ";
for (unsigned j = 0; j != NumOpts; ++j) {
if (Default.compare(getOptionValue(j)))
continue;
outs() << getOption(j);
break;
}
outs() << ")\n";
return;
}
outs() << "= *unknown option value*\n";
}
#define PRINT_OPT_DIFF(T) \
void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
size_t GlobalWidth) const { \
printOptionName(O, GlobalWidth); \
std::string Str; \
{ \
raw_string_ostream SS(Str); \
SS << V; \
} \
outs() << "= " << Str; \
size_t NumSpaces = \
MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
outs().indent(NumSpaces) << " (default: "; \
if (D.hasValue()) \
outs() << D.getValue(); \
else \
outs() << "*no default*"; \
outs() << ")\n"; \
}
PRINT_OPT_DIFF(bool)
PRINT_OPT_DIFF(boolOrDefault)
PRINT_OPT_DIFF(int)
PRINT_OPT_DIFF(long)
PRINT_OPT_DIFF(long long)
PRINT_OPT_DIFF(unsigned)
PRINT_OPT_DIFF(unsigned long)
PRINT_OPT_DIFF(unsigned long long)
PRINT_OPT_DIFF(double)
PRINT_OPT_DIFF(float)
PRINT_OPT_DIFF(char)
void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
const OptionValue<std::string> &D,
size_t GlobalWidth) const {
printOptionName(O, GlobalWidth);
outs() << "= " << V;
size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
outs().indent(NumSpaces) << " (default: ";
if (D.hasValue())
outs() << D.getValue();
else
outs() << "*no default*";
outs() << ")\n";
}
void basic_parser_impl::printOptionNoValue(const Option &O,
size_t GlobalWidth) const {
printOptionName(O, GlobalWidth);
outs() << "= *cannot print option value*\n";
}
static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
const std::pair<const char *, Option *> *RHS) {
return strcmp(LHS->first, RHS->first);
}
static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
const std::pair<const char *, SubCommand *> *RHS) {
return strcmp(LHS->first, RHS->first);
}
static void sortOpts(StringMap<Option *> &OptMap,
SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
bool ShowHidden) {
SmallPtrSet<Option *, 32> OptionSet;
for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
I != E; ++I) {
if (I->second->getOptionHiddenFlag() == ReallyHidden)
continue;
if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
continue;
if (!OptionSet.insert(I->second).second)
continue;
Opts.push_back(
std::pair<const char *, Option *>(I->getKey().data(), I->second));
}
array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
}
static void
sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
for (auto *S : SubMap) {
if (S->getName().empty())
continue;
Subs.push_back(std::make_pair(S->getName().data(), S));
}
array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
}
namespace {
class HelpPrinter {
protected:
const bool ShowHidden;
typedef SmallVector<std::pair<const char *, Option *>, 128>
StrOptionPairVector;
typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
StrSubCommandPairVector;
virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
for (size_t i = 0, e = Opts.size(); i != e; ++i)
Opts[i].second->printOptionInfo(MaxArgLen);
}
void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
for (const auto &S : Subs) {
outs() << " " << S.first;
if (!S.second->getDescription().empty()) {
outs().indent(MaxSubLen - strlen(S.first));
outs() << " - " << S.second->getDescription();
}
outs() << "\n";
}
}
public:
explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
virtual ~HelpPrinter() = default;
void operator=(bool Value) {
if (!Value)
return;
printHelp();
exit(0);
}
void printHelp() {
SubCommand *Sub = GlobalParser->getActiveSubCommand();
auto &OptionsMap = Sub->OptionsMap;
auto &PositionalOpts = Sub->PositionalOpts;
auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
StrOptionPairVector Opts;
sortOpts(OptionsMap, Opts, ShowHidden);
StrSubCommandPairVector Subs;
sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
if (!GlobalParser->ProgramOverview.empty())
outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
if (Sub == &*TopLevelSubCommand) {
outs() << "USAGE: " << GlobalParser->ProgramName;
if (Subs.size() > 2)
outs() << " [subcommand]";
outs() << " [options]";
} else {
if (!Sub->getDescription().empty()) {
outs() << "SUBCOMMAND '" << Sub->getName()
<< "': " << Sub->getDescription() << "\n\n";
}
outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
<< " [options]";
}
for (auto *Opt : PositionalOpts) {
if (Opt->hasArgStr())
outs() << " --" << Opt->ArgStr;
outs() << " " << Opt->HelpStr;
}
if (ConsumeAfterOpt)
outs() << " " << ConsumeAfterOpt->HelpStr;
if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
size_t MaxSubLen = 0;
for (size_t i = 0, e = Subs.size(); i != e; ++i)
MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
outs() << "\n\n";
outs() << "SUBCOMMANDS:\n\n";
printSubCommands(Subs, MaxSubLen);
outs() << "\n";
outs() << " Type \"" << GlobalParser->ProgramName
<< " <subcommand> --help\" to get more help on a specific "
"subcommand";
}
outs() << "\n\n";
size_t MaxArgLen = 0;
for (size_t i = 0, e = Opts.size(); i != e; ++i)
MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
outs() << "OPTIONS:\n";
printOptions(Opts, MaxArgLen);
for (const auto &I : GlobalParser->MoreHelp)
outs() << I;
GlobalParser->MoreHelp.clear();
}
};
class CategorizedHelpPrinter : public HelpPrinter {
public:
explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
static int OptionCategoryCompare(OptionCategory *const *A,
OptionCategory *const *B) {
return (*A)->getName().compare((*B)->getName());
}
using HelpPrinter::operator=;
protected:
void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
std::vector<OptionCategory *> SortedCategories;
DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions;
for (OptionCategory *Category : GlobalParser->RegisteredOptionCategories)
SortedCategories.push_back(Category);
assert(SortedCategories.size() > 0 && "No option categories registered!");
array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
OptionCategoryCompare);
for (size_t I = 0, E = Opts.size(); I != E; ++I) {
Option *Opt = Opts[I].second;
for (auto &Cat : Opt->Categories) {
assert(llvm::is_contained(SortedCategories, Cat) &&
"Option has an unregistered category");
CategorizedOptions[Cat].push_back(Opt);
}
}
for (OptionCategory *Category : SortedCategories) {
const auto &CategoryOptions = CategorizedOptions[Category];
bool IsEmptyCategory = CategoryOptions.empty();
if (!ShowHidden && IsEmptyCategory)
continue;
outs() << "\n";
outs() << Category->getName() << ":\n";
if (!Category->getDescription().empty())
outs() << Category->getDescription() << "\n\n";
else
outs() << "\n";
if (IsEmptyCategory) {
outs() << " This option category has no options.\n";
continue;
}
for (const Option *Opt : CategoryOptions)
Opt->printOptionInfo(MaxArgLen);
}
}
};
class HelpPrinterWrapper {
private:
HelpPrinter &UncategorizedPrinter;
CategorizedHelpPrinter &CategorizedPrinter;
public:
explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
CategorizedHelpPrinter &CategorizedPrinter)
: UncategorizedPrinter(UncategorizedPrinter),
CategorizedPrinter(CategorizedPrinter) {}
void operator=(bool Value);
};
}
#if defined(__GNUC__)
# if defined(__OPTIMIZE__)
# define LLVM_IS_DEBUG_BUILD 0
# else
# define LLVM_IS_DEBUG_BUILD 1
# endif
#elif defined(_MSC_VER)
# if defined(_DEBUG)
# define LLVM_IS_DEBUG_BUILD 1
# else
# define LLVM_IS_DEBUG_BUILD 0
# endif
#else
# define LLVM_IS_DEBUG_BUILD 0
#endif
namespace {
class VersionPrinter {
public:
void print() {
raw_ostream &OS = outs();
#ifdef PACKAGE_VENDOR
OS << PACKAGE_VENDOR << " ";
#else
OS << "LLVM (http://llvm.org/):\n ";
#endif
OS << PACKAGE_NAME << " version " << PACKAGE_VERSION << "\n ";
#if LLVM_IS_DEBUG_BUILD
OS << "DEBUG build";
#else
OS << "Optimized build";
#endif
#ifndef NDEBUG
OS << " with assertions";
#endif
#if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
std::string CPU = std::string(sys::getHostCPUName());
if (CPU == "generic")
CPU = "(unknown)";
OS << ".\n"
<< " Default target: " << sys::getDefaultTargetTriple() << '\n'
<< " Host CPU: " << CPU;
#endif
OS << '\n';
}
void operator=(bool OptionWasSpecified);
};
struct CommandLineCommonOptions {
HelpPrinter UncategorizedNormalPrinter{false};
HelpPrinter UncategorizedHiddenPrinter{true};
CategorizedHelpPrinter CategorizedNormalPrinter{false};
CategorizedHelpPrinter CategorizedHiddenPrinter{true};
HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
CategorizedNormalPrinter};
HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
CategorizedHiddenPrinter};
cl::OptionCategory GenericCategory{"Generic Options"};
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)};
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)};
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)};
cl::alias HOpA{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
cl::DefaultOption};
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)};
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)};
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)};
VersionPrinterTy OverrideVersionPrinter = nullptr;
std::vector<VersionPrinterTy> ExtraVersionPrinters;
VersionPrinter VersionPrinterInstance;
cl::opt<VersionPrinter, true, parser<bool>> VersOp{
"version", cl::desc("Display the version of this program"),
cl::location(VersionPrinterInstance), cl::ValueDisallowed,
cl::cat(GenericCategory)};
};
}
static ManagedStatic<CommandLineCommonOptions> CommonOptions;
static void initCommonOptions() {
*CommonOptions;
initDebugCounterOptions();
initGraphWriterOptions();
initSignalsOptions();
initStatisticOptions();
initTimerOptions();
initTypeSizeOptions();
initWithColorOptions();
initDebugOptions();
initRandomSeedOptions();
}
OptionCategory &cl::getGeneralCategory() {
static OptionCategory GeneralCategory{"General options"};
return GeneralCategory;
}
void VersionPrinter::operator=(bool OptionWasSpecified) {
if (!OptionWasSpecified)
return;
if (CommonOptions->OverrideVersionPrinter != nullptr) {
CommonOptions->OverrideVersionPrinter(outs());
exit(0);
}
print();
if (!CommonOptions->ExtraVersionPrinters.empty()) {
outs() << '\n';
for (const auto &I : CommonOptions->ExtraVersionPrinters)
I(outs());
}
exit(0);
}
void HelpPrinterWrapper::operator=(bool Value) {
if (!Value)
return;
if (GlobalParser->RegisteredOptionCategories.size() > 1) {
CommonOptions->HLOp.setHiddenFlag(NotHidden);
CategorizedPrinter = true; } else
UncategorizedPrinter = true; }
void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
void CommandLineParser::printOptionValues() {
if (!CommonOptions->PrintOptions && !CommonOptions->PrintAllOptions)
return;
SmallVector<std::pair<const char *, Option *>, 128> Opts;
sortOpts(ActiveSubCommand->OptionsMap, Opts, true);
size_t MaxArgLen = 0;
for (size_t i = 0, e = Opts.size(); i != e; ++i)
MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
for (size_t i = 0, e = Opts.size(); i != e; ++i)
Opts[i].second->printOptionValue(MaxArgLen, CommonOptions->PrintAllOptions);
}
void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
if (!Hidden && !Categorized)
CommonOptions->UncategorizedNormalPrinter.printHelp();
else if (!Hidden && Categorized)
CommonOptions->CategorizedNormalPrinter.printHelp();
else if (Hidden && !Categorized)
CommonOptions->UncategorizedHiddenPrinter.printHelp();
else
CommonOptions->CategorizedHiddenPrinter.printHelp();
}
void cl::PrintVersionMessage() {
CommonOptions->VersionPrinterInstance.print();
}
void cl::SetVersionPrinter(VersionPrinterTy func) {
CommonOptions->OverrideVersionPrinter = func;
}
void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
CommonOptions->ExtraVersionPrinters.push_back(func);
}
StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
initCommonOptions();
auto &Subs = GlobalParser->RegisteredSubCommands;
(void)Subs;
assert(is_contained(Subs, &Sub));
return Sub.OptionsMap;
}
iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
cl::getRegisteredSubcommands() {
return GlobalParser->getRegisteredSubcommands();
}
void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
initCommonOptions();
for (auto &I : Sub.OptionsMap) {
bool Unrelated = true;
for (auto &Cat : I.second->Categories) {
if (Cat == &Category || Cat == &CommonOptions->GenericCategory)
Unrelated = false;
}
if (Unrelated)
I.second->setHiddenFlag(cl::ReallyHidden);
}
}
void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
SubCommand &Sub) {
initCommonOptions();
for (auto &I : Sub.OptionsMap) {
bool Unrelated = true;
for (auto &Cat : I.second->Categories) {
if (is_contained(Categories, Cat) ||
Cat == &CommonOptions->GenericCategory)
Unrelated = false;
}
if (Unrelated)
I.second->setHiddenFlag(cl::ReallyHidden);
}
}
void cl::ResetCommandLineParser() { GlobalParser->reset(); }
void cl::ResetAllOptionOccurrences() {
GlobalParser->ResetAllOptionOccurrences();
}
void LLVMParseCommandLineOptions(int argc, const char *const *argv,
const char *Overview) {
llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
&llvm::nulls());
}