clang API Documentation

OptTable.cpp

Go to the documentation of this file.
00001 //===--- OptTable.cpp - Option Table Implementation ---------------------*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "clang/Driver/OptTable.h"
00011 #include "clang/Driver/Arg.h"
00012 #include "clang/Driver/ArgList.h"
00013 #include "clang/Driver/Option.h"
00014 #include "llvm/Support/raw_ostream.h"
00015 #include <algorithm>
00016 #include <cassert>
00017 #include <map>
00018 using namespace clang::driver;
00019 using namespace clang::driver::options;
00020 
00021 // Ordering on Info. The ordering is *almost* lexicographic, with two
00022 // exceptions. First, '\0' comes at the end of the alphabet instead of
00023 // the beginning (thus options preceed any other options which prefix
00024 // them). Second, for options with the same name, the less permissive
00025 // version should come first; a Flag option should preceed a Joined
00026 // option, for example.
00027 
00028 static int StrCmpOptionName(const char *A, const char *B) {
00029   char a = *A, b = *B;
00030   while (a == b) {
00031     if (a == '\0')
00032       return 0;
00033 
00034     a = *++A;
00035     b = *++B;
00036   }
00037 
00038   if (a == '\0') // A is a prefix of B.
00039     return 1;
00040   if (b == '\0') // B is a prefix of A.
00041     return -1;
00042 
00043   // Otherwise lexicographic.
00044   return (a < b) ? -1 : 1;
00045 }
00046 
00047 namespace clang {
00048 namespace driver {
00049 static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
00050   if (&A == &B)
00051     return false;
00052 
00053   if (int N = StrCmpOptionName(A.Name, B.Name))
00054     return N == -1;
00055 
00056   // Names are the same, check that classes are in order; exactly one
00057   // should be joined, and it should succeed the other.
00058   assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
00059          "Unexpected classes for options with same name.");
00060   return B.Kind == Option::JoinedClass;
00061 }
00062 
00063 // Support lower_bound between info and an option name.
00064 static inline bool operator<(const OptTable::Info &I, const char *Name) {
00065   return StrCmpOptionName(I.Name, Name) == -1;
00066 }
00067 static inline bool operator<(const char *Name, const OptTable::Info &I) {
00068   return StrCmpOptionName(Name, I.Name) == -1;
00069 }
00070 }
00071 }
00072 
00073 //
00074 
00075 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
00076 
00077 //
00078 
00079 OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos)
00080   : OptionInfos(_OptionInfos), NumOptionInfos(_NumOptionInfos),
00081     Options(new Option*[NumOptionInfos]),
00082     TheInputOption(0), TheUnknownOption(0), FirstSearchableIndex(0)
00083 {
00084   // Explicitly zero initialize the error to work around a bug in array
00085   // value-initialization on MinGW with gcc 4.3.5.
00086   memset(Options, 0, sizeof(*Options) * NumOptionInfos);
00087 
00088   // Find start of normal options.
00089   for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
00090     unsigned Kind = getInfo(i + 1).Kind;
00091     if (Kind == Option::InputClass) {
00092       assert(!TheInputOption && "Cannot have multiple input options!");
00093       TheInputOption = getOption(i + 1);
00094     } else if (Kind == Option::UnknownClass) {
00095       assert(!TheUnknownOption && "Cannot have multiple input options!");
00096       TheUnknownOption = getOption(i + 1);
00097     } else if (Kind != Option::GroupClass) {
00098       FirstSearchableIndex = i;
00099       break;
00100     }
00101   }
00102   assert(FirstSearchableIndex != 0 && "No searchable options?");
00103 
00104 #ifndef NDEBUG
00105   // Check that everything after the first searchable option is a
00106   // regular option class.
00107   for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
00108     Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
00109     assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
00110             Kind != Option::GroupClass) &&
00111            "Special options should be defined first!");
00112   }
00113 
00114   // Check that options are in order.
00115   for (unsigned i = FirstSearchableIndex+1, e = getNumOptions(); i != e; ++i) {
00116     if (!(getInfo(i) < getInfo(i + 1))) {
00117       getOption(i)->dump();
00118       getOption(i + 1)->dump();
00119       assert(0 && "Options are not in order!");
00120     }
00121   }
00122 #endif
00123 }
00124 
00125 OptTable::~OptTable() {
00126   for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
00127     delete Options[i];
00128   delete[] Options;
00129 }
00130 
00131 Option *OptTable::CreateOption(unsigned id) const {
00132   const Info &info = getInfo(id);
00133   const OptionGroup *Group =
00134     cast_or_null<OptionGroup>(getOption(info.GroupID));
00135   const Option *Alias = getOption(info.AliasID);
00136 
00137   Option *Opt = 0;
00138   switch (info.Kind) {
00139   case Option::InputClass:
00140     Opt = new InputOption(id); break;
00141   case Option::UnknownClass:
00142     Opt = new UnknownOption(id); break;
00143   case Option::GroupClass:
00144     Opt = new OptionGroup(id, info.Name, Group); break;
00145   case Option::FlagClass:
00146     Opt = new FlagOption(id, info.Name, Group, Alias); break;
00147   case Option::JoinedClass:
00148     Opt = new JoinedOption(id, info.Name, Group, Alias); break;
00149   case Option::SeparateClass:
00150     Opt = new SeparateOption(id, info.Name, Group, Alias); break;
00151   case Option::CommaJoinedClass:
00152     Opt = new CommaJoinedOption(id, info.Name, Group, Alias); break;
00153   case Option::MultiArgClass:
00154     Opt = new MultiArgOption(id, info.Name, Group, Alias, info.Param); break;
00155   case Option::JoinedOrSeparateClass:
00156     Opt = new JoinedOrSeparateOption(id, info.Name, Group, Alias); break;
00157   case Option::JoinedAndSeparateClass:
00158     Opt = new JoinedAndSeparateOption(id, info.Name, Group, Alias); break;
00159   }
00160 
00161   if (info.Flags & DriverOption)
00162     Opt->setDriverOption(true);
00163   if (info.Flags & LinkerInput)
00164     Opt->setLinkerInput(true);
00165   if (info.Flags & NoArgumentUnused)
00166     Opt->setNoArgumentUnused(true);
00167   if (info.Flags & RenderAsInput)
00168     Opt->setNoOptAsInput(true);
00169   if (info.Flags & RenderJoined) {
00170     assert(info.Kind == Option::SeparateClass && "Invalid option.");
00171     Opt->setForceJoinedRender(true);
00172   }
00173   if (info.Flags & RenderSeparate) {
00174     assert(info.Kind == Option::JoinedClass && "Invalid option.");
00175     Opt->setForceSeparateRender(true);
00176   }
00177   if (info.Flags & Unsupported)
00178     Opt->setUnsupported(true);
00179 
00180   return Opt;
00181 }
00182 
00183 Arg *OptTable::ParseOneArg(const InputArgList &Args, unsigned &Index) const {
00184   unsigned Prev = Index;
00185   const char *Str = Args.getArgString(Index);
00186 
00187   // Anything that doesn't start with '-' is an input, as is '-' itself.
00188   if (Str[0] != '-' || Str[1] == '\0')
00189     return new PositionalArg(TheInputOption, Index++);
00190 
00191   const Info *Start = OptionInfos + FirstSearchableIndex;
00192   const Info *End = OptionInfos + getNumOptions();
00193 
00194   // Search for the first next option which could be a prefix.
00195   Start = std::lower_bound(Start, End, Str);
00196 
00197   // Options are stored in sorted order, with '\0' at the end of the
00198   // alphabet. Since the only options which can accept a string must
00199   // prefix it, we iteratively search for the next option which could
00200   // be a prefix.
00201   //
00202   // FIXME: This is searching much more than necessary, but I am
00203   // blanking on the simplest way to make it fast. We can solve this
00204   // problem when we move to TableGen.
00205   for (; Start != End; ++Start) {
00206     // Scan for first option which is a proper prefix.
00207     for (; Start != End; ++Start)
00208       if (memcmp(Str, Start->Name, strlen(Start->Name)) == 0)
00209         break;
00210     if (Start == End)
00211       break;
00212 
00213     // See if this option matches.
00214     if (Arg *A = getOption(Start - OptionInfos + 1)->accept(Args, Index))
00215       return A;
00216 
00217     // Otherwise, see if this argument was missing values.
00218     if (Prev != Index)
00219       return 0;
00220   }
00221 
00222   return new PositionalArg(TheUnknownOption, Index++);
00223 }
00224 
00225 InputArgList *OptTable::ParseArgs(const char **ArgBegin, const char **ArgEnd,
00226                                   unsigned &MissingArgIndex,
00227                                   unsigned &MissingArgCount) const {
00228   InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
00229 
00230   // FIXME: Handle '@' args (or at least error on them).
00231 
00232   MissingArgIndex = MissingArgCount = 0;
00233   unsigned Index = 0, End = ArgEnd - ArgBegin;
00234   while (Index < End) {
00235     // Ignore empty arguments (other things may still take them as arguments).
00236     if (Args->getArgString(Index)[0] == '\0') {
00237       ++Index;
00238       continue;
00239     }
00240 
00241     unsigned Prev = Index;
00242     Arg *A = ParseOneArg(*Args, Index);
00243     assert(Index > Prev && "Parser failed to consume argument.");
00244 
00245     // Check for missing argument error.
00246     if (!A) {
00247       assert(Index >= End && "Unexpected parser error.");
00248       assert(Index - Prev - 1 && "No missing arguments!");
00249       MissingArgIndex = Prev;
00250       MissingArgCount = Index - Prev - 1;
00251       break;
00252     }
00253 
00254     Args->append(A);
00255   }
00256 
00257   return Args;
00258 }
00259 
00260 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
00261   std::string Name = Opts.getOptionName(Id);
00262 
00263   // Add metavar, if used.
00264   switch (Opts.getOptionKind(Id)) {
00265   case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
00266     assert(0 && "Invalid option with help text.");
00267 
00268   case Option::MultiArgClass: case Option::JoinedAndSeparateClass:
00269     assert(0 && "Cannot print metavar for this kind of option.");
00270 
00271   case Option::FlagClass:
00272     break;
00273 
00274   case Option::SeparateClass: case Option::JoinedOrSeparateClass:
00275     Name += ' ';
00276     // FALLTHROUGH
00277   case Option::JoinedClass: case Option::CommaJoinedClass:
00278     if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
00279       Name += MetaVarName;
00280     else
00281       Name += "<value>";
00282     break;
00283   }
00284 
00285   return Name;
00286 }
00287 
00288 static void PrintHelpOptionList(llvm::raw_ostream &OS, llvm::StringRef Title,
00289                                 std::vector<std::pair<std::string,
00290                                 const char*> > &OptionHelp) {
00291   OS << Title << ":\n";
00292 
00293   // Find the maximum option length.
00294   unsigned OptionFieldWidth = 0;
00295   for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
00296     // Skip titles.
00297     if (!OptionHelp[i].second)
00298       continue;
00299 
00300     // Limit the amount of padding we are willing to give up for alignment.
00301     unsigned Length = OptionHelp[i].first.size();
00302     if (Length <= 23)
00303       OptionFieldWidth = std::max(OptionFieldWidth, Length);
00304   }
00305 
00306   const unsigned InitialPad = 2;
00307   for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
00308     const std::string &Option = OptionHelp[i].first;
00309     int Pad = OptionFieldWidth - int(Option.size());
00310     OS.indent(InitialPad) << Option;
00311 
00312     // Break on long option names.
00313     if (Pad < 0) {
00314       OS << "\n";
00315       Pad = OptionFieldWidth + InitialPad;
00316     }
00317     OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
00318   }
00319 }
00320 
00321 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
00322   unsigned GroupID = Opts.getOptionGroupID(Id);
00323 
00324   // If not in a group, return the default help group.
00325   if (!GroupID)
00326     return "OPTIONS";
00327 
00328   // Abuse the help text of the option groups to store the "help group"
00329   // name.
00330   //
00331   // FIXME: Split out option groups.
00332   if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
00333     return GroupHelp;
00334 
00335   // Otherwise keep looking.
00336   return getOptionHelpGroup(Opts, GroupID);
00337 }
00338 
00339 void OptTable::PrintHelp(llvm::raw_ostream &OS, const char *Name,
00340                          const char *Title, bool ShowHidden) const {
00341   OS << "OVERVIEW: " << Title << "\n";
00342   OS << '\n';
00343   OS << "USAGE: " << Name << " [options] <inputs>\n";
00344   OS << '\n';
00345 
00346   // Render help text into a map of group-name to a list of (option, help)
00347   // pairs.
00348   typedef std::map<std::string,
00349                  std::vector<std::pair<std::string, const char*> > > helpmap_ty;
00350   helpmap_ty GroupedOptionHelp;
00351 
00352   for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
00353     unsigned Id = i + 1;
00354 
00355     // FIXME: Split out option groups.
00356     if (getOptionKind(Id) == Option::GroupClass)
00357       continue;
00358 
00359     if (!ShowHidden && isOptionHelpHidden(Id))
00360       continue;
00361 
00362     if (const char *Text = getOptionHelpText(Id)) {
00363       const char *HelpGroup = getOptionHelpGroup(*this, Id);
00364       const std::string &OptName = getOptionHelpName(*this, Id);
00365       GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
00366     }
00367   }
00368 
00369   for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
00370          ie = GroupedOptionHelp.end(); it != ie; ++it) {
00371     if (it != GroupedOptionHelp .begin())
00372       OS << "\n";
00373     PrintHelpOptionList(OS, it->first, it->second);
00374   }
00375 
00376   OS.flush();
00377 }