blob: e83536f2b57264bd416cd5e9352f5829e0a61118 [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"
Michael J. Spencer41ee0412012-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. Spencer41ee0412012-12-05 00:29:32 +000014#include "llvm/Support/ErrorHandling.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000015#include "llvm/Support/raw_ostream.h"
Michael J. Spencer41ee0412012-12-05 00:29:32 +000016#include <algorithm>
Rui Ueyama8fb5a912013-08-28 20:04:31 +000017#include <cctype>
Michael J. Spencer41ee0412012-12-05 00:29:32 +000018#include <map>
19
20using namespace llvm;
21using namespace llvm::opt;
22
Rui Ueyama8fb5a912013-08-28 20:04:31 +000023namespace llvm {
24namespace opt {
Rui Ueyama7159bd92013-08-27 23:47:01 +000025
Rui Ueyama8fb5a912013-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 Ueyamac3779ff2013-08-28 00:02:06 +000032 while (a == b) {
33 if (a == '\0')
34 return 0;
35
Rui Ueyama8fb5a912013-08-28 20:04:31 +000036 a = tolower(*++X);
37 b = tolower(*++Y);
Rui Ueyamac3779ff2013-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 Ueyama7159bd92013-08-27 23:47:01 +000047}
48
Eli Friedman3e7dca62013-09-10 23:22:56 +000049#ifndef NDEBUG
50static int StrCmpOptionName(const char *A, const char *B) {
51 if (int N = StrCmpOptionNameIgnoreCase(A, B))
52 return N;
53 return strcmp(A, B);
54}
55
56static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
57 if (&A == &B)
58 return false;
59
60 if (int N = StrCmpOptionName(A.Name, B.Name))
61 return N < 0;
62
63 for (const char * const *APre = A.Prefixes,
64 * const *BPre = B.Prefixes;
Craig Topper2617dcc2014-04-15 06:32:26 +000065 *APre != nullptr && *BPre != nullptr; ++APre, ++BPre){
Eli Friedman3e7dca62013-09-10 23:22:56 +000066 if (int N = StrCmpOptionName(*APre, *BPre))
67 return N < 0;
68 }
69
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;
75}
76#endif
77
Michael J. Spencer41ee0412012-12-05 00:29:32 +000078// Support lower_bound between info and an option name.
79static inline bool operator<(const OptTable::Info &I, const char *Name) {
Rui Ueyama8fb5a912013-08-28 20:04:31 +000080 return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
Michael J. Spencer41ee0412012-12-05 00:29:32 +000081}
Alexander Kornienkof00654e2015-06-23 09:49:53 +000082}
83}
Michael J. Spencer41ee0412012-12-05 00:29:32 +000084
85OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
86
David Blaikie9f380a32015-03-16 18:06:57 +000087OptTable::OptTable(const Info *OptionInfos, unsigned NumOptionInfos,
88 bool IgnoreCase)
89 : OptionInfos(OptionInfos), NumOptionInfos(NumOptionInfos),
90 IgnoreCase(IgnoreCase), TheInputOptionID(0), TheUnknownOptionID(0),
91 FirstSearchableIndex(0) {
Michael J. Spencer41ee0412012-12-05 00:29:32 +000092 // Explicitly zero initialize the error to work around a bug in array
93 // value-initialization on MinGW with gcc 4.3.5.
94
95 // Find start of normal options.
96 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
97 unsigned Kind = getInfo(i + 1).Kind;
98 if (Kind == Option::InputClass) {
99 assert(!TheInputOptionID && "Cannot have multiple input options!");
100 TheInputOptionID = getInfo(i + 1).ID;
101 } else if (Kind == Option::UnknownClass) {
102 assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
103 TheUnknownOptionID = getInfo(i + 1).ID;
104 } else if (Kind != Option::GroupClass) {
105 FirstSearchableIndex = i;
106 break;
107 }
108 }
109 assert(FirstSearchableIndex != 0 && "No searchable options?");
110
111#ifndef NDEBUG
112 // Check that everything after the first searchable option is a
113 // regular option class.
114 for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
115 Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
116 assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
117 Kind != Option::GroupClass) &&
118 "Special options should be defined first!");
119 }
120
121 // Check that options are in order.
122 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
123 if (!(getInfo(i) < getInfo(i + 1))) {
124 getOption(i).dump();
125 getOption(i + 1).dump();
126 llvm_unreachable("Options are not in order!");
127 }
128 }
129#endif
130
131 // Build prefixes.
132 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
133 i != e; ++i) {
134 if (const char *const *P = getInfo(i).Prefixes) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000135 for (; *P != nullptr; ++P) {
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000136 PrefixesUnion.insert(*P);
137 }
138 }
139 }
140
141 // Build prefix chars.
142 for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(),
143 E = PrefixesUnion.end(); I != E; ++I) {
144 StringRef Prefix = I->getKey();
145 for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
146 C != CE; ++C)
147 if (std::find(PrefixChars.begin(), PrefixChars.end(), *C)
148 == PrefixChars.end())
149 PrefixChars.push_back(*C);
150 }
151}
152
153OptTable::~OptTable() {
154}
155
156const Option OptTable::getOption(OptSpecifier Opt) const {
157 unsigned id = Opt.getID();
158 if (id == 0)
Craig Topper2617dcc2014-04-15 06:32:26 +0000159 return Option(nullptr, nullptr);
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000160 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
161 return Option(&getInfo(id), this);
162}
163
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000164static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
165 if (Arg == "-")
166 return true;
167 for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
168 E = Prefixes.end(); I != E; ++I)
169 if (Arg.startswith(I->getKey()))
170 return false;
171 return true;
172}
173
174/// \returns Matched size. 0 means no match.
Rui Ueyama8fb5a912013-08-28 20:04:31 +0000175static unsigned matchOption(const OptTable::Info *I, StringRef Str,
176 bool IgnoreCase) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000177 for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) {
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000178 StringRef Prefix(*Pre);
Rui Ueyama8fb5a912013-08-28 20:04:31 +0000179 if (Str.startswith(Prefix)) {
180 StringRef Rest = Str.substr(Prefix.size());
181 bool Matched = IgnoreCase
Jakub Staszakcfcfee02013-11-04 19:22:50 +0000182 ? Rest.startswith_lower(I->Name)
Rui Ueyama8fb5a912013-08-28 20:04:31 +0000183 : Rest.startswith(I->Name);
184 if (Matched)
185 return Prefix.size() + StringRef(I->Name).size();
186 }
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000187 }
188 return 0;
189}
190
Reid Klecknereadb7652013-07-19 18:04:57 +0000191Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
192 unsigned FlagsToInclude,
193 unsigned FlagsToExclude) const {
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000194 unsigned Prev = Index;
195 const char *Str = Args.getArgString(Index);
196
197 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
198 // itself.
199 if (isInput(PrefixesUnion, Str))
200 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
201
202 const Info *Start = OptionInfos + FirstSearchableIndex;
203 const Info *End = OptionInfos + getNumOptions();
204 StringRef Name = StringRef(Str).ltrim(PrefixChars);
205
206 // Search for the first next option which could be a prefix.
207 Start = std::lower_bound(Start, End, Name.data());
208
209 // Options are stored in sorted order, with '\0' at the end of the
210 // alphabet. Since the only options which can accept a string must
211 // prefix it, we iteratively search for the next option which could
212 // be a prefix.
213 //
214 // FIXME: This is searching much more than necessary, but I am
215 // blanking on the simplest way to make it fast. We can solve this
216 // problem when we move to TableGen.
217 for (; Start != End; ++Start) {
218 unsigned ArgSize = 0;
219 // Scan for first option which is a proper prefix.
220 for (; Start != End; ++Start)
Rui Ueyama8fb5a912013-08-28 20:04:31 +0000221 if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000222 break;
223 if (Start == End)
224 break;
225
Reid Klecknereadb7652013-07-19 18:04:57 +0000226 Option Opt(Start, this);
227
228 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
229 continue;
230 if (Opt.hasFlag(FlagsToExclude))
231 continue;
232
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000233 // See if this option matches.
Reid Klecknereadb7652013-07-19 18:04:57 +0000234 if (Arg *A = Opt.accept(Args, Index, ArgSize))
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000235 return A;
236
237 // Otherwise, see if this argument was missing values.
238 if (Prev != Index)
Craig Topper2617dcc2014-04-15 06:32:26 +0000239 return nullptr;
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000240 }
241
Reid Klecknereadb7652013-07-19 18:04:57 +0000242 // If we failed to find an option and this arg started with /, then it's
243 // probably an input path.
244 if (Str[0] == '/')
245 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
246
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000247 return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
248}
249
David Blaikiedb3d31d2015-06-22 22:06:37 +0000250InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr,
251 unsigned &MissingArgIndex,
252 unsigned &MissingArgCount,
253 unsigned FlagsToInclude,
254 unsigned FlagsToExclude) const {
255 InputArgList Args(ArgArr.begin(), ArgArr.end());
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000256
257 // FIXME: Handle '@' args (or at least error on them).
258
259 MissingArgIndex = MissingArgCount = 0;
David Blaikie259f61d2015-06-21 06:31:53 +0000260 unsigned Index = 0, End = ArgArr.size();
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000261 while (Index < End) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000262 // Ingore nullptrs, they are response file's EOL markers
David Blaikiedb3d31d2015-06-22 22:06:37 +0000263 if (Args.getArgString(Index) == nullptr) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000264 ++Index;
265 continue;
266 }
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000267 // Ignore empty arguments (other things may still take them as arguments).
David Blaikiedb3d31d2015-06-22 22:06:37 +0000268 StringRef Str = Args.getArgString(Index);
Hans Wennborgb8f34202013-08-02 21:20:27 +0000269 if (Str == "") {
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000270 ++Index;
271 continue;
272 }
273
274 unsigned Prev = Index;
David Blaikiedb3d31d2015-06-22 22:06:37 +0000275 Arg *A = ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000276 assert(Index > Prev && "Parser failed to consume argument.");
277
278 // Check for missing argument error.
279 if (!A) {
280 assert(Index >= End && "Unexpected parser error.");
281 assert(Index - Prev - 1 && "No missing arguments!");
282 MissingArgIndex = Prev;
283 MissingArgCount = Index - Prev - 1;
284 break;
285 }
286
David Blaikiedb3d31d2015-06-22 22:06:37 +0000287 Args.append(A);
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000288 }
289
Logan Chien9d5891f2015-06-22 23:16:02 +0000290 return Args;
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000291}
292
293static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
294 const Option O = Opts.getOption(Id);
295 std::string Name = O.getPrefixedName();
296
297 // Add metavar, if used.
298 switch (O.getKind()) {
299 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
300 llvm_unreachable("Invalid option with help text.");
301
302 case Option::MultiArgClass:
Nick Kledzikbcd6e2a2014-08-15 21:35:07 +0000303 if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
304 // For MultiArgs, metavar is full list of all argument names.
305 Name += ' ';
306 Name += MetaVarName;
307 }
308 else {
309 // For MultiArgs<N>, if metavar not supplied, print <value> N times.
310 for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
311 Name += " <value>";
312 }
313 }
314 break;
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000315
316 case Option::FlagClass:
317 break;
318
319 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
Hans Wennborgd505fbf2013-08-13 21:09:50 +0000320 case Option::RemainingArgsClass:
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000321 Name += ' ';
322 // FALLTHROUGH
323 case Option::JoinedClass: case Option::CommaJoinedClass:
324 case Option::JoinedAndSeparateClass:
325 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
326 Name += MetaVarName;
327 else
328 Name += "<value>";
329 break;
330 }
331
332 return Name;
333}
334
335static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
336 std::vector<std::pair<std::string,
337 const char*> > &OptionHelp) {
338 OS << Title << ":\n";
339
340 // Find the maximum option length.
341 unsigned OptionFieldWidth = 0;
342 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
343 // Skip titles.
344 if (!OptionHelp[i].second)
345 continue;
346
347 // Limit the amount of padding we are willing to give up for alignment.
348 unsigned Length = OptionHelp[i].first.size();
349 if (Length <= 23)
350 OptionFieldWidth = std::max(OptionFieldWidth, Length);
351 }
352
353 const unsigned InitialPad = 2;
354 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
355 const std::string &Option = OptionHelp[i].first;
356 int Pad = OptionFieldWidth - int(Option.size());
357 OS.indent(InitialPad) << Option;
358
359 // Break on long option names.
360 if (Pad < 0) {
361 OS << "\n";
362 Pad = OptionFieldWidth + InitialPad;
363 }
364 OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
365 }
366}
367
368static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
369 unsigned GroupID = Opts.getOptionGroupID(Id);
370
371 // If not in a group, return the default help group.
372 if (!GroupID)
373 return "OPTIONS";
374
375 // Abuse the help text of the option groups to store the "help group"
376 // name.
377 //
378 // FIXME: Split out option groups.
379 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
380 return GroupHelp;
381
382 // Otherwise keep looking.
383 return getOptionHelpGroup(Opts, GroupID);
384}
385
Reid Kleckner12e03322013-06-13 18:12:12 +0000386void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
387 bool ShowHidden) const {
388 PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
389 (ShowHidden ? 0 : HelpHidden));
390}
391
392
393void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
394 unsigned FlagsToInclude,
395 unsigned FlagsToExclude) const {
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000396 OS << "OVERVIEW: " << Title << "\n";
397 OS << '\n';
398 OS << "USAGE: " << Name << " [options] <inputs>\n";
399 OS << '\n';
400
401 // Render help text into a map of group-name to a list of (option, help)
402 // pairs.
403 typedef std::map<std::string,
404 std::vector<std::pair<std::string, const char*> > > helpmap_ty;
405 helpmap_ty GroupedOptionHelp;
406
407 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
408 unsigned Id = i + 1;
409
410 // FIXME: Split out option groups.
411 if (getOptionKind(Id) == Option::GroupClass)
412 continue;
413
Reid Kleckner12e03322013-06-13 18:12:12 +0000414 unsigned Flags = getInfo(Id).Flags;
415 if (FlagsToInclude && !(Flags & FlagsToInclude))
416 continue;
417 if (Flags & FlagsToExclude)
Michael J. Spencer41ee0412012-12-05 00:29:32 +0000418 continue;
419
420 if (const char *Text = getOptionHelpText(Id)) {
421 const char *HelpGroup = getOptionHelpGroup(*this, Id);
422 const std::string &OptName = getOptionHelpName(*this, Id);
423 GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
424 }
425 }
426
427 for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
428 ie = GroupedOptionHelp.end(); it != ie; ++it) {
429 if (it != GroupedOptionHelp .begin())
430 OS << "\n";
431 PrintHelpOptionList(OS, it->first, it->second);
432 }
433
434 OS.flush();
435}