LLVM 24.0.0git
OptTable.cpp
Go to the documentation of this file.
1//===- OptTable.cpp - Option Table Implementation -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "llvm/ADT/STLExtras.h"
11#include "llvm/ADT/StringRef.h"
12#include "llvm/Option/Arg.h"
13#include "llvm/Option/ArgList.h"
15#include "llvm/Option/Option.h"
16#include "llvm/Support/CommandLine.h" // for expandResponseFiles
21#include <algorithm>
22#include <cassert>
23#include <map>
24#include <string>
25#include <vector>
26
27using namespace llvm;
28using namespace llvm::opt;
29
30namespace {
31struct OptNameLess {
32 const StringTable *StrTable;
34
35 explicit OptNameLess(const StringTable &StrTable,
37 : StrTable(&StrTable), PrefixesTable(PrefixesTable) {}
38
39#ifndef NDEBUG
40 inline bool operator()(const OptTable::Info &A,
41 const OptTable::Info &B) const {
42 if (&A == &B)
43 return false;
44
45 if (int Cmp = StrCmpOptionName(A.getName(*StrTable, PrefixesTable),
46 B.getName(*StrTable, PrefixesTable)))
47 return Cmp < 0;
48
49 SmallVector<StringRef, 8> APrefixes, BPrefixes;
50 A.appendPrefixes(*StrTable, PrefixesTable, APrefixes);
51 B.appendPrefixes(*StrTable, PrefixesTable, BPrefixes);
52
53 if (int Cmp = StrCmpOptionPrefixes(APrefixes, BPrefixes))
54 return Cmp < 0;
55
56 // Names are the same, check that classes are in order; exactly one
57 // should be joined, and it should succeed the other.
58 assert(
59 ((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
60 "Unexpected classes for options with same name.");
61 return B.Kind == Option::JoinedClass;
62 }
63#endif
64
65 // Support lower_bound between info and an option name.
66 inline bool operator()(const OptTable::Info &I, StringRef Name) const {
67 // Do not fallback to case sensitive comparison.
68 return StrCmpOptionName(I.getName(*StrTable, PrefixesTable), Name, false) <
69 0;
70 }
71};
72} // namespace
73
74OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
75
76OptTable::OptTable(const Tables &T, bool IgnoreCase)
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) {
82 // Each prefix set in PrefixesTable starts with its size.
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))
88 continue;
89 PrefixesUnion.push_back(Prefix);
90 for (char C : Prefix)
91 if (!is_contained(PrefixChars, C))
92 PrefixChars.push_back(C);
93 }
94 }
95
96 // Find start of normal options.
97 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
98 unsigned Kind = getInfo(i + 1).Kind;
99 if (Kind == Option::InputClass) {
100 assert(!InputOptionID && "Cannot have multiple input options!");
101 InputOptionID = i + 1;
102 } else if (Kind == Option::UnknownClass) {
103 assert(!UnknownOptionID && "Cannot have multiple unknown options!");
104 UnknownOptionID = i + 1;
105 } else if (Kind != Option::GroupClass) {
106 FirstSearchableIndex = i;
107 break;
108 }
109 }
110 assert(FirstSearchableIndex != 0 && "No searchable options?");
111
112#ifndef NDEBUG
113 // Check that everything after the first searchable option is a
114 // regular option class.
115 for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
116 Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
117 assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
118 Kind != Option::GroupClass) &&
119 "Special options should be defined first!");
120 }
121
122 // Check that options are in order.
123 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
124 if (!(OptNameLess(StrTable, PrefixesTable)(getInfo(i), getInfo(i + 1)))) {
125 getOption(i).dump();
126 getOption(i + 1).dump();
127 llvm_unreachable("Options are not in order!");
128 }
129 }
130#endif
131}
132
133OptTable::~OptTable() = default;
134
136 unsigned id = Opt.getID();
137 if (id == 0)
138 return Option(nullptr, nullptr);
139 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
140 return Option(&getInfo(id), this);
141}
142
143static bool isInput(const ArrayRef<StringRef> &Prefixes, StringRef Arg) {
144 if (Arg == "-")
145 return true;
146 for (const StringRef &Prefix : Prefixes)
147 if (Arg.starts_with(Prefix))
148 return false;
149 return true;
150}
151
152/// \returns Matched size. 0 means no match.
153static unsigned matchOption(const StringTable &StrTable,
154 ArrayRef<StringTable::Offset> PrefixesTable,
155 const OptTable::Info *I, StringRef Str,
156 bool IgnoreCase) {
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)) {
161 StringRef Rest = Str.substr(Prefix.size());
162 bool Matched = IgnoreCase ? Rest.starts_with_insensitive(Name)
163 : Rest.starts_with(Name);
164 if (Matched)
165 return Prefix.size() + Name.size();
166 }
167 }
168 return 0;
169}
170
171// Returns true if one of the Prefixes + In.Names matches Option
172static bool optionMatches(const StringTable &StrTable,
173 ArrayRef<StringTable::Offset> PrefixesTable,
174 const OptTable::Info &In, StringRef Option) {
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])
179 return true;
180 return false;
181}
182
183// This function is for flag value completion.
184// Eg. When "-stdlib=" and "l" was passed to this function, it will return
185// appropiriate values for stdlib, which starts with l.
186std::vector<std::string>
188 // Search all options and return possible values.
189 for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
190 const Info &In = OptionInfos[I];
191 if (!optionMatches(StrTable, PrefixesTable, In, Option))
192 continue;
193 StringRef Values = getOptionValues(In);
194 if (Values.empty())
195 continue;
196
197 SmallVector<StringRef, 8> Candidates;
198 Values.split(Candidates, ",", -1, false);
199
200 std::vector<std::string> Result;
201 for (StringRef Val : Candidates)
202 if (Val.starts_with(Arg) && Arg != Val)
203 Result.push_back(std::string(Val));
204 return Result;
205 }
206 return {};
207}
208
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))
216 continue;
217 const InfoExtra &Extra = getExtra(In);
218 if (!(Extra.Visibility & VisibilityMask))
219 continue;
220 if (Extra.Flags & DisableFlags)
221 continue;
222
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];
228 if (StringRef(S).starts_with(Cur) && S != std::string(Cur) + "\t")
229 Ret.push_back(S);
230 }
231 }
232 return Ret;
233}
234
235unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
236 Visibility VisibilityMask,
237 unsigned MinimumLength,
238 unsigned MaximumDistance) const {
239 return internalFindNearest(
240 Option, NearestString, MinimumLength, MaximumDistance,
241 [this, VisibilityMask](const Info &CandidateInfo) {
242 return (getExtra(CandidateInfo).Visibility & VisibilityMask) == 0;
243 });
244}
245
246unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
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) {
253 unsigned Flags = getExtra(CandidateInfo).Flags;
254 if (FlagsToInclude && !(Flags & FlagsToInclude))
255 return true;
256 if (Flags & FlagsToExclude)
257 return true;
258 return false;
259 });
260}
261
262unsigned OptTable::internalFindNearest(
263 StringRef Option, std::string &NearestString, unsigned MinimumLength,
264 unsigned MaximumDistance,
265 std::function<bool(const Info &)> ExcludeOption) const {
266 // Consider each [option prefix + option name] pair as a candidate, finding
267 // the closest match.
268 unsigned BestDistance =
269 MaximumDistance == UINT_MAX ? UINT_MAX : MaximumDistance + 1;
270 SmallString<16> Candidate;
271 SmallString<16> NormalizedName;
272
273 for (const Info &CandidateInfo :
274 ArrayRef<Info>(OptionInfos).drop_front(FirstSearchableIndex)) {
275 StringRef CandidateName = CandidateInfo.getName(StrTable, PrefixesTable);
276
277 // We can eliminate some option prefix/name pairs as candidates right away:
278 // * Ignore option candidates with empty names, such as "--", or names
279 // that do not meet the minimum length.
280 if (CandidateName.size() < MinimumLength)
281 continue;
282
283 // Ignore options that are excluded via masks
284 if (ExcludeOption(CandidateInfo))
285 continue;
286
287 // * Ignore positional argument option candidates (which do not
288 // have prefixes).
289 if (CandidateInfo.hasNoPrefix())
290 continue;
291
292 // Now check if the candidate ends with a character commonly used when
293 // delimiting an option from its value, such as '=' or ':'. If it does,
294 // attempt to split the given option based on that delimiter.
295 char Last = CandidateName.back();
296 bool CandidateHasDelimiter = Last == '=' || Last == ':';
297 StringRef RHS;
298 if (CandidateHasDelimiter) {
299 std::tie(NormalizedName, RHS) = Option.split(Last);
300 if (Option.find(Last) == NormalizedName.size())
301 NormalizedName += Last;
302 } else if (CandidateInfo.Kind == opt::Option::FlagOrEqClass ||
303 CandidateInfo.Kind == opt::Option::SeparateOrEqClass) {
304 NormalizedName = Option.split('=').first;
305 RHS = Option.drop_front(NormalizedName.size());
306 } else
307 NormalizedName = Option;
308
309 // Consider each possible prefix for each candidate to find the most
310 // appropriate one. For example, if a user asks for "--helm", suggest
311 // "--help" over "-help".
312 for (auto CandidatePrefixOffset :
313 CandidateInfo.getPrefixOffsets(PrefixesTable)) {
314 StringRef CandidatePrefix = StrTable[CandidatePrefixOffset];
315 // If Candidate and NormalizedName have more than 'BestDistance'
316 // characters of difference, no need to compute the edit distance, it's
317 // going to be greater than BestDistance. Don't bother computing Candidate
318 // at all.
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) {
325 continue;
326 }
327 Candidate = CandidatePrefix;
328 Candidate += CandidateName;
329 unsigned Distance = StringRef(Candidate).edit_distance(
330 NormalizedName, /*AllowReplacements=*/true,
331 /*MaxEditDistance=*/BestDistance);
332 if (RHS.empty() && CandidateHasDelimiter) {
333 // The Candidate ends with a = or : delimiter, but the option passed in
334 // didn't contain the delimiter (or doesn't have anything after it).
335 // In that case, penalize the correction: `-nodefaultlibs` is more
336 // likely to be a spello for `-nodefaultlib` than `-nodefaultlib:` even
337 // though both have an unmodified editing distance of 1, since the
338 // latter would need an argument.
339 ++Distance;
340 }
341 if (Distance < BestDistance) {
342 BestDistance = Distance;
343 NearestString = (Candidate + RHS).str();
344 }
345 }
346 }
347 return BestDistance;
348}
349
350// Parse a single argument, return the new argument, and update Index. If
351// GroupedShortOptions is true, -a matches "-abc" and the argument in Args will
352// be updated to "-bc". This overload does not support VisibilityMask or case
353// insensitive options.
354std::unique_ptr<Arg> OptTable::parseOneArgGrouped(InputArgList &Args,
355 unsigned &Index) const {
356 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
357 // itself.
358 const char *CStr = Args.getArgString(Index);
359 StringRef Str(CStr);
360 if (isInput(PrefixesUnion, Str))
361 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++, CStr);
362
363 const Info *End = OptionInfos.data() + OptionInfos.size();
364 StringRef Name = Str.ltrim(PrefixChars);
365 const Info *Start =
366 std::lower_bound(OptionInfos.data() + FirstSearchableIndex, End, Name,
367 OptNameLess(StrTable, PrefixesTable));
368 const Info *Fallback = nullptr;
369 unsigned Prev = Index;
370
371 // Search for the option which matches Str.
372 for (; Start != End; ++Start) {
373 unsigned ArgSize =
374 matchOption(StrTable, PrefixesTable, Start, Str, IgnoreCase);
375 if (!ArgSize)
376 continue;
377
378 Option Opt(Start, this);
379 if (std::unique_ptr<Arg> A =
380 Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
381 /*GroupedShortOption=*/false, Index))
382 return A;
383
384 // If Opt is a Flag of length 2 (e.g. "-a"), we know it is a prefix of
385 // the current argument (e.g. "-abc"). Match it as a fallback if no longer
386 // option (e.g. "-ab") exists.
387 if (ArgSize == 2 && Opt.getKind() == Option::FlagClass)
388 Fallback = Start;
389
390 // Otherwise, see if the argument is missing.
391 if (Prev != Index)
392 return nullptr;
393 }
394 if (Fallback) {
395 Option Opt(Fallback, this);
396 // Check that the last option isn't a flag wrongly given an argument.
397 if (Str[2] == '=')
398 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
399 CStr);
400
401 if (std::unique_ptr<Arg> A = Opt.accept(
402 Args, Str.substr(0, 2), /*GroupedShortOption=*/true, Index)) {
403 Args.replaceArgString(Index, Twine('-') + Str.substr(2));
404 return A;
405 }
406 }
407
408 // In the case of an incorrect short option extract the character and move to
409 // the next one.
410 if (Str[1] != '-') {
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);
414 }
415
416 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++, CStr);
417}
418
419std::unique_ptr<Arg> OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
420 Visibility VisibilityMask) const {
421 return internalParseOneArg(Args, Index, [VisibilityMask](const Option &Opt) {
422 return !Opt.hasVisibilityFlag(VisibilityMask);
423 });
424}
425
426std::unique_ptr<Arg> OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
427 unsigned FlagsToInclude,
428 unsigned FlagsToExclude) const {
429 return internalParseOneArg(
430 Args, Index, [FlagsToInclude, FlagsToExclude](const Option &Opt) {
431 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
432 return true;
433 if (Opt.hasFlag(FlagsToExclude))
434 return true;
435 return false;
436 });
437}
438
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);
444
445 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
446 // itself.
447 if (isInput(PrefixesUnion, Str))
448 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++,
449 Str.data());
450
451 const Info *Start = OptionInfos.data() + FirstSearchableIndex;
452 const Info *End = OptionInfos.data() + OptionInfos.size();
453 StringRef Name = Str.ltrim(PrefixChars);
454
455 // Search for the first next option which could be a prefix.
456 Start =
457 std::lower_bound(Start, End, Name, OptNameLess(StrTable, PrefixesTable));
458
459 // Options are stored in sorted order, with '\0' at the end of the
460 // alphabet. Since the only options which can accept a string must
461 // prefix it, we iteratively search for the next option which could
462 // be a prefix.
463 //
464 // FIXME: This is searching much more than necessary, but I am
465 // blanking on the simplest way to make it fast. We can solve this
466 // problem when we move to TableGen.
467 for (; Start != End; ++Start) {
468 unsigned ArgSize = 0;
469 // Scan for first option which is a proper prefix.
470 for (; Start != End; ++Start)
471 if ((ArgSize =
472 matchOption(StrTable, PrefixesTable, Start, Str, IgnoreCase)))
473 break;
474 if (Start == End)
475 break;
476
477 Option Opt(Start, this);
478
479 if (ExcludeOption(Opt))
480 continue;
481
482 // See if this option matches.
483 if (std::unique_ptr<Arg> A =
484 Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
485 /*GroupedShortOption=*/false, Index))
486 return A;
487
488 // Otherwise, see if this argument was missing values.
489 if (Prev != Index)
490 return nullptr;
491 }
492
493 // If we failed to find an option and this arg started with /, then it's
494 // probably an input path.
495 if (Str[0] == '/')
496 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++,
497 Str.data());
498
499 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
500 Str.data());
501}
502
504 unsigned &MissingArgIndex,
505 unsigned &MissingArgCount,
506 Visibility VisibilityMask) const {
507 return internalParseArgs(
508 Args, MissingArgIndex, MissingArgCount,
509 [VisibilityMask](const Option &Opt) {
510 return !Opt.hasVisibilityFlag(VisibilityMask);
511 });
512}
513
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))
523 return true;
524 if (Opt.hasFlag(FlagsToExclude))
525 return true;
526 return false;
527 });
528}
529
530InputArgList OptTable::internalParseArgs(
531 ArrayRef<const char *> ArgArr, unsigned &MissingArgIndex,
532 unsigned &MissingArgCount,
533 std::function<bool(const Option &)> ExcludeOption) const {
534 InputArgList Args(ArgArr.begin(), ArgArr.end());
535
536 // FIXME: Handle '@' args (or at least error on them).
537
538 MissingArgIndex = MissingArgCount = 0;
539 unsigned Index = 0, End = ArgArr.size();
540 while (Index < End) {
541 // Ingore nullptrs, they are response file's EOL markers
542 if (Args.getArgString(Index) == nullptr) {
543 ++Index;
544 continue;
545 }
546 // Ignore empty arguments (other things may still take them as arguments).
547 StringRef Str = Args.getArgString(Index);
548 if (Str == "") {
549 ++Index;
550 continue;
551 }
552
553 // In DashDashParsing mode, the first "--" stops option scanning and treats
554 // all subsequent arguments as positional.
555 if (DashDashParsing && Str == "--") {
556 while (++Index < End) {
557 Args.append(new Arg(getOption(InputOptionID), Str, Index,
558 Args.getArgString(Index)));
559 }
560 break;
561 }
562
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.");
569
570 // Check for missing argument error.
571 if (!A) {
572 assert(Index >= End && "Unexpected parser error.");
573 assert(Index - Prev - 1 && "No missing arguments!");
574 MissingArgIndex = Prev;
575 MissingArgCount = Index - Prev - 1;
576 break;
577 }
578
579 Args.append(A.release());
580 }
581
582 return Args;
583}
584
585InputArgList OptTable::parseArgs(int Argc, char *const *Argv,
587 std::function<void(StringRef)> ErrorFn) const {
589 // The environment variable specifies initial options which can be overridden
590 // by commnad line options.
591 cl::expandResponseFiles(Argc, Argv, EnvVar, Saver, NewArgv);
592
593 unsigned MAI, MAC;
594 opt::InputArgList Args = ParseArgs(ArrayRef(NewArgv), MAI, MAC);
595 if (MAC)
596 ErrorFn((Twine(Args.getArgString(MAI)) + ": missing argument").str());
597
598 // For each unknwon option, call ErrorFn with a formatted error message. The
599 // message includes a suggested alternative option spelling if available.
600 std::string Nearest;
601 for (const opt::Arg *A : Args.filtered(Unknown)) {
602 std::string Spelling = A->getAsString(Args);
603 if (findNearest(Spelling, Nearest) > 1)
604 ErrorFn("unknown argument '" + Spelling + "'");
605 else
606 ErrorFn("unknown argument '" + Spelling + "', did you mean '" + Nearest +
607 "'?");
608 }
609 return Args;
610}
611
612static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
613 const Option O = Opts.getOption(Id);
614 std::string Name = O.getPrefixedName().str();
615
616 // Add metavar, if used.
617 switch (O.getKind()) {
619 llvm_unreachable("Invalid option with help text.");
620
622 if (StringRef MetaVarName = Opts.getOptionMetaVar(Id);
623 !MetaVarName.empty()) {
624 // For MultiArgs, metavar is full list of all argument names.
625 Name += ' ';
626 Name += MetaVarName;
627 } else {
628 // For MultiArgs<N>, if metavar not supplied, print <value> N times.
629 for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
630 Name += " <value>";
631 }
632 }
633 break;
634
637 break;
638
640 Name += '=';
641 if (StringRef MetaVarName = Opts.getOptionMetaVar(Id); !MetaVarName.empty())
642 Name += MetaVarName;
643 else
644 Name += "<value>";
645 break;
646
648 break;
649
652 Name += ' ';
653 [[fallthrough]];
656 if (StringRef MetaVarName = Opts.getOptionMetaVar(Id); !MetaVarName.empty())
657 Name += MetaVarName;
658 else
659 Name += "<value>";
660 break;
661 }
662
663 return Name;
664}
665
666namespace {
667struct OptionInfo {
668 std::string Name;
669 StringRef HelpText;
670};
671} // namespace
672
674 std::vector<OptionInfo> &OptionHelp) {
675 OS << Title << ":\n";
676
677 // Find the maximum option length.
678 unsigned OptionFieldWidth = 0;
679 for (const OptionInfo &Opt : OptionHelp) {
680 // Limit the amount of padding we are willing to give up for alignment.
681 unsigned Length = Opt.Name.size();
682 if (Length <= 23)
683 OptionFieldWidth = std::max(OptionFieldWidth, Length);
684 }
685
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());
691 OS.indent(InitialPad) << Option;
692
693 // Break on long option names.
694 if (FirstLinePad < 0) {
695 OS << "\n";
696 FirstLinePad = OptionFieldWidth + InitialPad;
697 Pad = FirstLinePad;
698 }
699
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';
707 }
708}
709
711 unsigned GroupID = Opts.getOptionGroupID(Id);
712
713 // If not in a group, return the default help group.
714 if (!GroupID)
715 return "OPTIONS";
716
717 // Abuse the help text of the option groups to store the "help group"
718 // name.
719 //
720 // FIXME: Split out option groups.
721 if (StringRef GroupHelp = Opts.getOptionHelpText(GroupID); !GroupHelp.empty())
722 return GroupHelp;
723
724 // Otherwise keep looking.
725 return getOptionHelpGroup(Opts, GroupID);
726}
727
728void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
729 bool ShowHidden, bool ShowAllAliases,
730 Visibility VisibilityMask,
731 StringRef SubCommand) const {
732 return internalPrintHelp(
733 OS, Usage, Title, SubCommand, ShowHidden, ShowAllAliases,
734 [this, VisibilityMask](const Info &CandidateInfo) -> bool {
735 return (getExtra(CandidateInfo).Visibility & VisibilityMask) == 0;
736 },
737 VisibilityMask);
738}
739
740void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
741 unsigned FlagsToInclude, unsigned FlagsToExclude,
742 bool ShowAllAliases) const {
743 bool ShowHidden = !(FlagsToExclude & HelpHidden);
744 FlagsToExclude &= ~HelpHidden;
745 return internalPrintHelp(
746 OS, Usage, Title, /*SubCommand=*/{}, ShowHidden, ShowAllAliases,
747 [this, FlagsToInclude, FlagsToExclude](const Info &CandidateInfo) {
748 unsigned Flags = getExtra(CandidateInfo).Flags;
749 if (FlagsToInclude && !(Flags & FlagsToInclude))
750 return true;
751 if (Flags & FlagsToExclude)
752 return true;
753 return false;
754 },
755 Visibility(0));
756}
757
758void OptTable::internalPrintHelp(
759 raw_ostream &OS, const char *Usage, const char *Title, StringRef SubCommand,
760 bool ShowHidden, bool ShowAllAliases,
761 std::function<bool(const Info &)> ExcludeOption,
762 Visibility VisibilityMask) const {
763 OS << "OVERVIEW: " << Title << "\n\n";
764
765 // Render help text into a map of group-name to a list of (option, help)
766 // pairs.
767 std::map<StringRef, std::vector<OptionInfo>> GroupedOptionHelp;
768
769 auto ActiveSubCommand = llvm::find_if(
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";
775 if (!StringRef(ActiveSubCommand->Usage).empty())
776 OS << "USAGE: " << ActiveSubCommand->Usage << "\n\n";
777 } else {
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";
783 OS << "\n";
784 }
785 }
786
787 auto DoesOptionBelongToSubcommand = [&](const Info &CandidateInfo) {
788 // Retrieve the SubCommandIDs registered to the given current CandidateInfo
789 // Option.
790 ArrayRef<unsigned> SubCommandIDs = getSubCommandIDs(CandidateInfo);
791
792 // If no registered subcommands, then only global options are to be printed.
793 // If no valid SubCommand (empty) in commandline then print the current
794 // global CandidateInfo Option.
795 if (SubCommandIDs.empty())
796 return SubCommand.empty();
797
798 // Handle CandidateInfo Option which has at least one registered SubCommand.
799 // If no valid SubCommand (empty) in commandline, this CandidateInfo option
800 // should not be printed.
801 if (SubCommand.empty())
802 return false;
803
804 // Find the ID of the valid subcommand passed in commandline (its index in
805 // the SubCommands table which contains all subcommands).
806 unsigned ActiveSubCommandID = ActiveSubCommand - &SubCommands[0];
807 // Print if the ActiveSubCommandID is registered with the CandidateInfo
808 // Option.
809 return llvm::is_contained(SubCommandIDs, ActiveSubCommandID);
810 };
811
812 for (unsigned Id = 1, e = getNumOptions() + 1; Id != e; ++Id) {
813 // FIXME: Split out option groups.
815 continue;
816
817 const Info &CandidateInfo = getInfo(Id);
818 if (!ShowHidden && (getExtra(CandidateInfo).Flags & opt::HelpHidden))
819 continue;
820
821 if (ExcludeOption(CandidateInfo))
822 continue;
823
824 if (!DoesOptionBelongToSubcommand(CandidateInfo))
825 continue;
826
827 // If an alias doesn't have a help text, show a help text for the aliased
828 // option instead.
829 StringTable::Offset HelpTextOffset =
830 getHelpTextOffset(CandidateInfo, VisibilityMask);
831 if (!HelpTextOffset.value() && ShowAllAliases) {
832 const Option Alias = getOption(Id).getAlias();
833 if (Alias.isValid())
834 HelpTextOffset =
835 getHelpTextOffset(getInfo(Alias.getID()), VisibilityMask);
836 }
837
838 if (StringRef HelpText = StrTable[HelpTextOffset]; !HelpText.empty()) {
839 StringRef HelpGroup = getOptionHelpGroup(*this, Id);
840 const std::string &OptName = getOptionHelpName(*this, Id);
841 GroupedOptionHelp[HelpGroup].push_back({OptName, HelpText});
842 }
843 }
844
845 for (auto& OptionGroup : GroupedOptionHelp) {
846 if (OptionGroup.first != GroupedOptionHelp.begin()->first)
847 OS << "\n";
848 PrintHelpOptionList(OS, OptionGroup.first, OptionGroup.second);
849 }
850
851 OS.flush();
852}
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")
#define I(x, y, z)
Definition MD5.cpp:57
#define T
static unsigned matchOption(const StringTable &StrTable, ArrayRef< StringTable::Offset > PrefixesTable, const OptTable::Info *I, StringRef Str, bool IgnoreCase)
Definition OptTable.cpp:153
static bool optionMatches(const StringTable &StrTable, ArrayRef< StringTable::Offset > PrefixesTable, const OptTable::Info &In, StringRef Option)
Definition OptTable.cpp:172
static StringRef getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id)
Definition OptTable.cpp:710
static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id)
Definition OptTable.cpp:612
static bool isInput(const ArrayRef< StringRef > &Prefixes, StringRef Arg)
Definition OptTable.cpp:143
static void PrintHelpOptionList(raw_ostream &OS, StringRef Title, std::vector< OptionInfo > &OptionHelp)
Definition OptTable.cpp:673
This file contains some templates that are useful if you are working with the STL at all.
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
Value * RHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
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.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
LLVM_ABI bool starts_with_insensitive(StringRef Prefix) const
Check if this string starts with the given Prefix, ignoring case.
Definition StringRef.cpp:41
LLVM_ABI unsigned edit_distance(StringRef Other, bool AllowReplacements=true, unsigned MaxEditDistance=0) const
Determine the edit distance between this string and another string.
Definition StringRef.cpp:88
char back() const
Get the last character in the string.
Definition StringRef.h:153
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition StringSaver.h:22
constexpr unsigned value() const
Definition StringTable.h:65
A table of densely packed, null-terminated strings indexed by offset.
Definition StringTable.h:34
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
ArgList - Ordered collection of driver arguments.
Definition ArgList.h:118
A concrete instance of a particular driver option.
Definition Arg.h:35
OptSpecifier - Wrapper class for abstracting references to option IDs.
unsigned getID() const
Provide access to the Option info table.
Definition OptTable.h:55
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,...
Definition OptTable.cpp:585
unsigned getOptionKind(OptSpecifier id) const
Get the kind of the given option.
Definition OptTable.h:312
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.
Definition OptTable.cpp:419
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.
Definition OptTable.cpp:235
const Option getOption(OptSpecifier Opt) const
Get the given Opt's Option instance, lazily creating it if necessary.
Definition OptTable.cpp:135
unsigned getOptionGroupID(OptSpecifier id) const
Get the group id for the given option.
Definition OptTable.h:317
StringRef getOptionMetaVar(OptSpecifier id) const
Get the meta-variable name to use when describing this options values in the help text.
Definition OptTable.h:336
const InfoExtra & getExtra(const Info &I) const
Definition OptTable.h:307
OptTable(const Tables &Tables, bool IgnoreCase=false)
Definition OptTable.cpp:76
std::vector< std::string > suggestValueCompletions(StringRef Option, StringRef Arg) const
Find possible value for given flags.
Definition OptTable.cpp:187
InputArgList ParseArgs(ArrayRef< const char * > Args, unsigned &MissingArgIndex, unsigned &MissingArgCount, Visibility VisibilityMask=Visibility()) const
Parse an list of arguments into an InputArgList.
Definition OptTable.cpp:503
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.
Definition OptTable.cpp:728
unsigned getNumOptions() const
Return the total number of option classes.
Definition OptTable.h:272
StringRef getOptionHelpText(OptSpecifier id) const
Get the help text to use to describe this option.
Definition OptTable.h:322
std::vector< std::string > findByPrefix(StringRef Cur, Visibility VisibilityMask, unsigned int DisableFlags) const
Find flags from OptTable which starts with Cur.
Definition OptTable.cpp:210
Option - Abstract representation for a single form of driver argument.
Definition Option.h:55
const Option getAlias() const
Definition Option.h:114
bool hasFlag(unsigned Val) const
Test if this option has the flag Val.
Definition Option.h:177
@ JoinedOrSeparateClass
Definition Option.h:71
@ JoinedAndSeparateClass
Definition Option.h:72
@ RemainingArgsJoinedClass
Definition Option.h:68
bool hasVisibilityFlag(unsigned Val) const
Test if this option has the visibility flag Val.
Definition Option.h:182
bool isValid() const
Definition Option.h:90
unsigned getID() const
Definition Option.h:94
Helper for overload resolution while transitioning from FlagsToInclude/FlagsToExclude APIs to Visibil...
Definition OptTable.h:38
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
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 ...
constexpr double e
@ HelpHidden
Definition Option.h:34
This is an optimization pass for GlobalISel generic memory operations.
@ Length
Definition DWP.cpp:577
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ 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.
Definition STLExtras.h:1788
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Fields that are rarely set or take few distinct values, shared by the options with equal values.
Definition OptTable.h:79
Entry for a single option instance in the option data table.
Definition OptTable.h:96
Represents a subcommand and its options in the option table.
Definition OptTable.h:58
The tables TableGen emits for an option set under OPTTABLE_CODE.
Definition OptTable.h:151