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 <cstring>
24#include <map>
25#include <set>
26#include <string>
27#include <vector>
28
29using namespace llvm;
30using namespace llvm::opt;
31
32namespace {
33struct OptNameLess {
34 const StringTable *StrTable;
36
37 explicit OptNameLess(const StringTable &StrTable,
39 : StrTable(&StrTable), PrefixesTable(PrefixesTable) {}
40
41#ifndef NDEBUG
42 inline bool operator()(const OptTable::Info &A,
43 const OptTable::Info &B) const {
44 if (&A == &B)
45 return false;
46
47 if (int Cmp = StrCmpOptionName(A.getName(*StrTable, PrefixesTable),
48 B.getName(*StrTable, PrefixesTable)))
49 return Cmp < 0;
50
51 SmallVector<StringRef, 8> APrefixes, BPrefixes;
52 A.appendPrefixes(*StrTable, PrefixesTable, APrefixes);
53 B.appendPrefixes(*StrTable, PrefixesTable, BPrefixes);
54
55 if (int Cmp = StrCmpOptionPrefixes(APrefixes, BPrefixes))
56 return Cmp < 0;
57
58 // Names are the same, check that classes are in order; exactly one
59 // should be joined, and it should succeed the other.
60 assert(
61 ((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
62 "Unexpected classes for options with same name.");
63 return B.Kind == Option::JoinedClass;
64 }
65#endif
66
67 // Support lower_bound between info and an option name.
68 inline bool operator()(const OptTable::Info &I, StringRef Name) const {
69 // Do not fallback to case sensitive comparison.
70 return StrCmpOptionName(I.getName(*StrTable, PrefixesTable), Name, false) <
71 0;
72 }
73};
74} // namespace
75
76OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
77
80 ArrayRef<Info> OptionInfos, bool IgnoreCase,
81 ArrayRef<SubCommand> SubCommands,
82 ArrayRef<unsigned> SubCommandIDsTable)
83 : StrTable(&StrTable), PrefixesTable(PrefixesTable),
84 OptionInfos(OptionInfos), IgnoreCase(IgnoreCase),
85 SubCommands(SubCommands), SubCommandIDsTable(SubCommandIDsTable) {
86 // Explicitly zero initialize the error to work around a bug in array
87 // value-initialization on MinGW with gcc 4.3.5.
88
89 // Find start of normal options.
90 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
91 unsigned Kind = getInfo(i + 1).Kind;
92 if (Kind == Option::InputClass) {
93 assert(!InputOptionID && "Cannot have multiple input options!");
94 InputOptionID = getInfo(i + 1).ID;
95 } else if (Kind == Option::UnknownClass) {
96 assert(!UnknownOptionID && "Cannot have multiple unknown options!");
97 UnknownOptionID = getInfo(i + 1).ID;
98 } else if (Kind != Option::GroupClass) {
100 break;
101 }
102 }
103 assert(FirstSearchableIndex != 0 && "No searchable options?");
104
105#ifndef NDEBUG
106 // Check that everything after the first searchable option is a
107 // regular option class.
108 for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
109 Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
110 assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
111 Kind != Option::GroupClass) &&
112 "Special options should be defined first!");
113 }
114
115 // Check that options are in order.
116 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
117 if (!(OptNameLess(StrTable, PrefixesTable)(getInfo(i), getInfo(i + 1)))) {
118 getOption(i).dump();
119 getOption(i + 1).dump();
120 llvm_unreachable("Options are not in order!");
121 }
122 }
123#endif
124}
125
127 assert(PrefixChars.empty() && "rebuilding a non-empty prefix char");
128
129 // Build prefix chars.
130 for (StringRef Prefix : PrefixesUnion) {
131 for (char C : Prefix)
133 PrefixChars.push_back(C);
134 }
135}
136
137OptTable::~OptTable() = default;
138
140 unsigned id = Opt.getID();
141 if (id == 0)
142 return Option(nullptr, nullptr);
143 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
144 return Option(&getInfo(id), this);
145}
146
147static bool isInput(const ArrayRef<StringRef> &Prefixes, StringRef Arg) {
148 if (Arg == "-")
149 return true;
150 for (const StringRef &Prefix : Prefixes)
151 if (Arg.starts_with(Prefix))
152 return false;
153 return true;
154}
155
156/// \returns Matched size. 0 means no match.
157static unsigned matchOption(const StringTable &StrTable,
158 ArrayRef<StringTable::Offset> PrefixesTable,
159 const OptTable::Info *I, StringRef Str,
160 bool IgnoreCase) {
161 StringRef Name = I->getName(StrTable, PrefixesTable);
162 for (auto PrefixOffset : I->getPrefixOffsets(PrefixesTable)) {
163 StringRef Prefix = StrTable[PrefixOffset];
164 if (Str.starts_with(Prefix)) {
165 StringRef Rest = Str.substr(Prefix.size());
166 bool Matched = IgnoreCase ? Rest.starts_with_insensitive(Name)
167 : Rest.starts_with(Name);
168 if (Matched)
169 return Prefix.size() + Name.size();
170 }
171 }
172 return 0;
173}
174
175// Returns true if one of the Prefixes + In.Names matches Option
176static bool optionMatches(const StringTable &StrTable,
177 ArrayRef<StringTable::Offset> PrefixesTable,
178 const OptTable::Info &In, StringRef Option) {
179 StringRef Name = In.getName(StrTable, PrefixesTable);
180 if (Option.consume_back(Name))
181 for (auto PrefixOffset : In.getPrefixOffsets(PrefixesTable))
182 if (Option == StrTable[PrefixOffset])
183 return true;
184 return false;
185}
186
187// This function is for flag value completion.
188// Eg. When "-stdlib=" and "l" was passed to this function, it will return
189// appropiriate values for stdlib, which starts with l.
190std::vector<std::string>
192 // Search all options and return possible values.
193 for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
194 const Info &In = OptionInfos[I];
195 if (!In.Values || !optionMatches(*StrTable, PrefixesTable, In, Option))
196 continue;
197
198 SmallVector<StringRef, 8> Candidates;
199 StringRef(In.Values).split(Candidates, ",", -1, false);
200
201 std::vector<std::string> Result;
202 for (StringRef Val : Candidates)
203 if (Val.starts_with(Arg) && Arg != Val)
204 Result.push_back(std::string(Val));
205 return Result;
206 }
207 return {};
208}
209
210std::vector<std::string>
212 unsigned int DisableFlags) const {
213 std::vector<std::string> Ret;
214 for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
215 const Info &In = OptionInfos[I];
216 if (In.hasNoPrefix() || (!In.HelpText && !In.GroupID))
217 continue;
218 if (!(In.Visibility & VisibilityMask))
219 continue;
220 if (In.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 if (In.HelpText)
228 S += In.HelpText;
229 if (StringRef(S).starts_with(Cur) && S != std::string(Cur) + "\t")
230 Ret.push_back(S);
231 }
232 }
233 return Ret;
234}
235
236unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
237 Visibility VisibilityMask,
238 unsigned MinimumLength,
239 unsigned MaximumDistance) const {
240 return internalFindNearest(
241 Option, NearestString, MinimumLength, MaximumDistance,
242 [VisibilityMask](const Info &CandidateInfo) {
243 return (CandidateInfo.Visibility & VisibilityMask) == 0;
244 });
245}
246
247unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
248 unsigned FlagsToInclude, unsigned FlagsToExclude,
249 unsigned MinimumLength,
250 unsigned MaximumDistance) const {
251 return internalFindNearest(
252 Option, NearestString, MinimumLength, MaximumDistance,
253 [FlagsToInclude, FlagsToExclude](const Info &CandidateInfo) {
254 if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
255 return true;
256 if (CandidateInfo.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
303 NormalizedName = Option;
304
305 // Consider each possible prefix for each candidate to find the most
306 // appropriate one. For example, if a user asks for "--helm", suggest
307 // "--help" over "-help".
308 for (auto CandidatePrefixOffset :
309 CandidateInfo.getPrefixOffsets(PrefixesTable)) {
310 StringRef CandidatePrefix = (*StrTable)[CandidatePrefixOffset];
311 // If Candidate and NormalizedName have more than 'BestDistance'
312 // characters of difference, no need to compute the edit distance, it's
313 // going to be greater than BestDistance. Don't bother computing Candidate
314 // at all.
315 size_t CandidateSize = CandidatePrefix.size() + CandidateName.size(),
316 NormalizedSize = NormalizedName.size();
317 size_t AbsDiff = CandidateSize > NormalizedSize
318 ? CandidateSize - NormalizedSize
319 : NormalizedSize - CandidateSize;
320 if (AbsDiff > BestDistance) {
321 continue;
322 }
323 Candidate = CandidatePrefix;
324 Candidate += CandidateName;
325 unsigned Distance = StringRef(Candidate).edit_distance(
326 NormalizedName, /*AllowReplacements=*/true,
327 /*MaxEditDistance=*/BestDistance);
328 if (RHS.empty() && CandidateHasDelimiter) {
329 // The Candidate ends with a = or : delimiter, but the option passed in
330 // didn't contain the delimiter (or doesn't have anything after it).
331 // In that case, penalize the correction: `-nodefaultlibs` is more
332 // likely to be a spello for `-nodefaultlib` than `-nodefaultlib:` even
333 // though both have an unmodified editing distance of 1, since the
334 // latter would need an argument.
335 ++Distance;
336 }
337 if (Distance < BestDistance) {
338 BestDistance = Distance;
339 NearestString = (Candidate + RHS).str();
340 }
341 }
342 }
343 return BestDistance;
344}
345
346// Parse a single argument, return the new argument, and update Index. If
347// GroupedShortOptions is true, -a matches "-abc" and the argument in Args will
348// be updated to "-bc". This overload does not support VisibilityMask or case
349// insensitive options.
350std::unique_ptr<Arg> OptTable::parseOneArgGrouped(InputArgList &Args,
351 unsigned &Index) const {
352 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
353 // itself.
354 const char *CStr = Args.getArgString(Index);
355 StringRef Str(CStr);
356 if (isInput(PrefixesUnion, Str))
357 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++, CStr);
358
359 const Info *End = OptionInfos.data() + OptionInfos.size();
360 StringRef Name = Str.ltrim(PrefixChars);
361 const Info *Start =
362 std::lower_bound(OptionInfos.data() + FirstSearchableIndex, End, Name,
363 OptNameLess(*StrTable, PrefixesTable));
364 const Info *Fallback = nullptr;
365 unsigned Prev = Index;
366
367 // Search for the option which matches Str.
368 for (; Start != End; ++Start) {
369 unsigned ArgSize =
370 matchOption(*StrTable, PrefixesTable, Start, Str, IgnoreCase);
371 if (!ArgSize)
372 continue;
373
374 Option Opt(Start, this);
375 if (std::unique_ptr<Arg> A =
376 Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
377 /*GroupedShortOption=*/false, Index))
378 return A;
379
380 // If Opt is a Flag of length 2 (e.g. "-a"), we know it is a prefix of
381 // the current argument (e.g. "-abc"). Match it as a fallback if no longer
382 // option (e.g. "-ab") exists.
383 if (ArgSize == 2 && Opt.getKind() == Option::FlagClass)
384 Fallback = Start;
385
386 // Otherwise, see if the argument is missing.
387 if (Prev != Index)
388 return nullptr;
389 }
390 if (Fallback) {
391 Option Opt(Fallback, this);
392 // Check that the last option isn't a flag wrongly given an argument.
393 if (Str[2] == '=')
394 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
395 CStr);
396
397 if (std::unique_ptr<Arg> A = Opt.accept(
398 Args, Str.substr(0, 2), /*GroupedShortOption=*/true, Index)) {
399 Args.replaceArgString(Index, Twine('-') + Str.substr(2));
400 return A;
401 }
402 }
403
404 // In the case of an incorrect short option extract the character and move to
405 // the next one.
406 if (Str[1] != '-') {
407 CStr = Args.MakeArgString(Str.substr(0, 2));
408 Args.replaceArgString(Index, Twine('-') + Str.substr(2));
409 return std::make_unique<Arg>(getOption(UnknownOptionID), CStr, Index, CStr);
410 }
411
412 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++, CStr);
413}
414
415std::unique_ptr<Arg> OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
416 Visibility VisibilityMask) const {
417 return internalParseOneArg(Args, Index, [VisibilityMask](const Option &Opt) {
418 return !Opt.hasVisibilityFlag(VisibilityMask);
419 });
420}
421
422std::unique_ptr<Arg> OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
423 unsigned FlagsToInclude,
424 unsigned FlagsToExclude) const {
425 return internalParseOneArg(
426 Args, Index, [FlagsToInclude, FlagsToExclude](const Option &Opt) {
427 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
428 return true;
429 if (Opt.hasFlag(FlagsToExclude))
430 return true;
431 return false;
432 });
433}
434
435std::unique_ptr<Arg> OptTable::internalParseOneArg(
436 const ArgList &Args, unsigned &Index,
437 std::function<bool(const Option &)> ExcludeOption) const {
438 unsigned Prev = Index;
439 StringRef Str = Args.getArgString(Index);
440
441 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
442 // itself.
443 if (isInput(PrefixesUnion, Str))
444 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++,
445 Str.data());
446
447 const Info *Start = OptionInfos.data() + FirstSearchableIndex;
448 const Info *End = OptionInfos.data() + OptionInfos.size();
449 StringRef Name = Str.ltrim(PrefixChars);
450
451 // Search for the first next option which could be a prefix.
452 Start =
453 std::lower_bound(Start, End, Name, OptNameLess(*StrTable, PrefixesTable));
454
455 // Options are stored in sorted order, with '\0' at the end of the
456 // alphabet. Since the only options which can accept a string must
457 // prefix it, we iteratively search for the next option which could
458 // be a prefix.
459 //
460 // FIXME: This is searching much more than necessary, but I am
461 // blanking on the simplest way to make it fast. We can solve this
462 // problem when we move to TableGen.
463 for (; Start != End; ++Start) {
464 unsigned ArgSize = 0;
465 // Scan for first option which is a proper prefix.
466 for (; Start != End; ++Start)
467 if ((ArgSize =
468 matchOption(*StrTable, PrefixesTable, Start, Str, IgnoreCase)))
469 break;
470 if (Start == End)
471 break;
472
473 Option Opt(Start, this);
474
475 if (ExcludeOption(Opt))
476 continue;
477
478 // See if this option matches.
479 if (std::unique_ptr<Arg> A =
480 Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
481 /*GroupedShortOption=*/false, Index))
482 return A;
483
484 // Otherwise, see if this argument was missing values.
485 if (Prev != Index)
486 return nullptr;
487 }
488
489 // If we failed to find an option and this arg started with /, then it's
490 // probably an input path.
491 if (Str[0] == '/')
492 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++,
493 Str.data());
494
495 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
496 Str.data());
497}
498
500 unsigned &MissingArgIndex,
501 unsigned &MissingArgCount,
502 Visibility VisibilityMask) const {
503 return internalParseArgs(
504 Args, MissingArgIndex, MissingArgCount,
505 [VisibilityMask](const Option &Opt) {
506 return !Opt.hasVisibilityFlag(VisibilityMask);
507 });
508}
509
511 unsigned &MissingArgIndex,
512 unsigned &MissingArgCount,
513 unsigned FlagsToInclude,
514 unsigned FlagsToExclude) const {
515 return internalParseArgs(
516 Args, MissingArgIndex, MissingArgCount,
517 [FlagsToInclude, FlagsToExclude](const Option &Opt) {
518 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
519 return true;
520 if (Opt.hasFlag(FlagsToExclude))
521 return true;
522 return false;
523 });
524}
525
526InputArgList OptTable::internalParseArgs(
527 ArrayRef<const char *> ArgArr, unsigned &MissingArgIndex,
528 unsigned &MissingArgCount,
529 std::function<bool(const Option &)> ExcludeOption) const {
530 InputArgList Args(ArgArr.begin(), ArgArr.end());
531
532 // FIXME: Handle '@' args (or at least error on them).
533
534 MissingArgIndex = MissingArgCount = 0;
535 unsigned Index = 0, End = ArgArr.size();
536 while (Index < End) {
537 // Ingore nullptrs, they are response file's EOL markers
538 if (Args.getArgString(Index) == nullptr) {
539 ++Index;
540 continue;
541 }
542 // Ignore empty arguments (other things may still take them as arguments).
543 StringRef Str = Args.getArgString(Index);
544 if (Str == "") {
545 ++Index;
546 continue;
547 }
548
549 // In DashDashParsing mode, the first "--" stops option scanning and treats
550 // all subsequent arguments as positional.
551 if (DashDashParsing && Str == "--") {
552 while (++Index < End) {
553 Args.append(new Arg(getOption(InputOptionID), Str, Index,
554 Args.getArgString(Index)));
555 }
556 break;
557 }
558
559 unsigned Prev = Index;
560 std::unique_ptr<Arg> A = GroupedShortOptions
561 ? parseOneArgGrouped(Args, Index)
562 : internalParseOneArg(Args, Index, ExcludeOption);
563 assert((Index > Prev || GroupedShortOptions) &&
564 "Parser failed to consume argument.");
565
566 // Check for missing argument error.
567 if (!A) {
568 assert(Index >= End && "Unexpected parser error.");
569 assert(Index - Prev - 1 && "No missing arguments!");
570 MissingArgIndex = Prev;
571 MissingArgCount = Index - Prev - 1;
572 break;
573 }
574
575 Args.append(A.release());
576 }
577
578 return Args;
579}
580
581InputArgList OptTable::parseArgs(int Argc, char *const *Argv,
583 std::function<void(StringRef)> ErrorFn) const {
585 // The environment variable specifies initial options which can be overridden
586 // by commnad line options.
587 cl::expandResponseFiles(Argc, Argv, EnvVar, Saver, NewArgv);
588
589 unsigned MAI, MAC;
590 opt::InputArgList Args = ParseArgs(ArrayRef(NewArgv), MAI, MAC);
591 if (MAC)
592 ErrorFn((Twine(Args.getArgString(MAI)) + ": missing argument").str());
593
594 // For each unknwon option, call ErrorFn with a formatted error message. The
595 // message includes a suggested alternative option spelling if available.
596 std::string Nearest;
597 for (const opt::Arg *A : Args.filtered(Unknown)) {
598 std::string Spelling = A->getAsString(Args);
599 if (findNearest(Spelling, Nearest) > 1)
600 ErrorFn("unknown argument '" + Spelling + "'");
601 else
602 ErrorFn("unknown argument '" + Spelling + "', did you mean '" + Nearest +
603 "'?");
604 }
605 return Args;
606}
607
608static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
609 const Option O = Opts.getOption(Id);
610 std::string Name = O.getPrefixedName().str();
611
612 // Add metavar, if used.
613 switch (O.getKind()) {
615 llvm_unreachable("Invalid option with help text.");
616
618 if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
619 // For MultiArgs, metavar is full list of all argument names.
620 Name += ' ';
621 Name += MetaVarName;
622 }
623 else {
624 // For MultiArgs<N>, if metavar not supplied, print <value> N times.
625 for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
626 Name += " <value>";
627 }
628 }
629 break;
630
632 break;
633
635 break;
636
639 Name += ' ';
640 [[fallthrough]];
643 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
644 Name += MetaVarName;
645 else
646 Name += "<value>";
647 break;
648 }
649
650 return Name;
651}
652
653namespace {
654struct OptionInfo {
655 std::string Name;
656 StringRef HelpText;
657};
658} // namespace
659
661 std::vector<OptionInfo> &OptionHelp) {
662 OS << Title << ":\n";
663
664 // Find the maximum option length.
665 unsigned OptionFieldWidth = 0;
666 for (const OptionInfo &Opt : OptionHelp) {
667 // Limit the amount of padding we are willing to give up for alignment.
668 unsigned Length = Opt.Name.size();
669 if (Length <= 23)
670 OptionFieldWidth = std::max(OptionFieldWidth, Length);
671 }
672
673 const unsigned InitialPad = 2;
674 for (const OptionInfo &Opt : OptionHelp) {
675 const std::string &Option = Opt.Name;
676 int Pad = OptionFieldWidth + InitialPad;
677 int FirstLinePad = OptionFieldWidth - int(Option.size());
678 OS.indent(InitialPad) << Option;
679
680 // Break on long option names.
681 if (FirstLinePad < 0) {
682 OS << "\n";
683 FirstLinePad = OptionFieldWidth + InitialPad;
684 Pad = FirstLinePad;
685 }
686
688 Opt.HelpText.split(Lines, '\n');
689 assert(Lines.size() && "Expected at least the first line in the help text");
690 auto *LinesIt = Lines.begin();
691 OS.indent(FirstLinePad + 1) << *LinesIt << '\n';
692 while (Lines.end() != ++LinesIt)
693 OS.indent(Pad + 1) << *LinesIt << '\n';
694 }
695}
696
697static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
698 unsigned GroupID = Opts.getOptionGroupID(Id);
699
700 // If not in a group, return the default help group.
701 if (!GroupID)
702 return "OPTIONS";
703
704 // Abuse the help text of the option groups to store the "help group"
705 // name.
706 //
707 // FIXME: Split out option groups.
708 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
709 return GroupHelp;
710
711 // Otherwise keep looking.
712 return getOptionHelpGroup(Opts, GroupID);
713}
714
715void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
716 bool ShowHidden, bool ShowAllAliases,
717 Visibility VisibilityMask,
718 StringRef SubCommand) const {
719 return internalPrintHelp(
720 OS, Usage, Title, SubCommand, ShowHidden, ShowAllAliases,
721 [VisibilityMask](const Info &CandidateInfo) -> bool {
722 return (CandidateInfo.Visibility & VisibilityMask) == 0;
723 },
724 VisibilityMask);
725}
726
727void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
728 unsigned FlagsToInclude, unsigned FlagsToExclude,
729 bool ShowAllAliases) const {
730 bool ShowHidden = !(FlagsToExclude & HelpHidden);
731 FlagsToExclude &= ~HelpHidden;
732 return internalPrintHelp(
733 OS, Usage, Title, /*SubCommand=*/{}, ShowHidden, ShowAllAliases,
734 [FlagsToInclude, FlagsToExclude](const Info &CandidateInfo) {
735 if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
736 return true;
737 if (CandidateInfo.Flags & FlagsToExclude)
738 return true;
739 return false;
740 },
741 Visibility(0));
742}
743
744void OptTable::internalPrintHelp(
745 raw_ostream &OS, const char *Usage, const char *Title, StringRef SubCommand,
746 bool ShowHidden, bool ShowAllAliases,
747 std::function<bool(const Info &)> ExcludeOption,
748 Visibility VisibilityMask) const {
749 OS << "OVERVIEW: " << Title << "\n\n";
750
751 // Render help text into a map of group-name to a list of (option, help)
752 // pairs.
753 std::map<std::string, std::vector<OptionInfo>> GroupedOptionHelp;
754
755 auto ActiveSubCommand = llvm::find_if(
756 SubCommands, [&](const auto &C) { return SubCommand == C.Name; });
757 if (!SubCommand.empty()) {
758 assert(ActiveSubCommand != SubCommands.end() &&
759 "Not a valid registered subcommand.");
760 OS << ActiveSubCommand->HelpText << "\n\n";
761 if (!StringRef(ActiveSubCommand->Usage).empty())
762 OS << "USAGE: " << ActiveSubCommand->Usage << "\n\n";
763 } else {
764 OS << "USAGE: " << Usage << "\n\n";
765 if (SubCommands.size() > 1) {
766 OS << "SUBCOMMANDS:\n\n";
767 for (const auto &C : SubCommands)
768 OS << C.Name << " - " << C.HelpText << "\n";
769 OS << "\n";
770 }
771 }
772
773 auto DoesOptionBelongToSubcommand = [&](const Info &CandidateInfo) {
774 // Retrieve the SubCommandIDs registered to the given current CandidateInfo
775 // Option.
776 ArrayRef<unsigned> SubCommandIDs =
777 CandidateInfo.getSubCommandIDs(SubCommandIDsTable);
778
779 // If no registered subcommands, then only global options are to be printed.
780 // If no valid SubCommand (empty) in commandline then print the current
781 // global CandidateInfo Option.
782 if (SubCommandIDs.empty())
783 return SubCommand.empty();
784
785 // Handle CandidateInfo Option which has at least one registered SubCommand.
786 // If no valid SubCommand (empty) in commandline, this CandidateInfo option
787 // should not be printed.
788 if (SubCommand.empty())
789 return false;
790
791 // Find the ID of the valid subcommand passed in commandline (its index in
792 // the SubCommands table which contains all subcommands).
793 unsigned ActiveSubCommandID = ActiveSubCommand - &SubCommands[0];
794 // Print if the ActiveSubCommandID is registered with the CandidateInfo
795 // Option.
796 return llvm::is_contained(SubCommandIDs, ActiveSubCommandID);
797 };
798
799 for (unsigned Id = 1, e = getNumOptions() + 1; Id != e; ++Id) {
800 // FIXME: Split out option groups.
802 continue;
803
804 const Info &CandidateInfo = getInfo(Id);
805 if (!ShowHidden && (CandidateInfo.Flags & opt::HelpHidden))
806 continue;
807
808 if (ExcludeOption(CandidateInfo))
809 continue;
810
811 if (!DoesOptionBelongToSubcommand(CandidateInfo))
812 continue;
813
814 // If an alias doesn't have a help text, show a help text for the aliased
815 // option instead.
816 const char *HelpText = getOptionHelpText(Id, VisibilityMask);
817 if (!HelpText && ShowAllAliases) {
818 const Option Alias = getOption(Id).getAlias();
819 if (Alias.isValid())
820 HelpText = getOptionHelpText(Alias.getID(), VisibilityMask);
821 }
822
823 if (HelpText && (strlen(HelpText) != 0)) {
824 const char *HelpGroup = getOptionHelpGroup(*this, Id);
825 const std::string &OptName = getOptionHelpName(*this, Id);
826 GroupedOptionHelp[HelpGroup].push_back({OptName, HelpText});
827 }
828 }
829
830 for (auto& OptionGroup : GroupedOptionHelp) {
831 if (OptionGroup.first != GroupedOptionHelp.begin()->first)
832 OS << "\n";
833 PrintHelpOptionList(OS, OptionGroup.first, OptionGroup.second);
834 }
835
836 OS.flush();
837}
838
840 ArrayRef<StringTable::Offset> PrefixesTable,
841 ArrayRef<Info> OptionInfos, bool IgnoreCase,
842 ArrayRef<SubCommand> SubCommands,
843 ArrayRef<unsigned> SubCommandIDsTable)
844 : OptTable(StrTable, PrefixesTable, OptionInfos, IgnoreCase, SubCommands,
845 SubCommandIDsTable) {
846
847 std::set<StringRef> TmpPrefixesUnion;
848 for (auto const &Info : OptionInfos.drop_front(FirstSearchableIndex))
849 for (auto PrefixOffset : Info.getPrefixOffsets(PrefixesTable))
850 TmpPrefixesUnion.insert(StrTable[PrefixOffset]);
851 PrefixesUnion.append(TmpPrefixesUnion.begin(), TmpPrefixesUnion.end());
853}
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< 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
static const char * getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id)
Definition OptTable.cpp:697
static unsigned matchOption(const StringTable &StrTable, ArrayRef< StringTable::Offset > PrefixesTable, const OptTable::Info *I, StringRef Str, bool IgnoreCase)
Definition OptTable.cpp:157
static bool optionMatches(const StringTable &StrTable, ArrayRef< StringTable::Offset > PrefixesTable, const OptTable::Info &In, StringRef Option)
Definition OptTable.cpp:176
static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id)
Definition OptTable.cpp:608
static bool isInput(const ArrayRef< StringRef > &Prefixes, StringRef Arg)
Definition OptTable.cpp:147
static void PrintHelpOptionList(raw_ostream &OS, StringRef Title, std::vector< OptionInfo > &OptionHelp)
Definition OptTable.cpp:660
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
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:736
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
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
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:839
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:126
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:581
unsigned getOptionKind(OptSpecifier id) const
Get the kind of the given option.
Definition OptTable.h:269
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:192
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:298
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:415
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:236
SmallVector< StringRef > PrefixesUnion
The union of all option prefixes.
Definition OptTable.h:196
const Option getOption(OptSpecifier Opt) const
Get the given Opt's Option instance, lazily creating it if necessary.
Definition OptTable.cpp:139
const char * getOptionHelpText(OptSpecifier id) const
Get the help text to use to describe this option.
Definition OptTable.h:279
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:78
unsigned getOptionGroupID(OptSpecifier id) const
Get the group id for the given option.
Definition OptTable.h:274
std::vector< std::string > suggestValueCompletions(StringRef Option, StringRef Arg) const
Find possible value for given flags.
Definition OptTable.cpp:191
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:499
SmallString< 8 > PrefixChars
The union of the first element of all option prefixes.
Definition OptTable.h:199
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:715
unsigned getNumOptions() const
Return the total number of option classes.
Definition OptTable.h:237
std::vector< std::string > findByPrefix(StringRef Cur, Visibility VisibilityMask, unsigned int DisableFlags) const
Find flags from OptTable which starts with Cur.
Definition OptTable.cpp:211
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.
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
@ 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:1772
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
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