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/raw_ostream.h"
20 #include <algorithm>
21 #include <cassert>
22 #include <cctype>
23 #include <cstring>
24 #include <map>
25 #include <set>
26 #include <string>
27 #include <utility>
28 #include <vector>
29
30 using namespace llvm;
31 using namespace llvm::opt;
32
33 namespace llvm {
34 namespace opt {
35
36 // Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
37 // with an exception. '\0' comes at the end of the alphabet instead of the
38 // beginning (thus options precede any other options which prefix them).
StrCmpOptionNameIgnoreCase(StringRef A,StringRef B)39 static int StrCmpOptionNameIgnoreCase(StringRef A, StringRef B) {
40 size_t MinSize = std::min(A.size(), B.size());
41 if (int Res = A.substr(0, MinSize).compare_insensitive(B.substr(0, MinSize)))
42 return Res;
43
44 if (A.size() == B.size())
45 return 0;
46
47 return (A.size() == MinSize) ? 1 /* A is a prefix of B. */
48 : -1 /* B is a prefix of A */;
49 }
50
51 #ifndef NDEBUG
StrCmpOptionName(StringRef A,StringRef B)52 static int StrCmpOptionName(StringRef A, StringRef B) {
53 if (int N = StrCmpOptionNameIgnoreCase(A, B))
54 return N;
55 return A.compare(B);
56 }
57
operator <(const OptTable::Info & A,const OptTable::Info & B)58 static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
59 if (&A == &B)
60 return false;
61
62 if (int N = StrCmpOptionName(A.Name, B.Name))
63 return N < 0;
64
65 for (size_t I = 0, K = std::min(A.Prefixes.size(), B.Prefixes.size()); I != K;
66 ++I)
67 if (int N = StrCmpOptionName(A.Prefixes[I], B.Prefixes[I]))
68 return N < 0;
69
70 // Names are the same, check that classes are in order; exactly one
71 // should be joined, and it should succeed the other.
72 assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
73 "Unexpected classes for options with same name.");
74 return B.Kind == Option::JoinedClass;
75 }
76 #endif
77
78 // Support lower_bound between info and an option name.
operator <(const OptTable::Info & I,StringRef Name)79 static inline bool operator<(const OptTable::Info &I, StringRef Name) {
80 return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
81 }
82
83 } // end namespace opt
84 } // end namespace llvm
85
OptSpecifier(const Option * Opt)86 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
87
OptTable(ArrayRef<Info> OptionInfos,bool IgnoreCase)88 OptTable::OptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase)
89 : OptionInfos(OptionInfos), IgnoreCase(IgnoreCase) {
90 // Explicitly zero initialize the error to work around a bug in array
91 // value-initialization on MinGW with gcc 4.3.5.
92
93 // Find start of normal options.
94 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
95 unsigned Kind = getInfo(i + 1).Kind;
96 if (Kind == Option::InputClass) {
97 assert(!InputOptionID && "Cannot have multiple input options!");
98 InputOptionID = getInfo(i + 1).ID;
99 } else if (Kind == Option::UnknownClass) {
100 assert(!UnknownOptionID && "Cannot have multiple unknown options!");
101 UnknownOptionID = getInfo(i + 1).ID;
102 } else if (Kind != Option::GroupClass) {
103 FirstSearchableIndex = i;
104 break;
105 }
106 }
107 assert(FirstSearchableIndex != 0 && "No searchable options?");
108
109 #ifndef NDEBUG
110 // Check that everything after the first searchable option is a
111 // regular option class.
112 for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
113 Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
114 assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
115 Kind != Option::GroupClass) &&
116 "Special options should be defined first!");
117 }
118
119 // Check that options are in order.
120 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
121 if (!(getInfo(i) < getInfo(i + 1))) {
122 getOption(i).dump();
123 getOption(i + 1).dump();
124 llvm_unreachable("Options are not in order!");
125 }
126 }
127 #endif
128 }
129
buildPrefixChars()130 void OptTable::buildPrefixChars() {
131 assert(PrefixChars.empty() && "rebuilding a non-empty prefix char");
132
133 // Build prefix chars.
134 for (const StringLiteral &Prefix : getPrefixesUnion()) {
135 for (char C : Prefix)
136 if (!is_contained(PrefixChars, C))
137 PrefixChars.push_back(C);
138 }
139 }
140
141 OptTable::~OptTable() = default;
142
getOption(OptSpecifier Opt) const143 const Option OptTable::getOption(OptSpecifier Opt) const {
144 unsigned id = Opt.getID();
145 if (id == 0)
146 return Option(nullptr, nullptr);
147 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
148 return Option(&getInfo(id), this);
149 }
150
isInput(const ArrayRef<StringLiteral> & Prefixes,StringRef Arg)151 static bool isInput(const ArrayRef<StringLiteral> &Prefixes, StringRef Arg) {
152 if (Arg == "-")
153 return true;
154 for (const StringRef &Prefix : Prefixes)
155 if (Arg.startswith(Prefix))
156 return false;
157 return true;
158 }
159
160 /// \returns Matched size. 0 means no match.
matchOption(const OptTable::Info * I,StringRef Str,bool IgnoreCase)161 static unsigned matchOption(const OptTable::Info *I, StringRef Str,
162 bool IgnoreCase) {
163 for (auto Prefix : I->Prefixes) {
164 if (Str.startswith(Prefix)) {
165 StringRef Rest = Str.substr(Prefix.size());
166 bool Matched = IgnoreCase ? Rest.startswith_insensitive(I->Name)
167 : Rest.startswith(I->Name);
168 if (Matched)
169 return Prefix.size() + StringRef(I->Name).size();
170 }
171 }
172 return 0;
173 }
174
175 // Returns true if one of the Prefixes + In.Names matches Option
optionMatches(const OptTable::Info & In,StringRef Option)176 static bool optionMatches(const OptTable::Info &In, StringRef Option) {
177 for (auto Prefix : In.Prefixes)
178 if (Option.endswith(In.Name))
179 if (Option.slice(0, Option.size() - In.Name.size()) == Prefix)
180 return true;
181 return false;
182 }
183
184 // This function is for flag value completion.
185 // Eg. When "-stdlib=" and "l" was passed to this function, it will return
186 // appropiriate values for stdlib, which starts with l.
187 std::vector<std::string>
suggestValueCompletions(StringRef Option,StringRef Arg) const188 OptTable::suggestValueCompletions(StringRef Option, StringRef Arg) const {
189 // Search all options and return possible values.
190 for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
191 const Info &In = OptionInfos[I];
192 if (!In.Values || !optionMatches(In, Option))
193 continue;
194
195 SmallVector<StringRef, 8> Candidates;
196 StringRef(In.Values).split(Candidates, ",", -1, false);
197
198 std::vector<std::string> Result;
199 for (StringRef Val : Candidates)
200 if (Val.startswith(Arg) && Arg.compare(Val))
201 Result.push_back(std::string(Val));
202 return Result;
203 }
204 return {};
205 }
206
207 std::vector<std::string>
findByPrefix(StringRef Cur,unsigned int DisableFlags) const208 OptTable::findByPrefix(StringRef Cur, unsigned int DisableFlags) const {
209 std::vector<std::string> Ret;
210 for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
211 const Info &In = OptionInfos[I];
212 if (In.Prefixes.empty() || (!In.HelpText && !In.GroupID))
213 continue;
214 if (In.Flags & DisableFlags)
215 continue;
216
217 for (auto Prefix : In.Prefixes) {
218 std::string S = (Prefix + In.Name + "\t").str();
219 if (In.HelpText)
220 S += In.HelpText;
221 if (StringRef(S).startswith(Cur) && S != std::string(Cur) + "\t")
222 Ret.push_back(S);
223 }
224 }
225 return Ret;
226 }
227
findNearest(StringRef Option,std::string & NearestString,unsigned FlagsToInclude,unsigned FlagsToExclude,unsigned MinimumLength,unsigned MaximumDistance) const228 unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
229 unsigned FlagsToInclude, unsigned FlagsToExclude,
230 unsigned MinimumLength,
231 unsigned MaximumDistance) const {
232 assert(!Option.empty());
233
234 // Consider each [option prefix + option name] pair as a candidate, finding
235 // the closest match.
236 unsigned BestDistance =
237 MaximumDistance == UINT_MAX ? UINT_MAX : MaximumDistance + 1;
238 SmallString<16> Candidate;
239 SmallString<16> NormalizedName;
240
241 for (const Info &CandidateInfo :
242 ArrayRef<Info>(OptionInfos).drop_front(FirstSearchableIndex)) {
243 StringRef CandidateName = CandidateInfo.Name;
244
245 // We can eliminate some option prefix/name pairs as candidates right away:
246 // * Ignore option candidates with empty names, such as "--", or names
247 // that do not meet the minimum length.
248 if (CandidateName.size() < MinimumLength)
249 continue;
250
251 // * If FlagsToInclude were specified, ignore options that don't include
252 // those flags.
253 if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
254 continue;
255 // * Ignore options that contain the FlagsToExclude.
256 if (CandidateInfo.Flags & FlagsToExclude)
257 continue;
258
259 // * Ignore positional argument option candidates (which do not
260 // have prefixes).
261 if (CandidateInfo.Prefixes.empty())
262 continue;
263
264 // Now check if the candidate ends with a character commonly used when
265 // delimiting an option from its value, such as '=' or ':'. If it does,
266 // attempt to split the given option based on that delimiter.
267 char Last = CandidateName.back();
268 bool CandidateHasDelimiter = Last == '=' || Last == ':';
269 StringRef RHS;
270 if (CandidateHasDelimiter) {
271 std::tie(NormalizedName, RHS) = Option.split(Last);
272 if (Option.find(Last) == NormalizedName.size())
273 NormalizedName += Last;
274 } else
275 NormalizedName = Option;
276
277 // Consider each possible prefix for each candidate to find the most
278 // appropriate one. For example, if a user asks for "--helm", suggest
279 // "--help" over "-help".
280 for (auto CandidatePrefix : CandidateInfo.Prefixes) {
281 // If Candidate and NormalizedName have more than 'BestDistance'
282 // characters of difference, no need to compute the edit distance, it's
283 // going to be greater than BestDistance. Don't bother computing Candidate
284 // at all.
285 size_t CandidateSize = CandidatePrefix.size() + CandidateName.size(),
286 NormalizedSize = NormalizedName.size();
287 size_t AbsDiff = CandidateSize > NormalizedSize
288 ? CandidateSize - NormalizedSize
289 : NormalizedSize - CandidateSize;
290 if (AbsDiff > BestDistance) {
291 continue;
292 }
293 Candidate = CandidatePrefix;
294 Candidate += CandidateName;
295 unsigned Distance = StringRef(Candidate).edit_distance(
296 NormalizedName, /*AllowReplacements=*/true,
297 /*MaxEditDistance=*/BestDistance);
298 if (RHS.empty() && CandidateHasDelimiter) {
299 // The Candidate ends with a = or : delimiter, but the option passed in
300 // didn't contain the delimiter (or doesn't have anything after it).
301 // In that case, penalize the correction: `-nodefaultlibs` is more
302 // likely to be a spello for `-nodefaultlib` than `-nodefaultlib:` even
303 // though both have an unmodified editing distance of 1, since the
304 // latter would need an argument.
305 ++Distance;
306 }
307 if (Distance < BestDistance) {
308 BestDistance = Distance;
309 NearestString = (Candidate + RHS).str();
310 }
311 }
312 }
313 return BestDistance;
314 }
315
316 // Parse a single argument, return the new argument, and update Index. If
317 // GroupedShortOptions is true, -a matches "-abc" and the argument in Args will
318 // be updated to "-bc". This overload does not support
319 // FlagsToInclude/FlagsToExclude or case insensitive options.
parseOneArgGrouped(InputArgList & Args,unsigned & Index) const320 std::unique_ptr<Arg> OptTable::parseOneArgGrouped(InputArgList &Args,
321 unsigned &Index) const {
322 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
323 // itself.
324 const char *CStr = Args.getArgString(Index);
325 StringRef Str(CStr);
326 if (isInput(getPrefixesUnion(), Str))
327 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++, CStr);
328
329 const Info *End = OptionInfos.data() + OptionInfos.size();
330 StringRef Name = Str.ltrim(PrefixChars);
331 const Info *Start =
332 std::lower_bound(OptionInfos.data() + FirstSearchableIndex, End, Name);
333 const Info *Fallback = nullptr;
334 unsigned Prev = Index;
335
336 // Search for the option which matches Str.
337 for (; Start != End; ++Start) {
338 unsigned ArgSize = matchOption(Start, Str, IgnoreCase);
339 if (!ArgSize)
340 continue;
341
342 Option Opt(Start, this);
343 if (std::unique_ptr<Arg> A =
344 Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
345 /*GroupedShortOption=*/false, Index))
346 return A;
347
348 // If Opt is a Flag of length 2 (e.g. "-a"), we know it is a prefix of
349 // the current argument (e.g. "-abc"). Match it as a fallback if no longer
350 // option (e.g. "-ab") exists.
351 if (ArgSize == 2 && Opt.getKind() == Option::FlagClass)
352 Fallback = Start;
353
354 // Otherwise, see if the argument is missing.
355 if (Prev != Index)
356 return nullptr;
357 }
358 if (Fallback) {
359 Option Opt(Fallback, this);
360 // Check that the last option isn't a flag wrongly given an argument.
361 if (Str[2] == '=')
362 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
363 CStr);
364
365 if (std::unique_ptr<Arg> A = Opt.accept(
366 Args, Str.substr(0, 2), /*GroupedShortOption=*/true, Index)) {
367 Args.replaceArgString(Index, Twine('-') + Str.substr(2));
368 return A;
369 }
370 }
371
372 // In the case of an incorrect short option extract the character and move to
373 // the next one.
374 if (Str[1] != '-') {
375 CStr = Args.MakeArgString(Str.substr(0, 2));
376 Args.replaceArgString(Index, Twine('-') + Str.substr(2));
377 return std::make_unique<Arg>(getOption(UnknownOptionID), CStr, Index, CStr);
378 }
379
380 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++, CStr);
381 }
382
ParseOneArg(const ArgList & Args,unsigned & Index,unsigned FlagsToInclude,unsigned FlagsToExclude) const383 std::unique_ptr<Arg> OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
384 unsigned FlagsToInclude,
385 unsigned FlagsToExclude) const {
386 unsigned Prev = Index;
387 StringRef Str = Args.getArgString(Index);
388
389 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
390 // itself.
391 if (isInput(getPrefixesUnion(), Str))
392 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++,
393 Str.data());
394
395 const Info *Start = OptionInfos.data() + FirstSearchableIndex;
396 const Info *End = OptionInfos.data() + OptionInfos.size();
397 StringRef Name = Str.ltrim(PrefixChars);
398
399 // Search for the first next option which could be a prefix.
400 Start = std::lower_bound(Start, End, Name);
401
402 // Options are stored in sorted order, with '\0' at the end of the
403 // alphabet. Since the only options which can accept a string must
404 // prefix it, we iteratively search for the next option which could
405 // be a prefix.
406 //
407 // FIXME: This is searching much more than necessary, but I am
408 // blanking on the simplest way to make it fast. We can solve this
409 // problem when we move to TableGen.
410 for (; Start != End; ++Start) {
411 unsigned ArgSize = 0;
412 // Scan for first option which is a proper prefix.
413 for (; Start != End; ++Start)
414 if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
415 break;
416 if (Start == End)
417 break;
418
419 Option Opt(Start, this);
420
421 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
422 continue;
423 if (Opt.hasFlag(FlagsToExclude))
424 continue;
425
426 // See if this option matches.
427 if (std::unique_ptr<Arg> A =
428 Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
429 /*GroupedShortOption=*/false, Index))
430 return A;
431
432 // Otherwise, see if this argument was missing values.
433 if (Prev != Index)
434 return nullptr;
435 }
436
437 // If we failed to find an option and this arg started with /, then it's
438 // probably an input path.
439 if (Str[0] == '/')
440 return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++,
441 Str.data());
442
443 return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
444 Str.data());
445 }
446
ParseArgs(ArrayRef<const char * > ArgArr,unsigned & MissingArgIndex,unsigned & MissingArgCount,unsigned FlagsToInclude,unsigned FlagsToExclude) const447 InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr,
448 unsigned &MissingArgIndex,
449 unsigned &MissingArgCount,
450 unsigned FlagsToInclude,
451 unsigned FlagsToExclude) const {
452 InputArgList Args(ArgArr.begin(), ArgArr.end());
453
454 // FIXME: Handle '@' args (or at least error on them).
455
456 MissingArgIndex = MissingArgCount = 0;
457 unsigned Index = 0, End = ArgArr.size();
458 while (Index < End) {
459 // Ingore nullptrs, they are response file's EOL markers
460 if (Args.getArgString(Index) == nullptr) {
461 ++Index;
462 continue;
463 }
464 // Ignore empty arguments (other things may still take them as arguments).
465 StringRef Str = Args.getArgString(Index);
466 if (Str == "") {
467 ++Index;
468 continue;
469 }
470
471 unsigned Prev = Index;
472 std::unique_ptr<Arg> A = GroupedShortOptions
473 ? parseOneArgGrouped(Args, Index)
474 : ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
475 assert((Index > Prev || GroupedShortOptions) &&
476 "Parser failed to consume argument.");
477
478 // Check for missing argument error.
479 if (!A) {
480 assert(Index >= End && "Unexpected parser error.");
481 assert(Index - Prev - 1 && "No missing arguments!");
482 MissingArgIndex = Prev;
483 MissingArgCount = Index - Prev - 1;
484 break;
485 }
486
487 Args.append(A.release());
488 }
489
490 return Args;
491 }
492
parseArgs(int Argc,char * const * Argv,OptSpecifier Unknown,StringSaver & Saver,function_ref<void (StringRef)> ErrorFn) const493 InputArgList OptTable::parseArgs(int Argc, char *const *Argv,
494 OptSpecifier Unknown, StringSaver &Saver,
495 function_ref<void(StringRef)> ErrorFn) const {
496 SmallVector<const char *, 0> NewArgv;
497 // The environment variable specifies initial options which can be overridden
498 // by commnad line options.
499 cl::expandResponseFiles(Argc, Argv, EnvVar, Saver, NewArgv);
500
501 unsigned MAI, MAC;
502 opt::InputArgList Args = ParseArgs(ArrayRef(NewArgv), MAI, MAC);
503 if (MAC)
504 ErrorFn((Twine(Args.getArgString(MAI)) + ": missing argument").str());
505
506 // For each unknwon option, call ErrorFn with a formatted error message. The
507 // message includes a suggested alternative option spelling if available.
508 std::string Nearest;
509 for (const opt::Arg *A : Args.filtered(Unknown)) {
510 std::string Spelling = A->getAsString(Args);
511 if (findNearest(Spelling, Nearest) > 1)
512 ErrorFn("unknown argument '" + Spelling + "'");
513 else
514 ErrorFn("unknown argument '" + Spelling + "', did you mean '" + Nearest +
515 "'?");
516 }
517 return Args;
518 }
519
getOptionHelpName(const OptTable & Opts,OptSpecifier Id)520 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
521 const Option O = Opts.getOption(Id);
522 std::string Name = O.getPrefixedName();
523
524 // Add metavar, if used.
525 switch (O.getKind()) {
526 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
527 llvm_unreachable("Invalid option with help text.");
528
529 case Option::MultiArgClass:
530 if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
531 // For MultiArgs, metavar is full list of all argument names.
532 Name += ' ';
533 Name += MetaVarName;
534 }
535 else {
536 // For MultiArgs<N>, if metavar not supplied, print <value> N times.
537 for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
538 Name += " <value>";
539 }
540 }
541 break;
542
543 case Option::FlagClass:
544 break;
545
546 case Option::ValuesClass:
547 break;
548
549 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
550 case Option::RemainingArgsClass: case Option::RemainingArgsJoinedClass:
551 Name += ' ';
552 [[fallthrough]];
553 case Option::JoinedClass: case Option::CommaJoinedClass:
554 case Option::JoinedAndSeparateClass:
555 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
556 Name += MetaVarName;
557 else
558 Name += "<value>";
559 break;
560 }
561
562 return Name;
563 }
564
565 namespace {
566 struct OptionInfo {
567 std::string Name;
568 StringRef HelpText;
569 };
570 } // namespace
571
PrintHelpOptionList(raw_ostream & OS,StringRef Title,std::vector<OptionInfo> & OptionHelp)572 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
573 std::vector<OptionInfo> &OptionHelp) {
574 OS << Title << ":\n";
575
576 // Find the maximum option length.
577 unsigned OptionFieldWidth = 0;
578 for (const OptionInfo &Opt : OptionHelp) {
579 // Limit the amount of padding we are willing to give up for alignment.
580 unsigned Length = Opt.Name.size();
581 if (Length <= 23)
582 OptionFieldWidth = std::max(OptionFieldWidth, Length);
583 }
584
585 const unsigned InitialPad = 2;
586 for (const OptionInfo &Opt : OptionHelp) {
587 const std::string &Option = Opt.Name;
588 int Pad = OptionFieldWidth - int(Option.size());
589 OS.indent(InitialPad) << Option;
590
591 // Break on long option names.
592 if (Pad < 0) {
593 OS << "\n";
594 Pad = OptionFieldWidth + InitialPad;
595 }
596 OS.indent(Pad + 1) << Opt.HelpText << '\n';
597 }
598 }
599
getOptionHelpGroup(const OptTable & Opts,OptSpecifier Id)600 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
601 unsigned GroupID = Opts.getOptionGroupID(Id);
602
603 // If not in a group, return the default help group.
604 if (!GroupID)
605 return "OPTIONS";
606
607 // Abuse the help text of the option groups to store the "help group"
608 // name.
609 //
610 // FIXME: Split out option groups.
611 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
612 return GroupHelp;
613
614 // Otherwise keep looking.
615 return getOptionHelpGroup(Opts, GroupID);
616 }
617
printHelp(raw_ostream & OS,const char * Usage,const char * Title,bool ShowHidden,bool ShowAllAliases) const618 void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
619 bool ShowHidden, bool ShowAllAliases) const {
620 printHelp(OS, Usage, Title, /*Include*/ 0, /*Exclude*/
621 (ShowHidden ? 0 : HelpHidden), ShowAllAliases);
622 }
623
printHelp(raw_ostream & OS,const char * Usage,const char * Title,unsigned FlagsToInclude,unsigned FlagsToExclude,bool ShowAllAliases) const624 void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
625 unsigned FlagsToInclude, unsigned FlagsToExclude,
626 bool ShowAllAliases) const {
627 OS << "OVERVIEW: " << Title << "\n\n";
628 OS << "USAGE: " << Usage << "\n\n";
629
630 // Render help text into a map of group-name to a list of (option, help)
631 // pairs.
632 std::map<std::string, std::vector<OptionInfo>> GroupedOptionHelp;
633
634 for (unsigned Id = 1, e = getNumOptions() + 1; Id != e; ++Id) {
635 // FIXME: Split out option groups.
636 if (getOptionKind(Id) == Option::GroupClass)
637 continue;
638
639 unsigned Flags = getInfo(Id).Flags;
640 if (FlagsToInclude && !(Flags & FlagsToInclude))
641 continue;
642 if (Flags & FlagsToExclude)
643 continue;
644
645 // If an alias doesn't have a help text, show a help text for the aliased
646 // option instead.
647 const char *HelpText = getOptionHelpText(Id);
648 if (!HelpText && ShowAllAliases) {
649 const Option Alias = getOption(Id).getAlias();
650 if (Alias.isValid())
651 HelpText = getOptionHelpText(Alias.getID());
652 }
653
654 if (HelpText && (strlen(HelpText) != 0)) {
655 const char *HelpGroup = getOptionHelpGroup(*this, Id);
656 const std::string &OptName = getOptionHelpName(*this, Id);
657 GroupedOptionHelp[HelpGroup].push_back({OptName, HelpText});
658 }
659 }
660
661 for (auto& OptionGroup : GroupedOptionHelp) {
662 if (OptionGroup.first != GroupedOptionHelp.begin()->first)
663 OS << "\n";
664 PrintHelpOptionList(OS, OptionGroup.first, OptionGroup.second);
665 }
666
667 OS.flush();
668 }
669
GenericOptTable(ArrayRef<Info> OptionInfos,bool IgnoreCase)670 GenericOptTable::GenericOptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase)
671 : OptTable(OptionInfos, IgnoreCase) {
672
673 std::set<StringLiteral> TmpPrefixesUnion;
674 for (auto const &Info : OptionInfos.drop_front(FirstSearchableIndex))
675 TmpPrefixesUnion.insert(Info.Prefixes.begin(), Info.Prefixes.end());
676 PrefixesUnionBuffer.append(TmpPrefixesUnion.begin(), TmpPrefixesUnion.end());
677 buildPrefixChars();
678 }
679