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;
49 static int StrCmpOptionName(const char *A, const char *B) {
50 if (int N = StrCmpOptionNameIgnoreCase(A, B))
55 static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
59 if (int N = StrCmpOptionName(A.Name, B.Name))
62 for (const char * const *APre = A.Prefixes,
63 * const *BPre = B.Prefixes;
64 *APre != 0 && *BPre != 0; ++APre, ++BPre) {
65 if (int N = StrCmpOptionName(*APre, *BPre))
69 // Names are the same, check that classes are in order; exactly one
70 // should be joined, and it should succeed the other.
71 assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
72 "Unexpected classes for options with same name.");
73 return B.Kind == Option::JoinedClass;
76 // Support lower_bound between info and an option name.
77 static inline bool operator<(const OptTable::Info &I, const char *Name) {
78 return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
80 static inline bool operator<(const char *Name, const OptTable::Info &I) {
81 return StrCmpOptionNameIgnoreCase(Name, I.Name) < 0;
86 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
88 OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos,
90 : OptionInfos(_OptionInfos),
91 NumOptionInfos(_NumOptionInfos),
92 IgnoreCase(_IgnoreCase),
94 TheUnknownOptionID(0),
95 FirstSearchableIndex(0)
97 // Explicitly zero initialize the error to work around a bug in array
98 // value-initialization on MinGW with gcc 4.3.5.
100 // Find start of normal options.
101 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
102 unsigned Kind = getInfo(i + 1).Kind;
103 if (Kind == Option::InputClass) {
104 assert(!TheInputOptionID && "Cannot have multiple input options!");
105 TheInputOptionID = getInfo(i + 1).ID;
106 } else if (Kind == Option::UnknownClass) {
107 assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
108 TheUnknownOptionID = getInfo(i + 1).ID;
109 } else if (Kind != Option::GroupClass) {
110 FirstSearchableIndex = i;
114 assert(FirstSearchableIndex != 0 && "No searchable options?");
117 // Check that everything after the first searchable option is a
118 // regular option class.
119 for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
120 Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
121 assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
122 Kind != Option::GroupClass) &&
123 "Special options should be defined first!");
126 // Check that options are in order.
127 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
128 if (!(getInfo(i) < getInfo(i + 1))) {
130 getOption(i + 1).dump();
131 llvm_unreachable("Options are not in order!");
137 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
139 if (const char *const *P = getInfo(i).Prefixes) {
140 for (; *P != 0; ++P) {
141 PrefixesUnion.insert(*P);
146 // Build prefix chars.
147 for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(),
148 E = PrefixesUnion.end(); I != E; ++I) {
149 StringRef Prefix = I->getKey();
150 for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
152 if (std::find(PrefixChars.begin(), PrefixChars.end(), *C)
153 == PrefixChars.end())
154 PrefixChars.push_back(*C);
158 OptTable::~OptTable() {
161 const Option OptTable::getOption(OptSpecifier Opt) const {
162 unsigned id = Opt.getID();
165 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
166 return Option(&getInfo(id), this);
169 static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
172 for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
173 E = Prefixes.end(); I != E; ++I)
174 if (Arg.startswith(I->getKey()))
179 // Returns true if X starts with Y, ignoring case.
180 static bool startsWithIgnoreCase(StringRef X, StringRef Y) {
181 if (X.size() < Y.size())
183 return X.substr(0, Y.size()).equals_lower(Y);
186 /// \returns Matched size. 0 means no match.
187 static unsigned matchOption(const OptTable::Info *I, StringRef Str,
189 for (const char * const *Pre = I->Prefixes; *Pre != 0; ++Pre) {
190 StringRef Prefix(*Pre);
191 if (Str.startswith(Prefix)) {
192 StringRef Rest = Str.substr(Prefix.size());
193 bool Matched = IgnoreCase
194 ? startsWithIgnoreCase(Rest, I->Name)
195 : Rest.startswith(I->Name);
197 return Prefix.size() + StringRef(I->Name).size();
203 Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
204 unsigned FlagsToInclude,
205 unsigned FlagsToExclude) const {
206 unsigned Prev = Index;
207 const char *Str = Args.getArgString(Index);
209 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
211 if (isInput(PrefixesUnion, Str))
212 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
214 const Info *Start = OptionInfos + FirstSearchableIndex;
215 const Info *End = OptionInfos + getNumOptions();
216 StringRef Name = StringRef(Str).ltrim(PrefixChars);
218 // Search for the first next option which could be a prefix.
219 Start = std::lower_bound(Start, End, Name.data());
221 // Options are stored in sorted order, with '\0' at the end of the
222 // alphabet. Since the only options which can accept a string must
223 // prefix it, we iteratively search for the next option which could
226 // FIXME: This is searching much more than necessary, but I am
227 // blanking on the simplest way to make it fast. We can solve this
228 // problem when we move to TableGen.
229 for (; Start != End; ++Start) {
230 unsigned ArgSize = 0;
231 // Scan for first option which is a proper prefix.
232 for (; Start != End; ++Start)
233 if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
238 Option Opt(Start, this);
240 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
242 if (Opt.hasFlag(FlagsToExclude))
245 // See if this option matches.
246 if (Arg *A = Opt.accept(Args, Index, ArgSize))
249 // Otherwise, see if this argument was missing values.
254 // If we failed to find an option and this arg started with /, then it's
255 // probably an input path.
257 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
259 return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
262 InputArgList *OptTable::ParseArgs(const char *const *ArgBegin,
263 const char *const *ArgEnd,
264 unsigned &MissingArgIndex,
265 unsigned &MissingArgCount,
266 unsigned FlagsToInclude,
267 unsigned FlagsToExclude) const {
268 InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
270 // FIXME: Handle '@' args (or at least error on them).
272 MissingArgIndex = MissingArgCount = 0;
273 unsigned Index = 0, End = ArgEnd - ArgBegin;
274 while (Index < End) {
275 // Ignore empty arguments (other things may still take them as arguments).
276 StringRef Str = Args->getArgString(Index);
282 unsigned Prev = Index;
283 Arg *A = ParseOneArg(*Args, Index, FlagsToInclude, FlagsToExclude);
284 assert(Index > Prev && "Parser failed to consume argument.");
286 // Check for missing argument error.
288 assert(Index >= End && "Unexpected parser error.");
289 assert(Index - Prev - 1 && "No missing arguments!");
290 MissingArgIndex = Prev;
291 MissingArgCount = Index - Prev - 1;
301 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
302 const Option O = Opts.getOption(Id);
303 std::string Name = O.getPrefixedName();
305 // Add metavar, if used.
306 switch (O.getKind()) {
307 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
308 llvm_unreachable("Invalid option with help text.");
310 case Option::MultiArgClass:
311 llvm_unreachable("Cannot print metavar for this kind of option.");
313 case Option::FlagClass:
316 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
317 case Option::RemainingArgsClass:
320 case Option::JoinedClass: case Option::CommaJoinedClass:
321 case Option::JoinedAndSeparateClass:
322 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
332 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
333 std::vector<std::pair<std::string,
334 const char*> > &OptionHelp) {
335 OS << Title << ":\n";
337 // Find the maximum option length.
338 unsigned OptionFieldWidth = 0;
339 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
341 if (!OptionHelp[i].second)
344 // Limit the amount of padding we are willing to give up for alignment.
345 unsigned Length = OptionHelp[i].first.size();
347 OptionFieldWidth = std::max(OptionFieldWidth, Length);
350 const unsigned InitialPad = 2;
351 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
352 const std::string &Option = OptionHelp[i].first;
353 int Pad = OptionFieldWidth - int(Option.size());
354 OS.indent(InitialPad) << Option;
356 // Break on long option names.
359 Pad = OptionFieldWidth + InitialPad;
361 OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
365 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
366 unsigned GroupID = Opts.getOptionGroupID(Id);
368 // If not in a group, return the default help group.
372 // Abuse the help text of the option groups to store the "help group"
375 // FIXME: Split out option groups.
376 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
379 // Otherwise keep looking.
380 return getOptionHelpGroup(Opts, GroupID);
383 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
384 bool ShowHidden) const {
385 PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
386 (ShowHidden ? 0 : HelpHidden));
390 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
391 unsigned FlagsToInclude,
392 unsigned FlagsToExclude) const {
393 OS << "OVERVIEW: " << Title << "\n";
395 OS << "USAGE: " << Name << " [options] <inputs>\n";
398 // Render help text into a map of group-name to a list of (option, help)
400 typedef std::map<std::string,
401 std::vector<std::pair<std::string, const char*> > > helpmap_ty;
402 helpmap_ty GroupedOptionHelp;
404 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
407 // FIXME: Split out option groups.
408 if (getOptionKind(Id) == Option::GroupClass)
411 unsigned Flags = getInfo(Id).Flags;
412 if (FlagsToInclude && !(Flags & FlagsToInclude))
414 if (Flags & FlagsToExclude)
417 if (const char *Text = getOptionHelpText(Id)) {
418 const char *HelpGroup = getOptionHelpGroup(*this, Id);
419 const std::string &OptName = getOptionHelpName(*this, Id);
420 GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
424 for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
425 ie = GroupedOptionHelp.end(); it != ie; ++it) {
426 if (it != GroupedOptionHelp .begin())
428 PrintHelpOptionList(OS, it->first, it->second);