blob: 8f21a4ff24cf1ba17a3d05d75e404ac20f208657 [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
22// Ordering on Info. The ordering is *almost* lexicographic, with two
23// exceptions. First, '\0' comes at the end of the alphabet instead of
24// the beginning (thus options precede any other options which prefix
25// them). Second, for options with the same name, the less permissive
26// version should come first; a Flag option should precede a Joined
27// option, for example.
28
29static int StrCmpOptionName(const char *A, const char *B) {
30 char a = *A, b = *B;
31 while (a == b) {
32 if (a == '\0')
33 return 0;
34
35 a = *++A;
36 b = *++B;
37 }
38
39 if (a == '\0') // A is a prefix of B.
40 return 1;
41 if (b == '\0') // B is a prefix of A.
42 return -1;
43
44 // Otherwise lexicographic.
45 return (a < b) ? -1 : 1;
46}
47
48namespace llvm {
49namespace opt {
50
51static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
52 if (&A == &B)
53 return false;
54
55 if (int N = StrCmpOptionName(A.Name, B.Name))
56 return N == -1;
57
58 for (const char * const *APre = A.Prefixes,
59 * const *BPre = B.Prefixes;
60 *APre != 0 && *BPre != 0; ++APre, ++BPre) {
61 if (int N = StrCmpOptionName(*APre, *BPre))
62 return N == -1;
63 }
64
65 // Names are the same, check that classes are in order; exactly one
66 // should be joined, and it should succeed the other.
67 assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
68 "Unexpected classes for options with same name.");
69 return B.Kind == Option::JoinedClass;
70}
71
72// Support lower_bound between info and an option name.
73static inline bool operator<(const OptTable::Info &I, const char *Name) {
74 return StrCmpOptionName(I.Name, Name) == -1;
75}
76static inline bool operator<(const char *Name, const OptTable::Info &I) {
77 return StrCmpOptionName(Name, I.Name) == -1;
78}
79}
80}
81
82OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
83
84OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos)
85 : OptionInfos(_OptionInfos),
86 NumOptionInfos(_NumOptionInfos),
87 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
173/// \returns Matched size. 0 means no match.
174static unsigned matchOption(const OptTable::Info *I, StringRef Str) {
175 for (const char * const *Pre = I->Prefixes; *Pre != 0; ++Pre) {
176 StringRef Prefix(*Pre);
177 if (Str.startswith(Prefix) && Str.substr(Prefix.size()).startswith(I->Name))
178 return Prefix.size() + StringRef(I->Name).size();
179 }
180 return 0;
181}
182
Reid Klecknera2549d32013-07-19 18:04:57 +0000183Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
184 unsigned FlagsToInclude,
185 unsigned FlagsToExclude) const {
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000186 unsigned Prev = Index;
187 const char *Str = Args.getArgString(Index);
188
189 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
190 // itself.
191 if (isInput(PrefixesUnion, Str))
192 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
193
194 const Info *Start = OptionInfos + FirstSearchableIndex;
195 const Info *End = OptionInfos + getNumOptions();
196 StringRef Name = StringRef(Str).ltrim(PrefixChars);
197
198 // Search for the first next option which could be a prefix.
199 Start = std::lower_bound(Start, End, Name.data());
200
201 // Options are stored in sorted order, with '\0' at the end of the
202 // alphabet. Since the only options which can accept a string must
203 // prefix it, we iteratively search for the next option which could
204 // be a prefix.
205 //
206 // FIXME: This is searching much more than necessary, but I am
207 // blanking on the simplest way to make it fast. We can solve this
208 // problem when we move to TableGen.
209 for (; Start != End; ++Start) {
210 unsigned ArgSize = 0;
211 // Scan for first option which is a proper prefix.
212 for (; Start != End; ++Start)
213 if ((ArgSize = matchOption(Start, Str)))
214 break;
215 if (Start == End)
216 break;
217
Reid Klecknera2549d32013-07-19 18:04:57 +0000218 Option Opt(Start, this);
219
220 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
221 continue;
222 if (Opt.hasFlag(FlagsToExclude))
223 continue;
224
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000225 // See if this option matches.
Reid Klecknera2549d32013-07-19 18:04:57 +0000226 if (Arg *A = Opt.accept(Args, Index, ArgSize))
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000227 return A;
228
229 // Otherwise, see if this argument was missing values.
230 if (Prev != Index)
231 return 0;
232 }
233
Reid Klecknera2549d32013-07-19 18:04:57 +0000234 // If we failed to find an option and this arg started with /, then it's
235 // probably an input path.
236 if (Str[0] == '/')
237 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
238
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000239 return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
240}
241
Reid Klecknera2549d32013-07-19 18:04:57 +0000242InputArgList *OptTable::ParseArgs(const char *const *ArgBegin,
243 const char *const *ArgEnd,
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000244 unsigned &MissingArgIndex,
Reid Klecknera2549d32013-07-19 18:04:57 +0000245 unsigned &MissingArgCount,
246 unsigned FlagsToInclude,
247 unsigned FlagsToExclude) const {
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000248 InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
249
250 // FIXME: Handle '@' args (or at least error on them).
251
252 MissingArgIndex = MissingArgCount = 0;
253 unsigned Index = 0, End = ArgEnd - ArgBegin;
254 while (Index < End) {
255 // Ignore empty arguments (other things may still take them as arguments).
Hans Wennborg6bf104b2013-08-02 21:20:27 +0000256 StringRef Str = Args->getArgString(Index);
257 if (Str == "") {
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000258 ++Index;
259 continue;
260 }
261
262 unsigned Prev = Index;
Reid Klecknera2549d32013-07-19 18:04:57 +0000263 Arg *A = ParseOneArg(*Args, Index, FlagsToInclude, FlagsToExclude);
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000264 assert(Index > Prev && "Parser failed to consume argument.");
265
266 // Check for missing argument error.
267 if (!A) {
268 assert(Index >= End && "Unexpected parser error.");
269 assert(Index - Prev - 1 && "No missing arguments!");
270 MissingArgIndex = Prev;
271 MissingArgCount = Index - Prev - 1;
272 break;
273 }
274
275 Args->append(A);
276 }
277
278 return Args;
279}
280
281static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
282 const Option O = Opts.getOption(Id);
283 std::string Name = O.getPrefixedName();
284
285 // Add metavar, if used.
286 switch (O.getKind()) {
287 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
288 llvm_unreachable("Invalid option with help text.");
289
290 case Option::MultiArgClass:
291 llvm_unreachable("Cannot print metavar for this kind of option.");
292
293 case Option::FlagClass:
294 break;
295
296 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
Hans Wennborgaf9e3552013-08-13 21:09:50 +0000297 case Option::RemainingArgsClass:
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000298 Name += ' ';
299 // FALLTHROUGH
300 case Option::JoinedClass: case Option::CommaJoinedClass:
301 case Option::JoinedAndSeparateClass:
302 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
303 Name += MetaVarName;
304 else
305 Name += "<value>";
306 break;
307 }
308
309 return Name;
310}
311
312static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
313 std::vector<std::pair<std::string,
314 const char*> > &OptionHelp) {
315 OS << Title << ":\n";
316
317 // Find the maximum option length.
318 unsigned OptionFieldWidth = 0;
319 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
320 // Skip titles.
321 if (!OptionHelp[i].second)
322 continue;
323
324 // Limit the amount of padding we are willing to give up for alignment.
325 unsigned Length = OptionHelp[i].first.size();
326 if (Length <= 23)
327 OptionFieldWidth = std::max(OptionFieldWidth, Length);
328 }
329
330 const unsigned InitialPad = 2;
331 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
332 const std::string &Option = OptionHelp[i].first;
333 int Pad = OptionFieldWidth - int(Option.size());
334 OS.indent(InitialPad) << Option;
335
336 // Break on long option names.
337 if (Pad < 0) {
338 OS << "\n";
339 Pad = OptionFieldWidth + InitialPad;
340 }
341 OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
342 }
343}
344
345static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
346 unsigned GroupID = Opts.getOptionGroupID(Id);
347
348 // If not in a group, return the default help group.
349 if (!GroupID)
350 return "OPTIONS";
351
352 // Abuse the help text of the option groups to store the "help group"
353 // name.
354 //
355 // FIXME: Split out option groups.
356 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
357 return GroupHelp;
358
359 // Otherwise keep looking.
360 return getOptionHelpGroup(Opts, GroupID);
361}
362
Reid Kleckner1ee21dc2013-06-13 18:12:12 +0000363void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
364 bool ShowHidden) const {
365 PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
366 (ShowHidden ? 0 : HelpHidden));
367}
368
369
370void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
371 unsigned FlagsToInclude,
372 unsigned FlagsToExclude) const {
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000373 OS << "OVERVIEW: " << Title << "\n";
374 OS << '\n';
375 OS << "USAGE: " << Name << " [options] <inputs>\n";
376 OS << '\n';
377
378 // Render help text into a map of group-name to a list of (option, help)
379 // pairs.
380 typedef std::map<std::string,
381 std::vector<std::pair<std::string, const char*> > > helpmap_ty;
382 helpmap_ty GroupedOptionHelp;
383
384 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
385 unsigned Id = i + 1;
386
387 // FIXME: Split out option groups.
388 if (getOptionKind(Id) == Option::GroupClass)
389 continue;
390
Reid Kleckner1ee21dc2013-06-13 18:12:12 +0000391 unsigned Flags = getInfo(Id).Flags;
392 if (FlagsToInclude && !(Flags & FlagsToInclude))
393 continue;
394 if (Flags & FlagsToExclude)
Michael J. Spencer96a564f2012-12-05 00:29:32 +0000395 continue;
396
397 if (const char *Text = getOptionHelpText(Id)) {
398 const char *HelpGroup = getOptionHelpGroup(*this, Id);
399 const std::string &OptName = getOptionHelpName(*this, Id);
400 GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
401 }
402 }
403
404 for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
405 ie = GroupedOptionHelp.end(); it != ie; ++it) {
406 if (it != GroupedOptionHelp .begin())
407 OS << "\n";
408 PrintHelpOptionList(OS, it->first, it->second);
409 }
410
411 OS.flush();
412}