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"
12 #include "llvm/Option/Arg.h"
13 #include "llvm/Option/ArgList.h"
14 #include "llvm/Option/Option.h"
15 #include "llvm/Support/raw_ostream.h"
16 #include "llvm/Support/ErrorHandling.h"
21 using namespace llvm::opt;
23 // Ordering on Info. The ordering is *almost* lexicographic, with two
24 // exceptions. First, '\0' comes at the end of the alphabet instead of
25 // the beginning (thus options precede any other options which prefix
26 // them). Second, for options with the same name, the less permissive
27 // version should come first; a Flag option should precede a Joined
28 // option, for example.
30 static int StrCmpOptionName(const char *A, const char *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;
52 static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
56 if (int N = StrCmpOptionName(A.Name, B.Name))
59 for (const char * const *APre = A.Prefixes,
60 * const *BPre = B.Prefixes;
61 *APre != 0 && *BPre != 0; ++APre, ++BPre) {
62 if (int N = StrCmpOptionName(*APre, *BPre))
66 // Names are the same, check that classes are in order; exactly one
67 // should be joined, and it should succeed the other.
68 assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
69 "Unexpected classes for options with same name.");
70 return B.Kind == Option::JoinedClass;
73 // Support lower_bound between info and an option name.
74 static inline bool operator<(const OptTable::Info &I, const char *Name) {
75 return StrCmpOptionName(I.Name, Name) == -1;
77 static inline bool operator<(const char *Name, const OptTable::Info &I) {
78 return StrCmpOptionName(Name, I.Name) == -1;
83 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
85 OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos)
86 : OptionInfos(_OptionInfos),
87 NumOptionInfos(_NumOptionInfos),
89 TheUnknownOptionID(0),
90 FirstSearchableIndex(0)
92 // Explicitly zero initialize the error to work around a bug in array
93 // value-initialization on MinGW with gcc 4.3.5.
95 // Find start of normal options.
96 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
97 unsigned Kind = getInfo(i + 1).Kind;
98 if (Kind == Option::InputClass) {
99 assert(!TheInputOptionID && "Cannot have multiple input options!");
100 TheInputOptionID = getInfo(i + 1).ID;
101 } else if (Kind == Option::UnknownClass) {
102 assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
103 TheUnknownOptionID = getInfo(i + 1).ID;
104 } else if (Kind != Option::GroupClass) {
105 FirstSearchableIndex = i;
109 assert(FirstSearchableIndex != 0 && "No searchable options?");
112 // Check that everything after the first searchable option is a
113 // regular option class.
114 for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
115 Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
116 assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
117 Kind != Option::GroupClass) &&
118 "Special options should be defined first!");
121 // Check that options are in order.
122 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
123 if (!(getInfo(i) < getInfo(i + 1))) {
125 getOption(i + 1).dump();
126 llvm_unreachable("Options are not in order!");
132 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
134 if (const char *const *P = getInfo(i).Prefixes) {
135 for (; *P != 0; ++P) {
136 PrefixesUnion.insert(*P);
141 // Build prefix chars.
142 for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(),
143 E = PrefixesUnion.end(); I != E; ++I) {
144 StringRef Prefix = I->getKey();
145 for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
147 if (std::find(PrefixChars.begin(), PrefixChars.end(), *C)
148 == PrefixChars.end())
149 PrefixChars.push_back(*C);
153 OptTable::~OptTable() {
156 const Option OptTable::getOption(OptSpecifier Opt) const {
157 unsigned id = Opt.getID();
160 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
161 return Option(&getInfo(id), this);
164 bool OptTable::isOptionHelpHidden(OptSpecifier id) const {
165 return getInfo(id).Flags & HelpHidden;
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 Matched size. 0 means no match.
179 static unsigned matchOption(const OptTable::Info *I, StringRef Str) {
180 for (const char * const *Pre = I->Prefixes; *Pre != 0; ++Pre) {
181 StringRef Prefix(*Pre);
182 if (Str.startswith(Prefix) && Str.substr(Prefix.size()).startswith(I->Name))
183 return Prefix.size() + StringRef(I->Name).size();
188 Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index) const {
189 unsigned Prev = Index;
190 const char *Str = Args.getArgString(Index);
192 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
194 if (isInput(PrefixesUnion, Str))
195 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
197 const Info *Start = OptionInfos + FirstSearchableIndex;
198 const Info *End = OptionInfos + getNumOptions();
199 StringRef Name = StringRef(Str).ltrim(PrefixChars);
201 // Search for the first next option which could be a prefix.
202 Start = std::lower_bound(Start, End, Name.data());
204 // Options are stored in sorted order, with '\0' at the end of the
205 // alphabet. Since the only options which can accept a string must
206 // prefix it, we iteratively search for the next option which could
209 // FIXME: This is searching much more than necessary, but I am
210 // blanking on the simplest way to make it fast. We can solve this
211 // problem when we move to TableGen.
212 for (; Start != End; ++Start) {
213 unsigned ArgSize = 0;
214 // Scan for first option which is a proper prefix.
215 for (; Start != End; ++Start)
216 if ((ArgSize = matchOption(Start, Str)))
221 // See if this option matches.
222 if (Arg *A = Option(Start, this).accept(Args, Index, ArgSize))
225 // Otherwise, see if this argument was missing values.
230 return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
233 InputArgList *OptTable::ParseArgs(const char* const *ArgBegin,
234 const char* const *ArgEnd,
235 unsigned &MissingArgIndex,
236 unsigned &MissingArgCount) const {
237 InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
239 // FIXME: Handle '@' args (or at least error on them).
241 MissingArgIndex = MissingArgCount = 0;
242 unsigned Index = 0, End = ArgEnd - ArgBegin;
243 while (Index < End) {
244 // Ignore empty arguments (other things may still take them as arguments).
245 if (Args->getArgString(Index)[0] == '\0') {
250 unsigned Prev = Index;
251 Arg *A = ParseOneArg(*Args, Index);
252 assert(Index > Prev && "Parser failed to consume argument.");
254 // Check for missing argument error.
256 assert(Index >= End && "Unexpected parser error.");
257 assert(Index - Prev - 1 && "No missing arguments!");
258 MissingArgIndex = Prev;
259 MissingArgCount = Index - Prev - 1;
269 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
270 const Option O = Opts.getOption(Id);
271 std::string Name = O.getPrefixedName();
273 // Add metavar, if used.
274 switch (O.getKind()) {
275 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
276 llvm_unreachable("Invalid option with help text.");
278 case Option::MultiArgClass:
279 llvm_unreachable("Cannot print metavar for this kind of option.");
281 case Option::FlagClass:
284 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
287 case Option::JoinedClass: case Option::CommaJoinedClass:
288 case Option::JoinedAndSeparateClass:
289 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
299 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
300 std::vector<std::pair<std::string,
301 const char*> > &OptionHelp) {
302 OS << Title << ":\n";
304 // Find the maximum option length.
305 unsigned OptionFieldWidth = 0;
306 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
308 if (!OptionHelp[i].second)
311 // Limit the amount of padding we are willing to give up for alignment.
312 unsigned Length = OptionHelp[i].first.size();
314 OptionFieldWidth = std::max(OptionFieldWidth, Length);
317 const unsigned InitialPad = 2;
318 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
319 const std::string &Option = OptionHelp[i].first;
320 int Pad = OptionFieldWidth - int(Option.size());
321 OS.indent(InitialPad) << Option;
323 // Break on long option names.
326 Pad = OptionFieldWidth + InitialPad;
328 OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
332 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
333 unsigned GroupID = Opts.getOptionGroupID(Id);
335 // If not in a group, return the default help group.
339 // Abuse the help text of the option groups to store the "help group"
342 // FIXME: Split out option groups.
343 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
346 // Otherwise keep looking.
347 return getOptionHelpGroup(Opts, GroupID);
350 void OptTable::PrintHelp(raw_ostream &OS, const char *Name,
351 const char *Title, bool ShowHidden) const {
352 OS << "OVERVIEW: " << Title << "\n";
354 OS << "USAGE: " << Name << " [options] <inputs>\n";
357 // Render help text into a map of group-name to a list of (option, help)
359 typedef std::map<std::string,
360 std::vector<std::pair<std::string, const char*> > > helpmap_ty;
361 helpmap_ty GroupedOptionHelp;
363 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
366 // FIXME: Split out option groups.
367 if (getOptionKind(Id) == Option::GroupClass)
370 if (!ShowHidden && isOptionHelpHidden(Id))
373 if (const char *Text = getOptionHelpText(Id)) {
374 const char *HelpGroup = getOptionHelpGroup(*this, Id);
375 const std::string &OptName = getOptionHelpName(*this, Id);
376 GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
380 for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
381 ie = GroupedOptionHelp.end(); it != ie; ++it) {
382 if (it != GroupedOptionHelp .begin())
384 PrintHelpOptionList(OS, it->first, it->second);