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