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 if (!(In.Visibility & VisibilityMask))
218 continue;
219 if (In.Flags & DisableFlags)
220 continue;
221
222 StringRef Name = In.getName(StrTable, PrefixesTable);
223 for (auto PrefixOffset : In.getPrefixOffsets(PrefixesTable)) {
224 StringRef Prefix = StrTable[PrefixOffset];
225 std::string S = (Twine(Prefix) + Name + "\t").str();
226 S += StrTable[In.HelpTextOffset];
227 if (StringRef(S).starts_with(Cur) && S != std::string(Cur) + "\t")
228 Ret.push_back(S);
229 }
230 }
231 return Ret;
232}
233
234unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
235 Visibility VisibilityMask,
236 unsigned MinimumLength,
237 unsigned MaximumDistance) const {
238 return internalFindNearest(
239 Option, NearestString, MinimumLength, MaximumDistance,
240 [VisibilityMask](const Info &CandidateInfo) {
241 return (CandidateInfo.Visibility & VisibilityMask) == 0;
242 });
243}
244
245unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
246 unsigned FlagsToInclude, unsigned FlagsToExclude,
247 unsigned MinimumLength,
248 unsigned MaximumDistance) const {
249 return internalFindNearest(
250 Option, NearestString, MinimumLength, MaximumDistance,
251 [FlagsToInclude, FlagsToExclude](const Info &CandidateInfo) {
252 if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
253 return true;
254 if (CandidateInfo.Flags & FlagsToExclude)
255 return true;
256 return false;
257 });
258}
259
260unsigned OptTable::internalFindNearest(
261 StringRef Option, std::string &NearestString, unsigned MinimumLength,
262 unsigned MaximumDistance,
263 std::function<bool(const Info &)> ExcludeOption) const {
264 // Consider each [option prefix + option name] pair as a candidate, finding
265 // the closest match.
266 unsigned BestDistance =
267 MaximumDistance == UINT_MAX ? UINT_MAX : MaximumDistance + 1;
268 SmallString<16> Candidate;
269 SmallString<16> NormalizedName;
270
271 for (const Info &CandidateInfo :
272 ArrayRef<Info>(OptionInfos).drop_front(FirstSearchableIndex)) {
273 StringRef CandidateName = CandidateInfo.getName(StrTable, PrefixesTable);
274
275 // We can eliminate some option prefix/name pairs as candidates right away:
276 // * Ignore option candidates with empty names, such as "--", or names
277 // that do not meet the minimum length.
278 if (CandidateName.size() < MinimumLength)
279 continue;
280
281 // Ignore options that are excluded via masks
282 if (ExcludeOption(CandidateInfo))
283 continue;
284
285 // * Ignore positional argument option candidates (which do not
286 // have prefixes).
287 if (CandidateInfo.hasNoPrefix())
288 continue;
289
290 // Now check if the candidate ends with a character commonly used when
291 // delimiting an option from its value, such as '=' or ':'. If it does,
292 // attempt to split the given option based on that delimiter.
293 char Last = CandidateName.back();
294 bool CandidateHasDelimiter = Last == '=' || Last == ':';
295 StringRef RHS;
296 if (CandidateHasDelimiter) {
297 std::tie(NormalizedName, RHS) = Option.split(Last);
298 if (Option.find(Last) == NormalizedName.size())
299 NormalizedName += Last;
300 } else
301 NormalizedName = Option;
302
303 // Consider each possible prefix for each candidate to find the most
304 // appropriate one. For example, if a user asks for "--helm", suggest
305 // "--help" over "-help".
306 for (auto CandidatePrefixOffset :
307 CandidateInfo.getPrefixOffsets(PrefixesTable)) {
308 StringRef CandidatePrefix = StrTable[CandidatePrefixOffset];
309 // If Candidate and NormalizedName have more than 'BestDistance'
310 // characters of difference, no need to compute the edit distance, it's
311 // going to be greater than BestDistance. Don't bother computing Candidate
312 // at all.
313 size_t CandidateSize = CandidatePrefix.size() + CandidateName.size(),
314 NormalizedSize = NormalizedName.size();
315 size_t AbsDiff = CandidateSize > NormalizedSize
316 ? CandidateSize - NormalizedSize
317 : NormalizedSize - CandidateSize;
318 if (AbsDiff > BestDistance) {
319 continue;
320 }
321 Candidate = CandidatePrefix;
322 Candidate += CandidateName;
323 unsigned Distance = StringRef(Candidate).edit_distance(
324 NormalizedName, /*AllowReplacements=*/true,
325 /*MaxEditDistance=*/BestDistance);
326 if (RHS.empty() && CandidateHasDelimiter) {
327 // The Candidate ends with a = or : delimiter, but the option passed in
328 // didn't contain the delimiter (or doesn't have anything after it).
329 // In that case, penalize the correction: `-nodefaultlibs` is more
330 // likely to be a spello for `-nodefaultlib` than `-nodefaultlib:` even
331 // though both have an unmodified editing distance of 1, since the
332 // latter would need an argument.
333 ++Distance;
334 }
335 if (Distance < BestDistance) {
336 BestDistance = Distance;
337 NearestString = (Candidate + RHS).str();
338 }
339 }
340 }
341 return BestDistance;
342}
343
344// Parse a single argument, return the new argument, and update Index. If
345// GroupedShortOptions is true, -a matches "-abc" and the argument in Args will
346// be updated to "-bc". This overload does not support VisibilityMask or case
347// insensitive options.
348std::unique_ptr<Arg> OptTable::parseOneArgGrouped(InputArgList &Args,
349 unsigned &Index) const {
350 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
351 // itself.
352 const char *CStr = Args.getArgString(Index);
353 StringRef Str(CStr);
354 if (isInput(PrefixesUnion, Str))
355 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++, CStr);
356
357 const Info *End = OptionInfos.data() + OptionInfos.size();
358 StringRef Name = Str.ltrim(PrefixChars);
359 const Info *Start =
360 std::lower_bound(OptionInfos.data() + FirstSearchableIndex, End, Name,
361 OptNameLess(StrTable, PrefixesTable));
362 const Info *Fallback = nullptr;
363 unsigned Prev = Index;
364
365 // Search for the option which matches Str.
366 for (; Start != End; ++Start) {
367 unsigned ArgSize =
368 matchOption(StrTable, PrefixesTable, Start, Str, IgnoreCase);
369 if (!ArgSize)
370 continue;
371
372 Option Opt(Start, this);
373 if (std::unique_ptr<Arg> A =
374 Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
375 /*GroupedShortOption=*/false, Index))
376 return A;
377
378 // If Opt is a Flag of length 2 (e.g. "-a"), we know it is a prefix of
379 // the current argument (e.g. "-abc"). Match it as a fallback if no longer
380 // option (e.g. "-ab") exists.
381 if (ArgSize == 2 && Opt.getKind() == Option::FlagClass)
382 Fallback = Start;
383
384 // Otherwise, see if the argument is missing.
385 if (Prev != Index)
386 return nullptr;
387 }
388 if (Fallback) {
389 Option Opt(Fallback, this);
390 // Check that the last option isn't a flag wrongly given an argument.
391 if (Str[2] == '=')
392 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
393 CStr);
394
395 if (std::unique_ptr<Arg> A = Opt.accept(
396 Args, Str.substr(0, 2), /*GroupedShortOption=*/true, Index)) {
397 Args.replaceArgString(Index, Twine('-') + Str.substr(2));
398 return A;
399 }
400 }
401
402 // In the case of an incorrect short option extract the character and move to
403 // the next one.
404 if (Str[1] != '-') {
405 CStr = Args.MakeArgString(Str.substr(0, 2));
406 Args.replaceArgString(Index, Twine('-') + Str.substr(2));
407 return std::make_unique<Arg>(getOption(UnknownOptionID), CStr, Index, CStr);
408 }
409
410 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++, CStr);
411}
412
413std::unique_ptr<Arg> OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
414 Visibility VisibilityMask) const {
415 return internalParseOneArg(Args, Index, [VisibilityMask](const Option &Opt) {
416 return !Opt.hasVisibilityFlag(VisibilityMask);
417 });
418}
419
420std::unique_ptr<Arg> OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
421 unsigned FlagsToInclude,
422 unsigned FlagsToExclude) const {
423 return internalParseOneArg(
424 Args, Index, [FlagsToInclude, FlagsToExclude](const Option &Opt) {
425 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
426 return true;
427 if (Opt.hasFlag(FlagsToExclude))
428 return true;
429 return false;
430 });
431}
432
433std::unique_ptr<Arg> OptTable::internalParseOneArg(
434 const ArgList &Args, unsigned &Index,
435 std::function<bool(const Option &)> ExcludeOption) const {
436 unsigned Prev = Index;
437 StringRef Str = Args.getArgString(Index);
438
439 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
440 // itself.
441 if (isInput(PrefixesUnion, Str))
442 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++,
443 Str.data());
444
445 const Info *Start = OptionInfos.data() + FirstSearchableIndex;
446 const Info *End = OptionInfos.data() + OptionInfos.size();
447 StringRef Name = Str.ltrim(PrefixChars);
448
449 // Search for the first next option which could be a prefix.
450 Start =
451 std::lower_bound(Start, End, Name, OptNameLess(StrTable, PrefixesTable));
452
453 // Options are stored in sorted order, with '\0' at the end of the
454 // alphabet. Since the only options which can accept a string must
455 // prefix it, we iteratively search for the next option which could
456 // be a prefix.
457 //
458 // FIXME: This is searching much more than necessary, but I am
459 // blanking on the simplest way to make it fast. We can solve this
460 // problem when we move to TableGen.
461 for (; Start != End; ++Start) {
462 unsigned ArgSize = 0;
463 // Scan for first option which is a proper prefix.
464 for (; Start != End; ++Start)
465 if ((ArgSize =
466 matchOption(StrTable, PrefixesTable, Start, Str, IgnoreCase)))
467 break;
468 if (Start == End)
469 break;
470
471 Option Opt(Start, this);
472
473 if (ExcludeOption(Opt))
474 continue;
475
476 // See if this option matches.
477 if (std::unique_ptr<Arg> A =
478 Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
479 /*GroupedShortOption=*/false, Index))
480 return A;
481
482 // Otherwise, see if this argument was missing values.
483 if (Prev != Index)
484 return nullptr;
485 }
486
487 // If we failed to find an option and this arg started with /, then it's
488 // probably an input path.
489 if (Str[0] == '/')
490 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++,
491 Str.data());
492
493 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
494 Str.data());
495}
496
498 unsigned &MissingArgIndex,
499 unsigned &MissingArgCount,
500 Visibility VisibilityMask) const {
501 return internalParseArgs(
502 Args, MissingArgIndex, MissingArgCount,
503 [VisibilityMask](const Option &Opt) {
504 return !Opt.hasVisibilityFlag(VisibilityMask);
505 });
506}
507
509 unsigned &MissingArgIndex,
510 unsigned &MissingArgCount,
511 unsigned FlagsToInclude,
512 unsigned FlagsToExclude) const {
513 return internalParseArgs(
514 Args, MissingArgIndex, MissingArgCount,
515 [FlagsToInclude, FlagsToExclude](const Option &Opt) {
516 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
517 return true;
518 if (Opt.hasFlag(FlagsToExclude))
519 return true;
520 return false;
521 });
522}
523
524InputArgList OptTable::internalParseArgs(
525 ArrayRef<const char *> ArgArr, unsigned &MissingArgIndex,
526 unsigned &MissingArgCount,
527 std::function<bool(const Option &)> ExcludeOption) const {
528 InputArgList Args(ArgArr.begin(), ArgArr.end());
529
530 // FIXME: Handle '@' args (or at least error on them).
531
532 MissingArgIndex = MissingArgCount = 0;
533 unsigned Index = 0, End = ArgArr.size();
534 while (Index < End) {
535 // Ingore nullptrs, they are response file's EOL markers
536 if (Args.getArgString(Index) == nullptr) {
537 ++Index;
538 continue;
539 }
540 // Ignore empty arguments (other things may still take them as arguments).
541 StringRef Str = Args.getArgString(Index);
542 if (Str == "") {
543 ++Index;
544 continue;
545 }
546
547 // In DashDashParsing mode, the first "--" stops option scanning and treats
548 // all subsequent arguments as positional.
549 if (DashDashParsing && Str == "--") {
550 while (++Index < End) {
551 Args.append(new Arg(getOption(InputOptionID), Str, Index,
552 Args.getArgString(Index)));
553 }
554 break;
555 }
556
557 unsigned Prev = Index;
558 std::unique_ptr<Arg> A = GroupedShortOptions
559 ? parseOneArgGrouped(Args, Index)
560 : internalParseOneArg(Args, Index, ExcludeOption);
561 assert((Index > Prev || GroupedShortOptions) &&
562 "Parser failed to consume argument.");
563
564 // Check for missing argument error.
565 if (!A) {
566 assert(Index >= End && "Unexpected parser error.");
567 assert(Index - Prev - 1 && "No missing arguments!");
568 MissingArgIndex = Prev;
569 MissingArgCount = Index - Prev - 1;
570 break;
571 }
572
573 Args.append(A.release());
574 }
575
576 return Args;
577}
578
579InputArgList OptTable::parseArgs(int Argc, char *const *Argv,
581 std::function<void(StringRef)> ErrorFn) const {
583 // The environment variable specifies initial options which can be overridden
584 // by commnad line options.
585 cl::expandResponseFiles(Argc, Argv, EnvVar, Saver, NewArgv);
586
587 unsigned MAI, MAC;
588 opt::InputArgList Args = ParseArgs(ArrayRef(NewArgv), MAI, MAC);
589 if (MAC)
590 ErrorFn((Twine(Args.getArgString(MAI)) + ": missing argument").str());
591
592 // For each unknwon option, call ErrorFn with a formatted error message. The
593 // message includes a suggested alternative option spelling if available.
594 std::string Nearest;
595 for (const opt::Arg *A : Args.filtered(Unknown)) {
596 std::string Spelling = A->getAsString(Args);
597 if (findNearest(Spelling, Nearest) > 1)
598 ErrorFn("unknown argument '" + Spelling + "'");
599 else
600 ErrorFn("unknown argument '" + Spelling + "', did you mean '" + Nearest +
601 "'?");
602 }
603 return Args;
604}
605
606static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
607 const Option O = Opts.getOption(Id);
608 std::string Name = O.getPrefixedName().str();
609
610 // Add metavar, if used.
611 switch (O.getKind()) {
613 llvm_unreachable("Invalid option with help text.");
614
616 if (StringRef MetaVarName = Opts.getOptionMetaVar(Id);
617 !MetaVarName.empty()) {
618 // For MultiArgs, metavar is full list of all argument names.
619 Name += ' ';
620 Name += MetaVarName;
621 } else {
622 // For MultiArgs<N>, if metavar not supplied, print <value> N times.
623 for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
624 Name += " <value>";
625 }
626 }
627 break;
628
630 break;
631
633 break;
634
637 Name += ' ';
638 [[fallthrough]];
641 if (StringRef MetaVarName = Opts.getOptionMetaVar(Id); !MetaVarName.empty())
642 Name += MetaVarName;
643 else
644 Name += "<value>";
645 break;
646 }
647
648 return Name;
649}
650
651namespace {
652struct OptionInfo {
653 std::string Name;
654 StringRef HelpText;
655};
656} // namespace
657
659 std::vector<OptionInfo> &OptionHelp) {
660 OS << Title << ":\n";
661
662 // Find the maximum option length.
663 unsigned OptionFieldWidth = 0;
664 for (const OptionInfo &Opt : OptionHelp) {
665 // Limit the amount of padding we are willing to give up for alignment.
666 unsigned Length = Opt.Name.size();
667 if (Length <= 23)
668 OptionFieldWidth = std::max(OptionFieldWidth, Length);
669 }
670
671 const unsigned InitialPad = 2;
672 for (const OptionInfo &Opt : OptionHelp) {
673 const std::string &Option = Opt.Name;
674 int Pad = OptionFieldWidth + InitialPad;
675 int FirstLinePad = OptionFieldWidth - int(Option.size());
676 OS.indent(InitialPad) << Option;
677
678 // Break on long option names.
679 if (FirstLinePad < 0) {
680 OS << "\n";
681 FirstLinePad = OptionFieldWidth + InitialPad;
682 Pad = FirstLinePad;
683 }
684
686 Opt.HelpText.split(Lines, '\n');
687 assert(Lines.size() && "Expected at least the first line in the help text");
688 auto *LinesIt = Lines.begin();
689 OS.indent(FirstLinePad + 1) << *LinesIt << '\n';
690 while (Lines.end() != ++LinesIt)
691 OS.indent(Pad + 1) << *LinesIt << '\n';
692 }
693}
694
696 unsigned GroupID = Opts.getOptionGroupID(Id);
697
698 // If not in a group, return the default help group.
699 if (!GroupID)
700 return "OPTIONS";
701
702 // Abuse the help text of the option groups to store the "help group"
703 // name.
704 //
705 // FIXME: Split out option groups.
706 if (StringRef GroupHelp = Opts.getOptionHelpText(GroupID); !GroupHelp.empty())
707 return GroupHelp;
708
709 // Otherwise keep looking.
710 return getOptionHelpGroup(Opts, GroupID);
711}
712
713void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
714 bool ShowHidden, bool ShowAllAliases,
715 Visibility VisibilityMask,
716 StringRef SubCommand) const {
717 return internalPrintHelp(
718 OS, Usage, Title, SubCommand, ShowHidden, ShowAllAliases,
719 [VisibilityMask](const Info &CandidateInfo) -> bool {
720 return (CandidateInfo.Visibility & VisibilityMask) == 0;
721 },
722 VisibilityMask);
723}
724
725void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
726 unsigned FlagsToInclude, unsigned FlagsToExclude,
727 bool ShowAllAliases) const {
728 bool ShowHidden = !(FlagsToExclude & HelpHidden);
729 FlagsToExclude &= ~HelpHidden;
730 return internalPrintHelp(
731 OS, Usage, Title, /*SubCommand=*/{}, ShowHidden, ShowAllAliases,
732 [FlagsToInclude, FlagsToExclude](const Info &CandidateInfo) {
733 if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
734 return true;
735 if (CandidateInfo.Flags & FlagsToExclude)
736 return true;
737 return false;
738 },
739 Visibility(0));
740}
741
742void OptTable::internalPrintHelp(
743 raw_ostream &OS, const char *Usage, const char *Title, StringRef SubCommand,
744 bool ShowHidden, bool ShowAllAliases,
745 std::function<bool(const Info &)> ExcludeOption,
746 Visibility VisibilityMask) const {
747 OS << "OVERVIEW: " << Title << "\n\n";
748
749 // Render help text into a map of group-name to a list of (option, help)
750 // pairs.
751 std::map<StringRef, std::vector<OptionInfo>> GroupedOptionHelp;
752
753 auto ActiveSubCommand = llvm::find_if(
754 SubCommands, [&](const auto &C) { return SubCommand == C.Name; });
755 if (!SubCommand.empty()) {
756 assert(ActiveSubCommand != SubCommands.end() &&
757 "Not a valid registered subcommand.");
758 OS << ActiveSubCommand->HelpText << "\n\n";
759 if (!StringRef(ActiveSubCommand->Usage).empty())
760 OS << "USAGE: " << ActiveSubCommand->Usage << "\n\n";
761 } else {
762 OS << "USAGE: " << Usage << "\n\n";
763 if (SubCommands.size() > 1) {
764 OS << "SUBCOMMANDS:\n\n";
765 for (const auto &C : SubCommands)
766 OS << C.Name << " - " << C.HelpText << "\n";
767 OS << "\n";
768 }
769 }
770
771 auto DoesOptionBelongToSubcommand = [&](const Info &CandidateInfo) {
772 // Retrieve the SubCommandIDs registered to the given current CandidateInfo
773 // Option.
774 ArrayRef<unsigned> SubCommandIDs = getSubCommandIDs(CandidateInfo);
775
776 // If no registered subcommands, then only global options are to be printed.
777 // If no valid SubCommand (empty) in commandline then print the current
778 // global CandidateInfo Option.
779 if (SubCommandIDs.empty())
780 return SubCommand.empty();
781
782 // Handle CandidateInfo Option which has at least one registered SubCommand.
783 // If no valid SubCommand (empty) in commandline, this CandidateInfo option
784 // should not be printed.
785 if (SubCommand.empty())
786 return false;
787
788 // Find the ID of the valid subcommand passed in commandline (its index in
789 // the SubCommands table which contains all subcommands).
790 unsigned ActiveSubCommandID = ActiveSubCommand - &SubCommands[0];
791 // Print if the ActiveSubCommandID is registered with the CandidateInfo
792 // Option.
793 return llvm::is_contained(SubCommandIDs, ActiveSubCommandID);
794 };
795
796 for (unsigned Id = 1, e = getNumOptions() + 1; Id != e; ++Id) {
797 // FIXME: Split out option groups.
799 continue;
800
801 const Info &CandidateInfo = getInfo(Id);
802 if (!ShowHidden && (CandidateInfo.Flags & opt::HelpHidden))
803 continue;
804
805 if (ExcludeOption(CandidateInfo))
806 continue;
807
808 if (!DoesOptionBelongToSubcommand(CandidateInfo))
809 continue;
810
811 // If an alias doesn't have a help text, show a help text for the aliased
812 // option instead.
813 StringTable::Offset HelpTextOffset =
814 getHelpTextOffset(CandidateInfo, VisibilityMask);
815 if (!HelpTextOffset.value() && ShowAllAliases) {
816 const Option Alias = getOption(Id).getAlias();
817 if (Alias.isValid())
818 HelpTextOffset =
819 getHelpTextOffset(getInfo(Alias.getID()), VisibilityMask);
820 }
821
822 if (StringRef HelpText = StrTable[HelpTextOffset]; !HelpText.empty()) {
823 StringRef HelpGroup = getOptionHelpGroup(*this, Id);
824 const std::string &OptName = getOptionHelpName(*this, Id);
825 GroupedOptionHelp[HelpGroup].push_back({OptName, HelpText});
826 }
827 }
828
829 for (auto& OptionGroup : GroupedOptionHelp) {
830 if (OptionGroup.first != GroupedOptionHelp.begin()->first)
831 OS << "\n";
832 PrintHelpOptionList(OS, OptionGroup.first, OptionGroup.second);
833 }
834
835 OS.flush();
836}
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:695
static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id)
Definition OptTable.cpp:606
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:658
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:54
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:579
unsigned getOptionKind(OptSpecifier id) const
Get the kind of the given option.
Definition OptTable.h:311
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:413
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:234
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:316
StringRef getOptionMetaVar(OptSpecifier id) const
Get the meta-variable name to use when describing this options values in the help text.
Definition OptTable.h:335
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:497
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:713
unsigned getNumOptions() const
Return the total number of option classes.
Definition OptTable.h:275
StringRef getOptionHelpText(OptSpecifier id) const
Get the help text to use to describe this option.
Definition OptTable.h:321
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:111
bool hasFlag(unsigned Val) const
Test if this option has the flag Val.
Definition Option.h:171
@ JoinedOrSeparateClass
Definition Option.h:69
@ JoinedAndSeparateClass
Definition Option.h:70
@ RemainingArgsJoinedClass
Definition Option.h:66
bool hasVisibilityFlag(unsigned Val) const
Test if this option has the visibility flag Val.
Definition Option.h:176
bool isValid() const
Definition Option.h:87
unsigned getID() const
Definition Option.h:91
Helper for overload resolution while transitioning from FlagsToInclude/FlagsToExclude APIs to Visibil...
Definition OptTable.h:37
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, 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
Entry for a single option instance in the option data table.
Definition OptTable.h:92
unsigned short Visibility
Definition OptTable.h:98
Represents a subcommand and its options in the option table.
Definition OptTable.h:57
The tables TableGen emits for an option set under OPTTABLE_CODE.
Definition OptTable.h:150