LLVM 22.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 <cctype>
24#include <cstring>
25#include <map>
26#include <set>
27#include <string>
28#include <utility>
29#include <vector>
30
31using namespace llvm;
32using namespace llvm::opt;
33
34namespace {
35struct OptNameLess {
36 const StringTable *StrTable;
38
39 explicit OptNameLess(const StringTable &StrTable,
41 : StrTable(&StrTable), PrefixesTable(PrefixesTable) {}
42
43#ifndef NDEBUG
44 inline bool operator()(const OptTable::Info &A,
45 const OptTable::Info &B) const {
46 if (&A == &B)
47 return false;
48
49 if (int Cmp = StrCmpOptionName(A.getName(*StrTable, PrefixesTable),
50 B.getName(*StrTable, PrefixesTable)))
51 return Cmp < 0;
52
53 SmallVector<StringRef, 8> APrefixes, BPrefixes;
54 A.appendPrefixes(*StrTable, PrefixesTable, APrefixes);
55 B.appendPrefixes(*StrTable, PrefixesTable, BPrefixes);
56
57 if (int Cmp = StrCmpOptionPrefixes(APrefixes, BPrefixes))
58 return Cmp < 0;
59
60 // Names are the same, check that classes are in order; exactly one
61 // should be joined, and it should succeed the other.
62 assert(
63 ((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
64 "Unexpected classes for options with same name.");
65 return B.Kind == Option::JoinedClass;
66 }
67#endif
68
69 // Support lower_bound between info and an option name.
70 inline bool operator()(const OptTable::Info &I, StringRef Name) const {
71 // Do not fallback to case sensitive comparison.
72 return StrCmpOptionName(I.getName(*StrTable, PrefixesTable), Name, false) <
73 0;
74 }
75};
76} // namespace
77
78OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
79
82 ArrayRef<Info> OptionInfos, bool IgnoreCase,
83 ArrayRef<SubCommand> SubCommands,
84 ArrayRef<unsigned> SubCommandIDsTable)
85 : StrTable(&StrTable), PrefixesTable(PrefixesTable),
86 OptionInfos(OptionInfos), IgnoreCase(IgnoreCase),
87 SubCommands(SubCommands), SubCommandIDsTable(SubCommandIDsTable) {
88 // Explicitly zero initialize the error to work around a bug in array
89 // value-initialization on MinGW with gcc 4.3.5.
90
91 // Find start of normal options.
92 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
93 unsigned Kind = getInfo(i + 1).Kind;
94 if (Kind == Option::InputClass) {
95 assert(!InputOptionID && "Cannot have multiple input options!");
96 InputOptionID = getInfo(i + 1).ID;
97 } else if (Kind == Option::UnknownClass) {
98 assert(!UnknownOptionID && "Cannot have multiple unknown options!");
99 UnknownOptionID = getInfo(i + 1).ID;
100 } else if (Kind != Option::GroupClass) {
102 break;
103 }
104 }
105 assert(FirstSearchableIndex != 0 && "No searchable options?");
106
107#ifndef NDEBUG
108 // Check that everything after the first searchable option is a
109 // regular option class.
110 for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
111 Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
112 assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
113 Kind != Option::GroupClass) &&
114 "Special options should be defined first!");
115 }
116
117 // Check that options are in order.
118 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
119 if (!(OptNameLess(StrTable, PrefixesTable)(getInfo(i), getInfo(i + 1)))) {
120 getOption(i).dump();
121 getOption(i + 1).dump();
122 llvm_unreachable("Options are not in order!");
123 }
124 }
125#endif
126}
127
129 assert(PrefixChars.empty() && "rebuilding a non-empty prefix char");
130
131 // Build prefix chars.
132 for (StringRef Prefix : PrefixesUnion) {
133 for (char C : Prefix)
135 PrefixChars.push_back(C);
136 }
137}
138
139OptTable::~OptTable() = default;
140
142 unsigned id = Opt.getID();
143 if (id == 0)
144 return Option(nullptr, nullptr);
145 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
146 return Option(&getInfo(id), this);
147}
148
149static bool isInput(const ArrayRef<StringRef> &Prefixes, StringRef Arg) {
150 if (Arg == "-")
151 return true;
152 for (const StringRef &Prefix : Prefixes)
153 if (Arg.starts_with(Prefix))
154 return false;
155 return true;
156}
157
158/// \returns Matched size. 0 means no match.
159static unsigned matchOption(const StringTable &StrTable,
160 ArrayRef<StringTable::Offset> PrefixesTable,
161 const OptTable::Info *I, StringRef Str,
162 bool IgnoreCase) {
163 StringRef Name = I->getName(StrTable, PrefixesTable);
164 for (auto PrefixOffset : I->getPrefixOffsets(PrefixesTable)) {
165 StringRef Prefix = StrTable[PrefixOffset];
166 if (Str.starts_with(Prefix)) {
167 StringRef Rest = Str.substr(Prefix.size());
168 bool Matched = IgnoreCase ? Rest.starts_with_insensitive(Name)
169 : Rest.starts_with(Name);
170 if (Matched)
171 return Prefix.size() + Name.size();
172 }
173 }
174 return 0;
175}
176
177// Returns true if one of the Prefixes + In.Names matches Option
178static bool optionMatches(const StringTable &StrTable,
179 ArrayRef<StringTable::Offset> PrefixesTable,
180 const OptTable::Info &In, StringRef Option) {
181 StringRef Name = In.getName(StrTable, PrefixesTable);
182 if (Option.consume_back(Name))
183 for (auto PrefixOffset : In.getPrefixOffsets(PrefixesTable))
184 if (Option == StrTable[PrefixOffset])
185 return true;
186 return false;
187}
188
189// This function is for flag value completion.
190// Eg. When "-stdlib=" and "l" was passed to this function, it will return
191// appropiriate values for stdlib, which starts with l.
192std::vector<std::string>
194 // Search all options and return possible values.
195 for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
196 const Info &In = OptionInfos[I];
197 if (!In.Values || !optionMatches(*StrTable, PrefixesTable, In, Option))
198 continue;
199
200 SmallVector<StringRef, 8> Candidates;
201 StringRef(In.Values).split(Candidates, ",", -1, false);
202
203 std::vector<std::string> Result;
204 for (StringRef Val : Candidates)
205 if (Val.starts_with(Arg) && Arg != Val)
206 Result.push_back(std::string(Val));
207 return Result;
208 }
209 return {};
210}
211
212std::vector<std::string>
214 unsigned int DisableFlags) const {
215 std::vector<std::string> Ret;
216 for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
217 const Info &In = OptionInfos[I];
218 if (In.hasNoPrefix() || (!In.HelpText && !In.GroupID))
219 continue;
220 if (!(In.Visibility & VisibilityMask))
221 continue;
222 if (In.Flags & DisableFlags)
223 continue;
224
225 StringRef Name = In.getName(*StrTable, PrefixesTable);
226 for (auto PrefixOffset : In.getPrefixOffsets(PrefixesTable)) {
227 StringRef Prefix = (*StrTable)[PrefixOffset];
228 std::string S = (Twine(Prefix) + Name + "\t").str();
229 if (In.HelpText)
230 S += In.HelpText;
231 if (StringRef(S).starts_with(Cur) && S != std::string(Cur) + "\t")
232 Ret.push_back(S);
233 }
234 }
235 return Ret;
236}
237
238unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
239 Visibility VisibilityMask,
240 unsigned MinimumLength,
241 unsigned MaximumDistance) const {
242 return internalFindNearest(
243 Option, NearestString, MinimumLength, MaximumDistance,
244 [VisibilityMask](const Info &CandidateInfo) {
245 return (CandidateInfo.Visibility & VisibilityMask) == 0;
246 });
247}
248
249unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
250 unsigned FlagsToInclude, unsigned FlagsToExclude,
251 unsigned MinimumLength,
252 unsigned MaximumDistance) const {
253 return internalFindNearest(
254 Option, NearestString, MinimumLength, MaximumDistance,
255 [FlagsToInclude, FlagsToExclude](const Info &CandidateInfo) {
256 if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
257 return true;
258 if (CandidateInfo.Flags & FlagsToExclude)
259 return true;
260 return false;
261 });
262}
263
264unsigned OptTable::internalFindNearest(
265 StringRef Option, std::string &NearestString, unsigned MinimumLength,
266 unsigned MaximumDistance,
267 std::function<bool(const Info &)> ExcludeOption) const {
268 assert(!Option.empty());
269
270 // Consider each [option prefix + option name] pair as a candidate, finding
271 // the closest match.
272 unsigned BestDistance =
273 MaximumDistance == UINT_MAX ? UINT_MAX : MaximumDistance + 1;
274 SmallString<16> Candidate;
275 SmallString<16> NormalizedName;
276
277 for (const Info &CandidateInfo :
278 ArrayRef<Info>(OptionInfos).drop_front(FirstSearchableIndex)) {
279 StringRef CandidateName = CandidateInfo.getName(*StrTable, PrefixesTable);
280
281 // We can eliminate some option prefix/name pairs as candidates right away:
282 // * Ignore option candidates with empty names, such as "--", or names
283 // that do not meet the minimum length.
284 if (CandidateName.size() < MinimumLength)
285 continue;
286
287 // Ignore options that are excluded via masks
288 if (ExcludeOption(CandidateInfo))
289 continue;
290
291 // * Ignore positional argument option candidates (which do not
292 // have prefixes).
293 if (CandidateInfo.hasNoPrefix())
294 continue;
295
296 // Now check if the candidate ends with a character commonly used when
297 // delimiting an option from its value, such as '=' or ':'. If it does,
298 // attempt to split the given option based on that delimiter.
299 char Last = CandidateName.back();
300 bool CandidateHasDelimiter = Last == '=' || Last == ':';
301 StringRef RHS;
302 if (CandidateHasDelimiter) {
303 std::tie(NormalizedName, RHS) = Option.split(Last);
304 if (Option.find(Last) == NormalizedName.size())
305 NormalizedName += Last;
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 (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
623 // For MultiArgs, metavar is full list of all argument names.
624 Name += ' ';
625 Name += MetaVarName;
626 }
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
636 break;
637
639 break;
640
643 Name += ' ';
644 [[fallthrough]];
647 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
648 Name += MetaVarName;
649 else
650 Name += "<value>";
651 break;
652 }
653
654 return Name;
655}
656
657namespace {
658struct OptionInfo {
659 std::string Name;
660 StringRef HelpText;
661};
662} // namespace
663
665 std::vector<OptionInfo> &OptionHelp) {
666 OS << Title << ":\n";
667
668 // Find the maximum option length.
669 unsigned OptionFieldWidth = 0;
670 for (const OptionInfo &Opt : OptionHelp) {
671 // Limit the amount of padding we are willing to give up for alignment.
672 unsigned Length = Opt.Name.size();
673 if (Length <= 23)
674 OptionFieldWidth = std::max(OptionFieldWidth, Length);
675 }
676
677 const unsigned InitialPad = 2;
678 for (const OptionInfo &Opt : OptionHelp) {
679 const std::string &Option = Opt.Name;
680 int Pad = OptionFieldWidth + InitialPad;
681 int FirstLinePad = OptionFieldWidth - int(Option.size());
682 OS.indent(InitialPad) << Option;
683
684 // Break on long option names.
685 if (FirstLinePad < 0) {
686 OS << "\n";
687 FirstLinePad = OptionFieldWidth + InitialPad;
688 Pad = FirstLinePad;
689 }
690
692 Opt.HelpText.split(Lines, '\n');
693 assert(Lines.size() && "Expected at least the first line in the help text");
694 auto *LinesIt = Lines.begin();
695 OS.indent(FirstLinePad + 1) << *LinesIt << '\n';
696 while (Lines.end() != ++LinesIt)
697 OS.indent(Pad + 1) << *LinesIt << '\n';
698 }
699}
700
701static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
702 unsigned GroupID = Opts.getOptionGroupID(Id);
703
704 // If not in a group, return the default help group.
705 if (!GroupID)
706 return "OPTIONS";
707
708 // Abuse the help text of the option groups to store the "help group"
709 // name.
710 //
711 // FIXME: Split out option groups.
712 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
713 return GroupHelp;
714
715 // Otherwise keep looking.
716 return getOptionHelpGroup(Opts, GroupID);
717}
718
719void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
720 bool ShowHidden, bool ShowAllAliases,
721 Visibility VisibilityMask,
722 StringRef SubCommand) const {
723 return internalPrintHelp(
724 OS, Usage, Title, SubCommand, ShowHidden, ShowAllAliases,
725 [VisibilityMask](const Info &CandidateInfo) -> bool {
726 return (CandidateInfo.Visibility & VisibilityMask) == 0;
727 },
728 VisibilityMask);
729}
730
731void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
732 unsigned FlagsToInclude, unsigned FlagsToExclude,
733 bool ShowAllAliases) const {
734 bool ShowHidden = !(FlagsToExclude & HelpHidden);
735 FlagsToExclude &= ~HelpHidden;
736 return internalPrintHelp(
737 OS, Usage, Title, /*SubCommand=*/{}, ShowHidden, ShowAllAliases,
738 [FlagsToInclude, FlagsToExclude](const Info &CandidateInfo) {
739 if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
740 return true;
741 if (CandidateInfo.Flags & FlagsToExclude)
742 return true;
743 return false;
744 },
745 Visibility(0));
746}
747
748void OptTable::internalPrintHelp(
749 raw_ostream &OS, const char *Usage, const char *Title, StringRef SubCommand,
750 bool ShowHidden, bool ShowAllAliases,
751 std::function<bool(const Info &)> ExcludeOption,
752 Visibility VisibilityMask) const {
753 OS << "OVERVIEW: " << Title << "\n\n";
754
755 // Render help text into a map of group-name to a list of (option, help)
756 // pairs.
757 std::map<std::string, std::vector<OptionInfo>> GroupedOptionHelp;
758
759 auto ActiveSubCommand =
760 std::find_if(SubCommands.begin(), SubCommands.end(),
761 [&](const auto &C) { return SubCommand == C.Name; });
762 if (!SubCommand.empty()) {
763 assert(ActiveSubCommand != SubCommands.end() &&
764 "Not a valid registered subcommand.");
765 OS << ActiveSubCommand->HelpText << "\n\n";
766 if (!StringRef(ActiveSubCommand->Usage).empty())
767 OS << "USAGE: " << ActiveSubCommand->Usage << "\n\n";
768 } else {
769 OS << "USAGE: " << Usage << "\n\n";
770 if (SubCommands.size() > 1) {
771 OS << "SUBCOMMANDS:\n\n";
772 for (const auto &C : SubCommands)
773 OS << C.Name << " - " << C.HelpText << "\n";
774 OS << "\n";
775 }
776 }
777
778 auto DoesOptionBelongToSubcommand = [&](const Info &CandidateInfo) {
779 // Retrieve the SubCommandIDs registered to the given current CandidateInfo
780 // Option.
781 ArrayRef<unsigned> SubCommandIDs =
782 CandidateInfo.getSubCommandIDs(SubCommandIDsTable);
783
784 // If no registered subcommands, then only global options are to be printed.
785 // If no valid SubCommand (empty) in commandline then print the current
786 // global CandidateInfo Option.
787 if (SubCommandIDs.empty())
788 return SubCommand.empty();
789
790 // Handle CandidateInfo Option which has at least one registered SubCommand.
791 // If no valid SubCommand (empty) in commandline, this CandidateInfo option
792 // should not be printed.
793 if (SubCommand.empty())
794 return false;
795
796 // Find the ID of the valid subcommand passed in commandline (its index in
797 // the SubCommands table which contains all subcommands).
798 unsigned ActiveSubCommandID = ActiveSubCommand - &SubCommands[0];
799 // Print if the ActiveSubCommandID is registered with the CandidateInfo
800 // Option.
801 return std::find(SubCommandIDs.begin(), SubCommandIDs.end(),
802 ActiveSubCommandID) != SubCommandIDs.end();
803 };
804
805 for (unsigned Id = 1, e = getNumOptions() + 1; Id != e; ++Id) {
806 // FIXME: Split out option groups.
808 continue;
809
810 const Info &CandidateInfo = getInfo(Id);
811 if (!ShowHidden && (CandidateInfo.Flags & opt::HelpHidden))
812 continue;
813
814 if (ExcludeOption(CandidateInfo))
815 continue;
816
817 if (!DoesOptionBelongToSubcommand(CandidateInfo))
818 continue;
819
820 // If an alias doesn't have a help text, show a help text for the aliased
821 // option instead.
822 const char *HelpText = getOptionHelpText(Id, VisibilityMask);
823 if (!HelpText && ShowAllAliases) {
824 const Option Alias = getOption(Id).getAlias();
825 if (Alias.isValid())
826 HelpText = getOptionHelpText(Alias.getID(), VisibilityMask);
827 }
828
829 if (HelpText && (strlen(HelpText) != 0)) {
830 const char *HelpGroup = getOptionHelpGroup(*this, Id);
831 const std::string &OptName = getOptionHelpName(*this, Id);
832 GroupedOptionHelp[HelpGroup].push_back({OptName, HelpText});
833 }
834 }
835
836 for (auto& OptionGroup : GroupedOptionHelp) {
837 if (OptionGroup.first != GroupedOptionHelp.begin()->first)
838 OS << "\n";
839 PrintHelpOptionList(OS, OptionGroup.first, OptionGroup.second);
840 }
841
842 OS.flush();
843}
844
846 ArrayRef<StringTable::Offset> PrefixesTable,
847 ArrayRef<Info> OptionInfos, bool IgnoreCase,
848 ArrayRef<SubCommand> SubCommands,
849 ArrayRef<unsigned> SubCommandIDsTable)
850 : OptTable(StrTable, PrefixesTable, OptionInfos, IgnoreCase, SubCommands,
851 SubCommandIDsTable) {
852
853 std::set<StringRef> TmpPrefixesUnion;
854 for (auto const &Info : OptionInfos.drop_front(FirstSearchableIndex))
855 for (auto PrefixOffset : Info.getPrefixOffsets(PrefixesTable))
856 TmpPrefixesUnion.insert(StrTable[PrefixOffset]);
857 PrefixesUnion.append(TmpPrefixesUnion.begin(), TmpPrefixesUnion.end());
859}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Defines the llvm::Arg class for parsed arguments.
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:58
static const char * getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id)
Definition OptTable.cpp:701
static unsigned matchOption(const StringTable &StrTable, ArrayRef< StringTable::Offset > PrefixesTable, const OptTable::Info *I, StringRef Str, bool IgnoreCase)
Definition OptTable.cpp:159
static bool optionMatches(const StringTable &StrTable, ArrayRef< StringTable::Offset > PrefixesTable, const OptTable::Info &In, StringRef Option)
Definition OptTable.cpp:178
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:149
static void PrintHelpOptionList(raw_ostream &OS, StringRef Title, std::vector< OptionInfo > &OptionHelp)
Definition OptTable.cpp:664
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
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
iterator end() const
Definition ArrayRef.h:136
size_t size() const
size - Get the array size.
Definition ArrayRef.h:147
iterator begin() const
Definition ArrayRef.h:135
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:142
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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:702
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:573
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:261
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
LLVM_ABI bool starts_with_insensitive(StringRef Prefix) const
Check if this string starts with the given Prefix, ignoring case.
Definition StringRef.cpp:46
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:93
char back() const
back - Get the last character in the string.
Definition StringRef.h:155
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:146
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition StringSaver.h:22
A table of densely packed, null-terminated strings indexed by offset.
Definition StringTable.h:33
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
LLVM_ABI GenericOptTable(const StringTable &StrTable, ArrayRef< StringTable::Offset > PrefixesTable, ArrayRef< Info > OptionInfos, bool IgnoreCase=false, ArrayRef< SubCommand > SubCommands={}, ArrayRef< unsigned > SubCommandIDsTable={})
Definition OptTable.cpp:845
OptSpecifier - Wrapper class for abstracting references to option IDs.
unsigned getID() const
Provide access to the Option info table.
Definition OptTable.h:54
void buildPrefixChars()
Build (or rebuild) the PrefixChars member.
Definition OptTable.cpp:128
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:271
unsigned FirstSearchableIndex
The index of the first option which can be parsed (i.e., is not a special option like 'input' or 'unk...
Definition OptTable.h:194
const char * getOptionMetaVar(OptSpecifier id) const
Get the meta-variable name to use when describing this options values in the help text.
Definition OptTable.h:300
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:238
SmallVector< StringRef > PrefixesUnion
The union of all option prefixes.
Definition OptTable.h:198
const Option getOption(OptSpecifier Opt) const
Get the given Opt's Option instance, lazily creating it if necessary.
Definition OptTable.cpp:141
const char * getOptionHelpText(OptSpecifier id) const
Get the help text to use to describe this option.
Definition OptTable.h:281
OptTable(const StringTable &StrTable, ArrayRef< StringTable::Offset > PrefixesTable, ArrayRef< Info > OptionInfos, bool IgnoreCase=false, ArrayRef< SubCommand > SubCommands={}, ArrayRef< unsigned > SubCommandIDsTable={})
Initialize OptTable using Tablegen'ed OptionInfos.
Definition OptTable.cpp:80
unsigned getOptionGroupID(OptSpecifier id) const
Get the group id for the given option.
Definition OptTable.h:276
std::vector< std::string > suggestValueCompletions(StringRef Option, StringRef Arg) const
Find possible value for given flags.
Definition OptTable.cpp:193
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
SmallString< 8 > PrefixChars
The union of the first element of all option prefixes.
Definition OptTable.h:201
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:719
unsigned getNumOptions() const
Return the total number of option classes.
Definition OptTable.h:239
std::vector< std::string > findByPrefix(StringRef Cur, Visibility VisibilityMask, unsigned int DisableFlags) const
Find flags from OptTable which starts with Cur.
Definition OptTable.cpp:213
Option - Abstract representation for a single form of driver argument.
Definition Option.h:55
const Option getAlias() const
Definition Option.h:114
LLVM_ABI void dump() const
Definition Option.cpp:93
bool hasFlag(unsigned Val) const
Test if this option has the flag Val.
Definition Option.h:188
@ 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:193
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.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
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
Definition MathExtras.h:47
@ HelpHidden
Definition Option.h:34
This is an optimization pass for GlobalISel generic memory operations.
@ Length
Definition DWP.cpp:477
int StrCmpOptionName(StringRef A, StringRef B, bool FallbackCaseSensitive=true)
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 >
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1899
Entry for a single option instance in the option data table.
Definition OptTable.h:64
ArrayRef< StringTable::Offset > getPrefixOffsets(ArrayRef< StringTable::Offset > PrefixesTable) const
Definition OptTable.h:100
unsigned int Visibility
Definition OptTable.h:84
Represents a subcommand and its options in the option table.
Definition OptTable.h:57