17c7aba6eSDimitry Andric //===- OptTable.cpp - Option Table Implementation -------------------------===//
24a16efa3SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
64a16efa3SDimitry Andric //
74a16efa3SDimitry Andric //===----------------------------------------------------------------------===//
84a16efa3SDimitry Andric
9b60736ecSDimitry Andric #include "llvm/Option/OptTable.h"
10b915e9e0SDimitry Andric #include "llvm/ADT/STLExtras.h"
117c7aba6eSDimitry Andric #include "llvm/ADT/StringRef.h"
124a16efa3SDimitry Andric #include "llvm/Option/Arg.h"
134a16efa3SDimitry Andric #include "llvm/Option/ArgList.h"
147c7aba6eSDimitry Andric #include "llvm/Option/OptSpecifier.h"
15b60736ecSDimitry Andric #include "llvm/Option/Option.h"
16b60736ecSDimitry Andric #include "llvm/Support/CommandLine.h" // for expandResponseFiles
177c7aba6eSDimitry Andric #include "llvm/Support/Compiler.h"
184a16efa3SDimitry Andric #include "llvm/Support/ErrorHandling.h"
194a16efa3SDimitry Andric #include "llvm/Support/raw_ostream.h"
204a16efa3SDimitry Andric #include <algorithm>
217c7aba6eSDimitry Andric #include <cassert>
22f8af5cf6SDimitry Andric #include <cctype>
237c7aba6eSDimitry Andric #include <cstring>
244a16efa3SDimitry Andric #include <map>
25e3b55780SDimitry Andric #include <set>
267c7aba6eSDimitry Andric #include <string>
277c7aba6eSDimitry Andric #include <utility>
287c7aba6eSDimitry Andric #include <vector>
294a16efa3SDimitry Andric
304a16efa3SDimitry Andric using namespace llvm;
314a16efa3SDimitry Andric using namespace llvm::opt;
324a16efa3SDimitry Andric
33f8af5cf6SDimitry Andric namespace llvm {
34f8af5cf6SDimitry Andric namespace opt {
354a16efa3SDimitry Andric
36f8af5cf6SDimitry Andric // Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
37044eb2f6SDimitry Andric // with an exception. '\0' comes at the end of the alphabet instead of the
38f8af5cf6SDimitry Andric // beginning (thus options precede any other options which prefix them).
StrCmpOptionNameIgnoreCase(StringRef A,StringRef B)39e3b55780SDimitry Andric static int StrCmpOptionNameIgnoreCase(StringRef A, StringRef B) {
40e3b55780SDimitry Andric size_t MinSize = std::min(A.size(), B.size());
41e3b55780SDimitry Andric if (int Res = A.substr(0, MinSize).compare_insensitive(B.substr(0, MinSize)))
42e3b55780SDimitry Andric return Res;
43e3b55780SDimitry Andric
44e3b55780SDimitry Andric if (A.size() == B.size())
454a16efa3SDimitry Andric return 0;
464a16efa3SDimitry Andric
47e3b55780SDimitry Andric return (A.size() == MinSize) ? 1 /* A is a prefix of B. */
48e3b55780SDimitry Andric : -1 /* B is a prefix of A */;
494a16efa3SDimitry Andric }
504a16efa3SDimitry Andric
51f8af5cf6SDimitry Andric #ifndef NDEBUG
StrCmpOptionName(StringRef A,StringRef B)52e3b55780SDimitry Andric static int StrCmpOptionName(StringRef A, StringRef B) {
53f8af5cf6SDimitry Andric if (int N = StrCmpOptionNameIgnoreCase(A, B))
54f8af5cf6SDimitry Andric return N;
55e3b55780SDimitry Andric return A.compare(B);
56f8af5cf6SDimitry Andric }
574a16efa3SDimitry Andric
operator <(const OptTable::Info & A,const OptTable::Info & B)584a16efa3SDimitry Andric static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
594a16efa3SDimitry Andric if (&A == &B)
604a16efa3SDimitry Andric return false;
614a16efa3SDimitry Andric
62b1c73532SDimitry Andric if (int N = StrCmpOptionName(A.getName(), B.getName()))
63f8af5cf6SDimitry Andric return N < 0;
644a16efa3SDimitry Andric
65e3b55780SDimitry Andric for (size_t I = 0, K = std::min(A.Prefixes.size(), B.Prefixes.size()); I != K;
66e3b55780SDimitry Andric ++I)
67e3b55780SDimitry Andric if (int N = StrCmpOptionName(A.Prefixes[I], B.Prefixes[I]))
68f8af5cf6SDimitry Andric return N < 0;
694a16efa3SDimitry Andric
704a16efa3SDimitry Andric // Names are the same, check that classes are in order; exactly one
714a16efa3SDimitry Andric // should be joined, and it should succeed the other.
724a16efa3SDimitry Andric assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
734a16efa3SDimitry Andric "Unexpected classes for options with same name.");
744a16efa3SDimitry Andric return B.Kind == Option::JoinedClass;
754a16efa3SDimitry Andric }
76f8af5cf6SDimitry Andric #endif
774a16efa3SDimitry Andric
784a16efa3SDimitry Andric // Support lower_bound between info and an option name.
operator <(const OptTable::Info & I,StringRef Name)79e3b55780SDimitry Andric static inline bool operator<(const OptTable::Info &I, StringRef Name) {
80b1c73532SDimitry Andric return StrCmpOptionNameIgnoreCase(I.getName(), Name) < 0;
814a16efa3SDimitry Andric }
827c7aba6eSDimitry Andric
837c7aba6eSDimitry Andric } // end namespace opt
847c7aba6eSDimitry Andric } // end namespace llvm
854a16efa3SDimitry Andric
OptSpecifier(const Option * Opt)864a16efa3SDimitry Andric OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
874a16efa3SDimitry Andric
OptTable(ArrayRef<Info> OptionInfos,bool IgnoreCase)88dd58ef01SDimitry Andric OptTable::OptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase)
897c7aba6eSDimitry Andric : OptionInfos(OptionInfos), IgnoreCase(IgnoreCase) {
904a16efa3SDimitry Andric // Explicitly zero initialize the error to work around a bug in array
914a16efa3SDimitry Andric // value-initialization on MinGW with gcc 4.3.5.
924a16efa3SDimitry Andric
934a16efa3SDimitry Andric // Find start of normal options.
944a16efa3SDimitry Andric for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
954a16efa3SDimitry Andric unsigned Kind = getInfo(i + 1).Kind;
964a16efa3SDimitry Andric if (Kind == Option::InputClass) {
97c0981da4SDimitry Andric assert(!InputOptionID && "Cannot have multiple input options!");
98c0981da4SDimitry Andric InputOptionID = getInfo(i + 1).ID;
994a16efa3SDimitry Andric } else if (Kind == Option::UnknownClass) {
100c0981da4SDimitry Andric assert(!UnknownOptionID && "Cannot have multiple unknown options!");
101c0981da4SDimitry Andric UnknownOptionID = getInfo(i + 1).ID;
1024a16efa3SDimitry Andric } else if (Kind != Option::GroupClass) {
1034a16efa3SDimitry Andric FirstSearchableIndex = i;
1044a16efa3SDimitry Andric break;
1054a16efa3SDimitry Andric }
1064a16efa3SDimitry Andric }
1074a16efa3SDimitry Andric assert(FirstSearchableIndex != 0 && "No searchable options?");
1084a16efa3SDimitry Andric
1094a16efa3SDimitry Andric #ifndef NDEBUG
1104a16efa3SDimitry Andric // Check that everything after the first searchable option is a
1114a16efa3SDimitry Andric // regular option class.
1124a16efa3SDimitry Andric for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
1134a16efa3SDimitry Andric Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
1144a16efa3SDimitry Andric assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
1154a16efa3SDimitry Andric Kind != Option::GroupClass) &&
1164a16efa3SDimitry Andric "Special options should be defined first!");
1174a16efa3SDimitry Andric }
1184a16efa3SDimitry Andric
1194a16efa3SDimitry Andric // Check that options are in order.
1204a16efa3SDimitry Andric for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
1214a16efa3SDimitry Andric if (!(getInfo(i) < getInfo(i + 1))) {
1224a16efa3SDimitry Andric getOption(i).dump();
1234a16efa3SDimitry Andric getOption(i + 1).dump();
1244a16efa3SDimitry Andric llvm_unreachable("Options are not in order!");
1254a16efa3SDimitry Andric }
1264a16efa3SDimitry Andric }
1274a16efa3SDimitry Andric #endif
128e3b55780SDimitry Andric }
1294a16efa3SDimitry Andric
buildPrefixChars()130e3b55780SDimitry Andric void OptTable::buildPrefixChars() {
131e3b55780SDimitry Andric assert(PrefixChars.empty() && "rebuilding a non-empty prefix char");
1324a16efa3SDimitry Andric
1334a16efa3SDimitry Andric // Build prefix chars.
134e3b55780SDimitry Andric for (const StringLiteral &Prefix : getPrefixesUnion()) {
135f65dcba8SDimitry Andric for (char C : Prefix)
136f65dcba8SDimitry Andric if (!is_contained(PrefixChars, C))
137f65dcba8SDimitry Andric PrefixChars.push_back(C);
1384a16efa3SDimitry Andric }
1394a16efa3SDimitry Andric }
1404a16efa3SDimitry Andric
1417c7aba6eSDimitry Andric OptTable::~OptTable() = default;
1424a16efa3SDimitry Andric
getOption(OptSpecifier Opt) const1434a16efa3SDimitry Andric const Option OptTable::getOption(OptSpecifier Opt) const {
1444a16efa3SDimitry Andric unsigned id = Opt.getID();
1454a16efa3SDimitry Andric if (id == 0)
1465ca98fd9SDimitry Andric return Option(nullptr, nullptr);
1474a16efa3SDimitry Andric assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
1484a16efa3SDimitry Andric return Option(&getInfo(id), this);
1494a16efa3SDimitry Andric }
1504a16efa3SDimitry Andric
isInput(const ArrayRef<StringLiteral> & Prefixes,StringRef Arg)151e3b55780SDimitry Andric static bool isInput(const ArrayRef<StringLiteral> &Prefixes, StringRef Arg) {
1524a16efa3SDimitry Andric if (Arg == "-")
1534a16efa3SDimitry Andric return true;
154e3b55780SDimitry Andric for (const StringRef &Prefix : Prefixes)
155312c0ed1SDimitry Andric if (Arg.starts_with(Prefix))
1564a16efa3SDimitry Andric return false;
1574a16efa3SDimitry Andric return true;
1584a16efa3SDimitry Andric }
1594a16efa3SDimitry Andric
1604a16efa3SDimitry Andric /// \returns Matched size. 0 means no match.
matchOption(const OptTable::Info * I,StringRef Str,bool IgnoreCase)161f8af5cf6SDimitry Andric static unsigned matchOption(const OptTable::Info *I, StringRef Str,
162f8af5cf6SDimitry Andric bool IgnoreCase) {
163e3b55780SDimitry Andric for (auto Prefix : I->Prefixes) {
164312c0ed1SDimitry Andric if (Str.starts_with(Prefix)) {
165f8af5cf6SDimitry Andric StringRef Rest = Str.substr(Prefix.size());
166b1c73532SDimitry Andric bool Matched = IgnoreCase ? Rest.starts_with_insensitive(I->getName())
167312c0ed1SDimitry Andric : Rest.starts_with(I->getName());
168f8af5cf6SDimitry Andric if (Matched)
169b1c73532SDimitry Andric return Prefix.size() + StringRef(I->getName()).size();
1704a16efa3SDimitry Andric }
171f8af5cf6SDimitry Andric }
1724a16efa3SDimitry Andric return 0;
1734a16efa3SDimitry Andric }
1744a16efa3SDimitry Andric
17508bbd35aSDimitry Andric // Returns true if one of the Prefixes + In.Names matches Option
optionMatches(const OptTable::Info & In,StringRef Option)17608bbd35aSDimitry Andric static bool optionMatches(const OptTable::Info &In, StringRef Option) {
177e3b55780SDimitry Andric for (auto Prefix : In.Prefixes)
178312c0ed1SDimitry Andric if (Option.ends_with(In.getName()))
179b1c73532SDimitry Andric if (Option.slice(0, Option.size() - In.getName().size()) == Prefix)
18008bbd35aSDimitry Andric return true;
18108bbd35aSDimitry Andric return false;
18208bbd35aSDimitry Andric }
18308bbd35aSDimitry Andric
18408bbd35aSDimitry Andric // This function is for flag value completion.
18508bbd35aSDimitry Andric // Eg. When "-stdlib=" and "l" was passed to this function, it will return
18608bbd35aSDimitry Andric // appropiriate values for stdlib, which starts with l.
18708bbd35aSDimitry Andric std::vector<std::string>
suggestValueCompletions(StringRef Option,StringRef Arg) const18808bbd35aSDimitry Andric OptTable::suggestValueCompletions(StringRef Option, StringRef Arg) const {
18908bbd35aSDimitry Andric // Search all options and return possible values.
190044eb2f6SDimitry Andric for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
191044eb2f6SDimitry Andric const Info &In = OptionInfos[I];
192044eb2f6SDimitry Andric if (!In.Values || !optionMatches(In, Option))
19308bbd35aSDimitry Andric continue;
19408bbd35aSDimitry Andric
19508bbd35aSDimitry Andric SmallVector<StringRef, 8> Candidates;
19608bbd35aSDimitry Andric StringRef(In.Values).split(Candidates, ",", -1, false);
19708bbd35aSDimitry Andric
19808bbd35aSDimitry Andric std::vector<std::string> Result;
19908bbd35aSDimitry Andric for (StringRef Val : Candidates)
200ac9a064cSDimitry Andric if (Val.starts_with(Arg) && Arg != Val)
201cfca06d7SDimitry Andric Result.push_back(std::string(Val));
20208bbd35aSDimitry Andric return Result;
20308bbd35aSDimitry Andric }
20408bbd35aSDimitry Andric return {};
20508bbd35aSDimitry Andric }
20608bbd35aSDimitry Andric
207ca089b24SDimitry Andric std::vector<std::string>
findByPrefix(StringRef Cur,Visibility VisibilityMask,unsigned int DisableFlags) const208b1c73532SDimitry Andric OptTable::findByPrefix(StringRef Cur, Visibility VisibilityMask,
209b1c73532SDimitry Andric unsigned int DisableFlags) const {
210ab44ce3dSDimitry Andric std::vector<std::string> Ret;
211044eb2f6SDimitry Andric for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
212044eb2f6SDimitry Andric const Info &In = OptionInfos[I];
213e3b55780SDimitry Andric if (In.Prefixes.empty() || (!In.HelpText && !In.GroupID))
214ab44ce3dSDimitry Andric continue;
215b1c73532SDimitry Andric if (!(In.Visibility & VisibilityMask))
216b1c73532SDimitry Andric continue;
217ca089b24SDimitry Andric if (In.Flags & DisableFlags)
218ca089b24SDimitry Andric continue;
219ca089b24SDimitry Andric
220e3b55780SDimitry Andric for (auto Prefix : In.Prefixes) {
221b1c73532SDimitry Andric std::string S = (Prefix + In.getName() + "\t").str();
2223ad6a4b4SDimitry Andric if (In.HelpText)
2233ad6a4b4SDimitry Andric S += In.HelpText;
224312c0ed1SDimitry Andric if (StringRef(S).starts_with(Cur) && S != std::string(Cur) + "\t")
225ab44ce3dSDimitry Andric Ret.push_back(S);
226ab44ce3dSDimitry Andric }
227ab44ce3dSDimitry Andric }
228ab44ce3dSDimitry Andric return Ret;
229ab44ce3dSDimitry Andric }
230ab44ce3dSDimitry Andric
findNearest(StringRef Option,std::string & NearestString,Visibility VisibilityMask,unsigned MinimumLength,unsigned MaximumDistance) const231eb11fae6SDimitry Andric unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
232b1c73532SDimitry Andric Visibility VisibilityMask,
233b1c73532SDimitry Andric unsigned MinimumLength,
234b1c73532SDimitry Andric unsigned MaximumDistance) const {
235b1c73532SDimitry Andric return internalFindNearest(
236b1c73532SDimitry Andric Option, NearestString, MinimumLength, MaximumDistance,
237b1c73532SDimitry Andric [VisibilityMask](const Info &CandidateInfo) {
238b1c73532SDimitry Andric return (CandidateInfo.Visibility & VisibilityMask) == 0;
239b1c73532SDimitry Andric });
240b1c73532SDimitry Andric }
241b1c73532SDimitry Andric
findNearest(StringRef Option,std::string & NearestString,unsigned FlagsToInclude,unsigned FlagsToExclude,unsigned MinimumLength,unsigned MaximumDistance) const242b1c73532SDimitry Andric unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
243eb11fae6SDimitry Andric unsigned FlagsToInclude, unsigned FlagsToExclude,
244e3b55780SDimitry Andric unsigned MinimumLength,
245e3b55780SDimitry Andric unsigned MaximumDistance) const {
246b1c73532SDimitry Andric return internalFindNearest(
247b1c73532SDimitry Andric Option, NearestString, MinimumLength, MaximumDistance,
248b1c73532SDimitry Andric [FlagsToInclude, FlagsToExclude](const Info &CandidateInfo) {
249b1c73532SDimitry Andric if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
250b1c73532SDimitry Andric return true;
251b1c73532SDimitry Andric if (CandidateInfo.Flags & FlagsToExclude)
252b1c73532SDimitry Andric return true;
253b1c73532SDimitry Andric return false;
254b1c73532SDimitry Andric });
255b1c73532SDimitry Andric }
256b1c73532SDimitry Andric
internalFindNearest(StringRef Option,std::string & NearestString,unsigned MinimumLength,unsigned MaximumDistance,std::function<bool (const Info &)> ExcludeOption) const257b1c73532SDimitry Andric unsigned OptTable::internalFindNearest(
258b1c73532SDimitry Andric StringRef Option, std::string &NearestString, unsigned MinimumLength,
259b1c73532SDimitry Andric unsigned MaximumDistance,
260b1c73532SDimitry Andric std::function<bool(const Info &)> ExcludeOption) const {
261eb11fae6SDimitry Andric assert(!Option.empty());
262eb11fae6SDimitry Andric
263e6d15924SDimitry Andric // Consider each [option prefix + option name] pair as a candidate, finding
264e6d15924SDimitry Andric // the closest match.
265e3b55780SDimitry Andric unsigned BestDistance =
266e3b55780SDimitry Andric MaximumDistance == UINT_MAX ? UINT_MAX : MaximumDistance + 1;
267e3b55780SDimitry Andric SmallString<16> Candidate;
268e3b55780SDimitry Andric SmallString<16> NormalizedName;
269e3b55780SDimitry Andric
270eb11fae6SDimitry Andric for (const Info &CandidateInfo :
271eb11fae6SDimitry Andric ArrayRef<Info>(OptionInfos).drop_front(FirstSearchableIndex)) {
272b1c73532SDimitry Andric StringRef CandidateName = CandidateInfo.getName();
273eb11fae6SDimitry Andric
274e6d15924SDimitry Andric // We can eliminate some option prefix/name pairs as candidates right away:
275e6d15924SDimitry Andric // * Ignore option candidates with empty names, such as "--", or names
276eb11fae6SDimitry Andric // that do not meet the minimum length.
277e3b55780SDimitry Andric if (CandidateName.size() < MinimumLength)
278eb11fae6SDimitry Andric continue;
279eb11fae6SDimitry Andric
280b1c73532SDimitry Andric // Ignore options that are excluded via masks
281b1c73532SDimitry Andric if (ExcludeOption(CandidateInfo))
282eb11fae6SDimitry Andric continue;
283eb11fae6SDimitry Andric
284e6d15924SDimitry Andric // * Ignore positional argument option candidates (which do not
285eb11fae6SDimitry Andric // have prefixes).
286e3b55780SDimitry Andric if (CandidateInfo.Prefixes.empty())
287eb11fae6SDimitry Andric continue;
288eb11fae6SDimitry Andric
289e6d15924SDimitry Andric // Now check if the candidate ends with a character commonly used when
290eb11fae6SDimitry Andric // delimiting an option from its value, such as '=' or ':'. If it does,
291eb11fae6SDimitry Andric // attempt to split the given option based on that delimiter.
292e6d15924SDimitry Andric char Last = CandidateName.back();
293e6d15924SDimitry Andric bool CandidateHasDelimiter = Last == '=' || Last == ':';
294e3b55780SDimitry Andric StringRef RHS;
295e6d15924SDimitry Andric if (CandidateHasDelimiter) {
296e3b55780SDimitry Andric std::tie(NormalizedName, RHS) = Option.split(Last);
297e3b55780SDimitry Andric if (Option.find(Last) == NormalizedName.size())
298e6d15924SDimitry Andric NormalizedName += Last;
299e3b55780SDimitry Andric } else
300e3b55780SDimitry Andric NormalizedName = Option;
301eb11fae6SDimitry Andric
302e6d15924SDimitry Andric // Consider each possible prefix for each candidate to find the most
303e6d15924SDimitry Andric // appropriate one. For example, if a user asks for "--helm", suggest
304e6d15924SDimitry Andric // "--help" over "-help".
305e3b55780SDimitry Andric for (auto CandidatePrefix : CandidateInfo.Prefixes) {
306e3b55780SDimitry Andric // If Candidate and NormalizedName have more than 'BestDistance'
307e3b55780SDimitry Andric // characters of difference, no need to compute the edit distance, it's
308e3b55780SDimitry Andric // going to be greater than BestDistance. Don't bother computing Candidate
309e3b55780SDimitry Andric // at all.
310e3b55780SDimitry Andric size_t CandidateSize = CandidatePrefix.size() + CandidateName.size(),
311e3b55780SDimitry Andric NormalizedSize = NormalizedName.size();
312e3b55780SDimitry Andric size_t AbsDiff = CandidateSize > NormalizedSize
313e3b55780SDimitry Andric ? CandidateSize - NormalizedSize
314e3b55780SDimitry Andric : NormalizedSize - CandidateSize;
315e3b55780SDimitry Andric if (AbsDiff > BestDistance) {
316e3b55780SDimitry Andric continue;
317e3b55780SDimitry Andric }
318e3b55780SDimitry Andric Candidate = CandidatePrefix;
319e3b55780SDimitry Andric Candidate += CandidateName;
320e3b55780SDimitry Andric unsigned Distance = StringRef(Candidate).edit_distance(
321e3b55780SDimitry Andric NormalizedName, /*AllowReplacements=*/true,
322eb11fae6SDimitry Andric /*MaxEditDistance=*/BestDistance);
323e6d15924SDimitry Andric if (RHS.empty() && CandidateHasDelimiter) {
324e6d15924SDimitry Andric // The Candidate ends with a = or : delimiter, but the option passed in
325e6d15924SDimitry Andric // didn't contain the delimiter (or doesn't have anything after it).
326e6d15924SDimitry Andric // In that case, penalize the correction: `-nodefaultlibs` is more
327e6d15924SDimitry Andric // likely to be a spello for `-nodefaultlib` than `-nodefaultlib:` even
328e6d15924SDimitry Andric // though both have an unmodified editing distance of 1, since the
329e6d15924SDimitry Andric // latter would need an argument.
330e6d15924SDimitry Andric ++Distance;
331e6d15924SDimitry Andric }
332eb11fae6SDimitry Andric if (Distance < BestDistance) {
333eb11fae6SDimitry Andric BestDistance = Distance;
334e6d15924SDimitry Andric NearestString = (Candidate + RHS).str();
335e6d15924SDimitry Andric }
336eb11fae6SDimitry Andric }
337eb11fae6SDimitry Andric }
338eb11fae6SDimitry Andric return BestDistance;
339eb11fae6SDimitry Andric }
340eb11fae6SDimitry Andric
341b60736ecSDimitry Andric // Parse a single argument, return the new argument, and update Index. If
342b60736ecSDimitry Andric // GroupedShortOptions is true, -a matches "-abc" and the argument in Args will
343b1c73532SDimitry Andric // be updated to "-bc". This overload does not support VisibilityMask or case
344b1c73532SDimitry Andric // insensitive options.
parseOneArgGrouped(InputArgList & Args,unsigned & Index) const345c0981da4SDimitry Andric std::unique_ptr<Arg> OptTable::parseOneArgGrouped(InputArgList &Args,
346c0981da4SDimitry Andric unsigned &Index) const {
347b60736ecSDimitry Andric // Anything that doesn't start with PrefixesUnion is an input, as is '-'
348b60736ecSDimitry Andric // itself.
349b60736ecSDimitry Andric const char *CStr = Args.getArgString(Index);
350b60736ecSDimitry Andric StringRef Str(CStr);
351e3b55780SDimitry Andric if (isInput(getPrefixesUnion(), Str))
352c0981da4SDimitry Andric return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++, CStr);
353b60736ecSDimitry Andric
354b60736ecSDimitry Andric const Info *End = OptionInfos.data() + OptionInfos.size();
355b60736ecSDimitry Andric StringRef Name = Str.ltrim(PrefixChars);
356e3b55780SDimitry Andric const Info *Start =
357e3b55780SDimitry Andric std::lower_bound(OptionInfos.data() + FirstSearchableIndex, End, Name);
358b60736ecSDimitry Andric const Info *Fallback = nullptr;
359b60736ecSDimitry Andric unsigned Prev = Index;
360b60736ecSDimitry Andric
361b60736ecSDimitry Andric // Search for the option which matches Str.
362b60736ecSDimitry Andric for (; Start != End; ++Start) {
363b60736ecSDimitry Andric unsigned ArgSize = matchOption(Start, Str, IgnoreCase);
364b60736ecSDimitry Andric if (!ArgSize)
365b60736ecSDimitry Andric continue;
366b60736ecSDimitry Andric
367b60736ecSDimitry Andric Option Opt(Start, this);
368c0981da4SDimitry Andric if (std::unique_ptr<Arg> A =
369c0981da4SDimitry Andric Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
370c0981da4SDimitry Andric /*GroupedShortOption=*/false, Index))
371b60736ecSDimitry Andric return A;
372b60736ecSDimitry Andric
373b60736ecSDimitry Andric // If Opt is a Flag of length 2 (e.g. "-a"), we know it is a prefix of
374b60736ecSDimitry Andric // the current argument (e.g. "-abc"). Match it as a fallback if no longer
375b60736ecSDimitry Andric // option (e.g. "-ab") exists.
376b60736ecSDimitry Andric if (ArgSize == 2 && Opt.getKind() == Option::FlagClass)
377b60736ecSDimitry Andric Fallback = Start;
378b60736ecSDimitry Andric
379b60736ecSDimitry Andric // Otherwise, see if the argument is missing.
380b60736ecSDimitry Andric if (Prev != Index)
381b60736ecSDimitry Andric return nullptr;
382b60736ecSDimitry Andric }
383b60736ecSDimitry Andric if (Fallback) {
384b60736ecSDimitry Andric Option Opt(Fallback, this);
385c0981da4SDimitry Andric // Check that the last option isn't a flag wrongly given an argument.
386c0981da4SDimitry Andric if (Str[2] == '=')
387c0981da4SDimitry Andric return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
388c0981da4SDimitry Andric CStr);
389c0981da4SDimitry Andric
390c0981da4SDimitry Andric if (std::unique_ptr<Arg> A = Opt.accept(
391c0981da4SDimitry Andric Args, Str.substr(0, 2), /*GroupedShortOption=*/true, Index)) {
392b60736ecSDimitry Andric Args.replaceArgString(Index, Twine('-') + Str.substr(2));
393b60736ecSDimitry Andric return A;
394b60736ecSDimitry Andric }
395b60736ecSDimitry Andric }
396b60736ecSDimitry Andric
397c0981da4SDimitry Andric // In the case of an incorrect short option extract the character and move to
398c0981da4SDimitry Andric // the next one.
399c0981da4SDimitry Andric if (Str[1] != '-') {
400c0981da4SDimitry Andric CStr = Args.MakeArgString(Str.substr(0, 2));
401c0981da4SDimitry Andric Args.replaceArgString(Index, Twine('-') + Str.substr(2));
402c0981da4SDimitry Andric return std::make_unique<Arg>(getOption(UnknownOptionID), CStr, Index, CStr);
403b60736ecSDimitry Andric }
404b60736ecSDimitry Andric
405c0981da4SDimitry Andric return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++, CStr);
406c0981da4SDimitry Andric }
407c0981da4SDimitry Andric
ParseOneArg(const ArgList & Args,unsigned & Index,Visibility VisibilityMask) const408c0981da4SDimitry Andric std::unique_ptr<Arg> OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
409b1c73532SDimitry Andric Visibility VisibilityMask) const {
410b1c73532SDimitry Andric return internalParseOneArg(Args, Index, [VisibilityMask](const Option &Opt) {
411b1c73532SDimitry Andric return !Opt.hasVisibilityFlag(VisibilityMask);
412b1c73532SDimitry Andric });
413b1c73532SDimitry Andric }
414b1c73532SDimitry Andric
ParseOneArg(const ArgList & Args,unsigned & Index,unsigned FlagsToInclude,unsigned FlagsToExclude) const415b1c73532SDimitry Andric std::unique_ptr<Arg> OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
416f8af5cf6SDimitry Andric unsigned FlagsToInclude,
417f8af5cf6SDimitry Andric unsigned FlagsToExclude) const {
418b1c73532SDimitry Andric return internalParseOneArg(
419b1c73532SDimitry Andric Args, Index, [FlagsToInclude, FlagsToExclude](const Option &Opt) {
420b1c73532SDimitry Andric if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
421b1c73532SDimitry Andric return true;
422b1c73532SDimitry Andric if (Opt.hasFlag(FlagsToExclude))
423b1c73532SDimitry Andric return true;
424b1c73532SDimitry Andric return false;
425b1c73532SDimitry Andric });
426b1c73532SDimitry Andric }
427b1c73532SDimitry Andric
internalParseOneArg(const ArgList & Args,unsigned & Index,std::function<bool (const Option &)> ExcludeOption) const428b1c73532SDimitry Andric std::unique_ptr<Arg> OptTable::internalParseOneArg(
429b1c73532SDimitry Andric const ArgList &Args, unsigned &Index,
430b1c73532SDimitry Andric std::function<bool(const Option &)> ExcludeOption) const {
4314a16efa3SDimitry Andric unsigned Prev = Index;
432e3b55780SDimitry Andric StringRef Str = Args.getArgString(Index);
4334a16efa3SDimitry Andric
4344a16efa3SDimitry Andric // Anything that doesn't start with PrefixesUnion is an input, as is '-'
4354a16efa3SDimitry Andric // itself.
436e3b55780SDimitry Andric if (isInput(getPrefixesUnion(), Str))
437e3b55780SDimitry Andric return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++,
438e3b55780SDimitry Andric Str.data());
4394a16efa3SDimitry Andric
440044eb2f6SDimitry Andric const Info *Start = OptionInfos.data() + FirstSearchableIndex;
441044eb2f6SDimitry Andric const Info *End = OptionInfos.data() + OptionInfos.size();
442e3b55780SDimitry Andric StringRef Name = Str.ltrim(PrefixChars);
4434a16efa3SDimitry Andric
4444a16efa3SDimitry Andric // Search for the first next option which could be a prefix.
445e3b55780SDimitry Andric Start = std::lower_bound(Start, End, Name);
4464a16efa3SDimitry Andric
4474a16efa3SDimitry Andric // Options are stored in sorted order, with '\0' at the end of the
4484a16efa3SDimitry Andric // alphabet. Since the only options which can accept a string must
4494a16efa3SDimitry Andric // prefix it, we iteratively search for the next option which could
4504a16efa3SDimitry Andric // be a prefix.
4514a16efa3SDimitry Andric //
4524a16efa3SDimitry Andric // FIXME: This is searching much more than necessary, but I am
4534a16efa3SDimitry Andric // blanking on the simplest way to make it fast. We can solve this
4544a16efa3SDimitry Andric // problem when we move to TableGen.
4554a16efa3SDimitry Andric for (; Start != End; ++Start) {
4564a16efa3SDimitry Andric unsigned ArgSize = 0;
4574a16efa3SDimitry Andric // Scan for first option which is a proper prefix.
4584a16efa3SDimitry Andric for (; Start != End; ++Start)
459f8af5cf6SDimitry Andric if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
4604a16efa3SDimitry Andric break;
4614a16efa3SDimitry Andric if (Start == End)
4624a16efa3SDimitry Andric break;
4634a16efa3SDimitry Andric
464f8af5cf6SDimitry Andric Option Opt(Start, this);
465f8af5cf6SDimitry Andric
466b1c73532SDimitry Andric if (ExcludeOption(Opt))
467f8af5cf6SDimitry Andric continue;
468f8af5cf6SDimitry Andric
4694a16efa3SDimitry Andric // See if this option matches.
470c0981da4SDimitry Andric if (std::unique_ptr<Arg> A =
471c0981da4SDimitry Andric Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
472c0981da4SDimitry Andric /*GroupedShortOption=*/false, Index))
4734a16efa3SDimitry Andric return A;
4744a16efa3SDimitry Andric
4754a16efa3SDimitry Andric // Otherwise, see if this argument was missing values.
4764a16efa3SDimitry Andric if (Prev != Index)
4775ca98fd9SDimitry Andric return nullptr;
4784a16efa3SDimitry Andric }
4794a16efa3SDimitry Andric
480f8af5cf6SDimitry Andric // If we failed to find an option and this arg started with /, then it's
481f8af5cf6SDimitry Andric // probably an input path.
482f8af5cf6SDimitry Andric if (Str[0] == '/')
483e3b55780SDimitry Andric return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++,
484e3b55780SDimitry Andric Str.data());
485f8af5cf6SDimitry Andric
486e3b55780SDimitry Andric return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
487e3b55780SDimitry Andric Str.data());
4884a16efa3SDimitry Andric }
4894a16efa3SDimitry Andric
ParseArgs(ArrayRef<const char * > Args,unsigned & MissingArgIndex,unsigned & MissingArgCount,Visibility VisibilityMask) const490b1c73532SDimitry Andric InputArgList OptTable::ParseArgs(ArrayRef<const char *> Args,
491b1c73532SDimitry Andric unsigned &MissingArgIndex,
492b1c73532SDimitry Andric unsigned &MissingArgCount,
493b1c73532SDimitry Andric Visibility VisibilityMask) const {
494b1c73532SDimitry Andric return internalParseArgs(
495b1c73532SDimitry Andric Args, MissingArgIndex, MissingArgCount,
496b1c73532SDimitry Andric [VisibilityMask](const Option &Opt) {
497b1c73532SDimitry Andric return !Opt.hasVisibilityFlag(VisibilityMask);
498b1c73532SDimitry Andric });
499b1c73532SDimitry Andric }
500b1c73532SDimitry Andric
ParseArgs(ArrayRef<const char * > Args,unsigned & MissingArgIndex,unsigned & MissingArgCount,unsigned FlagsToInclude,unsigned FlagsToExclude) const501b1c73532SDimitry Andric InputArgList OptTable::ParseArgs(ArrayRef<const char *> Args,
5024a16efa3SDimitry Andric unsigned &MissingArgIndex,
503f8af5cf6SDimitry Andric unsigned &MissingArgCount,
504f8af5cf6SDimitry Andric unsigned FlagsToInclude,
505f8af5cf6SDimitry Andric unsigned FlagsToExclude) const {
506b1c73532SDimitry Andric return internalParseArgs(
507b1c73532SDimitry Andric Args, MissingArgIndex, MissingArgCount,
508b1c73532SDimitry Andric [FlagsToInclude, FlagsToExclude](const Option &Opt) {
509b1c73532SDimitry Andric if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
510b1c73532SDimitry Andric return true;
511b1c73532SDimitry Andric if (Opt.hasFlag(FlagsToExclude))
512b1c73532SDimitry Andric return true;
513b1c73532SDimitry Andric return false;
514b1c73532SDimitry Andric });
515b1c73532SDimitry Andric }
516b1c73532SDimitry Andric
internalParseArgs(ArrayRef<const char * > ArgArr,unsigned & MissingArgIndex,unsigned & MissingArgCount,std::function<bool (const Option &)> ExcludeOption) const517b1c73532SDimitry Andric InputArgList OptTable::internalParseArgs(
518b1c73532SDimitry Andric ArrayRef<const char *> ArgArr, unsigned &MissingArgIndex,
519b1c73532SDimitry Andric unsigned &MissingArgCount,
520b1c73532SDimitry Andric std::function<bool(const Option &)> ExcludeOption) const {
5211a82d4c0SDimitry Andric InputArgList Args(ArgArr.begin(), ArgArr.end());
5224a16efa3SDimitry Andric
5234a16efa3SDimitry Andric // FIXME: Handle '@' args (or at least error on them).
5244a16efa3SDimitry Andric
5254a16efa3SDimitry Andric MissingArgIndex = MissingArgCount = 0;
5261a82d4c0SDimitry Andric unsigned Index = 0, End = ArgArr.size();
5274a16efa3SDimitry Andric while (Index < End) {
52867c32a98SDimitry Andric // Ingore nullptrs, they are response file's EOL markers
5291a82d4c0SDimitry Andric if (Args.getArgString(Index) == nullptr) {
53067c32a98SDimitry Andric ++Index;
53167c32a98SDimitry Andric continue;
53267c32a98SDimitry Andric }
5334a16efa3SDimitry Andric // Ignore empty arguments (other things may still take them as arguments).
5341a82d4c0SDimitry Andric StringRef Str = Args.getArgString(Index);
535f8af5cf6SDimitry Andric if (Str == "") {
5364a16efa3SDimitry Andric ++Index;
5374a16efa3SDimitry Andric continue;
5384a16efa3SDimitry Andric }
5394a16efa3SDimitry Andric
5407fa27ce4SDimitry Andric // In DashDashParsing mode, the first "--" stops option scanning and treats
5417fa27ce4SDimitry Andric // all subsequent arguments as positional.
5427fa27ce4SDimitry Andric if (DashDashParsing && Str == "--") {
5437fa27ce4SDimitry Andric while (++Index < End) {
5447fa27ce4SDimitry Andric Args.append(new Arg(getOption(InputOptionID), Str, Index,
5457fa27ce4SDimitry Andric Args.getArgString(Index)));
5467fa27ce4SDimitry Andric }
5477fa27ce4SDimitry Andric break;
5487fa27ce4SDimitry Andric }
5497fa27ce4SDimitry Andric
5504a16efa3SDimitry Andric unsigned Prev = Index;
551c0981da4SDimitry Andric std::unique_ptr<Arg> A = GroupedShortOptions
552b60736ecSDimitry Andric ? parseOneArgGrouped(Args, Index)
553b1c73532SDimitry Andric : internalParseOneArg(Args, Index, ExcludeOption);
554b60736ecSDimitry Andric assert((Index > Prev || GroupedShortOptions) &&
555b60736ecSDimitry Andric "Parser failed to consume argument.");
5564a16efa3SDimitry Andric
5574a16efa3SDimitry Andric // Check for missing argument error.
5584a16efa3SDimitry Andric if (!A) {
5594a16efa3SDimitry Andric assert(Index >= End && "Unexpected parser error.");
5604a16efa3SDimitry Andric assert(Index - Prev - 1 && "No missing arguments!");
5614a16efa3SDimitry Andric MissingArgIndex = Prev;
5624a16efa3SDimitry Andric MissingArgCount = Index - Prev - 1;
5634a16efa3SDimitry Andric break;
5644a16efa3SDimitry Andric }
5654a16efa3SDimitry Andric
566c0981da4SDimitry Andric Args.append(A.release());
5674a16efa3SDimitry Andric }
5684a16efa3SDimitry Andric
5694a16efa3SDimitry Andric return Args;
5704a16efa3SDimitry Andric }
5714a16efa3SDimitry Andric
parseArgs(int Argc,char * const * Argv,OptSpecifier Unknown,StringSaver & Saver,std::function<void (StringRef)> ErrorFn) const572b60736ecSDimitry Andric InputArgList OptTable::parseArgs(int Argc, char *const *Argv,
573b60736ecSDimitry Andric OptSpecifier Unknown, StringSaver &Saver,
574b1c73532SDimitry Andric std::function<void(StringRef)> ErrorFn) const {
575b60736ecSDimitry Andric SmallVector<const char *, 0> NewArgv;
576b60736ecSDimitry Andric // The environment variable specifies initial options which can be overridden
577b60736ecSDimitry Andric // by commnad line options.
578b60736ecSDimitry Andric cl::expandResponseFiles(Argc, Argv, EnvVar, Saver, NewArgv);
579b60736ecSDimitry Andric
580b60736ecSDimitry Andric unsigned MAI, MAC;
581e3b55780SDimitry Andric opt::InputArgList Args = ParseArgs(ArrayRef(NewArgv), MAI, MAC);
582b60736ecSDimitry Andric if (MAC)
583b60736ecSDimitry Andric ErrorFn((Twine(Args.getArgString(MAI)) + ": missing argument").str());
584b60736ecSDimitry Andric
585b60736ecSDimitry Andric // For each unknwon option, call ErrorFn with a formatted error message. The
586b60736ecSDimitry Andric // message includes a suggested alternative option spelling if available.
587b60736ecSDimitry Andric std::string Nearest;
588b60736ecSDimitry Andric for (const opt::Arg *A : Args.filtered(Unknown)) {
589b60736ecSDimitry Andric std::string Spelling = A->getAsString(Args);
590b60736ecSDimitry Andric if (findNearest(Spelling, Nearest) > 1)
591e3b55780SDimitry Andric ErrorFn("unknown argument '" + Spelling + "'");
592b60736ecSDimitry Andric else
593e3b55780SDimitry Andric ErrorFn("unknown argument '" + Spelling + "', did you mean '" + Nearest +
594e3b55780SDimitry Andric "'?");
595b60736ecSDimitry Andric }
596b60736ecSDimitry Andric return Args;
597b60736ecSDimitry Andric }
598b60736ecSDimitry Andric
getOptionHelpName(const OptTable & Opts,OptSpecifier Id)5994a16efa3SDimitry Andric static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
6004a16efa3SDimitry Andric const Option O = Opts.getOption(Id);
601b1c73532SDimitry Andric std::string Name = O.getPrefixedName().str();
6024a16efa3SDimitry Andric
6034a16efa3SDimitry Andric // Add metavar, if used.
6044a16efa3SDimitry Andric switch (O.getKind()) {
6054a16efa3SDimitry Andric case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
6064a16efa3SDimitry Andric llvm_unreachable("Invalid option with help text.");
6074a16efa3SDimitry Andric
6084a16efa3SDimitry Andric case Option::MultiArgClass:
60967c32a98SDimitry Andric if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
61067c32a98SDimitry Andric // For MultiArgs, metavar is full list of all argument names.
61167c32a98SDimitry Andric Name += ' ';
61267c32a98SDimitry Andric Name += MetaVarName;
61367c32a98SDimitry Andric }
61467c32a98SDimitry Andric else {
61567c32a98SDimitry Andric // For MultiArgs<N>, if metavar not supplied, print <value> N times.
61667c32a98SDimitry Andric for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
61767c32a98SDimitry Andric Name += " <value>";
61867c32a98SDimitry Andric }
61967c32a98SDimitry Andric }
62067c32a98SDimitry Andric break;
6214a16efa3SDimitry Andric
6224a16efa3SDimitry Andric case Option::FlagClass:
6234a16efa3SDimitry Andric break;
6244a16efa3SDimitry Andric
62508bbd35aSDimitry Andric case Option::ValuesClass:
62608bbd35aSDimitry Andric break;
62708bbd35aSDimitry Andric
6284a16efa3SDimitry Andric case Option::SeparateClass: case Option::JoinedOrSeparateClass:
62901095a5dSDimitry Andric case Option::RemainingArgsClass: case Option::RemainingArgsJoinedClass:
6304a16efa3SDimitry Andric Name += ' ';
631e3b55780SDimitry Andric [[fallthrough]];
6324a16efa3SDimitry Andric case Option::JoinedClass: case Option::CommaJoinedClass:
6334a16efa3SDimitry Andric case Option::JoinedAndSeparateClass:
6344a16efa3SDimitry Andric if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
6354a16efa3SDimitry Andric Name += MetaVarName;
6364a16efa3SDimitry Andric else
6374a16efa3SDimitry Andric Name += "<value>";
6384a16efa3SDimitry Andric break;
6394a16efa3SDimitry Andric }
6404a16efa3SDimitry Andric
6414a16efa3SDimitry Andric return Name;
6424a16efa3SDimitry Andric }
6434a16efa3SDimitry Andric
64493c91e39SDimitry Andric namespace {
64593c91e39SDimitry Andric struct OptionInfo {
64693c91e39SDimitry Andric std::string Name;
64793c91e39SDimitry Andric StringRef HelpText;
64893c91e39SDimitry Andric };
64993c91e39SDimitry Andric } // namespace
65093c91e39SDimitry Andric
PrintHelpOptionList(raw_ostream & OS,StringRef Title,std::vector<OptionInfo> & OptionHelp)6514a16efa3SDimitry Andric static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
65293c91e39SDimitry Andric std::vector<OptionInfo> &OptionHelp) {
6534a16efa3SDimitry Andric OS << Title << ":\n";
6544a16efa3SDimitry Andric
6554a16efa3SDimitry Andric // Find the maximum option length.
6564a16efa3SDimitry Andric unsigned OptionFieldWidth = 0;
65777fc4c14SDimitry Andric for (const OptionInfo &Opt : OptionHelp) {
6584a16efa3SDimitry Andric // Limit the amount of padding we are willing to give up for alignment.
65977fc4c14SDimitry Andric unsigned Length = Opt.Name.size();
6604a16efa3SDimitry Andric if (Length <= 23)
6614a16efa3SDimitry Andric OptionFieldWidth = std::max(OptionFieldWidth, Length);
6624a16efa3SDimitry Andric }
6634a16efa3SDimitry Andric
6644a16efa3SDimitry Andric const unsigned InitialPad = 2;
66577fc4c14SDimitry Andric for (const OptionInfo &Opt : OptionHelp) {
66677fc4c14SDimitry Andric const std::string &Option = Opt.Name;
667312c0ed1SDimitry Andric int Pad = OptionFieldWidth + InitialPad;
668312c0ed1SDimitry Andric int FirstLinePad = OptionFieldWidth - int(Option.size());
6694a16efa3SDimitry Andric OS.indent(InitialPad) << Option;
6704a16efa3SDimitry Andric
6714a16efa3SDimitry Andric // Break on long option names.
672312c0ed1SDimitry Andric if (FirstLinePad < 0) {
6734a16efa3SDimitry Andric OS << "\n";
674312c0ed1SDimitry Andric FirstLinePad = OptionFieldWidth + InitialPad;
675312c0ed1SDimitry Andric Pad = FirstLinePad;
6764a16efa3SDimitry Andric }
677312c0ed1SDimitry Andric
678312c0ed1SDimitry Andric SmallVector<StringRef> Lines;
679312c0ed1SDimitry Andric Opt.HelpText.split(Lines, '\n');
680312c0ed1SDimitry Andric assert(Lines.size() && "Expected at least the first line in the help text");
681312c0ed1SDimitry Andric auto *LinesIt = Lines.begin();
682312c0ed1SDimitry Andric OS.indent(FirstLinePad + 1) << *LinesIt << '\n';
683312c0ed1SDimitry Andric while (Lines.end() != ++LinesIt)
684312c0ed1SDimitry Andric OS.indent(Pad + 1) << *LinesIt << '\n';
6854a16efa3SDimitry Andric }
6864a16efa3SDimitry Andric }
6874a16efa3SDimitry Andric
getOptionHelpGroup(const OptTable & Opts,OptSpecifier Id)6884a16efa3SDimitry Andric static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
6894a16efa3SDimitry Andric unsigned GroupID = Opts.getOptionGroupID(Id);
6904a16efa3SDimitry Andric
6914a16efa3SDimitry Andric // If not in a group, return the default help group.
6924a16efa3SDimitry Andric if (!GroupID)
6934a16efa3SDimitry Andric return "OPTIONS";
6944a16efa3SDimitry Andric
6954a16efa3SDimitry Andric // Abuse the help text of the option groups to store the "help group"
6964a16efa3SDimitry Andric // name.
6974a16efa3SDimitry Andric //
6984a16efa3SDimitry Andric // FIXME: Split out option groups.
6994a16efa3SDimitry Andric if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
7004a16efa3SDimitry Andric return GroupHelp;
7014a16efa3SDimitry Andric
7024a16efa3SDimitry Andric // Otherwise keep looking.
7034a16efa3SDimitry Andric return getOptionHelpGroup(Opts, GroupID);
7044a16efa3SDimitry Andric }
7054a16efa3SDimitry Andric
printHelp(raw_ostream & OS,const char * Usage,const char * Title,bool ShowHidden,bool ShowAllAliases,Visibility VisibilityMask) const706344a3780SDimitry Andric void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
707b1c73532SDimitry Andric bool ShowHidden, bool ShowAllAliases,
708b1c73532SDimitry Andric Visibility VisibilityMask) const {
709b1c73532SDimitry Andric return internalPrintHelp(
710b1c73532SDimitry Andric OS, Usage, Title, ShowHidden, ShowAllAliases,
711b1c73532SDimitry Andric [VisibilityMask](const Info &CandidateInfo) -> bool {
712b1c73532SDimitry Andric return (CandidateInfo.Visibility & VisibilityMask) == 0;
713ac9a064cSDimitry Andric },
714ac9a064cSDimitry Andric VisibilityMask);
715f8af5cf6SDimitry Andric }
716f8af5cf6SDimitry Andric
printHelp(raw_ostream & OS,const char * Usage,const char * Title,unsigned FlagsToInclude,unsigned FlagsToExclude,bool ShowAllAliases) const717344a3780SDimitry Andric void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
718044eb2f6SDimitry Andric unsigned FlagsToInclude, unsigned FlagsToExclude,
719044eb2f6SDimitry Andric bool ShowAllAliases) const {
720b1c73532SDimitry Andric bool ShowHidden = !(FlagsToExclude & HelpHidden);
721b1c73532SDimitry Andric FlagsToExclude &= ~HelpHidden;
722b1c73532SDimitry Andric return internalPrintHelp(
723b1c73532SDimitry Andric OS, Usage, Title, ShowHidden, ShowAllAliases,
724b1c73532SDimitry Andric [FlagsToInclude, FlagsToExclude](const Info &CandidateInfo) {
725b1c73532SDimitry Andric if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
726b1c73532SDimitry Andric return true;
727b1c73532SDimitry Andric if (CandidateInfo.Flags & FlagsToExclude)
728b1c73532SDimitry Andric return true;
729b1c73532SDimitry Andric return false;
730ac9a064cSDimitry Andric },
731ac9a064cSDimitry Andric Visibility(0));
732b1c73532SDimitry Andric }
733b1c73532SDimitry Andric
internalPrintHelp(raw_ostream & OS,const char * Usage,const char * Title,bool ShowHidden,bool ShowAllAliases,std::function<bool (const Info &)> ExcludeOption,Visibility VisibilityMask) const734b1c73532SDimitry Andric void OptTable::internalPrintHelp(
735b1c73532SDimitry Andric raw_ostream &OS, const char *Usage, const char *Title, bool ShowHidden,
736ac9a064cSDimitry Andric bool ShowAllAliases, std::function<bool(const Info &)> ExcludeOption,
737ac9a064cSDimitry Andric Visibility VisibilityMask) const {
738d8e91e46SDimitry Andric OS << "OVERVIEW: " << Title << "\n\n";
739d8e91e46SDimitry Andric OS << "USAGE: " << Usage << "\n\n";
7404a16efa3SDimitry Andric
7414a16efa3SDimitry Andric // Render help text into a map of group-name to a list of (option, help)
7424a16efa3SDimitry Andric // pairs.
743eb11fae6SDimitry Andric std::map<std::string, std::vector<OptionInfo>> GroupedOptionHelp;
7444a16efa3SDimitry Andric
745eb11fae6SDimitry Andric for (unsigned Id = 1, e = getNumOptions() + 1; Id != e; ++Id) {
7464a16efa3SDimitry Andric // FIXME: Split out option groups.
7474a16efa3SDimitry Andric if (getOptionKind(Id) == Option::GroupClass)
7484a16efa3SDimitry Andric continue;
7494a16efa3SDimitry Andric
750b1c73532SDimitry Andric const Info &CandidateInfo = getInfo(Id);
751b1c73532SDimitry Andric if (!ShowHidden && (CandidateInfo.Flags & opt::HelpHidden))
752f8af5cf6SDimitry Andric continue;
753b1c73532SDimitry Andric
754b1c73532SDimitry Andric if (ExcludeOption(CandidateInfo))
7554a16efa3SDimitry Andric continue;
7564a16efa3SDimitry Andric
757044eb2f6SDimitry Andric // If an alias doesn't have a help text, show a help text for the aliased
758044eb2f6SDimitry Andric // option instead.
759ac9a064cSDimitry Andric const char *HelpText = getOptionHelpText(Id, VisibilityMask);
760044eb2f6SDimitry Andric if (!HelpText && ShowAllAliases) {
761044eb2f6SDimitry Andric const Option Alias = getOption(Id).getAlias();
762044eb2f6SDimitry Andric if (Alias.isValid())
763ac9a064cSDimitry Andric HelpText = getOptionHelpText(Alias.getID(), VisibilityMask);
764044eb2f6SDimitry Andric }
765044eb2f6SDimitry Andric
766c0981da4SDimitry Andric if (HelpText && (strlen(HelpText) != 0)) {
7674a16efa3SDimitry Andric const char *HelpGroup = getOptionHelpGroup(*this, Id);
7684a16efa3SDimitry Andric const std::string &OptName = getOptionHelpName(*this, Id);
769044eb2f6SDimitry Andric GroupedOptionHelp[HelpGroup].push_back({OptName, HelpText});
7704a16efa3SDimitry Andric }
7714a16efa3SDimitry Andric }
7724a16efa3SDimitry Andric
773eb11fae6SDimitry Andric for (auto& OptionGroup : GroupedOptionHelp) {
774eb11fae6SDimitry Andric if (OptionGroup.first != GroupedOptionHelp.begin()->first)
7754a16efa3SDimitry Andric OS << "\n";
776eb11fae6SDimitry Andric PrintHelpOptionList(OS, OptionGroup.first, OptionGroup.second);
7774a16efa3SDimitry Andric }
7784a16efa3SDimitry Andric
7794a16efa3SDimitry Andric OS.flush();
7804a16efa3SDimitry Andric }
781e3b55780SDimitry Andric
GenericOptTable(ArrayRef<Info> OptionInfos,bool IgnoreCase)782e3b55780SDimitry Andric GenericOptTable::GenericOptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase)
783e3b55780SDimitry Andric : OptTable(OptionInfos, IgnoreCase) {
784e3b55780SDimitry Andric
785e3b55780SDimitry Andric std::set<StringLiteral> TmpPrefixesUnion;
786e3b55780SDimitry Andric for (auto const &Info : OptionInfos.drop_front(FirstSearchableIndex))
787e3b55780SDimitry Andric TmpPrefixesUnion.insert(Info.Prefixes.begin(), Info.Prefixes.end());
788e3b55780SDimitry Andric PrefixesUnionBuffer.append(TmpPrefixesUnion.begin(), TmpPrefixesUnion.end());
789e3b55780SDimitry Andric buildPrefixChars();
790e3b55780SDimitry Andric }
791