1af615896SEugene Zelenko //===- OptTable.cpp - Option Table Implementation -------------------------===//
241ee041dSMichael J. Spencer //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
641ee041dSMichael J. Spencer //
741ee041dSMichael J. Spencer //===----------------------------------------------------------------------===//
841ee041dSMichael J. Spencer 
9593e1962SFangrui Song #include "llvm/Option/OptTable.h"
100d955d0bSDavid Majnemer #include "llvm/ADT/STLExtras.h"
11af615896SEugene Zelenko #include "llvm/ADT/StringRef.h"
12af615896SEugene Zelenko #include "llvm/ADT/StringSet.h"
1341ee041dSMichael J. Spencer #include "llvm/Option/Arg.h"
1441ee041dSMichael J. Spencer #include "llvm/Option/ArgList.h"
15af615896SEugene Zelenko #include "llvm/Option/OptSpecifier.h"
16593e1962SFangrui Song #include "llvm/Option/Option.h"
17593e1962SFangrui Song #include "llvm/Support/CommandLine.h" // for expandResponseFiles
18af615896SEugene Zelenko #include "llvm/Support/Compiler.h"
1941ee041dSMichael J. Spencer #include "llvm/Support/ErrorHandling.h"
20be81023dSChandler Carruth #include "llvm/Support/raw_ostream.h"
2141ee041dSMichael J. Spencer #include <algorithm>
22af615896SEugene Zelenko #include <cassert>
238fb5a911SRui Ueyama #include <cctype>
24af615896SEugene Zelenko #include <cstring>
2541ee041dSMichael J. Spencer #include <map>
26af615896SEugene Zelenko #include <string>
27af615896SEugene Zelenko #include <utility>
28af615896SEugene Zelenko #include <vector>
2941ee041dSMichael J. Spencer 
3041ee041dSMichael J. Spencer using namespace llvm;
3141ee041dSMichael J. Spencer using namespace llvm::opt;
3241ee041dSMichael J. Spencer 
338fb5a911SRui Ueyama namespace llvm {
348fb5a911SRui Ueyama namespace opt {
357159bd9dSRui Ueyama 
368fb5a911SRui Ueyama // Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
379b656ffbSNathan Hawes // with an exception. '\0' comes at the end of the alphabet instead of the
388fb5a911SRui Ueyama // beginning (thus options precede any other options which prefix them).
StrCmpOptionNameIgnoreCase(const char * A,const char * B)398fb5a911SRui Ueyama static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) {
408fb5a911SRui Ueyama   const char *X = A, *Y = B;
418fb5a911SRui Ueyama   char a = tolower(*A), b = tolower(*B);
42c3779ff8SRui Ueyama   while (a == b) {
43c3779ff8SRui Ueyama     if (a == '\0')
44c3779ff8SRui Ueyama       return 0;
45c3779ff8SRui Ueyama 
468fb5a911SRui Ueyama     a = tolower(*++X);
478fb5a911SRui Ueyama     b = tolower(*++Y);
487159bd9dSRui Ueyama   }
497159bd9dSRui Ueyama 
50c3779ff8SRui Ueyama   if (a == '\0') // A is a prefix of B.
51c3779ff8SRui Ueyama     return 1;
52c3779ff8SRui Ueyama   if (b == '\0') // B is a prefix of A.
53c3779ff8SRui Ueyama     return -1;
54c3779ff8SRui Ueyama 
55c3779ff8SRui Ueyama   // Otherwise lexicographic.
56c3779ff8SRui Ueyama   return (a < b) ? -1 : 1;
57c3779ff8SRui Ueyama }
58c3779ff8SRui Ueyama 
593e7dca67SEli Friedman #ifndef NDEBUG
StrCmpOptionName(const char * A,const char * B)603e7dca67SEli Friedman static int StrCmpOptionName(const char *A, const char *B) {
613e7dca67SEli Friedman   if (int N = StrCmpOptionNameIgnoreCase(A, B))
623e7dca67SEli Friedman     return N;
633e7dca67SEli Friedman   return strcmp(A, B);
643e7dca67SEli Friedman }
653e7dca67SEli Friedman 
operator <(const OptTable::Info & A,const OptTable::Info & B)663e7dca67SEli Friedman static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
673e7dca67SEli Friedman   if (&A == &B)
683e7dca67SEli Friedman     return false;
693e7dca67SEli Friedman 
703e7dca67SEli Friedman   if (int N = StrCmpOptionName(A.Name, B.Name))
713e7dca67SEli Friedman     return N < 0;
723e7dca67SEli Friedman 
733e7dca67SEli Friedman   for (const char * const *APre = A.Prefixes,
743e7dca67SEli Friedman                   * const *BPre = B.Prefixes;
752617dcceSCraig Topper                           *APre != nullptr && *BPre != nullptr; ++APre, ++BPre){
763e7dca67SEli Friedman     if (int N = StrCmpOptionName(*APre, *BPre))
773e7dca67SEli Friedman       return N < 0;
783e7dca67SEli Friedman   }
793e7dca67SEli Friedman 
803e7dca67SEli Friedman   // Names are the same, check that classes are in order; exactly one
813e7dca67SEli Friedman   // should be joined, and it should succeed the other.
823e7dca67SEli Friedman   assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
833e7dca67SEli Friedman          "Unexpected classes for options with same name.");
843e7dca67SEli Friedman   return B.Kind == Option::JoinedClass;
853e7dca67SEli Friedman }
863e7dca67SEli Friedman #endif
873e7dca67SEli Friedman 
8841ee041dSMichael J. Spencer // Support lower_bound between info and an option name.
operator <(const OptTable::Info & I,const char * Name)8941ee041dSMichael J. Spencer static inline bool operator<(const OptTable::Info &I, const char *Name) {
908fb5a911SRui Ueyama   return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
9141ee041dSMichael J. Spencer }
92af615896SEugene Zelenko 
93af615896SEugene Zelenko } // end namespace opt
94af615896SEugene Zelenko } // end namespace llvm
9541ee041dSMichael J. Spencer 
OptSpecifier(const Option * Opt)9641ee041dSMichael J. Spencer OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
9741ee041dSMichael J. Spencer 
OptTable(ArrayRef<Info> OptionInfos,bool IgnoreCase)988ea2390cSCraig Topper OptTable::OptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase)
99af615896SEugene Zelenko     : OptionInfos(OptionInfos), IgnoreCase(IgnoreCase) {
10041ee041dSMichael J. Spencer   // Explicitly zero initialize the error to work around a bug in array
10141ee041dSMichael J. Spencer   // value-initialization on MinGW with gcc 4.3.5.
10241ee041dSMichael J. Spencer 
10341ee041dSMichael J. Spencer   // Find start of normal options.
10441ee041dSMichael J. Spencer   for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
10541ee041dSMichael J. Spencer     unsigned Kind = getInfo(i + 1).Kind;
10641ee041dSMichael J. Spencer     if (Kind == Option::InputClass) {
107730bbc6fSNico Weber       assert(!InputOptionID && "Cannot have multiple input options!");
108730bbc6fSNico Weber       InputOptionID = getInfo(i + 1).ID;
10941ee041dSMichael J. Spencer     } else if (Kind == Option::UnknownClass) {
110730bbc6fSNico Weber       assert(!UnknownOptionID && "Cannot have multiple unknown options!");
111730bbc6fSNico Weber       UnknownOptionID = getInfo(i + 1).ID;
11241ee041dSMichael J. Spencer     } else if (Kind != Option::GroupClass) {
11341ee041dSMichael J. Spencer       FirstSearchableIndex = i;
11441ee041dSMichael J. Spencer       break;
11541ee041dSMichael J. Spencer     }
11641ee041dSMichael J. Spencer   }
11741ee041dSMichael J. Spencer   assert(FirstSearchableIndex != 0 && "No searchable options?");
11841ee041dSMichael J. Spencer 
11941ee041dSMichael J. Spencer #ifndef NDEBUG
12041ee041dSMichael J. Spencer   // Check that everything after the first searchable option is a
12141ee041dSMichael J. Spencer   // regular option class.
12241ee041dSMichael J. Spencer   for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
12341ee041dSMichael J. Spencer     Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
12441ee041dSMichael J. Spencer     assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
12541ee041dSMichael J. Spencer             Kind != Option::GroupClass) &&
12641ee041dSMichael J. Spencer            "Special options should be defined first!");
12741ee041dSMichael J. Spencer   }
12841ee041dSMichael J. Spencer 
12941ee041dSMichael J. Spencer   // Check that options are in order.
13041ee041dSMichael J. Spencer   for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
13141ee041dSMichael J. Spencer     if (!(getInfo(i) < getInfo(i + 1))) {
13241ee041dSMichael J. Spencer       getOption(i).dump();
13341ee041dSMichael J. Spencer       getOption(i + 1).dump();
13441ee041dSMichael J. Spencer       llvm_unreachable("Options are not in order!");
13541ee041dSMichael J. Spencer     }
13641ee041dSMichael J. Spencer   }
13741ee041dSMichael J. Spencer #endif
13841ee041dSMichael J. Spencer 
13941ee041dSMichael J. Spencer   // Build prefixes.
14041ee041dSMichael J. Spencer   for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
14141ee041dSMichael J. Spencer                 i != e; ++i) {
14241ee041dSMichael J. Spencer     if (const char *const *P = getInfo(i).Prefixes) {
1432617dcceSCraig Topper       for (; *P != nullptr; ++P) {
14441ee041dSMichael J. Spencer         PrefixesUnion.insert(*P);
14541ee041dSMichael J. Spencer       }
14641ee041dSMichael J. Spencer     }
14741ee041dSMichael J. Spencer   }
14841ee041dSMichael J. Spencer 
14941ee041dSMichael J. Spencer   // Build prefix chars.
150af615896SEugene Zelenko   for (StringSet<>::const_iterator I = PrefixesUnion.begin(),
15141ee041dSMichael J. Spencer                                    E = PrefixesUnion.end(); I != E; ++I) {
15241ee041dSMichael J. Spencer     StringRef Prefix = I->getKey();
153262dd1e4SKazu Hirata     for (char C : Prefix)
154262dd1e4SKazu Hirata       if (!is_contained(PrefixChars, C))
155262dd1e4SKazu Hirata         PrefixChars.push_back(C);
15641ee041dSMichael J. Spencer   }
15741ee041dSMichael J. Spencer }
15841ee041dSMichael J. Spencer 
159af615896SEugene Zelenko OptTable::~OptTable() = default;
16041ee041dSMichael J. Spencer 
getOption(OptSpecifier Opt) const16141ee041dSMichael J. Spencer const Option OptTable::getOption(OptSpecifier Opt) const {
16241ee041dSMichael J. Spencer   unsigned id = Opt.getID();
16341ee041dSMichael J. Spencer   if (id == 0)
1642617dcceSCraig Topper     return Option(nullptr, nullptr);
16541ee041dSMichael J. Spencer   assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
16641ee041dSMichael J. Spencer   return Option(&getInfo(id), this);
16741ee041dSMichael J. Spencer }
16841ee041dSMichael J. Spencer 
isInput(const StringSet<> & Prefixes,StringRef Arg)169af615896SEugene Zelenko static bool isInput(const StringSet<> &Prefixes, StringRef Arg) {
17041ee041dSMichael J. Spencer   if (Arg == "-")
17141ee041dSMichael J. Spencer     return true;
172af615896SEugene Zelenko   for (StringSet<>::const_iterator I = Prefixes.begin(),
17341ee041dSMichael J. Spencer                                    E = Prefixes.end(); I != E; ++I)
17441ee041dSMichael J. Spencer     if (Arg.startswith(I->getKey()))
17541ee041dSMichael J. Spencer       return false;
17641ee041dSMichael J. Spencer   return true;
17741ee041dSMichael J. Spencer }
17841ee041dSMichael J. Spencer 
17941ee041dSMichael J. Spencer /// \returns Matched size. 0 means no match.
matchOption(const OptTable::Info * I,StringRef Str,bool IgnoreCase)1808fb5a911SRui Ueyama static unsigned matchOption(const OptTable::Info *I, StringRef Str,
1818fb5a911SRui Ueyama                             bool IgnoreCase) {
1822617dcceSCraig Topper   for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) {
18341ee041dSMichael J. Spencer     StringRef Prefix(*Pre);
1848fb5a911SRui Ueyama     if (Str.startswith(Prefix)) {
1858fb5a911SRui Ueyama       StringRef Rest = Str.substr(Prefix.size());
18642f74e82SMartin Storsjö       bool Matched = IgnoreCase ? Rest.startswith_insensitive(I->Name)
1878fb5a911SRui Ueyama                                 : Rest.startswith(I->Name);
1888fb5a911SRui Ueyama       if (Matched)
18941ee041dSMichael J. Spencer         return Prefix.size() + StringRef(I->Name).size();
19041ee041dSMichael J. Spencer     }
1918fb5a911SRui Ueyama   }
19241ee041dSMichael J. Spencer   return 0;
19341ee041dSMichael J. Spencer }
19441ee041dSMichael J. Spencer 
195ba5d4af4SYuka Takahashi // Returns true if one of the Prefixes + In.Names matches Option
optionMatches(const OptTable::Info & In,StringRef Option)196ba5d4af4SYuka Takahashi static bool optionMatches(const OptTable::Info &In, StringRef Option) {
197c4e327a9SAditya Kumar   if (In.Prefixes) {
198c4e327a9SAditya Kumar     StringRef InName(In.Name);
199ba5d4af4SYuka Takahashi     for (size_t I = 0; In.Prefixes[I]; I++)
200c4e327a9SAditya Kumar       if (Option.endswith(InName))
201c4e327a9SAditya Kumar         if (Option.slice(0, Option.size() - InName.size()) == In.Prefixes[I])
202ba5d4af4SYuka Takahashi           return true;
203c4e327a9SAditya Kumar   }
204ba5d4af4SYuka Takahashi   return false;
205ba5d4af4SYuka Takahashi }
206ba5d4af4SYuka Takahashi 
207ba5d4af4SYuka Takahashi // This function is for flag value completion.
208ba5d4af4SYuka Takahashi // Eg. When "-stdlib=" and "l" was passed to this function, it will return
209ba5d4af4SYuka Takahashi // appropiriate values for stdlib, which starts with l.
210ba5d4af4SYuka Takahashi std::vector<std::string>
suggestValueCompletions(StringRef Option,StringRef Arg) const211ba5d4af4SYuka Takahashi OptTable::suggestValueCompletions(StringRef Option, StringRef Arg) const {
212ba5d4af4SYuka Takahashi   // Search all options and return possible values.
21324bc6a4cSYuka Takahashi   for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
21424bc6a4cSYuka Takahashi     const Info &In = OptionInfos[I];
21524bc6a4cSYuka Takahashi     if (!In.Values || !optionMatches(In, Option))
216ba5d4af4SYuka Takahashi       continue;
217ba5d4af4SYuka Takahashi 
218ba5d4af4SYuka Takahashi     SmallVector<StringRef, 8> Candidates;
219ba5d4af4SYuka Takahashi     StringRef(In.Values).split(Candidates, ",", -1, false);
220ba5d4af4SYuka Takahashi 
221ba5d4af4SYuka Takahashi     std::vector<std::string> Result;
222ba5d4af4SYuka Takahashi     for (StringRef Val : Candidates)
22341789e46SYuka Takahashi       if (Val.startswith(Arg) && Arg.compare(Val))
224adcd0268SBenjamin Kramer         Result.push_back(std::string(Val));
225ba5d4af4SYuka Takahashi     return Result;
226ba5d4af4SYuka Takahashi   }
227ba5d4af4SYuka Takahashi   return {};
228ba5d4af4SYuka Takahashi }
229ba5d4af4SYuka Takahashi 
23033cf63b7SYuka Takahashi std::vector<std::string>
findByPrefix(StringRef Cur,unsigned int DisableFlags) const2314eed800bSAndrzej Warzynski OptTable::findByPrefix(StringRef Cur, unsigned int DisableFlags) const {
232c8068dbbSYuka Takahashi   std::vector<std::string> Ret;
23324bc6a4cSYuka Takahashi   for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
23424bc6a4cSYuka Takahashi     const Info &In = OptionInfos[I];
23534a7c3baSYuka Takahashi     if (!In.Prefixes || (!In.HelpText && !In.GroupID))
236c8068dbbSYuka Takahashi       continue;
23733cf63b7SYuka Takahashi     if (In.Flags & DisableFlags)
23833cf63b7SYuka Takahashi       continue;
23933cf63b7SYuka Takahashi 
240c8068dbbSYuka Takahashi     for (int I = 0; In.Prefixes[I]; I++) {
24166256906SYuka Takahashi       std::string S = std::string(In.Prefixes[I]) + std::string(In.Name) + "\t";
24266256906SYuka Takahashi       if (In.HelpText)
24366256906SYuka Takahashi         S += In.HelpText;
244e5b4dbabSKazu Hirata       if (StringRef(S).startswith(Cur) && S != std::string(Cur) + "\t")
245c8068dbbSYuka Takahashi         Ret.push_back(S);
246c8068dbbSYuka Takahashi     }
247c8068dbbSYuka Takahashi   }
248c8068dbbSYuka Takahashi   return Ret;
249c8068dbbSYuka Takahashi }
250c8068dbbSYuka Takahashi 
findNearest(StringRef Option,std::string & NearestString,unsigned FlagsToInclude,unsigned FlagsToExclude,unsigned MinimumLength) const2517b84de79SBrian Gesiak unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
2527b84de79SBrian Gesiak                                unsigned FlagsToInclude, unsigned FlagsToExclude,
2537b84de79SBrian Gesiak                                unsigned MinimumLength) const {
2547b84de79SBrian Gesiak   assert(!Option.empty());
2557b84de79SBrian Gesiak 
25698ca8da5SNico Weber   // Consider each [option prefix + option name] pair as a candidate, finding
25798ca8da5SNico Weber   // the closest match.
2587b84de79SBrian Gesiak   unsigned BestDistance = UINT_MAX;
2597b84de79SBrian Gesiak   for (const Info &CandidateInfo :
2607b84de79SBrian Gesiak        ArrayRef<Info>(OptionInfos).drop_front(FirstSearchableIndex)) {
2617b84de79SBrian Gesiak     StringRef CandidateName = CandidateInfo.Name;
2627b84de79SBrian Gesiak 
26398ca8da5SNico Weber     // We can eliminate some option prefix/name pairs as candidates right away:
26498ca8da5SNico Weber     // * Ignore option candidates with empty names, such as "--", or names
2657b84de79SBrian Gesiak     //   that do not meet the minimum length.
2667b84de79SBrian Gesiak     if (CandidateName.empty() || CandidateName.size() < MinimumLength)
2677b84de79SBrian Gesiak       continue;
2687b84de79SBrian Gesiak 
26998ca8da5SNico Weber     // * If FlagsToInclude were specified, ignore options that don't include
2707b84de79SBrian Gesiak     //   those flags.
2717b84de79SBrian Gesiak     if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
2727b84de79SBrian Gesiak       continue;
27398ca8da5SNico Weber     // * Ignore options that contain the FlagsToExclude.
2747b84de79SBrian Gesiak     if (CandidateInfo.Flags & FlagsToExclude)
2757b84de79SBrian Gesiak       continue;
2767b84de79SBrian Gesiak 
27798ca8da5SNico Weber     // * Ignore positional argument option candidates (which do not
2787b84de79SBrian Gesiak     //   have prefixes).
2797b84de79SBrian Gesiak     if (!CandidateInfo.Prefixes)
2807b84de79SBrian Gesiak       continue;
2817b84de79SBrian Gesiak 
28298ca8da5SNico Weber     // Now check if the candidate ends with a character commonly used when
2837b84de79SBrian Gesiak     // delimiting an option from its value, such as '=' or ':'. If it does,
2847b84de79SBrian Gesiak     // attempt to split the given option based on that delimiter.
2857b84de79SBrian Gesiak     StringRef LHS, RHS;
286f68e0f79SNico Weber     char Last = CandidateName.back();
287f68e0f79SNico Weber     bool CandidateHasDelimiter = Last == '=' || Last == ':';
288adcd0268SBenjamin Kramer     std::string NormalizedName = std::string(Option);
289f68e0f79SNico Weber     if (CandidateHasDelimiter) {
2907b84de79SBrian Gesiak       std::tie(LHS, RHS) = Option.split(Last);
291adcd0268SBenjamin Kramer       NormalizedName = std::string(LHS);
292f68e0f79SNico Weber       if (Option.find(Last) == LHS.size())
293f68e0f79SNico Weber         NormalizedName += Last;
294f68e0f79SNico Weber     }
2957b84de79SBrian Gesiak 
29698ca8da5SNico Weber     // Consider each possible prefix for each candidate to find the most
29798ca8da5SNico Weber     // appropriate one. For example, if a user asks for "--helm", suggest
29898ca8da5SNico Weber     // "--help" over "-help".
2994e701ab1SNico Weber     for (int P = 0;
3004e701ab1SNico Weber          const char *const CandidatePrefix = CandidateInfo.Prefixes[P]; P++) {
301e7fa09e4SNico Weber       std::string Candidate = (CandidatePrefix + CandidateName).str();
302e7fa09e4SNico Weber       StringRef CandidateRef = Candidate;
3037b84de79SBrian Gesiak       unsigned Distance =
304e7fa09e4SNico Weber           CandidateRef.edit_distance(NormalizedName, /*AllowReplacements=*/true,
3057b84de79SBrian Gesiak                                      /*MaxEditDistance=*/BestDistance);
306c991daa5SNico Weber       if (RHS.empty() && CandidateHasDelimiter) {
307c991daa5SNico Weber         // The Candidate ends with a = or : delimiter, but the option passed in
308c991daa5SNico Weber         // didn't contain the delimiter (or doesn't have anything after it).
309c991daa5SNico Weber         // In that case, penalize the correction: `-nodefaultlibs` is more
310c991daa5SNico Weber         // likely to be a spello for `-nodefaultlib` than `-nodefaultlib:` even
311c991daa5SNico Weber         // though both have an unmodified editing distance of 1, since the
312c991daa5SNico Weber         // latter would need an argument.
313c991daa5SNico Weber         ++Distance;
314c991daa5SNico Weber       }
3157b84de79SBrian Gesiak       if (Distance < BestDistance) {
3167b84de79SBrian Gesiak         BestDistance = Distance;
31798ca8da5SNico Weber         NearestString = (Candidate + RHS).str();
31898ca8da5SNico Weber       }
3197b84de79SBrian Gesiak     }
3207b84de79SBrian Gesiak   }
3217b84de79SBrian Gesiak   return BestDistance;
3227b84de79SBrian Gesiak }
3237b84de79SBrian Gesiak 
addValues(const char * Option,const char * Values)32424bc6a4cSYuka Takahashi bool OptTable::addValues(const char *Option, const char *Values) {
32524bc6a4cSYuka Takahashi   for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
32624bc6a4cSYuka Takahashi     Info &In = OptionInfos[I];
32724bc6a4cSYuka Takahashi     if (optionMatches(In, Option)) {
32824bc6a4cSYuka Takahashi       In.Values = Values;
32924bc6a4cSYuka Takahashi       return true;
33024bc6a4cSYuka Takahashi     }
33124bc6a4cSYuka Takahashi   }
33224bc6a4cSYuka Takahashi   return false;
33324bc6a4cSYuka Takahashi }
33424bc6a4cSYuka Takahashi 
335f8a29b17SFangrui Song // Parse a single argument, return the new argument, and update Index. If
336f8a29b17SFangrui Song // GroupedShortOptions is true, -a matches "-abc" and the argument in Args will
337f8a29b17SFangrui Song // be updated to "-bc". This overload does not support
338f8a29b17SFangrui Song // FlagsToInclude/FlagsToExclude or case insensitive options.
parseOneArgGrouped(InputArgList & Args,unsigned & Index) const3397789a68eSNico Weber std::unique_ptr<Arg> OptTable::parseOneArgGrouped(InputArgList &Args,
3407789a68eSNico Weber                                                   unsigned &Index) const {
341f8a29b17SFangrui Song   // Anything that doesn't start with PrefixesUnion is an input, as is '-'
342f8a29b17SFangrui Song   // itself.
343f8a29b17SFangrui Song   const char *CStr = Args.getArgString(Index);
344f8a29b17SFangrui Song   StringRef Str(CStr);
345f8a29b17SFangrui Song   if (isInput(PrefixesUnion, Str))
346730bbc6fSNico Weber     return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++, CStr);
347f8a29b17SFangrui Song 
348f8a29b17SFangrui Song   const Info *End = OptionInfos.data() + OptionInfos.size();
349f8a29b17SFangrui Song   StringRef Name = Str.ltrim(PrefixChars);
350f8a29b17SFangrui Song   const Info *Start = std::lower_bound(
351f8a29b17SFangrui Song       OptionInfos.data() + FirstSearchableIndex, End, Name.data());
352f8a29b17SFangrui Song   const Info *Fallback = nullptr;
353f8a29b17SFangrui Song   unsigned Prev = Index;
354f8a29b17SFangrui Song 
355f8a29b17SFangrui Song   // Search for the option which matches Str.
356f8a29b17SFangrui Song   for (; Start != End; ++Start) {
357f8a29b17SFangrui Song     unsigned ArgSize = matchOption(Start, Str, IgnoreCase);
358f8a29b17SFangrui Song     if (!ArgSize)
359f8a29b17SFangrui Song       continue;
360f8a29b17SFangrui Song 
361f8a29b17SFangrui Song     Option Opt(Start, this);
36276645089SNico Weber     if (std::unique_ptr<Arg> A =
36376645089SNico Weber             Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
36476645089SNico Weber                        /*GroupedShortOption=*/false, Index))
3657789a68eSNico Weber       return A;
366f8a29b17SFangrui Song 
367f8a29b17SFangrui Song     // If Opt is a Flag of length 2 (e.g. "-a"), we know it is a prefix of
368f8a29b17SFangrui Song     // the current argument (e.g. "-abc"). Match it as a fallback if no longer
369f8a29b17SFangrui Song     // option (e.g. "-ab") exists.
370f8a29b17SFangrui Song     if (ArgSize == 2 && Opt.getKind() == Option::FlagClass)
371f8a29b17SFangrui Song       Fallback = Start;
372f8a29b17SFangrui Song 
373f8a29b17SFangrui Song     // Otherwise, see if the argument is missing.
374f8a29b17SFangrui Song     if (Prev != Index)
375f8a29b17SFangrui Song       return nullptr;
376f8a29b17SFangrui Song   }
377f8a29b17SFangrui Song   if (Fallback) {
378f8a29b17SFangrui Song     Option Opt(Fallback, this);
379e28cd75aSgbreynoo     // Check that the last option isn't a flag wrongly given an argument.
380e28cd75aSgbreynoo     if (Str[2] == '=')
381730bbc6fSNico Weber       return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
3827789a68eSNico Weber                                    CStr);
383e28cd75aSgbreynoo 
38476645089SNico Weber     if (std::unique_ptr<Arg> A = Opt.accept(
38576645089SNico Weber             Args, Str.substr(0, 2), /*GroupedShortOption=*/true, Index)) {
386f8a29b17SFangrui Song       Args.replaceArgString(Index, Twine('-') + Str.substr(2));
3877789a68eSNico Weber       return A;
388f8a29b17SFangrui Song     }
389f8a29b17SFangrui Song   }
390f8a29b17SFangrui Song 
391e28cd75aSgbreynoo   // In the case of an incorrect short option extract the character and move to
392e28cd75aSgbreynoo   // the next one.
393e28cd75aSgbreynoo   if (Str[1] != '-') {
394e28cd75aSgbreynoo     CStr = Args.MakeArgString(Str.substr(0, 2));
395e28cd75aSgbreynoo     Args.replaceArgString(Index, Twine('-') + Str.substr(2));
396730bbc6fSNico Weber     return std::make_unique<Arg>(getOption(UnknownOptionID), CStr, Index, CStr);
397e28cd75aSgbreynoo   }
398e28cd75aSgbreynoo 
399730bbc6fSNico Weber   return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++, CStr);
400f8a29b17SFangrui Song }
401f8a29b17SFangrui Song 
ParseOneArg(const ArgList & Args,unsigned & Index,unsigned FlagsToInclude,unsigned FlagsToExclude) const4026ffd8e39SNico Weber std::unique_ptr<Arg> OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
403eadb765fSReid Kleckner                                            unsigned FlagsToInclude,
404eadb765fSReid Kleckner                                            unsigned FlagsToExclude) const {
40541ee041dSMichael J. Spencer   unsigned Prev = Index;
40641ee041dSMichael J. Spencer   const char *Str = Args.getArgString(Index);
40741ee041dSMichael J. Spencer 
40841ee041dSMichael J. Spencer   // Anything that doesn't start with PrefixesUnion is an input, as is '-'
40941ee041dSMichael J. Spencer   // itself.
41041ee041dSMichael J. Spencer   if (isInput(PrefixesUnion, Str))
411730bbc6fSNico Weber     return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++, Str);
41241ee041dSMichael J. Spencer 
41324bc6a4cSYuka Takahashi   const Info *Start = OptionInfos.data() + FirstSearchableIndex;
41424bc6a4cSYuka Takahashi   const Info *End = OptionInfos.data() + OptionInfos.size();
41541ee041dSMichael J. Spencer   StringRef Name = StringRef(Str).ltrim(PrefixChars);
41641ee041dSMichael J. Spencer 
41741ee041dSMichael J. Spencer   // Search for the first next option which could be a prefix.
41841ee041dSMichael J. Spencer   Start = std::lower_bound(Start, End, Name.data());
41941ee041dSMichael J. Spencer 
42041ee041dSMichael J. Spencer   // Options are stored in sorted order, with '\0' at the end of the
42141ee041dSMichael J. Spencer   // alphabet. Since the only options which can accept a string must
42241ee041dSMichael J. Spencer   // prefix it, we iteratively search for the next option which could
42341ee041dSMichael J. Spencer   // be a prefix.
42441ee041dSMichael J. Spencer   //
42541ee041dSMichael J. Spencer   // FIXME: This is searching much more than necessary, but I am
42641ee041dSMichael J. Spencer   // blanking on the simplest way to make it fast. We can solve this
42741ee041dSMichael J. Spencer   // problem when we move to TableGen.
42841ee041dSMichael J. Spencer   for (; Start != End; ++Start) {
42941ee041dSMichael J. Spencer     unsigned ArgSize = 0;
43041ee041dSMichael J. Spencer     // Scan for first option which is a proper prefix.
43141ee041dSMichael J. Spencer     for (; Start != End; ++Start)
4328fb5a911SRui Ueyama       if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
43341ee041dSMichael J. Spencer         break;
43441ee041dSMichael J. Spencer     if (Start == End)
43541ee041dSMichael J. Spencer       break;
43641ee041dSMichael J. Spencer 
437eadb765fSReid Kleckner     Option Opt(Start, this);
438eadb765fSReid Kleckner 
439eadb765fSReid Kleckner     if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
440eadb765fSReid Kleckner       continue;
441eadb765fSReid Kleckner     if (Opt.hasFlag(FlagsToExclude))
442eadb765fSReid Kleckner       continue;
443eadb765fSReid Kleckner 
44441ee041dSMichael J. Spencer     // See if this option matches.
44576645089SNico Weber     if (std::unique_ptr<Arg> A =
44676645089SNico Weber             Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
44776645089SNico Weber                        /*GroupedShortOption=*/false, Index))
4486ffd8e39SNico Weber       return A;
44941ee041dSMichael J. Spencer 
45041ee041dSMichael J. Spencer     // Otherwise, see if this argument was missing values.
45141ee041dSMichael J. Spencer     if (Prev != Index)
4522617dcceSCraig Topper       return nullptr;
45341ee041dSMichael J. Spencer   }
45441ee041dSMichael J. Spencer 
455eadb765fSReid Kleckner   // If we failed to find an option and this arg started with /, then it's
456eadb765fSReid Kleckner   // probably an input path.
457eadb765fSReid Kleckner   if (Str[0] == '/')
458730bbc6fSNico Weber     return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++, Str);
459eadb765fSReid Kleckner 
460730bbc6fSNico Weber   return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++, Str);
46141ee041dSMichael J. Spencer }
46241ee041dSMichael J. Spencer 
ParseArgs(ArrayRef<const char * > ArgArr,unsigned & MissingArgIndex,unsigned & MissingArgCount,unsigned FlagsToInclude,unsigned FlagsToExclude) const463db3d31d0SDavid Blaikie InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr,
46441ee041dSMichael J. Spencer                                  unsigned &MissingArgIndex,
465eadb765fSReid Kleckner                                  unsigned &MissingArgCount,
466eadb765fSReid Kleckner                                  unsigned FlagsToInclude,
467eadb765fSReid Kleckner                                  unsigned FlagsToExclude) const {
468db3d31d0SDavid Blaikie   InputArgList Args(ArgArr.begin(), ArgArr.end());
46941ee041dSMichael J. Spencer 
47041ee041dSMichael J. Spencer   // FIXME: Handle '@' args (or at least error on them).
47141ee041dSMichael J. Spencer 
47241ee041dSMichael J. Spencer   MissingArgIndex = MissingArgCount = 0;
473259f61d4SDavid Blaikie   unsigned Index = 0, End = ArgArr.size();
47441ee041dSMichael J. Spencer   while (Index < End) {
475e3f146d9SReid Kleckner     // Ingore nullptrs, they are response file's EOL markers
476db3d31d0SDavid Blaikie     if (Args.getArgString(Index) == nullptr) {
477e3f146d9SReid Kleckner       ++Index;
478e3f146d9SReid Kleckner       continue;
479e3f146d9SReid Kleckner     }
48041ee041dSMichael J. Spencer     // Ignore empty arguments (other things may still take them as arguments).
481db3d31d0SDavid Blaikie     StringRef Str = Args.getArgString(Index);
482b8f3420dSHans Wennborg     if (Str == "") {
48341ee041dSMichael J. Spencer       ++Index;
48441ee041dSMichael J. Spencer       continue;
48541ee041dSMichael J. Spencer     }
48641ee041dSMichael J. Spencer 
48741ee041dSMichael J. Spencer     unsigned Prev = Index;
4886ffd8e39SNico Weber     std::unique_ptr<Arg> A = GroupedShortOptions
4896ffd8e39SNico Weber                  ? parseOneArgGrouped(Args, Index)
490f8a29b17SFangrui Song                  : ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
491f8a29b17SFangrui Song     assert((Index > Prev || GroupedShortOptions) &&
492f8a29b17SFangrui Song            "Parser failed to consume argument.");
49341ee041dSMichael J. Spencer 
49441ee041dSMichael J. Spencer     // Check for missing argument error.
49541ee041dSMichael J. Spencer     if (!A) {
49641ee041dSMichael J. Spencer       assert(Index >= End && "Unexpected parser error.");
49741ee041dSMichael J. Spencer       assert(Index - Prev - 1 && "No missing arguments!");
49841ee041dSMichael J. Spencer       MissingArgIndex = Prev;
49941ee041dSMichael J. Spencer       MissingArgCount = Index - Prev - 1;
50041ee041dSMichael J. Spencer       break;
50141ee041dSMichael J. Spencer     }
50241ee041dSMichael J. Spencer 
5036ffd8e39SNico Weber     Args.append(A.release());
50441ee041dSMichael J. Spencer   }
50541ee041dSMichael J. Spencer 
5069d5891fdSLogan Chien   return Args;
50741ee041dSMichael J. Spencer }
50841ee041dSMichael J. Spencer 
parseArgs(int Argc,char * const * Argv,OptSpecifier Unknown,StringSaver & Saver,function_ref<void (StringRef)> ErrorFn) const509593e1962SFangrui Song InputArgList OptTable::parseArgs(int Argc, char *const *Argv,
510593e1962SFangrui Song                                  OptSpecifier Unknown, StringSaver &Saver,
511593e1962SFangrui Song                                  function_ref<void(StringRef)> ErrorFn) const {
512593e1962SFangrui Song   SmallVector<const char *, 0> NewArgv;
513593e1962SFangrui Song   // The environment variable specifies initial options which can be overridden
514593e1962SFangrui Song   // by commnad line options.
515593e1962SFangrui Song   cl::expandResponseFiles(Argc, Argv, EnvVar, Saver, NewArgv);
516593e1962SFangrui Song 
517593e1962SFangrui Song   unsigned MAI, MAC;
518593e1962SFangrui Song   opt::InputArgList Args = ParseArgs(makeArrayRef(NewArgv), MAI, MAC);
519593e1962SFangrui Song   if (MAC)
520593e1962SFangrui Song     ErrorFn((Twine(Args.getArgString(MAI)) + ": missing argument").str());
521593e1962SFangrui Song 
522593e1962SFangrui Song   // For each unknwon option, call ErrorFn with a formatted error message. The
523593e1962SFangrui Song   // message includes a suggested alternative option spelling if available.
524593e1962SFangrui Song   std::string Nearest;
525593e1962SFangrui Song   for (const opt::Arg *A : Args.filtered(Unknown)) {
526593e1962SFangrui Song     std::string Spelling = A->getAsString(Args);
527593e1962SFangrui Song     if (findNearest(Spelling, Nearest) > 1)
528593e1962SFangrui Song       ErrorFn("unknown argument '" + A->getAsString(Args) + "'");
529593e1962SFangrui Song     else
530593e1962SFangrui Song       ErrorFn("unknown argument '" + A->getAsString(Args) +
531593e1962SFangrui Song               "', did you mean '" + Nearest + "'?");
532593e1962SFangrui Song   }
533593e1962SFangrui Song   return Args;
534593e1962SFangrui Song }
535593e1962SFangrui Song 
getOptionHelpName(const OptTable & Opts,OptSpecifier Id)53641ee041dSMichael J. Spencer static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
53741ee041dSMichael J. Spencer   const Option O = Opts.getOption(Id);
53841ee041dSMichael J. Spencer   std::string Name = O.getPrefixedName();
53941ee041dSMichael J. Spencer 
54041ee041dSMichael J. Spencer   // Add metavar, if used.
54141ee041dSMichael J. Spencer   switch (O.getKind()) {
54241ee041dSMichael J. Spencer   case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
54341ee041dSMichael J. Spencer     llvm_unreachable("Invalid option with help text.");
54441ee041dSMichael J. Spencer 
54541ee041dSMichael J. Spencer   case Option::MultiArgClass:
546bcd6e2a9SNick Kledzik     if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
547bcd6e2a9SNick Kledzik       // For MultiArgs, metavar is full list of all argument names.
548bcd6e2a9SNick Kledzik       Name += ' ';
549bcd6e2a9SNick Kledzik       Name += MetaVarName;
550bcd6e2a9SNick Kledzik     }
551bcd6e2a9SNick Kledzik     else {
552bcd6e2a9SNick Kledzik       // For MultiArgs<N>, if metavar not supplied, print <value> N times.
553bcd6e2a9SNick Kledzik       for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
554bcd6e2a9SNick Kledzik         Name += " <value>";
555bcd6e2a9SNick Kledzik       }
556bcd6e2a9SNick Kledzik     }
557bcd6e2a9SNick Kledzik     break;
55841ee041dSMichael J. Spencer 
55941ee041dSMichael J. Spencer   case Option::FlagClass:
56041ee041dSMichael J. Spencer     break;
56141ee041dSMichael J. Spencer 
562ba5d4af4SYuka Takahashi   case Option::ValuesClass:
563ba5d4af4SYuka Takahashi     break;
564ba5d4af4SYuka Takahashi 
56541ee041dSMichael J. Spencer   case Option::SeparateClass: case Option::JoinedOrSeparateClass:
56640cfde3cSHans Wennborg   case Option::RemainingArgsClass: case Option::RemainingArgsJoinedClass:
56741ee041dSMichael J. Spencer     Name += ' ';
568b03fd12cSJustin Bogner     LLVM_FALLTHROUGH;
56941ee041dSMichael J. Spencer   case Option::JoinedClass: case Option::CommaJoinedClass:
57041ee041dSMichael J. Spencer   case Option::JoinedAndSeparateClass:
57141ee041dSMichael J. Spencer     if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
57241ee041dSMichael J. Spencer       Name += MetaVarName;
57341ee041dSMichael J. Spencer     else
57441ee041dSMichael J. Spencer       Name += "<value>";
57541ee041dSMichael J. Spencer     break;
57641ee041dSMichael J. Spencer   }
57741ee041dSMichael J. Spencer 
57841ee041dSMichael J. Spencer   return Name;
57941ee041dSMichael J. Spencer }
58041ee041dSMichael J. Spencer 
581b4e76f6bSGeorge Rimar namespace {
582b4e76f6bSGeorge Rimar struct OptionInfo {
583b4e76f6bSGeorge Rimar   std::string Name;
584b4e76f6bSGeorge Rimar   StringRef HelpText;
585b4e76f6bSGeorge Rimar };
586b4e76f6bSGeorge Rimar } // namespace
587b4e76f6bSGeorge Rimar 
PrintHelpOptionList(raw_ostream & OS,StringRef Title,std::vector<OptionInfo> & OptionHelp)58841ee041dSMichael J. Spencer static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
589b4e76f6bSGeorge Rimar                                 std::vector<OptionInfo> &OptionHelp) {
59041ee041dSMichael J. Spencer   OS << Title << ":\n";
59141ee041dSMichael J. Spencer 
59241ee041dSMichael J. Spencer   // Find the maximum option length.
59341ee041dSMichael J. Spencer   unsigned OptionFieldWidth = 0;
594*ccdd5bb2SKazu Hirata   for (const OptionInfo &Opt : OptionHelp) {
59541ee041dSMichael J. Spencer     // Limit the amount of padding we are willing to give up for alignment.
596*ccdd5bb2SKazu Hirata     unsigned Length = Opt.Name.size();
59741ee041dSMichael J. Spencer     if (Length <= 23)
59841ee041dSMichael J. Spencer       OptionFieldWidth = std::max(OptionFieldWidth, Length);
59941ee041dSMichael J. Spencer   }
60041ee041dSMichael J. Spencer 
60141ee041dSMichael J. Spencer   const unsigned InitialPad = 2;
602*ccdd5bb2SKazu Hirata   for (const OptionInfo &Opt : OptionHelp) {
603*ccdd5bb2SKazu Hirata     const std::string &Option = Opt.Name;
60441ee041dSMichael J. Spencer     int Pad = OptionFieldWidth - int(Option.size());
60541ee041dSMichael J. Spencer     OS.indent(InitialPad) << Option;
60641ee041dSMichael J. Spencer 
60741ee041dSMichael J. Spencer     // Break on long option names.
60841ee041dSMichael J. Spencer     if (Pad < 0) {
60941ee041dSMichael J. Spencer       OS << "\n";
61041ee041dSMichael J. Spencer       Pad = OptionFieldWidth + InitialPad;
61141ee041dSMichael J. Spencer     }
612*ccdd5bb2SKazu Hirata     OS.indent(Pad + 1) << Opt.HelpText << '\n';
61341ee041dSMichael J. Spencer   }
61441ee041dSMichael J. Spencer }
61541ee041dSMichael J. Spencer 
getOptionHelpGroup(const OptTable & Opts,OptSpecifier Id)61641ee041dSMichael J. Spencer static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
61741ee041dSMichael J. Spencer   unsigned GroupID = Opts.getOptionGroupID(Id);
61841ee041dSMichael J. Spencer 
61941ee041dSMichael J. Spencer   // If not in a group, return the default help group.
62041ee041dSMichael J. Spencer   if (!GroupID)
62141ee041dSMichael J. Spencer     return "OPTIONS";
62241ee041dSMichael J. Spencer 
62341ee041dSMichael J. Spencer   // Abuse the help text of the option groups to store the "help group"
62441ee041dSMichael J. Spencer   // name.
62541ee041dSMichael J. Spencer   //
62641ee041dSMichael J. Spencer   // FIXME: Split out option groups.
62741ee041dSMichael J. Spencer   if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
62841ee041dSMichael J. Spencer     return GroupHelp;
62941ee041dSMichael J. Spencer 
63041ee041dSMichael J. Spencer   // Otherwise keep looking.
63141ee041dSMichael J. Spencer   return getOptionHelpGroup(Opts, GroupID);
63241ee041dSMichael J. Spencer }
63341ee041dSMichael J. Spencer 
printHelp(raw_ostream & OS,const char * Usage,const char * Title,bool ShowHidden,bool ShowAllAliases) const634f1e2d585SFangrui Song void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
6354530dffbSGeorge Rimar                          bool ShowHidden, bool ShowAllAliases) const {
636f1e2d585SFangrui Song   printHelp(OS, Usage, Title, /*Include*/ 0, /*Exclude*/
6374530dffbSGeorge Rimar             (ShowHidden ? 0 : HelpHidden), ShowAllAliases);
63812e0332bSReid Kleckner }
63912e0332bSReid Kleckner 
printHelp(raw_ostream & OS,const char * Usage,const char * Title,unsigned FlagsToInclude,unsigned FlagsToExclude,bool ShowAllAliases) const640f1e2d585SFangrui Song void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
6414530dffbSGeorge Rimar                          unsigned FlagsToInclude, unsigned FlagsToExclude,
6424530dffbSGeorge Rimar                          bool ShowAllAliases) const {
64388478bbcSFangrui Song   OS << "OVERVIEW: " << Title << "\n\n";
64488478bbcSFangrui Song   OS << "USAGE: " << Usage << "\n\n";
64541ee041dSMichael J. Spencer 
64641ee041dSMichael J. Spencer   // Render help text into a map of group-name to a list of (option, help)
64741ee041dSMichael J. Spencer   // pairs.
6488d315b8eSJan Korous   std::map<std::string, std::vector<OptionInfo>> GroupedOptionHelp;
64941ee041dSMichael J. Spencer 
65041e9a15dSJan Korous   for (unsigned Id = 1, e = getNumOptions() + 1; Id != e; ++Id) {
65141ee041dSMichael J. Spencer     // FIXME: Split out option groups.
65241ee041dSMichael J. Spencer     if (getOptionKind(Id) == Option::GroupClass)
65341ee041dSMichael J. Spencer       continue;
65441ee041dSMichael J. Spencer 
65512e0332bSReid Kleckner     unsigned Flags = getInfo(Id).Flags;
65612e0332bSReid Kleckner     if (FlagsToInclude && !(Flags & FlagsToInclude))
65712e0332bSReid Kleckner       continue;
65812e0332bSReid Kleckner     if (Flags & FlagsToExclude)
65941ee041dSMichael J. Spencer       continue;
66041ee041dSMichael J. Spencer 
6614530dffbSGeorge Rimar     // If an alias doesn't have a help text, show a help text for the aliased
6624530dffbSGeorge Rimar     // option instead.
6634530dffbSGeorge Rimar     const char *HelpText = getOptionHelpText(Id);
6644530dffbSGeorge Rimar     if (!HelpText && ShowAllAliases) {
6654530dffbSGeorge Rimar       const Option Alias = getOption(Id).getAlias();
6664530dffbSGeorge Rimar       if (Alias.isValid())
6674530dffbSGeorge Rimar         HelpText = getOptionHelpText(Alias.getID());
6684530dffbSGeorge Rimar     }
6694530dffbSGeorge Rimar 
670dcc6b7b1SAndrzej Warzynski     if (HelpText && (strlen(HelpText) != 0)) {
67141ee041dSMichael J. Spencer       const char *HelpGroup = getOptionHelpGroup(*this, Id);
67241ee041dSMichael J. Spencer       const std::string &OptName = getOptionHelpName(*this, Id);
6734530dffbSGeorge Rimar       GroupedOptionHelp[HelpGroup].push_back({OptName, HelpText});
67441ee041dSMichael J. Spencer     }
67541ee041dSMichael J. Spencer   }
67641ee041dSMichael J. Spencer 
6778d315b8eSJan Korous   for (auto& OptionGroup : GroupedOptionHelp) {
6788d315b8eSJan Korous     if (OptionGroup.first != GroupedOptionHelp.begin()->first)
67941ee041dSMichael J. Spencer       OS << "\n";
6808d315b8eSJan Korous     PrintHelpOptionList(OS, OptionGroup.first, OptionGroup.second);
68141ee041dSMichael J. Spencer   }
68241ee041dSMichael J. Spencer 
68341ee041dSMichael J. Spencer   OS.flush();
68441ee041dSMichael J. Spencer }
685