35 explicit OptNameLess(
const StringTable &StrTable,
37 : StrTable(&StrTable), PrefixesTable(PrefixesTable) {}
40 inline bool operator()(
const OptTable::Info &
A,
41 const OptTable::Info &
B)
const {
46 B.getName(*StrTable, PrefixesTable)))
50 A.appendPrefixes(*StrTable, PrefixesTable, APrefixes);
51 B.appendPrefixes(*StrTable, PrefixesTable, BPrefixes);
60 "Unexpected classes for options with same name.");
66 inline bool operator()(
const OptTable::Info &
I, StringRef Name)
const {
77 : StrTable(
T.StrTable), PrefixesTable(
T.PrefixesTable),
78 OptionInfos(
T.Infos), InfoExtrasTable(
T.InfoExtras),
79 IgnoreCase(IgnoreCase), SubCommands(
T.SubCommands),
80 SubCommandIDsTable(
T.SubCommandIDs),
81 HelpTextVariantsTable(
T.HelpTextVariants) {
83 for (
unsigned I = 0, E = PrefixesTable.size();
I != E;) {
84 unsigned Size = PrefixesTable[I++].value();
85 for (unsigned J = 0; J != Size; ++J) {
86 StringRef Prefix = StrTable[PrefixesTable[I++]];
87 if (is_contained(PrefixesUnion, Prefix))
89 PrefixesUnion.push_back(Prefix);
91 if (!is_contained(PrefixChars, C))
92 PrefixChars.push_back(C);
97 for (
unsigned i = 0, e = getNumOptions(); i != e; ++i) {
98 unsigned Kind = getInfo(i + 1).Kind;
100 assert(!InputOptionID &&
"Cannot have multiple input options!");
101 InputOptionID = i + 1;
103 assert(!UnknownOptionID &&
"Cannot have multiple unknown options!");
104 UnknownOptionID = i + 1;
106 FirstSearchableIndex = i;
110 assert(FirstSearchableIndex != 0 &&
"No searchable options?");
115 for (
unsigned i = FirstSearchableIndex, e = getNumOptions(); i !=
e; ++i) {
119 "Special options should be defined first!");
123 for (
unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i !=
e; ++i){
124 if (!(OptNameLess(StrTable, PrefixesTable)(getInfo(i), getInfo(i + 1)))) {
126 getOption(i + 1).dump();
136 unsigned id = Opt.
getID();
138 return Option(
nullptr,
nullptr);
140 return Option(&getInfo(
id),
this);
147 if (
Arg.starts_with(Prefix))
157 StringRef Name =
I->getName(StrTable, PrefixesTable);
158 for (
auto PrefixOffset :
I->getPrefixOffsets(PrefixesTable)) {
159 StringRef Prefix = StrTable[PrefixOffset];
160 if (Str.starts_with(Prefix)) {
165 return Prefix.size() + Name.size();
175 StringRef Name = In.getName(StrTable, PrefixesTable);
176 if (
Option.consume_back(Name))
177 for (
auto PrefixOffset : In.getPrefixOffsets(PrefixesTable))
178 if (
Option == StrTable[PrefixOffset])
186std::vector<std::string>
189 for (
size_t I = FirstSearchableIndex, E = OptionInfos.size();
I < E;
I++) {
190 const Info &In = OptionInfos[
I];
198 Values.split(Candidates,
",", -1,
false);
200 std::vector<std::string> Result;
202 if (Val.starts_with(
Arg) &&
Arg != Val)
203 Result.push_back(std::string(Val));
209std::vector<std::string>
211 unsigned int DisableFlags)
const {
212 std::vector<std::string> Ret;
213 for (
size_t I = FirstSearchableIndex, E = OptionInfos.size();
I < E;
I++) {
214 const Info &In = OptionInfos[
I];
215 if (In.hasNoPrefix() || (!In.hasHelpText() && !In.GroupID))
220 if (Extra.
Flags & DisableFlags)
223 StringRef Name = In.getName(StrTable, PrefixesTable);
224 for (
auto PrefixOffset : In.getPrefixOffsets(PrefixesTable)) {
225 StringRef Prefix = StrTable[PrefixOffset];
226 std::string S = (
Twine(Prefix) + Name +
"\t").str();
227 S += StrTable[In.HelpTextOffset];
237 unsigned MinimumLength,
238 unsigned MaximumDistance)
const {
239 return internalFindNearest(
240 Option, NearestString, MinimumLength, MaximumDistance,
241 [
this, VisibilityMask](
const Info &CandidateInfo) {
247 unsigned FlagsToInclude,
unsigned FlagsToExclude,
248 unsigned MinimumLength,
249 unsigned MaximumDistance)
const {
250 return internalFindNearest(
251 Option, NearestString, MinimumLength, MaximumDistance,
252 [
this, FlagsToInclude, FlagsToExclude](
const Info &CandidateInfo) {
254 if (FlagsToInclude && !(Flags & FlagsToInclude))
256 if (Flags & FlagsToExclude)
262unsigned OptTable::internalFindNearest(
264 unsigned MaximumDistance,
265 std::function<
bool(
const Info &)> ExcludeOption)
const {
268 unsigned BestDistance =
269 MaximumDistance == UINT_MAX ? UINT_MAX : MaximumDistance + 1;
273 for (
const Info &CandidateInfo :
275 StringRef CandidateName = CandidateInfo.getName(StrTable, PrefixesTable);
280 if (CandidateName.
size() < MinimumLength)
284 if (ExcludeOption(CandidateInfo))
289 if (CandidateInfo.hasNoPrefix())
296 bool CandidateHasDelimiter =
Last ==
'=' ||
Last ==
':';
298 if (CandidateHasDelimiter) {
299 std::tie(NormalizedName, RHS) =
Option.split(
Last);
301 NormalizedName +=
Last;
304 NormalizedName =
Option.split(
'=').first;
305 RHS =
Option.drop_front(NormalizedName.
size());
312 for (
auto CandidatePrefixOffset :
313 CandidateInfo.getPrefixOffsets(PrefixesTable)) {
314 StringRef CandidatePrefix = StrTable[CandidatePrefixOffset];
319 size_t CandidateSize = CandidatePrefix.
size() + CandidateName.
size(),
320 NormalizedSize = NormalizedName.
size();
321 size_t AbsDiff = CandidateSize > NormalizedSize
322 ? CandidateSize - NormalizedSize
323 : NormalizedSize - CandidateSize;
324 if (AbsDiff > BestDistance) {
327 Candidate = CandidatePrefix;
328 Candidate += CandidateName;
330 NormalizedName,
true,
332 if (
RHS.empty() && CandidateHasDelimiter) {
341 if (Distance < BestDistance) {
342 BestDistance = Distance;
343 NearestString = (Candidate +
RHS).str();
354std::unique_ptr<Arg> OptTable::parseOneArgGrouped(
InputArgList &Args,
355 unsigned &Index)
const {
358 const char *CStr =
Args.getArgString(Index);
360 if (
isInput(PrefixesUnion, Str))
361 return std::make_unique<Arg>(
getOption(InputOptionID), Str, Index++, CStr);
363 const Info *End = OptionInfos.data() + OptionInfos.size();
364 StringRef
Name = Str.ltrim(PrefixChars);
366 std::lower_bound(OptionInfos.data() + FirstSearchableIndex, End, Name,
367 OptNameLess(StrTable, PrefixesTable));
369 unsigned Prev =
Index;
374 matchOption(StrTable, PrefixesTable, Start, Str, IgnoreCase);
378 Option Opt(Start,
this);
379 if (std::unique_ptr<Arg>
A =
380 Opt.accept(Args, StringRef(
Args.getArgString(Index), ArgSize),
398 return std::make_unique<Arg>(
getOption(UnknownOptionID), Str, Index++,
401 if (std::unique_ptr<Arg>
A = Opt.accept(
402 Args, Str.substr(0, 2),
true, Index)) {
403 Args.replaceArgString(Index, Twine(
'-') + Str.substr(2));
411 CStr =
Args.MakeArgString(Str.substr(0, 2));
412 Args.replaceArgString(Index, Twine(
'-') + Str.substr(2));
413 return std::make_unique<Arg>(
getOption(UnknownOptionID), CStr, Index, CStr);
416 return std::make_unique<Arg>(
getOption(UnknownOptionID), Str, Index++, CStr);
421 return internalParseOneArg(Args, Index, [VisibilityMask](
const Option &Opt) {
427 unsigned FlagsToInclude,
428 unsigned FlagsToExclude)
const {
429 return internalParseOneArg(
430 Args, Index, [FlagsToInclude, FlagsToExclude](
const Option &Opt) {
431 if (FlagsToInclude && !Opt.
hasFlag(FlagsToInclude))
433 if (Opt.
hasFlag(FlagsToExclude))
439std::unique_ptr<Arg> OptTable::internalParseOneArg(
440 const ArgList &Args,
unsigned &Index,
441 std::function<
bool(
const Option &)> ExcludeOption)
const {
442 unsigned Prev = Index;
443 StringRef Str = Args.getArgString(Index);
447 if (
isInput(PrefixesUnion, Str))
448 return std::make_unique<Arg>(
getOption(InputOptionID), Str, Index++,
451 const Info *Start = OptionInfos.data() + FirstSearchableIndex;
452 const Info *End = OptionInfos.data() + OptionInfos.size();
457 std::lower_bound(Start, End, Name, OptNameLess(StrTable, PrefixesTable));
467 for (; Start != End; ++Start) {
468 unsigned ArgSize = 0;
470 for (; Start != End; ++Start)
472 matchOption(StrTable, PrefixesTable, Start, Str, IgnoreCase)))
479 if (ExcludeOption(Opt))
483 if (std::unique_ptr<Arg>
A =
484 Opt.accept(Args,
StringRef(Args.getArgString(Index), ArgSize),
496 return std::make_unique<Arg>(
getOption(InputOptionID), Str, Index++,
499 return std::make_unique<Arg>(
getOption(UnknownOptionID), Str, Index++,
504 unsigned &MissingArgIndex,
505 unsigned &MissingArgCount,
507 return internalParseArgs(
508 Args, MissingArgIndex, MissingArgCount,
509 [VisibilityMask](
const Option &Opt) {
515 unsigned &MissingArgIndex,
516 unsigned &MissingArgCount,
517 unsigned FlagsToInclude,
518 unsigned FlagsToExclude)
const {
519 return internalParseArgs(
520 Args, MissingArgIndex, MissingArgCount,
521 [FlagsToInclude, FlagsToExclude](
const Option &Opt) {
522 if (FlagsToInclude && !Opt.
hasFlag(FlagsToInclude))
524 if (Opt.
hasFlag(FlagsToExclude))
532 unsigned &MissingArgCount,
533 std::function<
bool(
const Option &)> ExcludeOption)
const {
538 MissingArgIndex = MissingArgCount = 0;
539 unsigned Index = 0, End = ArgArr.
size();
540 while (Index < End) {
542 if (Args.getArgString(Index) ==
nullptr) {
547 StringRef Str = Args.getArgString(Index);
555 if (DashDashParsing && Str ==
"--") {
556 while (++Index < End) {
557 Args.append(
new Arg(
getOption(InputOptionID), Str, Index,
558 Args.getArgString(Index)));
563 unsigned Prev =
Index;
564 std::unique_ptr<Arg>
A = GroupedShortOptions
565 ? parseOneArgGrouped(Args, Index)
566 : internalParseOneArg(
Args,
Index, ExcludeOption);
567 assert((Index > Prev || GroupedShortOptions) &&
568 "Parser failed to consume argument.");
572 assert(Index >= End &&
"Unexpected parser error.");
573 assert(Index - Prev - 1 &&
"No missing arguments!");
574 MissingArgIndex = Prev;
575 MissingArgCount =
Index - Prev - 1;
579 Args.append(
A.release());
587 std::function<
void(
StringRef)> ErrorFn)
const {
596 ErrorFn((
Twine(Args.getArgString(MAI)) +
": missing argument").str());
602 std::string
Spelling =
A->getAsString(Args);
604 ErrorFn(
"unknown argument '" +
Spelling +
"'");
606 ErrorFn(
"unknown argument '" +
Spelling +
"', did you mean '" + Nearest +
614 std::string Name = O.getPrefixedName().str();
617 switch (O.getKind()) {
623 !MetaVarName.
empty()) {
629 for (
unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
674 std::vector<OptionInfo> &OptionHelp) {
675 OS << Title <<
":\n";
678 unsigned OptionFieldWidth = 0;
679 for (
const OptionInfo &Opt : OptionHelp) {
681 unsigned Length = Opt.Name.size();
683 OptionFieldWidth = std::max(OptionFieldWidth,
Length);
686 const unsigned InitialPad = 2;
687 for (
const OptionInfo &Opt : OptionHelp) {
688 const std::string &
Option = Opt.Name;
689 int Pad = OptionFieldWidth + InitialPad;
690 int FirstLinePad = OptionFieldWidth - int(
Option.size());
694 if (FirstLinePad < 0) {
696 FirstLinePad = OptionFieldWidth + InitialPad;
701 Opt.HelpText.split(Lines,
'\n');
702 assert(Lines.size() &&
"Expected at least the first line in the help text");
703 auto *LinesIt = Lines.begin();
704 OS.
indent(FirstLinePad + 1) << *LinesIt <<
'\n';
705 while (Lines.end() != ++LinesIt)
706 OS.
indent(Pad + 1) << *LinesIt <<
'\n';
729 bool ShowHidden,
bool ShowAllAliases,
732 return internalPrintHelp(
733 OS, Usage, Title,
SubCommand, ShowHidden, ShowAllAliases,
734 [
this, VisibilityMask](
const Info &CandidateInfo) ->
bool {
741 unsigned FlagsToInclude,
unsigned FlagsToExclude,
742 bool ShowAllAliases)
const {
743 bool ShowHidden = !(FlagsToExclude &
HelpHidden);
745 return internalPrintHelp(
746 OS, Usage, Title, {}, ShowHidden, ShowAllAliases,
747 [
this, FlagsToInclude, FlagsToExclude](
const Info &CandidateInfo) {
749 if (FlagsToInclude && !(Flags & FlagsToInclude))
751 if (Flags & FlagsToExclude)
758void OptTable::internalPrintHelp(
760 bool ShowHidden,
bool ShowAllAliases,
761 std::function<
bool(
const Info &)> ExcludeOption,
763 OS <<
"OVERVIEW: " << Title <<
"\n\n";
767 std::map<StringRef, std::vector<OptionInfo>> GroupedOptionHelp;
770 SubCommands, [&](
const auto &
C) {
return SubCommand ==
C.Name; });
771 if (!SubCommand.
empty()) {
772 assert(ActiveSubCommand != SubCommands.end() &&
773 "Not a valid registered subcommand.");
774 OS << ActiveSubCommand->HelpText <<
"\n\n";
776 OS <<
"USAGE: " << ActiveSubCommand->Usage <<
"\n\n";
778 OS <<
"USAGE: " << Usage <<
"\n\n";
779 if (SubCommands.size() > 1) {
780 OS <<
"SUBCOMMANDS:\n\n";
781 for (
const auto &
C : SubCommands)
782 OS <<
C.Name <<
" - " <<
C.HelpText <<
"\n";
787 auto DoesOptionBelongToSubcommand = [&](
const Info &CandidateInfo) {
790 ArrayRef<unsigned> SubCommandIDs = getSubCommandIDs(CandidateInfo);
795 if (SubCommandIDs.
empty())
806 unsigned ActiveSubCommandID = ActiveSubCommand - &SubCommands[0];
817 const Info &CandidateInfo = getInfo(Id);
821 if (ExcludeOption(CandidateInfo))
824 if (!DoesOptionBelongToSubcommand(CandidateInfo))
829 StringTable::Offset HelpTextOffset =
830 getHelpTextOffset(CandidateInfo, VisibilityMask);
831 if (!HelpTextOffset.
value() && ShowAllAliases) {
835 getHelpTextOffset(getInfo(Alias.
getID()), VisibilityMask);
838 if (StringRef HelpText = StrTable[HelpTextOffset]; !HelpText.empty()) {
841 GroupedOptionHelp[HelpGroup].push_back({OptName, HelpText});
845 for (
auto& OptionGroup : GroupedOptionHelp) {
846 if (OptionGroup.first != GroupedOptionHelp.begin()->first)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Defines the llvm::Arg class for parsed arguments.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static unsigned matchOption(const StringTable &StrTable, ArrayRef< StringTable::Offset > PrefixesTable, const OptTable::Info *I, StringRef Str, bool IgnoreCase)
static bool optionMatches(const StringTable &StrTable, ArrayRef< StringTable::Offset > PrefixesTable, const OptTable::Info &In, StringRef Option)
static StringRef getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id)
static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id)
static bool isInput(const ArrayRef< StringRef > &Prefixes, StringRef Arg)
static void PrintHelpOptionList(raw_ostream &OS, StringRef Title, std::vector< OptionInfo > &OptionHelp)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
Check if the string is empty.
LLVM_ABI bool starts_with_insensitive(StringRef Prefix) const
Check if this string starts with the given Prefix, ignoring case.
LLVM_ABI unsigned edit_distance(StringRef Other, bool AllowReplacements=true, unsigned MaxEditDistance=0) const
Determine the edit distance between this string and another string.
char back() const
Get the last character in the string.
constexpr size_t size() const
Get the string size.
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
constexpr unsigned value() const
A table of densely packed, null-terminated strings indexed by offset.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
ArgList - Ordered collection of driver arguments.
A concrete instance of a particular driver option.
OptSpecifier - Wrapper class for abstracting references to option IDs.
Provide access to the Option info table.
InputArgList parseArgs(int Argc, char *const *Argv, OptSpecifier Unknown, StringSaver &Saver, std::function< void(StringRef)> ErrorFn) const
A convenience helper which handles optional initial options populated from an environment variable,...
unsigned getOptionKind(OptSpecifier id) const
Get the kind of the given option.
std::unique_ptr< Arg > ParseOneArg(const ArgList &Args, unsigned &Index, Visibility VisibilityMask=Visibility()) const
Parse a single argument; returning the new argument and updating Index.
unsigned findNearest(StringRef Option, std::string &NearestString, Visibility VisibilityMask=Visibility(), unsigned MinimumLength=4, unsigned MaximumDistance=UINT_MAX) const
Find the OptTable option that most closely matches the given string.
const Option getOption(OptSpecifier Opt) const
Get the given Opt's Option instance, lazily creating it if necessary.
unsigned getOptionGroupID(OptSpecifier id) const
Get the group id for the given option.
StringRef getOptionMetaVar(OptSpecifier id) const
Get the meta-variable name to use when describing this options values in the help text.
const InfoExtra & getExtra(const Info &I) const
OptTable(const Tables &Tables, bool IgnoreCase=false)
std::vector< std::string > suggestValueCompletions(StringRef Option, StringRef Arg) const
Find possible value for given flags.
InputArgList ParseArgs(ArrayRef< const char * > Args, unsigned &MissingArgIndex, unsigned &MissingArgCount, Visibility VisibilityMask=Visibility()) const
Parse an list of arguments into an InputArgList.
void printHelp(raw_ostream &OS, const char *Usage, const char *Title, bool ShowHidden=false, bool ShowAllAliases=false, Visibility VisibilityMask=Visibility(), StringRef SubCommand={}) const
Render the help text for an option table.
unsigned getNumOptions() const
Return the total number of option classes.
StringRef getOptionHelpText(OptSpecifier id) const
Get the help text to use to describe this option.
std::vector< std::string > findByPrefix(StringRef Cur, Visibility VisibilityMask, unsigned int DisableFlags) const
Find flags from OptTable which starts with Cur.
Option - Abstract representation for a single form of driver argument.
const Option getAlias() const
bool hasFlag(unsigned Val) const
Test if this option has the flag Val.
@ RemainingArgsJoinedClass
bool hasVisibilityFlag(unsigned Val) const
Test if this option has the visibility flag Val.
Helper for overload resolution while transitioning from FlagsToInclude/FlagsToExclude APIs to Visibil...
This class implements an extremely fast bulk output stream that can only output to a stream.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
LLVM_ABI bool expandResponseFiles(int Argc, const char *const *Argv, const char *EnvVar, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv)
A convenience helper which concatenates the options specified by the environment variable EnvVar and ...
This is an optimization pass for GlobalISel generic memory operations.
RelativeUniformCounterPtr Values
@ Unknown
Not known to have no common set bits.
LLVM_ABI int StrCmpOptionName(StringRef A, StringRef B, bool FallbackCaseSensitive=true)
LLVM_ABI int StrCmpOptionPrefixes(ArrayRef< StringRef > APrefixes, ArrayRef< StringRef > BPrefixes)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
ArrayRef(const T &OneElt) -> ArrayRef< T >
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Entry for a single option instance in the option data table.
Represents a subcommand and its options in the option table.
The tables TableGen emits for an option set under OPTTABLE_CODE.