blob: b126841f72c19d7db93e3f91db3e6ce7482a31d0 [file] [log] [blame]
Michael J. Spencer96a564f2012-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"
Michael J. Spencer96a564f2012-12-05 00:29:32 +000011#include "llvm/Option/Arg.h"
12#include "llvm/Option/ArgList.h"
13#include "llvm/Option/Option.h"
Michael J. Spencer96a564f2012-12-05 00:29:32 +000014#include "llvm/Support/ErrorHandling.h"
Chandler Carruth58a2cbe2013-01-02 10:22:59 +000015#include "llvm/Support/raw_ostream.h"
Michael J. Spencer96a564f2012-12-05 00:29:32 +000016#include <algorithm>
Rui Ueyama29572732013-08-28 20:04:31 +000017#include <cctype>
Michael J. Spencer96a564f2012-12-05 00:29:32 +000018#include <map>
19
20using namespace llvm;
21using namespace llvm::opt;
22
Rui Ueyama29572732013-08-28 20:04:31 +000023namespace llvm {
24namespace opt {
Rui Ueyama055f4e92013-08-27 23:47:01 +000025
Rui Ueyama29572732013-08-28 20:04:31 +000026// 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).
29static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) {
30 const char *X = A, *Y = B;
31 char a = tolower(*A), b = tolower(*B);
Rui Ueyama19977342013-08-28 00:02:06 +000032 while (a == b) {
33 if (a == '\0')
34 return 0;
35
Rui Ueyama29572732013-08-28 20:04:31 +000036 a = tolower(*++X);
37 b = tolower(*++Y);
Rui Ueyama19977342013-08-28 00:02:06 +000038 }
39
40 if (a == '\0') // A is a prefix of B.
41 return 1;
42 if (b == '\0') // B is a prefix of A.
43 return -1;
44
45 // Otherwise lexicographic.
46 return (a < b) ? -1 : 1;
Rui Ueyama055f4e92013-08-27 23:47:01 +000047}
48
Rui Ueyama29572732013-08-28 20:04:31 +000049static int StrCmpOptionName(const char *A, const char *B) {
50 if (int N = StrCmpOptionNameIgnoreCase(A, B))
51 return N;
52 return strcmp(A, B);
53}
Rui Ueyama19977342013-08-28 00:02:06 +000054
Michael J. Spencer96a564f2012-12-05 00:29:32 +000055static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
56 if (&A == &B)
57 return false;
58
59 if (int N = StrCmpOptionName(A.Name, B.Name))
Rui Ueyama29572732013-08-28 20:04:31 +000060 return N < 0;
Michael J. Spencer96a564f2012-12-05 00:29:32 +000061
62 for (const char * const *APre = A.Prefixes,
63 * const *BPre = B.Prefixes;
64 *APre != 0 && *BPre != 0; ++APre, ++BPre) {
65 if (int N = StrCmpOptionName(*APre, *BPre))
Rui Ueyama29572732013-08-28 20:04:31 +000066 return N < 0;
Michael J. Spencer96a564f2012-12-05 00:29:32 +000067 }
68
69 // Names are the same, check that classes are in order; exactly one
70 // should be joined, and it should succeed the other.
71 assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
72 "Unexpected classes for options with same name.");
73 return B.Kind == Option::JoinedClass;
74}
75
76// Support lower_bound between info and an option name.
77static inline bool operator<(const OptTable::Info &I, const char *Name) {
Rui Ueyama29572732013-08-28 20:04:31 +000078 return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
Michael J. Spencer96a564f2012-12-05 00:29:32 +000079}
80static inline bool operator<(const char *Name, const OptTable::Info &I) {
Rui Ueyama29572732013-08-28 20:04:31 +000081 return StrCmpOptionNameIgnoreCase(Name, I.Name) < 0;
Michael J. Spencer96a564f2012-12-05 00:29:32 +000082}
83}
84}
85
86OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
87
Rui Ueyama29572732013-08-28 20:04:31 +000088OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos,
89 bool _IgnoreCase)
Michael J. Spencer96a564f2012-12-05 00:29:32 +000090 : OptionInfos(_OptionInfos),
91 NumOptionInfos(_NumOptionInfos),
Rui Ueyama29572732013-08-28 20:04:31 +000092 IgnoreCase(_IgnoreCase),
Michael J. Spencer96a564f2012-12-05 00:29:32 +000093 TheInputOptionID(0),
94 TheUnknownOptionID(0),
95 FirstSearchableIndex(0)
96{
97 // Explicitly zero initialize the error to work around a bug in array
98 // value-initialization on MinGW with gcc 4.3.5.
99
100 // Find start of normal options.
101 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
102 unsigned Kind = getInfo(i + 1).Kind;
103 if (Kind == Option::InputClass) {
104 assert(!TheInputOptionID && "Cannot have multiple input options!");
105 TheInputOptionID = getInfo(i + 1).ID;
106 } else if (Kind == Option::UnknownClass) {
107 assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
108 TheUnknownOptionID = getInfo(i + 1).ID;
109 } else if (Kind != Option::GroupClass) {
110 FirstSearchableIndex = i;
111 break;
112 }
113 }
114 assert(FirstSearchableIndex != 0 && "No searchable options?");
115
116#ifndef NDEBUG
117 // Check that everything after the first searchable option is a
118 // regular option class.
119 for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
120 Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
121 assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
122 Kind != Option::GroupClass) &&
123 "Special options should be defined first!");
124 }
125
126 // Check that options are in order.
127 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
128 if (!(getInfo(i) < getInfo(i + 1))) {
129 getOption(i).dump();
130 getOption(i + 1).dump();
131 llvm_unreachable("Options are not in order!");
132 }
133 }
134#endif
135
136 // Build prefixes.
137 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
138 i != e; ++i) {
139 if (const char *const *P = getInfo(i).Prefixes) {
140 for (; *P != 0; ++P) {
141 PrefixesUnion.insert(*P);
142 }
143 }
144 }
145
146 // Build prefix chars.
147 for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(),
148 E = PrefixesUnion.end(); I != E; ++I) {
149 StringRef Prefix = I->getKey();
150 for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
151 C != CE; ++C)
152 if (std::find(PrefixChars.begin(), PrefixChars.end(), *C)
153 == PrefixChars.end())
154 PrefixChars.push_back(*C);
155 }
156}
157
158OptTable::~OptTable() {
159}
160
161const Option OptTable::getOption(OptSpecifier Opt) const {
162 unsigned id = Opt.getID();
163 if (id == 0)
164 return Option(0, 0);
165 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
166 return Option(&getInfo(id), this);
167}
168
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000169static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
170 if (Arg == "-")
171 return true;
172 for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
173 E = Prefixes.end(); I != E; ++I)
174 if (Arg.startswith(I->getKey()))
175 return false;
176 return true;
177}
178
Rui Ueyama29572732013-08-28 20:04:31 +0000179// Returns true if X starts with Y, ignoring case.
180static bool startsWithIgnoreCase(StringRef X, StringRef Y) {
181 if (X.size() < Y.size())
182 return false;
183 return X.substr(0, Y.size()).equals_lower(Y);
184}
185
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000186/// \returns Matched size. 0 means no match.
Rui Ueyama29572732013-08-28 20:04:31 +0000187static unsigned matchOption(const OptTable::Info *I, StringRef Str,
188 bool IgnoreCase) {
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000189 for (const char * const *Pre = I->Prefixes; *Pre != 0; ++Pre) {
190 StringRef Prefix(*Pre);
Rui Ueyama29572732013-08-28 20:04:31 +0000191 if (Str.startswith(Prefix)) {
192 StringRef Rest = Str.substr(Prefix.size());
193 bool Matched = IgnoreCase
194 ? startsWithIgnoreCase(Rest, I->Name)
195 : Rest.startswith(I->Name);
196 if (Matched)
197 return Prefix.size() + StringRef(I->Name).size();
198 }
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000199 }
200 return 0;
201}
202
Reid Klecknera2549d32013-07-19 18:04:57 +0000203Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
204 unsigned FlagsToInclude,
205 unsigned FlagsToExclude) const {
Michael J. Spencer96a564f2012-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
214 const Info *Start = OptionInfos + FirstSearchableIndex;
215 const Info *End = OptionInfos + getNumOptions();
216 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 Ueyama29572732013-08-28 20:04:31 +0000233 if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000234 break;
235 if (Start == End)
236 break;
237
Reid Klecknera2549d32013-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. Spencer96a564f2012-12-05 00:29:32 +0000245 // See if this option matches.
Reid Klecknera2549d32013-07-19 18:04:57 +0000246 if (Arg *A = Opt.accept(Args, Index, ArgSize))
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000247 return A;
248
249 // Otherwise, see if this argument was missing values.
250 if (Prev != Index)
251 return 0;
252 }
253
Reid Klecknera2549d32013-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. Spencer96a564f2012-12-05 00:29:32 +0000259 return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
260}
261
Reid Klecknera2549d32013-07-19 18:04:57 +0000262InputArgList *OptTable::ParseArgs(const char *const *ArgBegin,
263 const char *const *ArgEnd,
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000264 unsigned &MissingArgIndex,
Reid Klecknera2549d32013-07-19 18:04:57 +0000265 unsigned &MissingArgCount,
266 unsigned FlagsToInclude,
267 unsigned FlagsToExclude) const {
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000268 InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
269
270 // FIXME: Handle '@' args (or at least error on them).
271
272 MissingArgIndex = MissingArgCount = 0;
273 unsigned Index = 0, End = ArgEnd - ArgBegin;
274 while (Index < End) {
275 // Ignore empty arguments (other things may still take them as arguments).
Hans Wennborg6bf104b2013-08-02 21:20:27 +0000276 StringRef Str = Args->getArgString(Index);
277 if (Str == "") {
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000278 ++Index;
279 continue;
280 }
281
282 unsigned Prev = Index;
Reid Klecknera2549d32013-07-19 18:04:57 +0000283 Arg *A = ParseOneArg(*Args, Index, FlagsToInclude, FlagsToExclude);
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000284 assert(Index > Prev && "Parser failed to consume argument.");
285
286 // Check for missing argument error.
287 if (!A) {
288 assert(Index >= End && "Unexpected parser error.");
289 assert(Index - Prev - 1 && "No missing arguments!");
290 MissingArgIndex = Prev;
291 MissingArgCount = Index - Prev - 1;
292 break;
293 }
294
295 Args->append(A);
296 }
297
298 return Args;
299}
300
301static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
302 const Option O = Opts.getOption(Id);
303 std::string Name = O.getPrefixedName();
304
305 // Add metavar, if used.
306 switch (O.getKind()) {
307 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
308 llvm_unreachable("Invalid option with help text.");
309
310 case Option::MultiArgClass:
311 llvm_unreachable("Cannot print metavar for this kind of option.");
312
313 case Option::FlagClass:
314 break;
315
316 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
Hans Wennborgaf9e3552013-08-13 21:09:50 +0000317 case Option::RemainingArgsClass:
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000318 Name += ' ';
319 // FALLTHROUGH
320 case Option::JoinedClass: case Option::CommaJoinedClass:
321 case Option::JoinedAndSeparateClass:
322 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
323 Name += MetaVarName;
324 else
325 Name += "<value>";
326 break;
327 }
328
329 return Name;
330}
331
332static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
333 std::vector<std::pair<std::string,
334 const char*> > &OptionHelp) {
335 OS << Title << ":\n";
336
337 // Find the maximum option length.
338 unsigned OptionFieldWidth = 0;
339 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
340 // Skip titles.
341 if (!OptionHelp[i].second)
342 continue;
343
344 // Limit the amount of padding we are willing to give up for alignment.
345 unsigned Length = OptionHelp[i].first.size();
346 if (Length <= 23)
347 OptionFieldWidth = std::max(OptionFieldWidth, Length);
348 }
349
350 const unsigned InitialPad = 2;
351 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
352 const std::string &Option = OptionHelp[i].first;
353 int Pad = OptionFieldWidth - int(Option.size());
354 OS.indent(InitialPad) << Option;
355
356 // Break on long option names.
357 if (Pad < 0) {
358 OS << "\n";
359 Pad = OptionFieldWidth + InitialPad;
360 }
361 OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
362 }
363}
364
365static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
366 unsigned GroupID = Opts.getOptionGroupID(Id);
367
368 // If not in a group, return the default help group.
369 if (!GroupID)
370 return "OPTIONS";
371
372 // Abuse the help text of the option groups to store the "help group"
373 // name.
374 //
375 // FIXME: Split out option groups.
376 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
377 return GroupHelp;
378
379 // Otherwise keep looking.
380 return getOptionHelpGroup(Opts, GroupID);
381}
382
Reid Kleckner1ee21dc2013-06-13 18:12:12 +0000383void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
384 bool ShowHidden) const {
385 PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
386 (ShowHidden ? 0 : HelpHidden));
387}
388
389
390void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
391 unsigned FlagsToInclude,
392 unsigned FlagsToExclude) const {
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000393 OS << "OVERVIEW: " << Title << "\n";
394 OS << '\n';
395 OS << "USAGE: " << Name << " [options] <inputs>\n";
396 OS << '\n';
397
398 // Render help text into a map of group-name to a list of (option, help)
399 // pairs.
400 typedef std::map<std::string,
401 std::vector<std::pair<std::string, const char*> > > helpmap_ty;
402 helpmap_ty GroupedOptionHelp;
403
404 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
405 unsigned Id = i + 1;
406
407 // FIXME: Split out option groups.
408 if (getOptionKind(Id) == Option::GroupClass)
409 continue;
410
Reid Kleckner1ee21dc2013-06-13 18:12:12 +0000411 unsigned Flags = getInfo(Id).Flags;
412 if (FlagsToInclude && !(Flags & FlagsToInclude))
413 continue;
414 if (Flags & FlagsToExclude)
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000415 continue;
416
417 if (const char *Text = getOptionHelpText(Id)) {
418 const char *HelpGroup = getOptionHelpGroup(*this, Id);
419 const std::string &OptName = getOptionHelpName(*this, Id);
420 GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
421 }
422 }
423
424 for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
425 ie = GroupedOptionHelp.end(); it != ie; ++it) {
426 if (it != GroupedOptionHelp .begin())
427 OS << "\n";
428 PrintHelpOptionList(OS, it->first, it->second);
429 }
430
431 OS.flush();
432}