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