• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
StrCmpOptionName(const char * A,const char * B)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 {
operator <(const OptTable::Info & A,const OptTable::Info & B)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.
operator <(const OptTable::Info & I,const char * Name)65 static inline bool operator<(const OptTable::Info &I, const char *Name) {
66   return StrCmpOptionName(I.Name, Name) == -1;
67 }
operator <(const char * Name,const OptTable::Info & I)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 
OptSpecifier(const Option * Opt)76 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
77 
78 //
79 
OptTable(const Info * _OptionInfos,unsigned _NumOptionInfos)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 
~OptTable()126 OptTable::~OptTable() {
127   for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
128     delete Options[i];
129   delete[] Options;
130 }
131 
isOptionHelpHidden(OptSpecifier id) const132 bool OptTable::isOptionHelpHidden(OptSpecifier id) const {
133   return getInfo(id).Flags & options::HelpHidden;
134 }
135 
CreateOption(unsigned id) const136 Option *OptTable::CreateOption(unsigned id) const {
137   const Info &info = getInfo(id);
138   const Option *Group = getOption(info.GroupID);
139   const Option *Alias = getOption(info.AliasID);
140 
141   Option *Opt = new Option(&info, id, Group, Alias);
142 
143   return Opt;
144 }
145 
ParseOneArg(const ArgList & Args,unsigned & Index) const146 Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index) const {
147   unsigned Prev = Index;
148   const char *Str = Args.getArgString(Index);
149 
150   // Anything that doesn't start with '-' is an input, as is '-' itself.
151   if (Str[0] != '-' || Str[1] == '\0')
152     return new Arg(TheInputOption, Index++, Str);
153 
154   const Info *Start = OptionInfos + FirstSearchableIndex;
155   const Info *End = OptionInfos + getNumOptions();
156 
157   // Search for the first next option which could be a prefix.
158   Start = std::lower_bound(Start, End, Str);
159 
160   // Options are stored in sorted order, with '\0' at the end of the
161   // alphabet. Since the only options which can accept a string must
162   // prefix it, we iteratively search for the next option which could
163   // be a prefix.
164   //
165   // FIXME: This is searching much more than necessary, but I am
166   // blanking on the simplest way to make it fast. We can solve this
167   // problem when we move to TableGen.
168   for (; Start != End; ++Start) {
169     // Scan for first option which is a proper prefix.
170     for (; Start != End; ++Start)
171       if (memcmp(Str, Start->Name, strlen(Start->Name)) == 0)
172         break;
173     if (Start == End)
174       break;
175 
176     // See if this option matches.
177     if (Arg *A = getOption(Start - OptionInfos + 1)->accept(Args, Index))
178       return A;
179 
180     // Otherwise, see if this argument was missing values.
181     if (Prev != Index)
182       return 0;
183   }
184 
185   return new Arg(TheUnknownOption, Index++, Str);
186 }
187 
ParseArgs(const char * const * ArgBegin,const char * const * ArgEnd,unsigned & MissingArgIndex,unsigned & MissingArgCount) const188 InputArgList *OptTable::ParseArgs(const char* const *ArgBegin,
189                                   const char* const *ArgEnd,
190                                   unsigned &MissingArgIndex,
191                                   unsigned &MissingArgCount) const {
192   InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
193 
194   // FIXME: Handle '@' args (or at least error on them).
195 
196   MissingArgIndex = MissingArgCount = 0;
197   unsigned Index = 0, End = ArgEnd - ArgBegin;
198   while (Index < End) {
199     // Ignore empty arguments (other things may still take them as arguments).
200     if (Args->getArgString(Index)[0] == '\0') {
201       ++Index;
202       continue;
203     }
204 
205     unsigned Prev = Index;
206     Arg *A = ParseOneArg(*Args, Index);
207     assert(Index > Prev && "Parser failed to consume argument.");
208 
209     // Check for missing argument error.
210     if (!A) {
211       assert(Index >= End && "Unexpected parser error.");
212       assert(Index - Prev - 1 && "No missing arguments!");
213       MissingArgIndex = Prev;
214       MissingArgCount = Index - Prev - 1;
215       break;
216     }
217 
218     Args->append(A);
219   }
220 
221   return Args;
222 }
223 
getOptionHelpName(const OptTable & Opts,OptSpecifier Id)224 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
225   std::string Name = Opts.getOptionName(Id);
226 
227   // Add metavar, if used.
228   switch (Opts.getOptionKind(Id)) {
229   case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
230     llvm_unreachable("Invalid option with help text.");
231 
232   case Option::MultiArgClass:
233     llvm_unreachable("Cannot print metavar for this kind of option.");
234 
235   case Option::FlagClass:
236     break;
237 
238   case Option::SeparateClass: case Option::JoinedOrSeparateClass:
239     Name += ' ';
240     // FALLTHROUGH
241   case Option::JoinedClass: case Option::CommaJoinedClass:
242   case Option::JoinedAndSeparateClass:
243     if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
244       Name += MetaVarName;
245     else
246       Name += "<value>";
247     break;
248   }
249 
250   return Name;
251 }
252 
PrintHelpOptionList(raw_ostream & OS,StringRef Title,std::vector<std::pair<std::string,const char * >> & OptionHelp)253 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
254                                 std::vector<std::pair<std::string,
255                                 const char*> > &OptionHelp) {
256   OS << Title << ":\n";
257 
258   // Find the maximum option length.
259   unsigned OptionFieldWidth = 0;
260   for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
261     // Skip titles.
262     if (!OptionHelp[i].second)
263       continue;
264 
265     // Limit the amount of padding we are willing to give up for alignment.
266     unsigned Length = OptionHelp[i].first.size();
267     if (Length <= 23)
268       OptionFieldWidth = std::max(OptionFieldWidth, Length);
269   }
270 
271   const unsigned InitialPad = 2;
272   for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
273     const std::string &Option = OptionHelp[i].first;
274     int Pad = OptionFieldWidth - int(Option.size());
275     OS.indent(InitialPad) << Option;
276 
277     // Break on long option names.
278     if (Pad < 0) {
279       OS << "\n";
280       Pad = OptionFieldWidth + InitialPad;
281     }
282     OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
283   }
284 }
285 
getOptionHelpGroup(const OptTable & Opts,OptSpecifier Id)286 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
287   unsigned GroupID = Opts.getOptionGroupID(Id);
288 
289   // If not in a group, return the default help group.
290   if (!GroupID)
291     return "OPTIONS";
292 
293   // Abuse the help text of the option groups to store the "help group"
294   // name.
295   //
296   // FIXME: Split out option groups.
297   if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
298     return GroupHelp;
299 
300   // Otherwise keep looking.
301   return getOptionHelpGroup(Opts, GroupID);
302 }
303 
PrintHelp(raw_ostream & OS,const char * Name,const char * Title,bool ShowHidden) const304 void OptTable::PrintHelp(raw_ostream &OS, const char *Name,
305                          const char *Title, bool ShowHidden) const {
306   OS << "OVERVIEW: " << Title << "\n";
307   OS << '\n';
308   OS << "USAGE: " << Name << " [options] <inputs>\n";
309   OS << '\n';
310 
311   // Render help text into a map of group-name to a list of (option, help)
312   // pairs.
313   typedef std::map<std::string,
314                  std::vector<std::pair<std::string, const char*> > > helpmap_ty;
315   helpmap_ty GroupedOptionHelp;
316 
317   for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
318     unsigned Id = i + 1;
319 
320     // FIXME: Split out option groups.
321     if (getOptionKind(Id) == Option::GroupClass)
322       continue;
323 
324     if (!ShowHidden && isOptionHelpHidden(Id))
325       continue;
326 
327     if (const char *Text = getOptionHelpText(Id)) {
328       const char *HelpGroup = getOptionHelpGroup(*this, Id);
329       const std::string &OptName = getOptionHelpName(*this, Id);
330       GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
331     }
332   }
333 
334   for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
335          ie = GroupedOptionHelp.end(); it != ie; ++it) {
336     if (it != GroupedOptionHelp .begin())
337       OS << "\n";
338     PrintHelpOptionList(OS, it->first, it->second);
339   }
340 
341   OS.flush();
342 }
343