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 != nullptr && *BPre != nullptr; ++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), NumOptionInfos(NumOptionInfos),
90 IgnoreCase(IgnoreCase), TheInputOptionID(0), TheUnknownOptionID(0),
91 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 != nullptr; ++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();
159 return Option(nullptr, nullptr);
160 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
161 return Option(&getInfo(id), this);
164 static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
167 for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
168 E = Prefixes.end(); I != E; ++I)
169 if (Arg.startswith(I->getKey()))
174 /// \returns Matched size. 0 means no match.
175 static unsigned matchOption(const OptTable::Info *I, StringRef Str,
177 for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) {
178 StringRef Prefix(*Pre);
179 if (Str.startswith(Prefix)) {
180 StringRef Rest = Str.substr(Prefix.size());
181 bool Matched = IgnoreCase
182 ? Rest.startswith_lower(I->Name)
183 : Rest.startswith(I->Name);
185 return Prefix.size() + StringRef(I->Name).size();
191 Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
192 unsigned FlagsToInclude,
193 unsigned FlagsToExclude) const {
194 unsigned Prev = Index;
195 const char *Str = Args.getArgString(Index);
197 // Anything that doesn't start with PrefixesUnion is an input, as is '-'
199 if (isInput(PrefixesUnion, Str))
200 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
202 const Info *Start = OptionInfos + FirstSearchableIndex;
203 const Info *End = OptionInfos + getNumOptions();
204 StringRef Name = StringRef(Str).ltrim(PrefixChars);
206 // Search for the first next option which could be a prefix.
207 Start = std::lower_bound(Start, End, Name.data());
209 // Options are stored in sorted order, with '\0' at the end of the
210 // alphabet. Since the only options which can accept a string must
211 // prefix it, we iteratively search for the next option which could
214 // FIXME: This is searching much more than necessary, but I am
215 // blanking on the simplest way to make it fast. We can solve this
216 // problem when we move to TableGen.
217 for (; Start != End; ++Start) {
218 unsigned ArgSize = 0;
219 // Scan for first option which is a proper prefix.
220 for (; Start != End; ++Start)
221 if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
226 Option Opt(Start, this);
228 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
230 if (Opt.hasFlag(FlagsToExclude))
233 // See if this option matches.
234 if (Arg *A = Opt.accept(Args, Index, ArgSize))
237 // Otherwise, see if this argument was missing values.
242 // If we failed to find an option and this arg started with /, then it's
243 // probably an input path.
245 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
247 return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
250 InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr,
251 unsigned &MissingArgIndex,
252 unsigned &MissingArgCount,
253 unsigned FlagsToInclude,
254 unsigned FlagsToExclude) const {
255 InputArgList Args(ArgArr.begin(), ArgArr.end());
257 // FIXME: Handle '@' args (or at least error on them).
259 MissingArgIndex = MissingArgCount = 0;
260 unsigned Index = 0, End = ArgArr.size();
261 while (Index < End) {
262 // Ingore nullptrs, they are response file's EOL markers
263 if (Args.getArgString(Index) == nullptr) {
267 // Ignore empty arguments (other things may still take them as arguments).
268 StringRef Str = Args.getArgString(Index);
274 unsigned Prev = Index;
275 Arg *A = ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
276 assert(Index > Prev && "Parser failed to consume argument.");
278 // Check for missing argument error.
280 assert(Index >= End && "Unexpected parser error.");
281 assert(Index - Prev - 1 && "No missing arguments!");
282 MissingArgIndex = Prev;
283 MissingArgCount = Index - Prev - 1;
293 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
294 const Option O = Opts.getOption(Id);
295 std::string Name = O.getPrefixedName();
297 // Add metavar, if used.
298 switch (O.getKind()) {
299 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
300 llvm_unreachable("Invalid option with help text.");
302 case Option::MultiArgClass:
303 if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
304 // For MultiArgs, metavar is full list of all argument names.
309 // For MultiArgs<N>, if metavar not supplied, print <value> N times.
310 for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
316 case Option::FlagClass:
319 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
320 case Option::RemainingArgsClass:
323 case Option::JoinedClass: case Option::CommaJoinedClass:
324 case Option::JoinedAndSeparateClass:
325 if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
335 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
336 std::vector<std::pair<std::string,
337 const char*> > &OptionHelp) {
338 OS << Title << ":\n";
340 // Find the maximum option length.
341 unsigned OptionFieldWidth = 0;
342 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
344 if (!OptionHelp[i].second)
347 // Limit the amount of padding we are willing to give up for alignment.
348 unsigned Length = OptionHelp[i].first.size();
350 OptionFieldWidth = std::max(OptionFieldWidth, Length);
353 const unsigned InitialPad = 2;
354 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
355 const std::string &Option = OptionHelp[i].first;
356 int Pad = OptionFieldWidth - int(Option.size());
357 OS.indent(InitialPad) << Option;
359 // Break on long option names.
362 Pad = OptionFieldWidth + InitialPad;
364 OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
368 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
369 unsigned GroupID = Opts.getOptionGroupID(Id);
371 // If not in a group, return the default help group.
375 // Abuse the help text of the option groups to store the "help group"
378 // FIXME: Split out option groups.
379 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
382 // Otherwise keep looking.
383 return getOptionHelpGroup(Opts, GroupID);
386 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
387 bool ShowHidden) const {
388 PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
389 (ShowHidden ? 0 : HelpHidden));
393 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
394 unsigned FlagsToInclude,
395 unsigned FlagsToExclude) const {
396 OS << "OVERVIEW: " << Title << "\n";
398 OS << "USAGE: " << Name << " [options] <inputs>\n";
401 // Render help text into a map of group-name to a list of (option, help)
403 typedef std::map<std::string,
404 std::vector<std::pair<std::string, const char*> > > helpmap_ty;
405 helpmap_ty GroupedOptionHelp;
407 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
410 // FIXME: Split out option groups.
411 if (getOptionKind(Id) == Option::GroupClass)
414 unsigned Flags = getInfo(Id).Flags;
415 if (FlagsToInclude && !(Flags & FlagsToInclude))
417 if (Flags & FlagsToExclude)
420 if (const char *Text = getOptionHelpText(Id)) {
421 const char *HelpGroup = getOptionHelpGroup(*this, Id);
422 const std::string &OptName = getOptionHelpName(*this, Id);
423 GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
427 for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
428 ie = GroupedOptionHelp.end(); it != ie; ++it) {
429 if (it != GroupedOptionHelp .begin())
431 PrintHelpOptionList(OS, it->first, it->second);