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