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