1 //===--- OptTable.cpp - Option Table Implementation -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Option/OptTable.h"
11 #include "llvm/Option/Arg.h"
12 #include "llvm/Option/ArgList.h"
13 #include "llvm/Option/Option.h"
14 #include "llvm/Support/ErrorHandling.h"
15 #include "llvm/Support/raw_ostream.h"
21 using namespace llvm::opt;
26 // Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
27 // with an exceptions. '\0' comes at the end of the alphabet instead of the
28 // beginning (thus options precede any other options which prefix them).
29 static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) {
30 const char *X = A, *Y = B;
31 char a = tolower(*A), b = tolower(*B);
40 if (a == '\0') // A is a prefix of B.
42 if (b == '\0') // B is a prefix of A.
45 // Otherwise lexicographic.
46 return (a < b) ? -1 : 1;
50 static int StrCmpOptionName(const char *A, const char *B) {
51 if (int N = StrCmpOptionNameIgnoreCase(A, B))
56 static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
60 if (int N = StrCmpOptionName(A.Name, B.Name))
63 for (const char * const *APre = A.Prefixes,
64 * const *BPre = B.Prefixes;
65 *APre != nullptr && *BPre != nullptr; ++APre, ++BPre){
66 if (int N = StrCmpOptionName(*APre, *BPre))
70 // Names are the same, check that classes are in order; exactly one
71 // should be joined, and it should succeed the other.
72 assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
73 "Unexpected classes for options with same name.");
74 return B.Kind == Option::JoinedClass;
78 // Support lower_bound between info and an option name.
79 static inline bool operator<(const OptTable::Info &I, const char *Name) {
80 return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
85 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
87 OptTable::OptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase)
88 : OptionInfos(OptionInfos), IgnoreCase(IgnoreCase), TheInputOptionID(0),
89 TheUnknownOptionID(0), FirstSearchableIndex(0) {
90 // Explicitly zero initialize the error to work around a bug in array
91 // value-initialization on MinGW with gcc 4.3.5.
93 // Find start of normal options.
94 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
95 unsigned Kind = getInfo(i + 1).Kind;
96 if (Kind == Option::InputClass) {
97 assert(!TheInputOptionID && "Cannot have multiple input options!");
98 TheInputOptionID = getInfo(i + 1).ID;
99 } else if (Kind == Option::UnknownClass) {
100 assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
101 TheUnknownOptionID = getInfo(i + 1).ID;
102 } else if (Kind != Option::GroupClass) {
103 FirstSearchableIndex = i;
107 assert(FirstSearchableIndex != 0 && "No searchable options?");
110 // Check that everything after the first searchable option is a
111 // regular option class.
112 for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
113 Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
114 assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
115 Kind != Option::GroupClass) &&
116 "Special options should be defined first!");
119 // Check that options are in order.
120 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
121 if (!(getInfo(i) < getInfo(i + 1))) {
123 getOption(i + 1).dump();
124 llvm_unreachable("Options are not in order!");
130 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
132 if (const char *const *P = getInfo(i).Prefixes) {
133 for (; *P != nullptr; ++P) {
134 PrefixesUnion.insert(*P);
139 // Build prefix chars.
140 for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(),
141 E = PrefixesUnion.end(); I != E; ++I) {
142 StringRef Prefix = I->getKey();
143 for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
145 if (std::find(PrefixChars.begin(), PrefixChars.end(), *C)
146 == PrefixChars.end())
147 PrefixChars.push_back(*C);
151 OptTable::~OptTable() {
154 const Option OptTable::getOption(OptSpecifier Opt) const {
155 unsigned id = Opt.getID();
157 return Option(nullptr, nullptr);
158 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
159 return Option(&getInfo(id), this);
162 static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
165 for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
166 E = Prefixes.end(); I != E; ++I)
167 if (Arg.startswith(I->getKey()))
172 /// \returns Matched size. 0 means no match.
173 static unsigned matchOption(const OptTable::Info *I, StringRef Str,
175 for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) {
176 StringRef Prefix(*Pre);
177 if (Str.startswith(Prefix)) {
178 StringRef Rest = Str.substr(Prefix.size());
179 bool Matched = IgnoreCase
180 ? Rest.startswith_lower(I->Name)
181 : Rest.startswith(I->Name);
183 return Prefix.size() + StringRef(I->Name).size();
189 Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
190 unsigned FlagsToInclude,
191 unsigned FlagsToExclude) const {
192 unsigned Prev = Index;
193 const char *Str = Args.getArgString(Index);
195 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
197 if (isInput(PrefixesUnion, Str))
198 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
200 const Info *Start = OptionInfos.begin() + FirstSearchableIndex;
201 const Info *End = OptionInfos.end();
202 StringRef Name = StringRef(Str).ltrim(PrefixChars);
204 // Search for the first next option which could be a prefix.
205 Start = std::lower_bound(Start, End, Name.data());
207 // Options are stored in sorted order, with '\0' at the end of the
208 // alphabet. Since the only options which can accept a string must
209 // prefix it, we iteratively search for the next option which could
212 // FIXME: This is searching much more than necessary, but I am
213 // blanking on the simplest way to make it fast. We can solve this
214 // problem when we move to TableGen.
215 for (; Start != End; ++Start) {
216 unsigned ArgSize = 0;
217 // Scan for first option which is a proper prefix.
218 for (; Start != End; ++Start)
219 if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
224 Option Opt(Start, this);
226 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
228 if (Opt.hasFlag(FlagsToExclude))
231 // See if this option matches.
232 if (Arg *A = Opt.accept(Args, Index, ArgSize))
235 // Otherwise, see if this argument was missing values.
240 // If we failed to find an option and this arg started with /, then it's
241 // probably an input path.
243 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
245 return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
248 InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr,
249 unsigned &MissingArgIndex,
250 unsigned &MissingArgCount,
251 unsigned FlagsToInclude,
252 unsigned FlagsToExclude) const {
253 InputArgList Args(ArgArr.begin(), ArgArr.end());
255 // FIXME: Handle '@' args (or at least error on them).
257 MissingArgIndex = MissingArgCount = 0;
258 unsigned Index = 0, End = ArgArr.size();
259 while (Index < End) {
260 // Ingore nullptrs, they are response file's EOL markers
261 if (Args.getArgString(Index) == nullptr) {
265 // Ignore empty arguments (other things may still take them as arguments).
266 StringRef Str = Args.getArgString(Index);
272 unsigned Prev = Index;
273 Arg *A = ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
274 assert(Index > Prev && "Parser failed to consume argument.");
276 // Check for missing argument error.
278 assert(Index >= End && "Unexpected parser error.");
279 assert(Index - Prev - 1 && "No missing arguments!");
280 MissingArgIndex = Prev;
281 MissingArgCount = Index - Prev - 1;
291 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
292 const Option O = Opts.getOption(Id);
293 std::string Name = O.getPrefixedName();
295 // Add metavar, if used.
296 switch (O.getKind()) {
297 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
298 llvm_unreachable("Invalid option with help text.");
300 case Option::MultiArgClass:
301 if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
302 // For MultiArgs, metavar is full list of all argument names.
307 // For MultiArgs<N>, if metavar not supplied, print <value> N times.
308 for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
314 case Option::FlagClass:
317 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
318 case Option::RemainingArgsClass:
321 case Option::JoinedClass: case Option::CommaJoinedClass:
322 case Option::JoinedAndSeparateClass:
323 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
333 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
334 std::vector<std::pair<std::string,
335 const char*> > &OptionHelp) {
336 OS << Title << ":\n";
338 // Find the maximum option length.
339 unsigned OptionFieldWidth = 0;
340 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
342 if (!OptionHelp[i].second)
345 // Limit the amount of padding we are willing to give up for alignment.
346 unsigned Length = OptionHelp[i].first.size();
348 OptionFieldWidth = std::max(OptionFieldWidth, Length);
351 const unsigned InitialPad = 2;
352 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
353 const std::string &Option = OptionHelp[i].first;
354 int Pad = OptionFieldWidth - int(Option.size());
355 OS.indent(InitialPad) << Option;
357 // Break on long option names.
360 Pad = OptionFieldWidth + InitialPad;
362 OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
366 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
367 unsigned GroupID = Opts.getOptionGroupID(Id);
369 // If not in a group, return the default help group.
373 // Abuse the help text of the option groups to store the "help group"
376 // FIXME: Split out option groups.
377 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
380 // Otherwise keep looking.
381 return getOptionHelpGroup(Opts, GroupID);
384 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
385 bool ShowHidden) const {
386 PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
387 (ShowHidden ? 0 : HelpHidden));
391 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
392 unsigned FlagsToInclude,
393 unsigned FlagsToExclude) const {
394 OS << "OVERVIEW: " << Title << "\n";
396 OS << "USAGE: " << Name << " [options] <inputs>\n";
399 // Render help text into a map of group-name to a list of (option, help)
401 typedef std::map<std::string,
402 std::vector<std::pair<std::string, const char*> > > helpmap_ty;
403 helpmap_ty GroupedOptionHelp;
405 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
408 // FIXME: Split out option groups.
409 if (getOptionKind(Id) == Option::GroupClass)
412 unsigned Flags = getInfo(Id).Flags;
413 if (FlagsToInclude && !(Flags & FlagsToInclude))
415 if (Flags & FlagsToExclude)
418 if (const char *Text = getOptionHelpText(Id)) {
419 const char *HelpGroup = getOptionHelpGroup(*this, Id);
420 const std::string &OptName = getOptionHelpName(*this, Id);
421 GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
425 for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
426 ie = GroupedOptionHelp.end(); it != ie; ++it) {
427 if (it != GroupedOptionHelp .begin())
429 PrintHelpOptionList(OS, it->first, it->second);