blob: e7e83cc724e6f5f79b7bdff84c57c1060414fce8 [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>
17#include <map>
18
19using namespace llvm;
20using namespace llvm::opt;
21
Michael J. Spencer96a564f2012-12-05 00:29:32 +000022namespace llvm {
23namespace opt {
24
Rui Ueyama055f4e92013-08-27 23:47:01 +000025// Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
26// with an exceptions. '\0' comes at the end of the alphabet instead of the
27// beginning (thus options precede any other options which prefix them).
28static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) {
29 size_t I = strlen(A);
30 size_t J = strlen(B);
31 // If A and B are the same length, compare them ignoring case.
32 if (I == J)
33 return strcasecmp(A, B);
34 // A is shorter than B. In this case A is less than B only when it's
35 // lexicographically less than B. strncasecmp() == 0 means A is a prefix of B,
36 // which in turn means A should appear *after* B.
37 if (I < J)
38 return strncasecmp(A, B, I) < 0 ? -1 : 1;
39 // Otherwise, vice versa.
40 return strncasecmp(A, B, J) <= 0 ? -1 : 1;
41}
42
43static int StrCmpOptionName(const char *A, const char *B) {
44 if (int N = StrCmpOptionNameIgnoreCase(A, B))
45 return N;
46 return strcmp(A, B);
47}
48
Michael J. Spencer96a564f2012-12-05 00:29:32 +000049static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
50 if (&A == &B)
51 return false;
52
53 if (int N = StrCmpOptionName(A.Name, B.Name))
Rui Ueyama055f4e92013-08-27 23:47:01 +000054 return N < 0;
Michael J. Spencer96a564f2012-12-05 00:29:32 +000055
56 for (const char * const *APre = A.Prefixes,
57 * const *BPre = B.Prefixes;
58 *APre != 0 && *BPre != 0; ++APre, ++BPre) {
59 if (int N = StrCmpOptionName(*APre, *BPre))
Rui Ueyama055f4e92013-08-27 23:47:01 +000060 return N < 0;
Michael J. Spencer96a564f2012-12-05 00:29:32 +000061 }
62
63 // Names are the same, check that classes are in order; exactly one
64 // should be joined, and it should succeed the other.
65 assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
66 "Unexpected classes for options with same name.");
67 return B.Kind == Option::JoinedClass;
68}
69
70// Support lower_bound between info and an option name.
71static inline bool operator<(const OptTable::Info &I, const char *Name) {
Rui Ueyama055f4e92013-08-27 23:47:01 +000072 return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
Michael J. Spencer96a564f2012-12-05 00:29:32 +000073}
74static inline bool operator<(const char *Name, const OptTable::Info &I) {
Rui Ueyama055f4e92013-08-27 23:47:01 +000075 return StrCmpOptionNameIgnoreCase(Name, I.Name) < 0;
Michael J. Spencer96a564f2012-12-05 00:29:32 +000076}
77}
78}
79
80OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
81
Rui Ueyama055f4e92013-08-27 23:47:01 +000082OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos,
83 bool _IgnoreCase)
Michael J. Spencer96a564f2012-12-05 00:29:32 +000084 : OptionInfos(_OptionInfos),
85 NumOptionInfos(_NumOptionInfos),
Rui Ueyama055f4e92013-08-27 23:47:01 +000086 IgnoreCase(_IgnoreCase),
Michael J. Spencer96a564f2012-12-05 00:29:32 +000087 TheInputOptionID(0),
88 TheUnknownOptionID(0),
89 FirstSearchableIndex(0)
90{
91 // 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) {
134 for (; *P != 0; ++P) {
135 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)
146 if (std::find(PrefixChars.begin(), PrefixChars.end(), *C)
147 == PrefixChars.end())
148 PrefixChars.push_back(*C);
149 }
150}
151
152OptTable::~OptTable() {
153}
154
155const Option OptTable::getOption(OptSpecifier Opt) const {
156 unsigned id = Opt.getID();
157 if (id == 0)
158 return Option(0, 0);
159 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
160 return Option(&getInfo(id), this);
161}
162
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000163static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
164 if (Arg == "-")
165 return true;
166 for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
167 E = Prefixes.end(); I != E; ++I)
168 if (Arg.startswith(I->getKey()))
169 return false;
170 return true;
171}
172
Rui Ueyama055f4e92013-08-27 23:47:01 +0000173// Returns true if X starts with Y, ignoring case.
174static bool startsWithIgnoreCase(StringRef X, StringRef Y) {
175 if (X.size() < Y.size())
176 return false;
177 return X.substr(0, Y.size()).equals_lower(Y);
178}
179
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000180/// \returns Matched size. 0 means no match.
Rui Ueyama055f4e92013-08-27 23:47:01 +0000181static unsigned matchOption(const OptTable::Info *I, StringRef Str,
182 bool IgnoreCase) {
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000183 for (const char * const *Pre = I->Prefixes; *Pre != 0; ++Pre) {
184 StringRef Prefix(*Pre);
Rui Ueyama055f4e92013-08-27 23:47:01 +0000185 if (Str.startswith(Prefix)) {
186 StringRef Rest = Str.substr(Prefix.size());
187 bool Matched = IgnoreCase
188 ? startsWithIgnoreCase(Rest, I->Name)
189 : Rest.startswith(I->Name);
190 if (Matched)
191 return Prefix.size() + StringRef(I->Name).size();
192 }
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000193 }
194 return 0;
195}
196
Reid Klecknera2549d32013-07-19 18:04:57 +0000197Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
198 unsigned FlagsToInclude,
199 unsigned FlagsToExclude) const {
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000200 unsigned Prev = Index;
201 const char *Str = Args.getArgString(Index);
202
203 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
204 // itself.
205 if (isInput(PrefixesUnion, Str))
206 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
207
208 const Info *Start = OptionInfos + FirstSearchableIndex;
209 const Info *End = OptionInfos + getNumOptions();
210 StringRef Name = StringRef(Str).ltrim(PrefixChars);
211
212 // Search for the first next option which could be a prefix.
213 Start = std::lower_bound(Start, End, Name.data());
214
215 // Options are stored in sorted order, with '\0' at the end of the
216 // alphabet. Since the only options which can accept a string must
217 // prefix it, we iteratively search for the next option which could
218 // be a prefix.
219 //
220 // FIXME: This is searching much more than necessary, but I am
221 // blanking on the simplest way to make it fast. We can solve this
222 // problem when we move to TableGen.
223 for (; Start != End; ++Start) {
224 unsigned ArgSize = 0;
225 // Scan for first option which is a proper prefix.
226 for (; Start != End; ++Start)
Rui Ueyama055f4e92013-08-27 23:47:01 +0000227 if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000228 break;
229 if (Start == End)
230 break;
231
Reid Klecknera2549d32013-07-19 18:04:57 +0000232 Option Opt(Start, this);
233
234 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
235 continue;
236 if (Opt.hasFlag(FlagsToExclude))
237 continue;
238
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000239 // See if this option matches.
Reid Klecknera2549d32013-07-19 18:04:57 +0000240 if (Arg *A = Opt.accept(Args, Index, ArgSize))
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000241 return A;
242
243 // Otherwise, see if this argument was missing values.
244 if (Prev != Index)
245 return 0;
246 }
247
Reid Klecknera2549d32013-07-19 18:04:57 +0000248 // If we failed to find an option and this arg started with /, then it's
249 // probably an input path.
250 if (Str[0] == '/')
251 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
252
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000253 return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
254}
255
Reid Klecknera2549d32013-07-19 18:04:57 +0000256InputArgList *OptTable::ParseArgs(const char *const *ArgBegin,
257 const char *const *ArgEnd,
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000258 unsigned &MissingArgIndex,
Reid Klecknera2549d32013-07-19 18:04:57 +0000259 unsigned &MissingArgCount,
260 unsigned FlagsToInclude,
261 unsigned FlagsToExclude) const {
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000262 InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
263
264 // FIXME: Handle '@' args (or at least error on them).
265
266 MissingArgIndex = MissingArgCount = 0;
267 unsigned Index = 0, End = ArgEnd - ArgBegin;
268 while (Index < End) {
269 // Ignore empty arguments (other things may still take them as arguments).
Hans Wennborg6bf104b2013-08-02 21:20:27 +0000270 StringRef Str = Args->getArgString(Index);
271 if (Str == "") {
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000272 ++Index;
273 continue;
274 }
275
276 unsigned Prev = Index;
Reid Klecknera2549d32013-07-19 18:04:57 +0000277 Arg *A = ParseOneArg(*Args, Index, FlagsToInclude, FlagsToExclude);
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000278 assert(Index > Prev && "Parser failed to consume argument.");
279
280 // Check for missing argument error.
281 if (!A) {
282 assert(Index >= End && "Unexpected parser error.");
283 assert(Index - Prev - 1 && "No missing arguments!");
284 MissingArgIndex = Prev;
285 MissingArgCount = Index - Prev - 1;
286 break;
287 }
288
289 Args->append(A);
290 }
291
292 return Args;
293}
294
295static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
296 const Option O = Opts.getOption(Id);
297 std::string Name = O.getPrefixedName();
298
299 // Add metavar, if used.
300 switch (O.getKind()) {
301 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
302 llvm_unreachable("Invalid option with help text.");
303
304 case Option::MultiArgClass:
305 llvm_unreachable("Cannot print metavar for this kind of option.");
306
307 case Option::FlagClass:
308 break;
309
310 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
Hans Wennborgaf9e3552013-08-13 21:09:50 +0000311 case Option::RemainingArgsClass:
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000312 Name += ' ';
313 // FALLTHROUGH
314 case Option::JoinedClass: case Option::CommaJoinedClass:
315 case Option::JoinedAndSeparateClass:
316 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
317 Name += MetaVarName;
318 else
319 Name += "<value>";
320 break;
321 }
322
323 return Name;
324}
325
326static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
327 std::vector<std::pair<std::string,
328 const char*> > &OptionHelp) {
329 OS << Title << ":\n";
330
331 // Find the maximum option length.
332 unsigned OptionFieldWidth = 0;
333 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
334 // Skip titles.
335 if (!OptionHelp[i].second)
336 continue;
337
338 // Limit the amount of padding we are willing to give up for alignment.
339 unsigned Length = OptionHelp[i].first.size();
340 if (Length <= 23)
341 OptionFieldWidth = std::max(OptionFieldWidth, Length);
342 }
343
344 const unsigned InitialPad = 2;
345 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
346 const std::string &Option = OptionHelp[i].first;
347 int Pad = OptionFieldWidth - int(Option.size());
348 OS.indent(InitialPad) << Option;
349
350 // Break on long option names.
351 if (Pad < 0) {
352 OS << "\n";
353 Pad = OptionFieldWidth + InitialPad;
354 }
355 OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
356 }
357}
358
359static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
360 unsigned GroupID = Opts.getOptionGroupID(Id);
361
362 // If not in a group, return the default help group.
363 if (!GroupID)
364 return "OPTIONS";
365
366 // Abuse the help text of the option groups to store the "help group"
367 // name.
368 //
369 // FIXME: Split out option groups.
370 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
371 return GroupHelp;
372
373 // Otherwise keep looking.
374 return getOptionHelpGroup(Opts, GroupID);
375}
376
Reid Kleckner1ee21dc2013-06-13 18:12:12 +0000377void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
378 bool ShowHidden) const {
379 PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
380 (ShowHidden ? 0 : HelpHidden));
381}
382
383
384void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
385 unsigned FlagsToInclude,
386 unsigned FlagsToExclude) const {
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000387 OS << "OVERVIEW: " << Title << "\n";
388 OS << '\n';
389 OS << "USAGE: " << Name << " [options] <inputs>\n";
390 OS << '\n';
391
392 // Render help text into a map of group-name to a list of (option, help)
393 // pairs.
394 typedef std::map<std::string,
395 std::vector<std::pair<std::string, const char*> > > helpmap_ty;
396 helpmap_ty GroupedOptionHelp;
397
398 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
399 unsigned Id = i + 1;
400
401 // FIXME: Split out option groups.
402 if (getOptionKind(Id) == Option::GroupClass)
403 continue;
404
Reid Kleckner1ee21dc2013-06-13 18:12:12 +0000405 unsigned Flags = getInfo(Id).Flags;
406 if (FlagsToInclude && !(Flags & FlagsToInclude))
407 continue;
408 if (Flags & FlagsToExclude)
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000409 continue;
410
411 if (const char *Text = getOptionHelpText(Id)) {
412 const char *HelpGroup = getOptionHelpGroup(*this, Id);
413 const std::string &OptName = getOptionHelpName(*this, Id);
414 GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
415 }
416 }
417
418 for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
419 ie = GroupedOptionHelp.end(); it != ie; ++it) {
420 if (it != GroupedOptionHelp .begin())
421 OS << "\n";
422 PrintHelpOptionList(OS, it->first, it->second);
423 }
424
425 OS.flush();
426}