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 // Support lower_bound between info and an option name.
50 static inline bool operator<(const OptTable::Info &I, const char *Name) {
51 return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
56 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
58 OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos,
60 : OptionInfos(_OptionInfos),
61 NumOptionInfos(_NumOptionInfos),
62 IgnoreCase(_IgnoreCase),
64 TheUnknownOptionID(0),
65 FirstSearchableIndex(0)
67 // Explicitly zero initialize the error to work around a bug in array
68 // value-initialization on MinGW with gcc 4.3.5.
70 // Find start of normal options.
71 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
72 unsigned Kind = getInfo(i + 1).Kind;
73 if (Kind == Option::InputClass) {
74 assert(!TheInputOptionID && "Cannot have multiple input options!");
75 TheInputOptionID = getInfo(i + 1).ID;
76 } else if (Kind == Option::UnknownClass) {
77 assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
78 TheUnknownOptionID = getInfo(i + 1).ID;
79 } else if (Kind != Option::GroupClass) {
80 FirstSearchableIndex = i;
84 assert(FirstSearchableIndex != 0 && "No searchable options?");
87 // Check that everything after the first searchable option is a
88 // regular option class.
89 for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
90 Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
91 assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
92 Kind != Option::GroupClass) &&
93 "Special options should be defined first!");
96 // Check that options are in order.
97 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
98 if (!(getInfo(i) < getInfo(i + 1))) {
100 getOption(i + 1).dump();
101 llvm_unreachable("Options are not in order!");
107 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
109 if (const char *const *P = getInfo(i).Prefixes) {
110 for (; *P != 0; ++P) {
111 PrefixesUnion.insert(*P);
116 // Build prefix chars.
117 for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(),
118 E = PrefixesUnion.end(); I != E; ++I) {
119 StringRef Prefix = I->getKey();
120 for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
122 if (std::find(PrefixChars.begin(), PrefixChars.end(), *C)
123 == PrefixChars.end())
124 PrefixChars.push_back(*C);
128 OptTable::~OptTable() {
131 const Option OptTable::getOption(OptSpecifier Opt) const {
132 unsigned id = Opt.getID();
135 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
136 return Option(&getInfo(id), this);
139 static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
142 for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
143 E = Prefixes.end(); I != E; ++I)
144 if (Arg.startswith(I->getKey()))
149 // Returns true if X starts with Y, ignoring case.
150 static bool startsWithIgnoreCase(StringRef X, StringRef Y) {
151 if (X.size() < Y.size())
153 return X.substr(0, Y.size()).equals_lower(Y);
156 /// \returns Matched size. 0 means no match.
157 static unsigned matchOption(const OptTable::Info *I, StringRef Str,
159 for (const char * const *Pre = I->Prefixes; *Pre != 0; ++Pre) {
160 StringRef Prefix(*Pre);
161 if (Str.startswith(Prefix)) {
162 StringRef Rest = Str.substr(Prefix.size());
163 bool Matched = IgnoreCase
164 ? startsWithIgnoreCase(Rest, I->Name)
165 : Rest.startswith(I->Name);
167 return Prefix.size() + StringRef(I->Name).size();
173 Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
174 unsigned FlagsToInclude,
175 unsigned FlagsToExclude) const {
176 unsigned Prev = Index;
177 const char *Str = Args.getArgString(Index);
179 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
181 if (isInput(PrefixesUnion, Str))
182 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
184 const Info *Start = OptionInfos + FirstSearchableIndex;
185 const Info *End = OptionInfos + getNumOptions();
186 StringRef Name = StringRef(Str).ltrim(PrefixChars);
188 // Search for the first next option which could be a prefix.
189 Start = std::lower_bound(Start, End, Name.data());
191 // Options are stored in sorted order, with '\0' at the end of the
192 // alphabet. Since the only options which can accept a string must
193 // prefix it, we iteratively search for the next option which could
196 // FIXME: This is searching much more than necessary, but I am
197 // blanking on the simplest way to make it fast. We can solve this
198 // problem when we move to TableGen.
199 for (; Start != End; ++Start) {
200 unsigned ArgSize = 0;
201 // Scan for first option which is a proper prefix.
202 for (; Start != End; ++Start)
203 if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
208 Option Opt(Start, this);
210 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
212 if (Opt.hasFlag(FlagsToExclude))
215 // See if this option matches.
216 if (Arg *A = Opt.accept(Args, Index, ArgSize))
219 // Otherwise, see if this argument was missing values.
224 // If we failed to find an option and this arg started with /, then it's
225 // probably an input path.
227 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
229 return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
232 InputArgList *OptTable::ParseArgs(const char *const *ArgBegin,
233 const char *const *ArgEnd,
234 unsigned &MissingArgIndex,
235 unsigned &MissingArgCount,
236 unsigned FlagsToInclude,
237 unsigned FlagsToExclude) const {
238 InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
240 // FIXME: Handle '@' args (or at least error on them).
242 MissingArgIndex = MissingArgCount = 0;
243 unsigned Index = 0, End = ArgEnd - ArgBegin;
244 while (Index < End) {
245 // Ignore empty arguments (other things may still take them as arguments).
246 StringRef Str = Args->getArgString(Index);
252 unsigned Prev = Index;
253 Arg *A = ParseOneArg(*Args, Index, FlagsToInclude, FlagsToExclude);
254 assert(Index > Prev && "Parser failed to consume argument.");
256 // Check for missing argument error.
258 assert(Index >= End && "Unexpected parser error.");
259 assert(Index - Prev - 1 && "No missing arguments!");
260 MissingArgIndex = Prev;
261 MissingArgCount = Index - Prev - 1;
271 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
272 const Option O = Opts.getOption(Id);
273 std::string Name = O.getPrefixedName();
275 // Add metavar, if used.
276 switch (O.getKind()) {
277 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
278 llvm_unreachable("Invalid option with help text.");
280 case Option::MultiArgClass:
281 llvm_unreachable("Cannot print metavar for this kind of option.");
283 case Option::FlagClass:
286 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
287 case Option::RemainingArgsClass:
290 case Option::JoinedClass: case Option::CommaJoinedClass:
291 case Option::JoinedAndSeparateClass:
292 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
302 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
303 std::vector<std::pair<std::string,
304 const char*> > &OptionHelp) {
305 OS << Title << ":\n";
307 // Find the maximum option length.
308 unsigned OptionFieldWidth = 0;
309 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
311 if (!OptionHelp[i].second)
314 // Limit the amount of padding we are willing to give up for alignment.
315 unsigned Length = OptionHelp[i].first.size();
317 OptionFieldWidth = std::max(OptionFieldWidth, Length);
320 const unsigned InitialPad = 2;
321 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
322 const std::string &Option = OptionHelp[i].first;
323 int Pad = OptionFieldWidth - int(Option.size());
324 OS.indent(InitialPad) << Option;
326 // Break on long option names.
329 Pad = OptionFieldWidth + InitialPad;
331 OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
335 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
336 unsigned GroupID = Opts.getOptionGroupID(Id);
338 // If not in a group, return the default help group.
342 // Abuse the help text of the option groups to store the "help group"
345 // FIXME: Split out option groups.
346 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
349 // Otherwise keep looking.
350 return getOptionHelpGroup(Opts, GroupID);
353 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
354 bool ShowHidden) const {
355 PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
356 (ShowHidden ? 0 : HelpHidden));
360 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
361 unsigned FlagsToInclude,
362 unsigned FlagsToExclude) const {
363 OS << "OVERVIEW: " << Title << "\n";
365 OS << "USAGE: " << Name << " [options] <inputs>\n";
368 // Render help text into a map of group-name to a list of (option, help)
370 typedef std::map<std::string,
371 std::vector<std::pair<std::string, const char*> > > helpmap_ty;
372 helpmap_ty GroupedOptionHelp;
374 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
377 // FIXME: Split out option groups.
378 if (getOptionKind(Id) == Option::GroupClass)
381 unsigned Flags = getInfo(Id).Flags;
382 if (FlagsToInclude && !(Flags & FlagsToInclude))
384 if (Flags & FlagsToExclude)
387 if (const char *Text = getOptionHelpText(Id)) {
388 const char *HelpGroup = getOptionHelpGroup(*this, Id);
389 const std::string &OptName = getOptionHelpName(*this, Id);
390 GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
394 for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
395 ie = GroupedOptionHelp.end(); it != ie; ++it) {
396 if (it != GroupedOptionHelp .begin())
398 PrintHelpOptionList(OS, it->first, it->second);