1 //===--- OptTable.cpp - Option Table Implementation -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
21 using namespace llvm::opt;
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);
40 if (a == '\0') // A is a prefix of B.
42 if (b == '\0') // B is a prefix of A.
45 // Otherwise lexicographic.
46 return (a < b) ? -1 : 1;
50 static int StrCmpOptionName(const char *A, const char *B) {
51 if (int N = StrCmpOptionNameIgnoreCase(A, B))
56 static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
60 if (int N = StrCmpOptionName(A.Name, B.Name))
63 for (const char * const *APre = A.Prefixes,
64 * const *BPre = B.Prefixes;
65 *APre != 0 && *BPre != 0; ++APre, ++BPre) {
66 if (int N = StrCmpOptionName(*APre, *BPre))
70 // Names are the same, check that classes are in order; exactly one
71 // should be joined, and it should succeed the other.
72 assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
73 "Unexpected classes for options with same name.");
74 return B.Kind == Option::JoinedClass;
78 // Support lower_bound between info and an option name.
79 static inline bool operator<(const OptTable::Info &I, const char *Name) {
80 return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
85 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
87 OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos,
89 : OptionInfos(_OptionInfos),
90 NumOptionInfos(_NumOptionInfos),
91 IgnoreCase(_IgnoreCase),
93 TheUnknownOptionID(0),
94 FirstSearchableIndex(0)
96 // Explicitly zero initialize the error to work around a bug in array
97 // value-initialization on MinGW with gcc 4.3.5.
99 // Find start of normal options.
100 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
101 unsigned Kind = getInfo(i + 1).Kind;
102 if (Kind == Option::InputClass) {
103 assert(!TheInputOptionID && "Cannot have multiple input options!");
104 TheInputOptionID = getInfo(i + 1).ID;
105 } else if (Kind == Option::UnknownClass) {
106 assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
107 TheUnknownOptionID = getInfo(i + 1).ID;
108 } else if (Kind != Option::GroupClass) {
109 FirstSearchableIndex = i;
113 assert(FirstSearchableIndex != 0 && "No searchable options?");
116 // Check that everything after the first searchable option is a
117 // regular option class.
118 for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
119 Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
120 assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
121 Kind != Option::GroupClass) &&
122 "Special options should be defined first!");
125 // Check that options are in order.
126 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
127 if (!(getInfo(i) < getInfo(i + 1))) {
129 getOption(i + 1).dump();
130 llvm_unreachable("Options are not in order!");
136 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
138 if (const char *const *P = getInfo(i).Prefixes) {
139 for (; *P != 0; ++P) {
140 PrefixesUnion.insert(*P);
145 // Build prefix chars.
146 for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(),
147 E = PrefixesUnion.end(); I != E; ++I) {
148 StringRef Prefix = I->getKey();
149 for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
151 if (std::find(PrefixChars.begin(), PrefixChars.end(), *C)
152 == PrefixChars.end())
153 PrefixChars.push_back(*C);
157 OptTable::~OptTable() {
160 const Option OptTable::getOption(OptSpecifier Opt) const {
161 unsigned id = Opt.getID();
164 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
165 return Option(&getInfo(id), this);
168 static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
171 for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
172 E = Prefixes.end(); I != E; ++I)
173 if (Arg.startswith(I->getKey()))
178 // Returns true if X starts with Y, ignoring case.
179 static bool startsWithIgnoreCase(StringRef X, StringRef Y) {
180 if (X.size() < Y.size())
182 return X.substr(0, Y.size()).equals_lower(Y);
185 /// \returns Matched size. 0 means no match.
186 static unsigned matchOption(const OptTable::Info *I, StringRef Str,
188 for (const char * const *Pre = I->Prefixes; *Pre != 0; ++Pre) {
189 StringRef Prefix(*Pre);
190 if (Str.startswith(Prefix)) {
191 StringRef Rest = Str.substr(Prefix.size());
192 bool Matched = IgnoreCase
193 ? startsWithIgnoreCase(Rest, I->Name)
194 : Rest.startswith(I->Name);
196 return Prefix.size() + StringRef(I->Name).size();
202 Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
203 unsigned FlagsToInclude,
204 unsigned FlagsToExclude) const {
205 unsigned Prev = Index;
206 const char *Str = Args.getArgString(Index);
208 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
210 if (isInput(PrefixesUnion, Str))
211 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
213 const Info *Start = OptionInfos + FirstSearchableIndex;
214 const Info *End = OptionInfos + getNumOptions();
215 StringRef Name = StringRef(Str).ltrim(PrefixChars);
217 // Search for the first next option which could be a prefix.
218 Start = std::lower_bound(Start, End, Name.data());
220 // Options are stored in sorted order, with '\0' at the end of the
221 // alphabet. Since the only options which can accept a string must
222 // prefix it, we iteratively search for the next option which could
225 // FIXME: This is searching much more than necessary, but I am
226 // blanking on the simplest way to make it fast. We can solve this
227 // problem when we move to TableGen.
228 for (; Start != End; ++Start) {
229 unsigned ArgSize = 0;
230 // Scan for first option which is a proper prefix.
231 for (; Start != End; ++Start)
232 if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
237 Option Opt(Start, this);
239 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
241 if (Opt.hasFlag(FlagsToExclude))
244 // See if this option matches.
245 if (Arg *A = Opt.accept(Args, Index, ArgSize))
248 // Otherwise, see if this argument was missing values.
253 // If we failed to find an option and this arg started with /, then it's
254 // probably an input path.
256 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
258 return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
261 InputArgList *OptTable::ParseArgs(const char *const *ArgBegin,
262 const char *const *ArgEnd,
263 unsigned &MissingArgIndex,
264 unsigned &MissingArgCount,
265 unsigned FlagsToInclude,
266 unsigned FlagsToExclude) const {
267 InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
269 // FIXME: Handle '@' args (or at least error on them).
271 MissingArgIndex = MissingArgCount = 0;
272 unsigned Index = 0, End = ArgEnd - ArgBegin;
273 while (Index < End) {
274 // Ignore empty arguments (other things may still take them as arguments).
275 StringRef Str = Args->getArgString(Index);
281 unsigned Prev = Index;
282 Arg *A = ParseOneArg(*Args, Index, FlagsToInclude, FlagsToExclude);
283 assert(Index > Prev && "Parser failed to consume argument.");
285 // Check for missing argument error.
287 assert(Index >= End && "Unexpected parser error.");
288 assert(Index - Prev - 1 && "No missing arguments!");
289 MissingArgIndex = Prev;
290 MissingArgCount = Index - Prev - 1;
300 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
301 const Option O = Opts.getOption(Id);
302 std::string Name = O.getPrefixedName();
304 // Add metavar, if used.
305 switch (O.getKind()) {
306 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
307 llvm_unreachable("Invalid option with help text.");
309 case Option::MultiArgClass:
310 llvm_unreachable("Cannot print metavar for this kind of option.");
312 case Option::FlagClass:
315 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
316 case Option::RemainingArgsClass:
319 case Option::JoinedClass: case Option::CommaJoinedClass:
320 case Option::JoinedAndSeparateClass:
321 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
331 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
332 std::vector<std::pair<std::string,
333 const char*> > &OptionHelp) {
334 OS << Title << ":\n";
336 // Find the maximum option length.
337 unsigned OptionFieldWidth = 0;
338 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
340 if (!OptionHelp[i].second)
343 // Limit the amount of padding we are willing to give up for alignment.
344 unsigned Length = OptionHelp[i].first.size();
346 OptionFieldWidth = std::max(OptionFieldWidth, Length);
349 const unsigned InitialPad = 2;
350 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
351 const std::string &Option = OptionHelp[i].first;
352 int Pad = OptionFieldWidth - int(Option.size());
353 OS.indent(InitialPad) << Option;
355 // Break on long option names.
358 Pad = OptionFieldWidth + InitialPad;
360 OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
364 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
365 unsigned GroupID = Opts.getOptionGroupID(Id);
367 // If not in a group, return the default help group.
371 // Abuse the help text of the option groups to store the "help group"
374 // FIXME: Split out option groups.
375 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
378 // Otherwise keep looking.
379 return getOptionHelpGroup(Opts, GroupID);
382 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
383 bool ShowHidden) const {
384 PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
385 (ShowHidden ? 0 : HelpHidden));
389 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
390 unsigned FlagsToInclude,
391 unsigned FlagsToExclude) const {
392 OS << "OVERVIEW: " << Title << "\n";
394 OS << "USAGE: " << Name << " [options] <inputs>\n";
397 // Render help text into a map of group-name to a list of (option, help)
399 typedef std::map<std::string,
400 std::vector<std::pair<std::string, const char*> > > helpmap_ty;
401 helpmap_ty GroupedOptionHelp;
403 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
406 // FIXME: Split out option groups.
407 if (getOptionKind(Id) == Option::GroupClass)
410 unsigned Flags = getInfo(Id).Flags;
411 if (FlagsToInclude && !(Flags & FlagsToInclude))
413 if (Flags & FlagsToExclude)
416 if (const char *Text = getOptionHelpText(Id)) {
417 const char *HelpGroup = getOptionHelpGroup(*this, Id);
418 const std::string &OptName = getOptionHelpName(*this, Id);
419 GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
423 for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
424 ie = GroupedOptionHelp.end(); it != ie; ++it) {
425 if (it != GroupedOptionHelp .begin())
427 PrintHelpOptionList(OS, it->first, it->second);