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