Handle non-default array bounds.
[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
12 #include "llvm/Option/Arg.h"
13 #include "llvm/Option/ArgList.h"
14 #include "llvm/Option/Option.h"
15 #include "llvm/Support/raw_ostream.h"
16 #include "llvm/Support/ErrorHandling.h"
17 #include <algorithm>
18 #include <map>
19
20 using namespace llvm;
21 using namespace llvm::opt;
22
23 // Ordering on Info. The ordering is *almost* lexicographic, with two
24 // exceptions. First, '\0' comes at the end of the alphabet instead of
25 // the beginning (thus options precede any other options which prefix
26 // them). Second, for options with the same name, the less permissive
27 // version should come first; a Flag option should precede a Joined
28 // option, for example.
29
30 static int StrCmpOptionName(const char *A, const char *B) {
31   char a = *A, b = *B;
32   while (a == b) {
33     if (a == '\0')
34       return 0;
35
36     a = *++A;
37     b = *++B;
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 namespace llvm {
50 namespace opt {
51
52 static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
53   if (&A == &B)
54     return false;
55
56   if (int N = StrCmpOptionName(A.Name, B.Name))
57     return N == -1;
58
59   for (const char * const *APre = A.Prefixes,
60                   * const *BPre = B.Prefixes;
61                           *APre != 0 && *BPre != 0; ++APre, ++BPre) {
62     if (int N = StrCmpOptionName(*APre, *BPre))
63       return N == -1;
64   }
65
66   // Names are the same, check that classes are in order; exactly one
67   // should be joined, and it should succeed the other.
68   assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
69          "Unexpected classes for options with same name.");
70   return B.Kind == Option::JoinedClass;
71 }
72
73 // Support lower_bound between info and an option name.
74 static inline bool operator<(const OptTable::Info &I, const char *Name) {
75   return StrCmpOptionName(I.Name, Name) == -1;
76 }
77 static inline bool operator<(const char *Name, const OptTable::Info &I) {
78   return StrCmpOptionName(Name, I.Name) == -1;
79 }
80 }
81 }
82
83 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
84
85 OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos)
86   : OptionInfos(_OptionInfos),
87     NumOptionInfos(_NumOptionInfos),
88     TheInputOptionID(0),
89     TheUnknownOptionID(0),
90     FirstSearchableIndex(0)
91 {
92   // 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) {
135       for (; *P != 0; ++P) {
136         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
153 OptTable::~OptTable() {
154 }
155
156 const Option OptTable::getOption(OptSpecifier Opt) const {
157   unsigned id = Opt.getID();
158   if (id == 0)
159     return Option(0, 0);
160   assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
161   return Option(&getInfo(id), this);
162 }
163
164 bool OptTable::isOptionHelpHidden(OptSpecifier id) const {
165   return getInfo(id).Flags & HelpHidden;
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 Matched size. 0 means no match.
179 static unsigned matchOption(const OptTable::Info *I, StringRef Str) {
180   for (const char * const *Pre = I->Prefixes; *Pre != 0; ++Pre) {
181     StringRef Prefix(*Pre);
182     if (Str.startswith(Prefix) && Str.substr(Prefix.size()).startswith(I->Name))
183       return Prefix.size() + StringRef(I->Name).size();
184   }
185   return 0;
186 }
187
188 Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index) const {
189   unsigned Prev = Index;
190   const char *Str = Args.getArgString(Index);
191
192   // Anything that doesn't start with PrefixesUnion is an input, as is '-'
193   // itself.
194   if (isInput(PrefixesUnion, Str))
195     return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
196
197   const Info *Start = OptionInfos + FirstSearchableIndex;
198   const Info *End = OptionInfos + getNumOptions();
199   StringRef Name = StringRef(Str).ltrim(PrefixChars);
200
201   // Search for the first next option which could be a prefix.
202   Start = std::lower_bound(Start, End, Name.data());
203
204   // Options are stored in sorted order, with '\0' at the end of the
205   // alphabet. Since the only options which can accept a string must
206   // prefix it, we iteratively search for the next option which could
207   // be a prefix.
208   //
209   // FIXME: This is searching much more than necessary, but I am
210   // blanking on the simplest way to make it fast. We can solve this
211   // problem when we move to TableGen.
212   for (; Start != End; ++Start) {
213     unsigned ArgSize = 0;
214     // Scan for first option which is a proper prefix.
215     for (; Start != End; ++Start)
216       if ((ArgSize = matchOption(Start, Str)))
217         break;
218     if (Start == End)
219       break;
220
221     // See if this option matches.
222     if (Arg *A = Option(Start, this).accept(Args, Index, ArgSize))
223       return A;
224
225     // Otherwise, see if this argument was missing values.
226     if (Prev != Index)
227       return 0;
228   }
229
230   return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
231 }
232
233 InputArgList *OptTable::ParseArgs(const char* const *ArgBegin,
234                                   const char* const *ArgEnd,
235                                   unsigned &MissingArgIndex,
236                                   unsigned &MissingArgCount) const {
237   InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
238
239   // FIXME: Handle '@' args (or at least error on them).
240
241   MissingArgIndex = MissingArgCount = 0;
242   unsigned Index = 0, End = ArgEnd - ArgBegin;
243   while (Index < End) {
244     // Ignore empty arguments (other things may still take them as arguments).
245     if (Args->getArgString(Index)[0] == '\0') {
246       ++Index;
247       continue;
248     }
249
250     unsigned Prev = Index;
251     Arg *A = ParseOneArg(*Args, Index);
252     assert(Index > Prev && "Parser failed to consume argument.");
253
254     // Check for missing argument error.
255     if (!A) {
256       assert(Index >= End && "Unexpected parser error.");
257       assert(Index - Prev - 1 && "No missing arguments!");
258       MissingArgIndex = Prev;
259       MissingArgCount = Index - Prev - 1;
260       break;
261     }
262
263     Args->append(A);
264   }
265
266   return Args;
267 }
268
269 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
270   const Option O = Opts.getOption(Id);
271   std::string Name = O.getPrefixedName();
272
273   // Add metavar, if used.
274   switch (O.getKind()) {
275   case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
276     llvm_unreachable("Invalid option with help text.");
277
278   case Option::MultiArgClass:
279     llvm_unreachable("Cannot print metavar for this kind of option.");
280
281   case Option::FlagClass:
282     break;
283
284   case Option::SeparateClass: case Option::JoinedOrSeparateClass:
285     Name += ' ';
286     // FALLTHROUGH
287   case Option::JoinedClass: case Option::CommaJoinedClass:
288   case Option::JoinedAndSeparateClass:
289     if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
290       Name += MetaVarName;
291     else
292       Name += "<value>";
293     break;
294   }
295
296   return Name;
297 }
298
299 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
300                                 std::vector<std::pair<std::string,
301                                 const char*> > &OptionHelp) {
302   OS << Title << ":\n";
303
304   // Find the maximum option length.
305   unsigned OptionFieldWidth = 0;
306   for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
307     // Skip titles.
308     if (!OptionHelp[i].second)
309       continue;
310
311     // Limit the amount of padding we are willing to give up for alignment.
312     unsigned Length = OptionHelp[i].first.size();
313     if (Length <= 23)
314       OptionFieldWidth = std::max(OptionFieldWidth, Length);
315   }
316
317   const unsigned InitialPad = 2;
318   for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
319     const std::string &Option = OptionHelp[i].first;
320     int Pad = OptionFieldWidth - int(Option.size());
321     OS.indent(InitialPad) << Option;
322
323     // Break on long option names.
324     if (Pad < 0) {
325       OS << "\n";
326       Pad = OptionFieldWidth + InitialPad;
327     }
328     OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
329   }
330 }
331
332 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
333   unsigned GroupID = Opts.getOptionGroupID(Id);
334
335   // If not in a group, return the default help group.
336   if (!GroupID)
337     return "OPTIONS";
338
339   // Abuse the help text of the option groups to store the "help group"
340   // name.
341   //
342   // FIXME: Split out option groups.
343   if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
344     return GroupHelp;
345
346   // Otherwise keep looking.
347   return getOptionHelpGroup(Opts, GroupID);
348 }
349
350 void OptTable::PrintHelp(raw_ostream &OS, const char *Name,
351                          const char *Title, bool ShowHidden) const {
352   OS << "OVERVIEW: " << Title << "\n";
353   OS << '\n';
354   OS << "USAGE: " << Name << " [options] <inputs>\n";
355   OS << '\n';
356
357   // Render help text into a map of group-name to a list of (option, help)
358   // pairs.
359   typedef std::map<std::string,
360                  std::vector<std::pair<std::string, const char*> > > helpmap_ty;
361   helpmap_ty GroupedOptionHelp;
362
363   for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
364     unsigned Id = i + 1;
365
366     // FIXME: Split out option groups.
367     if (getOptionKind(Id) == Option::GroupClass)
368       continue;
369
370     if (!ShowHidden && isOptionHelpHidden(Id))
371       continue;
372
373     if (const char *Text = getOptionHelpText(Id)) {
374       const char *HelpGroup = getOptionHelpGroup(*this, Id);
375       const std::string &OptName = getOptionHelpName(*this, Id);
376       GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
377     }
378   }
379
380   for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
381          ie = GroupedOptionHelp.end(); it != ie; ++it) {
382     if (it != GroupedOptionHelp .begin())
383       OS << "\n";
384     PrintHelpOptionList(OS, it->first, it->second);
385   }
386
387   OS.flush();
388 }