blob: b00d21ec8f6719bdaf5f657fe122f6a7a07d7fbe [file] [log] [blame]
Michael J. Spencer41ee0412012-12-05 00:29:32 +00001//===--- OptTable.cpp - Option Table Implementation -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Option/OptTable.h"
David Majnemer0d955d02016-08-11 22:21:41 +000011#include "llvm/ADT/STLExtras.h"
Michael J. Spencer41ee0412012-12-05 00:29:32 +000012#include "llvm/Option/Arg.h"
13#include "llvm/Option/ArgList.h"
14#include "llvm/Option/Option.h"
Michael J. Spencer41ee0412012-12-05 00:29:32 +000015#include "llvm/Support/ErrorHandling.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000016#include "llvm/Support/raw_ostream.h"
Michael J. Spencer41ee0412012-12-05 00:29:32 +000017#include <algorithm>
Rui Ueyama8fb5a912013-08-28 20:04:31 +000018#include <cctype>
Michael J. Spencer41ee0412012-12-05 00:29:32 +000019#include <map>
20
21using namespace llvm;
22using namespace llvm::opt;
23
Rui Ueyama8fb5a912013-08-28 20:04:31 +000024namespace llvm {
25namespace opt {
Rui Ueyama7159bd92013-08-27 23:47:01 +000026
Rui Ueyama8fb5a912013-08-28 20:04:31 +000027// Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
28// with an exceptions. '\0' comes at the end of the alphabet instead of the
29// beginning (thus options precede any other options which prefix them).
30static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) {
31 const char *X = A, *Y = B;
32 char a = tolower(*A), b = tolower(*B);
Rui Ueyamac3779ff2013-08-28 00:02:06 +000033 while (a == b) {
34 if (a == '\0')
35 return 0;
36
Rui Ueyama8fb5a912013-08-28 20:04:31 +000037 a = tolower(*++X);
38 b = tolower(*++Y);
Rui Ueyamac3779ff2013-08-28 00:02:06 +000039 }
40
41 if (a == '\0') // A is a prefix of B.
42 return 1;
43 if (b == '\0') // B is a prefix of A.
44 return -1;
45
46 // Otherwise lexicographic.
47 return (a < b) ? -1 : 1;
Rui Ueyama7159bd92013-08-27 23:47:01 +000048}
49
Eli Friedman3e7dca62013-09-10 23:22:56 +000050#ifndef NDEBUG
51static int StrCmpOptionName(const char *A, const char *B) {
52 if (int N = StrCmpOptionNameIgnoreCase(A, B))
53 return N;
54 return strcmp(A, B);
55}
56
57static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
58 if (&A == &B)
59 return false;
60
61 if (int N = StrCmpOptionName(A.Name, B.Name))
62 return N < 0;
63
64 for (const char * const *APre = A.Prefixes,
65 * const *BPre = B.Prefixes;
Craig Topper2617dcc2014-04-15 06:32:26 +000066 *APre != nullptr && *BPre != nullptr; ++APre, ++BPre){
Eli Friedman3e7dca62013-09-10 23:22:56 +000067 if (int N = StrCmpOptionName(*APre, *BPre))
68 return N < 0;
69 }
70
71 // Names are the same, check that classes are in order; exactly one
72 // should be joined, and it should succeed the other.
73 assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
74 "Unexpected classes for options with same name.");
75 return B.Kind == Option::JoinedClass;
76}
77#endif
78
Michael J. Spencer41ee0412012-12-05 00:29:32 +000079// Support lower_bound between info and an option name.
80static inline bool operator<(const OptTable::Info &I, const char *Name) {
Rui Ueyama8fb5a912013-08-28 20:04:31 +000081 return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
Michael J. Spencer41ee0412012-12-05 00:29:32 +000082}
Alexander Kornienkof00654e2015-06-23 09:49:53 +000083}
84}
Michael J. Spencer41ee0412012-12-05 00:29:32 +000085
86OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
87
Craig Topper8ea23902015-10-21 16:30:42 +000088OptTable::OptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase)
89 : OptionInfos(OptionInfos), IgnoreCase(IgnoreCase), TheInputOptionID(0),
90 TheUnknownOptionID(0), FirstSearchableIndex(0) {
Michael J. Spencer41ee0412012-12-05 00:29:32 +000091 // Explicitly zero initialize the error to work around a bug in array
92 // value-initialization on MinGW with gcc 4.3.5.
93
94 // Find start of normal options.
95 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
96 unsigned Kind = getInfo(i + 1).Kind;
97 if (Kind == Option::InputClass) {
98 assert(!TheInputOptionID && "Cannot have multiple input options!");
99 TheInputOptionID = getInfo(i + 1).ID;
100 } else if (Kind == Option::UnknownClass) {
101 assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
102 TheUnknownOptionID = getInfo(i + 1).ID;
103 } else if (Kind != Option::GroupClass) {
104 FirstSearchableIndex = i;
105 break;
106 }
107 }
108 assert(FirstSearchableIndex != 0 && "No searchable options?");
109
110#ifndef NDEBUG
111 // Check that everything after the first searchable option is a
112 // regular option class.
113 for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
114 Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
115 assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
116 Kind != Option::GroupClass) &&
117 "Special options should be defined first!");
118 }
119
120 // Check that options are in order.
121 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
122 if (!(getInfo(i) < getInfo(i + 1))) {
123 getOption(i).dump();
124 getOption(i + 1).dump();
125 llvm_unreachable("Options are not in order!");
126 }
127 }
128#endif
129
130 // Build prefixes.
131 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
132 i != e; ++i) {
133 if (const char *const *P = getInfo(i).Prefixes) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000134 for (; *P != nullptr; ++P) {
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000135 PrefixesUnion.insert(*P);
136 }
137 }
138 }
139
140 // Build prefix chars.
141 for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(),
142 E = PrefixesUnion.end(); I != E; ++I) {
143 StringRef Prefix = I->getKey();
144 for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
145 C != CE; ++C)
David Majnemer0d955d02016-08-11 22:21:41 +0000146 if (!is_contained(PrefixChars, *C))
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000147 PrefixChars.push_back(*C);
148 }
149}
150
151OptTable::~OptTable() {
152}
153
154const Option OptTable::getOption(OptSpecifier Opt) const {
155 unsigned id = Opt.getID();
156 if (id == 0)
Craig Topper2617dcc2014-04-15 06:32:26 +0000157 return Option(nullptr, nullptr);
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000158 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
159 return Option(&getInfo(id), this);
160}
161
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000162static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
163 if (Arg == "-")
164 return true;
165 for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
166 E = Prefixes.end(); I != E; ++I)
167 if (Arg.startswith(I->getKey()))
168 return false;
169 return true;
170}
171
172/// \returns Matched size. 0 means no match.
Rui Ueyama8fb5a912013-08-28 20:04:31 +0000173static unsigned matchOption(const OptTable::Info *I, StringRef Str,
174 bool IgnoreCase) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000175 for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) {
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000176 StringRef Prefix(*Pre);
Rui Ueyama8fb5a912013-08-28 20:04:31 +0000177 if (Str.startswith(Prefix)) {
178 StringRef Rest = Str.substr(Prefix.size());
179 bool Matched = IgnoreCase
Jakub Staszakcfcfee02013-11-04 19:22:50 +0000180 ? Rest.startswith_lower(I->Name)
Rui Ueyama8fb5a912013-08-28 20:04:31 +0000181 : Rest.startswith(I->Name);
182 if (Matched)
183 return Prefix.size() + StringRef(I->Name).size();
184 }
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000185 }
186 return 0;
187}
188
Yuka Takahashic8068db2017-05-23 18:39:08 +0000189std::vector<std::string> OptTable::findByPrefix(StringRef Cur) const {
190 std::vector<std::string> Ret;
191 for (const Info &In : OptionInfos.slice(FirstSearchableIndex)) {
192 if (!In.Prefixes)
193 continue;
194 for (int I = 0; In.Prefixes[I]; I++) {
195 std::string S = std::string(In.Prefixes[I]) + std::string(In.Name);
196 if (StringRef(S).startswith(Cur))
197 Ret.push_back(S);
198 }
199 }
200 return Ret;
201}
202
Reid Klecknereadb7652013-07-19 18:04:57 +0000203Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
204 unsigned FlagsToInclude,
205 unsigned FlagsToExclude) const {
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000206 unsigned Prev = Index;
207 const char *Str = Args.getArgString(Index);
208
209 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
210 // itself.
211 if (isInput(PrefixesUnion, Str))
212 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
213
Craig Topper8ea23902015-10-21 16:30:42 +0000214 const Info *Start = OptionInfos.begin() + FirstSearchableIndex;
215 const Info *End = OptionInfos.end();
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000216 StringRef Name = StringRef(Str).ltrim(PrefixChars);
217
218 // Search for the first next option which could be a prefix.
219 Start = std::lower_bound(Start, End, Name.data());
220
221 // Options are stored in sorted order, with '\0' at the end of the
222 // alphabet. Since the only options which can accept a string must
223 // prefix it, we iteratively search for the next option which could
224 // be a prefix.
225 //
226 // FIXME: This is searching much more than necessary, but I am
227 // blanking on the simplest way to make it fast. We can solve this
228 // problem when we move to TableGen.
229 for (; Start != End; ++Start) {
230 unsigned ArgSize = 0;
231 // Scan for first option which is a proper prefix.
232 for (; Start != End; ++Start)
Rui Ueyama8fb5a912013-08-28 20:04:31 +0000233 if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000234 break;
235 if (Start == End)
236 break;
237
Reid Klecknereadb7652013-07-19 18:04:57 +0000238 Option Opt(Start, this);
239
240 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
241 continue;
242 if (Opt.hasFlag(FlagsToExclude))
243 continue;
244
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000245 // See if this option matches.
Reid Klecknereadb7652013-07-19 18:04:57 +0000246 if (Arg *A = Opt.accept(Args, Index, ArgSize))
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000247 return A;
248
249 // Otherwise, see if this argument was missing values.
250 if (Prev != Index)
Craig Topper2617dcc2014-04-15 06:32:26 +0000251 return nullptr;
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000252 }
253
Reid Klecknereadb7652013-07-19 18:04:57 +0000254 // If we failed to find an option and this arg started with /, then it's
255 // probably an input path.
256 if (Str[0] == '/')
257 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
258
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000259 return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
260}
261
David Blaikiedb3d31d2015-06-22 22:06:37 +0000262InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr,
263 unsigned &MissingArgIndex,
264 unsigned &MissingArgCount,
265 unsigned FlagsToInclude,
266 unsigned FlagsToExclude) const {
267 InputArgList Args(ArgArr.begin(), ArgArr.end());
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000268
269 // FIXME: Handle '@' args (or at least error on them).
270
271 MissingArgIndex = MissingArgCount = 0;
David Blaikie259f61d2015-06-21 06:31:53 +0000272 unsigned Index = 0, End = ArgArr.size();
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000273 while (Index < End) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000274 // Ingore nullptrs, they are response file's EOL markers
David Blaikiedb3d31d2015-06-22 22:06:37 +0000275 if (Args.getArgString(Index) == nullptr) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000276 ++Index;
277 continue;
278 }
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000279 // Ignore empty arguments (other things may still take them as arguments).
David Blaikiedb3d31d2015-06-22 22:06:37 +0000280 StringRef Str = Args.getArgString(Index);
Hans Wennborgb8f34202013-08-02 21:20:27 +0000281 if (Str == "") {
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000282 ++Index;
283 continue;
284 }
285
286 unsigned Prev = Index;
David Blaikiedb3d31d2015-06-22 22:06:37 +0000287 Arg *A = ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000288 assert(Index > Prev && "Parser failed to consume argument.");
289
290 // Check for missing argument error.
291 if (!A) {
292 assert(Index >= End && "Unexpected parser error.");
293 assert(Index - Prev - 1 && "No missing arguments!");
294 MissingArgIndex = Prev;
295 MissingArgCount = Index - Prev - 1;
296 break;
297 }
298
David Blaikiedb3d31d2015-06-22 22:06:37 +0000299 Args.append(A);
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000300 }
301
Logan Chien9d5891f2015-06-22 23:16:02 +0000302 return Args;
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000303}
304
305static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
306 const Option O = Opts.getOption(Id);
307 std::string Name = O.getPrefixedName();
308
309 // Add metavar, if used.
310 switch (O.getKind()) {
311 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
312 llvm_unreachable("Invalid option with help text.");
313
314 case Option::MultiArgClass:
Nick Kledzikbcd6e2a2014-08-15 21:35:07 +0000315 if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
316 // For MultiArgs, metavar is full list of all argument names.
317 Name += ' ';
318 Name += MetaVarName;
319 }
320 else {
321 // For MultiArgs<N>, if metavar not supplied, print <value> N times.
322 for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
323 Name += " <value>";
324 }
325 }
326 break;
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000327
328 case Option::FlagClass:
329 break;
330
331 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
Hans Wennborg40cfde32016-04-15 00:23:30 +0000332 case Option::RemainingArgsClass: case Option::RemainingArgsJoinedClass:
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000333 Name += ' ';
Justin Bognerb03fd122016-08-17 05:10:15 +0000334 LLVM_FALLTHROUGH;
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000335 case Option::JoinedClass: case Option::CommaJoinedClass:
336 case Option::JoinedAndSeparateClass:
337 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
338 Name += MetaVarName;
339 else
340 Name += "<value>";
341 break;
342 }
343
344 return Name;
345}
346
347static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
348 std::vector<std::pair<std::string,
349 const char*> > &OptionHelp) {
350 OS << Title << ":\n";
351
352 // Find the maximum option length.
353 unsigned OptionFieldWidth = 0;
354 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
355 // Skip titles.
356 if (!OptionHelp[i].second)
357 continue;
358
359 // Limit the amount of padding we are willing to give up for alignment.
360 unsigned Length = OptionHelp[i].first.size();
361 if (Length <= 23)
362 OptionFieldWidth = std::max(OptionFieldWidth, Length);
363 }
364
365 const unsigned InitialPad = 2;
366 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
367 const std::string &Option = OptionHelp[i].first;
368 int Pad = OptionFieldWidth - int(Option.size());
369 OS.indent(InitialPad) << Option;
370
371 // Break on long option names.
372 if (Pad < 0) {
373 OS << "\n";
374 Pad = OptionFieldWidth + InitialPad;
375 }
376 OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
377 }
378}
379
380static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
381 unsigned GroupID = Opts.getOptionGroupID(Id);
382
383 // If not in a group, return the default help group.
384 if (!GroupID)
385 return "OPTIONS";
386
387 // Abuse the help text of the option groups to store the "help group"
388 // name.
389 //
390 // FIXME: Split out option groups.
391 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
392 return GroupHelp;
393
394 // Otherwise keep looking.
395 return getOptionHelpGroup(Opts, GroupID);
396}
397
Reid Kleckner12e03322013-06-13 18:12:12 +0000398void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
399 bool ShowHidden) const {
400 PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
401 (ShowHidden ? 0 : HelpHidden));
402}
403
404
405void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
406 unsigned FlagsToInclude,
407 unsigned FlagsToExclude) const {
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000408 OS << "OVERVIEW: " << Title << "\n";
409 OS << '\n';
410 OS << "USAGE: " << Name << " [options] <inputs>\n";
411 OS << '\n';
412
413 // Render help text into a map of group-name to a list of (option, help)
414 // pairs.
415 typedef std::map<std::string,
416 std::vector<std::pair<std::string, const char*> > > helpmap_ty;
417 helpmap_ty GroupedOptionHelp;
418
419 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
420 unsigned Id = i + 1;
421
422 // FIXME: Split out option groups.
423 if (getOptionKind(Id) == Option::GroupClass)
424 continue;
425
Reid Kleckner12e03322013-06-13 18:12:12 +0000426 unsigned Flags = getInfo(Id).Flags;
427 if (FlagsToInclude && !(Flags & FlagsToInclude))
428 continue;
429 if (Flags & FlagsToExclude)
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000430 continue;
431
432 if (const char *Text = getOptionHelpText(Id)) {
433 const char *HelpGroup = getOptionHelpGroup(*this, Id);
434 const std::string &OptName = getOptionHelpName(*this, Id);
435 GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
436 }
437 }
438
439 for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
440 ie = GroupedOptionHelp.end(); it != ie; ++it) {
441 if (it != GroupedOptionHelp .begin())
442 OS << "\n";
443 PrintHelpOptionList(OS, it->first, it->second);
444 }
445
446 OS.flush();
447}