]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/OptTable.cpp
Merge OpenBSM 1.2-alpha2 from vendor branch to FreeBSD 10-CURRENT; the
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Driver / 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 "clang/Driver/OptTable.h"
11 #include "clang/Driver/Arg.h"
12 #include "clang/Driver/ArgList.h"
13 #include "clang/Driver/Option.h"
14 #include "llvm/Support/raw_ostream.h"
15 #include "llvm/Support/ErrorHandling.h"
16 #include <algorithm>
17 #include <map>
18 using namespace clang::driver;
19 using namespace clang::driver::options;
20 using namespace clang;
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
29 static 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
48 namespace clang {
49 namespace driver {
50 static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
51   if (&A == &B)
52     return false;
53
54   if (int N = StrCmpOptionName(A.Name, B.Name))
55     return N == -1;
56
57   // Names are the same, check that classes are in order; exactly one
58   // should be joined, and it should succeed the other.
59   assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
60          "Unexpected classes for options with same name.");
61   return B.Kind == Option::JoinedClass;
62 }
63
64 // Support lower_bound between info and an option name.
65 static inline bool operator<(const OptTable::Info &I, const char *Name) {
66   return StrCmpOptionName(I.Name, Name) == -1;
67 }
68 static inline bool operator<(const char *Name, const OptTable::Info &I) {
69   return StrCmpOptionName(Name, I.Name) == -1;
70 }
71 }
72 }
73
74 //
75
76 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
77
78 //
79
80 OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos)
81   : OptionInfos(_OptionInfos), NumOptionInfos(_NumOptionInfos),
82     Options(new Option*[NumOptionInfos]),
83     TheInputOption(0), TheUnknownOption(0), FirstSearchableIndex(0)
84 {
85   // Explicitly zero initialize the error to work around a bug in array
86   // value-initialization on MinGW with gcc 4.3.5.
87   memset(Options, 0, sizeof(*Options) * NumOptionInfos);
88
89   // Find start of normal options.
90   for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
91     unsigned Kind = getInfo(i + 1).Kind;
92     if (Kind == Option::InputClass) {
93       assert(!TheInputOption && "Cannot have multiple input options!");
94       TheInputOption = getOption(i + 1);
95     } else if (Kind == Option::UnknownClass) {
96       assert(!TheUnknownOption && "Cannot have multiple input options!");
97       TheUnknownOption = getOption(i + 1);
98     } else if (Kind != Option::GroupClass) {
99       FirstSearchableIndex = i;
100       break;
101     }
102   }
103   assert(FirstSearchableIndex != 0 && "No searchable options?");
104
105 #ifndef NDEBUG
106   // Check that everything after the first searchable option is a
107   // regular option class.
108   for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
109     Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
110     assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
111             Kind != Option::GroupClass) &&
112            "Special options should be defined first!");
113   }
114
115   // Check that options are in order.
116   for (unsigned i = FirstSearchableIndex+1, e = getNumOptions(); i != e; ++i) {
117     if (!(getInfo(i) < getInfo(i + 1))) {
118       getOption(i)->dump();
119       getOption(i + 1)->dump();
120       llvm_unreachable("Options are not in order!");
121     }
122   }
123 #endif
124 }
125
126 OptTable::~OptTable() {
127   for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
128     delete Options[i];
129   delete[] Options;
130 }
131
132 Option *OptTable::CreateOption(unsigned id) const {
133   const Info &info = getInfo(id);
134   const OptionGroup *Group =
135     cast_or_null<OptionGroup>(getOption(info.GroupID));
136   const Option *Alias = getOption(info.AliasID);
137
138   Option *Opt = 0;
139   switch (info.Kind) {
140   case Option::InputClass:
141     Opt = new InputOption(id); break;
142   case Option::UnknownClass:
143     Opt = new UnknownOption(id); break;
144   case Option::GroupClass:
145     Opt = new OptionGroup(id, info.Name, Group); break;
146   case Option::FlagClass:
147     Opt = new FlagOption(id, info.Name, Group, Alias); break;
148   case Option::JoinedClass:
149     Opt = new JoinedOption(id, info.Name, Group, Alias); break;
150   case Option::SeparateClass:
151     Opt = new SeparateOption(id, info.Name, Group, Alias); break;
152   case Option::CommaJoinedClass:
153     Opt = new CommaJoinedOption(id, info.Name, Group, Alias); break;
154   case Option::MultiArgClass:
155     Opt = new MultiArgOption(id, info.Name, Group, Alias, info.Param); break;
156   case Option::JoinedOrSeparateClass:
157     Opt = new JoinedOrSeparateOption(id, info.Name, Group, Alias); break;
158   case Option::JoinedAndSeparateClass:
159     Opt = new JoinedAndSeparateOption(id, info.Name, Group, Alias); break;
160   }
161
162   if (info.Flags & DriverOption)
163     Opt->setDriverOption(true);
164   if (info.Flags & LinkerInput)
165     Opt->setLinkerInput(true);
166   if (info.Flags & NoArgumentUnused)
167     Opt->setNoArgumentUnused(true);
168   if (info.Flags & NoForward)
169     Opt->setNoForward(true);
170   if (info.Flags & RenderAsInput)
171     Opt->setNoOptAsInput(true);
172   if (info.Flags & RenderJoined) {
173     assert((info.Kind == Option::JoinedOrSeparateClass ||
174             info.Kind == Option::SeparateClass) && "Invalid option.");
175     Opt->setRenderStyle(Option::RenderJoinedStyle);
176   }
177   if (info.Flags & RenderSeparate) {
178     assert((info.Kind == Option::JoinedOrSeparateClass ||
179             info.Kind == Option::JoinedClass) && "Invalid option.");
180     Opt->setRenderStyle(Option::RenderSeparateStyle);
181   }
182   if (info.Flags & Unsupported)
183     Opt->setUnsupported(true);
184   if (info.Flags & CC1Option)
185     Opt->setIsCC1Option(true);
186
187   return Opt;
188 }
189
190 Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index) const {
191   unsigned Prev = Index;
192   const char *Str = Args.getArgString(Index);
193
194   // Anything that doesn't start with '-' is an input, as is '-' itself.
195   if (Str[0] != '-' || Str[1] == '\0')
196     return new Arg(TheInputOption, Index++, Str);
197
198   const Info *Start = OptionInfos + FirstSearchableIndex;
199   const Info *End = OptionInfos + getNumOptions();
200
201   // Search for the first next option which could be a prefix.
202   Start = std::lower_bound(Start, End, Str);
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     // Scan for first option which is a proper prefix.
214     for (; Start != End; ++Start)
215       if (memcmp(Str, Start->Name, strlen(Start->Name)) == 0)
216         break;
217     if (Start == End)
218       break;
219
220     // See if this option matches.
221     if (Arg *A = getOption(Start - OptionInfos + 1)->accept(Args, Index))
222       return A;
223
224     // Otherwise, see if this argument was missing values.
225     if (Prev != Index)
226       return 0;
227   }
228
229   return new Arg(TheUnknownOption, Index++, Str);
230 }
231
232 InputArgList *OptTable::ParseArgs(const char* const *ArgBegin,
233                                   const char* const *ArgEnd,
234                                   unsigned &MissingArgIndex,
235                                   unsigned &MissingArgCount) const {
236   InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
237
238   // FIXME: Handle '@' args (or at least error on them).
239
240   MissingArgIndex = MissingArgCount = 0;
241   unsigned Index = 0, End = ArgEnd - ArgBegin;
242   while (Index < End) {
243     // Ignore empty arguments (other things may still take them as arguments).
244     if (Args->getArgString(Index)[0] == '\0') {
245       ++Index;
246       continue;
247     }
248
249     unsigned Prev = Index;
250     Arg *A = ParseOneArg(*Args, Index);
251     assert(Index > Prev && "Parser failed to consume argument.");
252
253     // Check for missing argument error.
254     if (!A) {
255       assert(Index >= End && "Unexpected parser error.");
256       assert(Index - Prev - 1 && "No missing arguments!");
257       MissingArgIndex = Prev;
258       MissingArgCount = Index - Prev - 1;
259       break;
260     }
261
262     Args->append(A);
263   }
264
265   return Args;
266 }
267
268 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
269   std::string Name = Opts.getOptionName(Id);
270
271   // Add metavar, if used.
272   switch (Opts.getOptionKind(Id)) {
273   case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
274     llvm_unreachable("Invalid option with help text.");
275
276   case Option::MultiArgClass:
277     llvm_unreachable("Cannot print metavar for this kind of option.");
278
279   case Option::FlagClass:
280     break;
281
282   case Option::SeparateClass: case Option::JoinedOrSeparateClass:
283     Name += ' ';
284     // FALLTHROUGH
285   case Option::JoinedClass: case Option::CommaJoinedClass:
286   case Option::JoinedAndSeparateClass:
287     if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
288       Name += MetaVarName;
289     else
290       Name += "<value>";
291     break;
292   }
293
294   return Name;
295 }
296
297 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
298                                 std::vector<std::pair<std::string,
299                                 const char*> > &OptionHelp) {
300   OS << Title << ":\n";
301
302   // Find the maximum option length.
303   unsigned OptionFieldWidth = 0;
304   for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
305     // Skip titles.
306     if (!OptionHelp[i].second)
307       continue;
308
309     // Limit the amount of padding we are willing to give up for alignment.
310     unsigned Length = OptionHelp[i].first.size();
311     if (Length <= 23)
312       OptionFieldWidth = std::max(OptionFieldWidth, Length);
313   }
314
315   const unsigned InitialPad = 2;
316   for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
317     const std::string &Option = OptionHelp[i].first;
318     int Pad = OptionFieldWidth - int(Option.size());
319     OS.indent(InitialPad) << Option;
320
321     // Break on long option names.
322     if (Pad < 0) {
323       OS << "\n";
324       Pad = OptionFieldWidth + InitialPad;
325     }
326     OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
327   }
328 }
329
330 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
331   unsigned GroupID = Opts.getOptionGroupID(Id);
332
333   // If not in a group, return the default help group.
334   if (!GroupID)
335     return "OPTIONS";
336
337   // Abuse the help text of the option groups to store the "help group"
338   // name.
339   //
340   // FIXME: Split out option groups.
341   if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
342     return GroupHelp;
343
344   // Otherwise keep looking.
345   return getOptionHelpGroup(Opts, GroupID);
346 }
347
348 void OptTable::PrintHelp(raw_ostream &OS, const char *Name,
349                          const char *Title, bool ShowHidden) const {
350   OS << "OVERVIEW: " << Title << "\n";
351   OS << '\n';
352   OS << "USAGE: " << Name << " [options] <inputs>\n";
353   OS << '\n';
354
355   // Render help text into a map of group-name to a list of (option, help)
356   // pairs.
357   typedef std::map<std::string,
358                  std::vector<std::pair<std::string, const char*> > > helpmap_ty;
359   helpmap_ty GroupedOptionHelp;
360
361   for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
362     unsigned Id = i + 1;
363
364     // FIXME: Split out option groups.
365     if (getOptionKind(Id) == Option::GroupClass)
366       continue;
367
368     if (!ShowHidden && isOptionHelpHidden(Id))
369       continue;
370
371     if (const char *Text = getOptionHelpText(Id)) {
372       const char *HelpGroup = getOptionHelpGroup(*this, Id);
373       const std::string &OptName = getOptionHelpName(*this, Id);
374       GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
375     }
376   }
377
378   for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
379          ie = GroupedOptionHelp.end(); it != ie; ++it) {
380     if (it != GroupedOptionHelp .begin())
381       OS << "\n";
382     PrintHelpOptionList(OS, it->first, it->second);
383   }
384
385   OS.flush();
386 }