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