78c5ea2c4419bcf0e80ba2d862e6eb5aee97c7b3
[oota-llvm.git] / lib / Option / OptTable.cpp
1 //===--- 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"
11 #include "llvm/Option/Arg.h"
12 #include "llvm/Option/ArgList.h"
13 #include "llvm/Option/Option.h"
14 #include "llvm/Support/ErrorHandling.h"
15 #include "llvm/Support/raw_ostream.h"
16 #include <algorithm>
17 #include <cctype>
18 #include <map>
19
20 using namespace llvm;
21 using namespace llvm::opt;
22
23 namespace llvm {
24 namespace opt {
25
26 // 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).
29 static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) {
30   const char *X = A, *Y = B;
31   char a = tolower(*A), b = tolower(*B);
32   while (a == b) {
33     if (a == '\0')
34       return 0;
35
36     a = tolower(*++X);
37     b = tolower(*++Y);
38   }
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;
47 }
48
49 #ifndef NDEBUG
50 static 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
56 static 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;
65                           *APre != 0 && *BPre != 0; ++APre, ++BPre) {
66     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
78 // Support lower_bound between info and an option name.
79 static inline bool operator<(const OptTable::Info &I, const char *Name) {
80   return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
81 }
82 }
83 }
84
85 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
86
87 OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos,
88                    bool _IgnoreCase)
89   : OptionInfos(_OptionInfos),
90     NumOptionInfos(_NumOptionInfos),
91     IgnoreCase(_IgnoreCase),
92     TheInputOptionID(0),
93     TheUnknownOptionID(0),
94     FirstSearchableIndex(0)
95 {
96   // Explicitly zero initialize the error to work around a bug in array
97   // value-initialization on MinGW with gcc 4.3.5.
98
99   // Find start of normal options.
100   for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
101     unsigned Kind = getInfo(i + 1).Kind;
102     if (Kind == Option::InputClass) {
103       assert(!TheInputOptionID && "Cannot have multiple input options!");
104       TheInputOptionID = getInfo(i + 1).ID;
105     } else if (Kind == Option::UnknownClass) {
106       assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
107       TheUnknownOptionID = getInfo(i + 1).ID;
108     } else if (Kind != Option::GroupClass) {
109       FirstSearchableIndex = i;
110       break;
111     }
112   }
113   assert(FirstSearchableIndex != 0 && "No searchable options?");
114
115 #ifndef NDEBUG
116   // Check that everything after the first searchable option is a
117   // regular option class.
118   for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
119     Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
120     assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
121             Kind != Option::GroupClass) &&
122            "Special options should be defined first!");
123   }
124
125   // Check that options are in order.
126   for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
127     if (!(getInfo(i) < getInfo(i + 1))) {
128       getOption(i).dump();
129       getOption(i + 1).dump();
130       llvm_unreachable("Options are not in order!");
131     }
132   }
133 #endif
134
135   // Build prefixes.
136   for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
137                 i != e; ++i) {
138     if (const char *const *P = getInfo(i).Prefixes) {
139       for (; *P != 0; ++P) {
140         PrefixesUnion.insert(*P);
141       }
142     }
143   }
144
145   // Build prefix chars.
146   for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(),
147                                          E = PrefixesUnion.end(); I != E; ++I) {
148     StringRef Prefix = I->getKey();
149     for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
150                                    C != CE; ++C)
151       if (std::find(PrefixChars.begin(), PrefixChars.end(), *C)
152             == PrefixChars.end())
153         PrefixChars.push_back(*C);
154   }
155 }
156
157 OptTable::~OptTable() {
158 }
159
160 const Option OptTable::getOption(OptSpecifier Opt) const {
161   unsigned id = Opt.getID();
162   if (id == 0)
163     return Option(0, 0);
164   assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
165   return Option(&getInfo(id), this);
166 }
167
168 static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
169   if (Arg == "-")
170     return true;
171   for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
172                                          E = Prefixes.end(); I != E; ++I)
173     if (Arg.startswith(I->getKey()))
174       return false;
175   return true;
176 }
177
178 // Returns true if X starts with Y, ignoring case.
179 static bool startsWithIgnoreCase(StringRef X, StringRef Y) {
180   if (X.size() < Y.size())
181     return false;
182   return X.substr(0, Y.size()).equals_lower(Y);
183 }
184
185 /// \returns Matched size. 0 means no match.
186 static unsigned matchOption(const OptTable::Info *I, StringRef Str,
187                             bool IgnoreCase) {
188   for (const char * const *Pre = I->Prefixes; *Pre != 0; ++Pre) {
189     StringRef Prefix(*Pre);
190     if (Str.startswith(Prefix)) {
191       StringRef Rest = Str.substr(Prefix.size());
192       bool Matched = IgnoreCase
193           ? startsWithIgnoreCase(Rest, I->Name)
194           : Rest.startswith(I->Name);
195       if (Matched)
196         return Prefix.size() + StringRef(I->Name).size();
197     }
198   }
199   return 0;
200 }
201
202 Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
203                            unsigned FlagsToInclude,
204                            unsigned FlagsToExclude) const {
205   unsigned Prev = Index;
206   const char *Str = Args.getArgString(Index);
207
208   // Anything that doesn't start with PrefixesUnion is an input, as is '-'
209   // itself.
210   if (isInput(PrefixesUnion, Str))
211     return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
212
213   const Info *Start = OptionInfos + FirstSearchableIndex;
214   const Info *End = OptionInfos + getNumOptions();
215   StringRef Name = StringRef(Str).ltrim(PrefixChars);
216
217   // Search for the first next option which could be a prefix.
218   Start = std::lower_bound(Start, End, Name.data());
219
220   // Options are stored in sorted order, with '\0' at the end of the
221   // alphabet. Since the only options which can accept a string must
222   // prefix it, we iteratively search for the next option which could
223   // be a prefix.
224   //
225   // FIXME: This is searching much more than necessary, but I am
226   // blanking on the simplest way to make it fast. We can solve this
227   // problem when we move to TableGen.
228   for (; Start != End; ++Start) {
229     unsigned ArgSize = 0;
230     // Scan for first option which is a proper prefix.
231     for (; Start != End; ++Start)
232       if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
233         break;
234     if (Start == End)
235       break;
236
237     Option Opt(Start, this);
238
239     if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
240       continue;
241     if (Opt.hasFlag(FlagsToExclude))
242       continue;
243
244     // See if this option matches.
245     if (Arg *A = Opt.accept(Args, Index, ArgSize))
246       return A;
247
248     // Otherwise, see if this argument was missing values.
249     if (Prev != Index)
250       return 0;
251   }
252
253   // If we failed to find an option and this arg started with /, then it's
254   // probably an input path.
255   if (Str[0] == '/')
256     return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
257
258   return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
259 }
260
261 InputArgList *OptTable::ParseArgs(const char *const *ArgBegin,
262                                   const char *const *ArgEnd,
263                                   unsigned &MissingArgIndex,
264                                   unsigned &MissingArgCount,
265                                   unsigned FlagsToInclude,
266                                   unsigned FlagsToExclude) const {
267   InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
268
269   // FIXME: Handle '@' args (or at least error on them).
270
271   MissingArgIndex = MissingArgCount = 0;
272   unsigned Index = 0, End = ArgEnd - ArgBegin;
273   while (Index < End) {
274     // Ignore empty arguments (other things may still take them as arguments).
275     StringRef Str = Args->getArgString(Index);
276     if (Str == "") {
277       ++Index;
278       continue;
279     }
280
281     unsigned Prev = Index;
282     Arg *A = ParseOneArg(*Args, Index, FlagsToInclude, FlagsToExclude);
283     assert(Index > Prev && "Parser failed to consume argument.");
284
285     // Check for missing argument error.
286     if (!A) {
287       assert(Index >= End && "Unexpected parser error.");
288       assert(Index - Prev - 1 && "No missing arguments!");
289       MissingArgIndex = Prev;
290       MissingArgCount = Index - Prev - 1;
291       break;
292     }
293
294     Args->append(A);
295   }
296
297   return Args;
298 }
299
300 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
301   const Option O = Opts.getOption(Id);
302   std::string Name = O.getPrefixedName();
303
304   // Add metavar, if used.
305   switch (O.getKind()) {
306   case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
307     llvm_unreachable("Invalid option with help text.");
308
309   case Option::MultiArgClass:
310     llvm_unreachable("Cannot print metavar for this kind of option.");
311
312   case Option::FlagClass:
313     break;
314
315   case Option::SeparateClass: case Option::JoinedOrSeparateClass:
316   case Option::RemainingArgsClass:
317     Name += ' ';
318     // FALLTHROUGH
319   case Option::JoinedClass: case Option::CommaJoinedClass:
320   case Option::JoinedAndSeparateClass:
321     if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
322       Name += MetaVarName;
323     else
324       Name += "<value>";
325     break;
326   }
327
328   return Name;
329 }
330
331 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
332                                 std::vector<std::pair<std::string,
333                                 const char*> > &OptionHelp) {
334   OS << Title << ":\n";
335
336   // Find the maximum option length.
337   unsigned OptionFieldWidth = 0;
338   for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
339     // Skip titles.
340     if (!OptionHelp[i].second)
341       continue;
342
343     // Limit the amount of padding we are willing to give up for alignment.
344     unsigned Length = OptionHelp[i].first.size();
345     if (Length <= 23)
346       OptionFieldWidth = std::max(OptionFieldWidth, Length);
347   }
348
349   const unsigned InitialPad = 2;
350   for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
351     const std::string &Option = OptionHelp[i].first;
352     int Pad = OptionFieldWidth - int(Option.size());
353     OS.indent(InitialPad) << Option;
354
355     // Break on long option names.
356     if (Pad < 0) {
357       OS << "\n";
358       Pad = OptionFieldWidth + InitialPad;
359     }
360     OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
361   }
362 }
363
364 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
365   unsigned GroupID = Opts.getOptionGroupID(Id);
366
367   // If not in a group, return the default help group.
368   if (!GroupID)
369     return "OPTIONS";
370
371   // Abuse the help text of the option groups to store the "help group"
372   // name.
373   //
374   // FIXME: Split out option groups.
375   if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
376     return GroupHelp;
377
378   // Otherwise keep looking.
379   return getOptionHelpGroup(Opts, GroupID);
380 }
381
382 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
383                          bool ShowHidden) const {
384   PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
385             (ShowHidden ? 0 : HelpHidden));
386 }
387
388
389 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
390                          unsigned FlagsToInclude,
391                          unsigned FlagsToExclude) const {
392   OS << "OVERVIEW: " << Title << "\n";
393   OS << '\n';
394   OS << "USAGE: " << Name << " [options] <inputs>\n";
395   OS << '\n';
396
397   // Render help text into a map of group-name to a list of (option, help)
398   // pairs.
399   typedef std::map<std::string,
400                  std::vector<std::pair<std::string, const char*> > > helpmap_ty;
401   helpmap_ty GroupedOptionHelp;
402
403   for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
404     unsigned Id = i + 1;
405
406     // FIXME: Split out option groups.
407     if (getOptionKind(Id) == Option::GroupClass)
408       continue;
409
410     unsigned Flags = getInfo(Id).Flags;
411     if (FlagsToInclude && !(Flags & FlagsToInclude))
412       continue;
413     if (Flags & FlagsToExclude)
414       continue;
415
416     if (const char *Text = getOptionHelpText(Id)) {
417       const char *HelpGroup = getOptionHelpGroup(*this, Id);
418       const std::string &OptName = getOptionHelpName(*this, Id);
419       GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
420     }
421   }
422
423   for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
424          ie = GroupedOptionHelp.end(); it != ie; ++it) {
425     if (it != GroupedOptionHelp .begin())
426       OS << "\n";
427     PrintHelpOptionList(OS, it->first, it->second);
428   }
429
430   OS.flush();
431 }