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