2
0

OptTable.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. //===--- OptTable.cpp - Option Table Implementation -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "llvm/Option/OptTable.h"
  10. #include "llvm/Option/Arg.h"
  11. #include "llvm/Option/ArgList.h"
  12. #include "llvm/Option/Option.h"
  13. #include "llvm/Support/ErrorHandling.h"
  14. #include "llvm/Support/raw_ostream.h"
  15. #include <algorithm>
  16. #include <cctype>
  17. #include <map>
  18. using namespace llvm;
  19. using namespace llvm::opt;
  20. namespace llvm {
  21. namespace opt {
  22. // Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
  23. // with an exceptions. '\0' comes at the end of the alphabet instead of the
  24. // beginning (thus options precede any other options which prefix them).
  25. static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) {
  26. const char *X = A, *Y = B;
  27. char a = tolower(*A), b = tolower(*B);
  28. while (a == b) {
  29. if (a == '\0')
  30. return 0;
  31. a = tolower(*++X);
  32. b = tolower(*++Y);
  33. }
  34. if (a == '\0') // A is a prefix of B.
  35. return 1;
  36. if (b == '\0') // B is a prefix of A.
  37. return -1;
  38. // Otherwise lexicographic.
  39. return (a < b) ? -1 : 1;
  40. }
  41. #ifndef NDEBUG
  42. static int StrCmpOptionName(const char *A, const char *B) {
  43. if (int N = StrCmpOptionNameIgnoreCase(A, B))
  44. return N;
  45. return strcmp(A, B);
  46. }
  47. static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
  48. if (&A == &B)
  49. return false;
  50. if (int N = StrCmpOptionName(A.Name, B.Name))
  51. return N < 0;
  52. for (const char * const *APre = A.Prefixes,
  53. * const *BPre = B.Prefixes;
  54. *APre != nullptr && *BPre != nullptr; ++APre, ++BPre){
  55. if (int N = StrCmpOptionName(*APre, *BPre))
  56. return N < 0;
  57. }
  58. // Names are the same, check that classes are in order; exactly one
  59. // should be joined, and it should succeed the other.
  60. assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
  61. "Unexpected classes for options with same name.");
  62. return B.Kind == Option::JoinedClass;
  63. }
  64. #endif
  65. // Support lower_bound between info and an option name.
  66. static inline bool operator<(const OptTable::Info &I, const char *Name) {
  67. return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
  68. }
  69. }
  70. }
  71. OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
  72. OptTable::OptTable(const Info *OptionInfos, unsigned NumOptionInfos,
  73. bool IgnoreCase)
  74. : OptionInfos(OptionInfos), NumOptionInfos(NumOptionInfos),
  75. IgnoreCase(IgnoreCase), TheInputOptionID(0), TheUnknownOptionID(0),
  76. FirstSearchableIndex(0) {
  77. // Explicitly zero initialize the error to work around a bug in array
  78. // value-initialization on MinGW with gcc 4.3.5.
  79. // Find start of normal options.
  80. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  81. unsigned Kind = getInfo(i + 1).Kind;
  82. if (Kind == Option::InputClass) {
  83. assert(!TheInputOptionID && "Cannot have multiple input options!");
  84. TheInputOptionID = getInfo(i + 1).ID;
  85. } else if (Kind == Option::UnknownClass) {
  86. assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
  87. TheUnknownOptionID = getInfo(i + 1).ID;
  88. } else if (Kind != Option::GroupClass) {
  89. FirstSearchableIndex = i;
  90. break;
  91. }
  92. }
  93. assert(FirstSearchableIndex != 0 && "No searchable options?");
  94. #ifndef NDEBUG
  95. // Check that everything after the first searchable option is a
  96. // regular option class.
  97. for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
  98. Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
  99. assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
  100. Kind != Option::GroupClass) &&
  101. "Special options should be defined first!");
  102. }
  103. // Check that options are in order.
  104. for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
  105. if (!(getInfo(i) < getInfo(i + 1))) {
  106. getOption(i).dump();
  107. getOption(i + 1).dump();
  108. llvm_unreachable("Options are not in order!");
  109. }
  110. }
  111. #endif
  112. // Build prefixes.
  113. for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
  114. i != e; ++i) {
  115. if (const char *const *P = getInfo(i).Prefixes) {
  116. for (; *P != nullptr; ++P) {
  117. PrefixesUnion.insert(*P);
  118. }
  119. }
  120. }
  121. // Build prefix chars.
  122. for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(),
  123. E = PrefixesUnion.end(); I != E; ++I) {
  124. StringRef Prefix = I->getKey();
  125. for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
  126. C != CE; ++C)
  127. if (std::find(PrefixChars.begin(), PrefixChars.end(), *C)
  128. == PrefixChars.end())
  129. PrefixChars.push_back(*C);
  130. }
  131. }
  132. OptTable::~OptTable() {
  133. }
  134. const Option OptTable::getOption(OptSpecifier Opt) const {
  135. unsigned id = Opt.getID();
  136. if (id == 0)
  137. return Option(nullptr, nullptr);
  138. assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
  139. return Option(&getInfo(id), this);
  140. }
  141. static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
  142. if (Arg == "-")
  143. return true;
  144. for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
  145. E = Prefixes.end(); I != E; ++I)
  146. if (Arg.startswith(I->getKey()))
  147. return false;
  148. return true;
  149. }
  150. /// \returns Matched size. 0 means no match.
  151. static unsigned matchOption(const OptTable::Info *I, StringRef Str,
  152. bool IgnoreCase) {
  153. for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) {
  154. StringRef Prefix(*Pre);
  155. if (Str.startswith(Prefix)) {
  156. StringRef Rest = Str.substr(Prefix.size());
  157. bool Matched = IgnoreCase
  158. ? Rest.startswith_lower(I->Name)
  159. : Rest.startswith(I->Name);
  160. if (Matched)
  161. return Prefix.size() + StringRef(I->Name).size();
  162. }
  163. }
  164. return 0;
  165. }
  166. Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
  167. unsigned FlagsToInclude,
  168. unsigned FlagsToExclude) const {
  169. unsigned Prev = Index;
  170. const char *Str = Args.getArgString(Index);
  171. // Anything that doesn't start with PrefixesUnion is an input, as is '-'
  172. // itself.
  173. if (isInput(PrefixesUnion, Str))
  174. return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
  175. const Info *Start = OptionInfos + FirstSearchableIndex;
  176. const Info *End = OptionInfos + getNumOptions();
  177. StringRef Name = StringRef(Str).ltrim(PrefixChars);
  178. // Search for the first next option which could be a prefix.
  179. Start = std::lower_bound(Start, End, Name.data());
  180. // Options are stored in sorted order, with '\0' at the end of the
  181. // alphabet. Since the only options which can accept a string must
  182. // prefix it, we iteratively search for the next option which could
  183. // be a prefix.
  184. //
  185. // FIXME: This is searching much more than necessary, but I am
  186. // blanking on the simplest way to make it fast. We can solve this
  187. // problem when we move to TableGen.
  188. for (; Start != End; ++Start) {
  189. unsigned ArgSize = 0;
  190. // Scan for first option which is a proper prefix.
  191. for (; Start != End; ++Start)
  192. if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
  193. break;
  194. if (Start == End)
  195. break;
  196. Option Opt(Start, this);
  197. if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
  198. continue;
  199. if (Opt.hasFlag(FlagsToExclude))
  200. continue;
  201. // See if this option matches.
  202. if (Arg *A = Opt.accept(Args, Index, ArgSize))
  203. return A;
  204. // Otherwise, see if this argument was missing values.
  205. if (Prev != Index)
  206. return nullptr;
  207. }
  208. // If we failed to find an option and this arg started with /, then it's
  209. // probably an input path.
  210. if (Str[0] == '/')
  211. return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
  212. return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
  213. }
  214. InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr,
  215. unsigned &MissingArgIndex,
  216. unsigned &MissingArgCount,
  217. unsigned FlagsToInclude,
  218. unsigned FlagsToExclude) const {
  219. InputArgList Args(ArgArr.begin(), ArgArr.end());
  220. // FIXME: Handle '@' args (or at least error on them).
  221. MissingArgIndex = MissingArgCount = 0;
  222. unsigned Index = 0, End = ArgArr.size();
  223. while (Index < End) {
  224. // Ingore nullptrs, they are response file's EOL markers
  225. if (Args.getArgString(Index) == nullptr) {
  226. ++Index;
  227. continue;
  228. }
  229. // Ignore empty arguments (other things may still take them as arguments).
  230. StringRef Str = Args.getArgString(Index);
  231. if (Str == "") {
  232. ++Index;
  233. continue;
  234. }
  235. unsigned Prev = Index;
  236. Arg *A = ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
  237. assert(Index > Prev && "Parser failed to consume argument.");
  238. // Check for missing argument error.
  239. if (!A) {
  240. assert(Index >= End && "Unexpected parser error.");
  241. assert(Index - Prev - 1 && "No missing arguments!");
  242. MissingArgIndex = Prev;
  243. MissingArgCount = Index - Prev - 1;
  244. break;
  245. }
  246. Args.append(A);
  247. }
  248. return Args;
  249. }
  250. static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
  251. const Option O = Opts.getOption(Id);
  252. std::string Name = O.getPrefixedName();
  253. // Add metavar, if used.
  254. switch (O.getKind()) {
  255. case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
  256. llvm_unreachable("Invalid option with help text.");
  257. case Option::MultiArgClass:
  258. if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
  259. // For MultiArgs, metavar is full list of all argument names.
  260. Name += ' ';
  261. Name += MetaVarName;
  262. }
  263. else {
  264. // For MultiArgs<N>, if metavar not supplied, print <value> N times.
  265. for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
  266. Name += " <value>";
  267. }
  268. }
  269. break;
  270. case Option::FlagClass:
  271. break;
  272. case Option::SeparateClass: case Option::JoinedOrSeparateClass:
  273. case Option::RemainingArgsClass:
  274. Name += ' ';
  275. // FALLTHROUGH
  276. case Option::JoinedClass: case Option::CommaJoinedClass:
  277. case Option::JoinedAndSeparateClass:
  278. if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
  279. Name += MetaVarName;
  280. else
  281. Name += "<value>";
  282. break;
  283. }
  284. return Name;
  285. }
  286. static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
  287. std::vector<std::pair<std::string,
  288. const char*> > &OptionHelp) {
  289. OS << Title << ":\n";
  290. // Find the maximum option length.
  291. unsigned OptionFieldWidth = 0;
  292. for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
  293. // Skip titles.
  294. if (!OptionHelp[i].second)
  295. continue;
  296. // Limit the amount of padding we are willing to give up for alignment.
  297. unsigned Length = OptionHelp[i].first.size();
  298. if (Length <= 23)
  299. OptionFieldWidth = std::max(OptionFieldWidth, Length);
  300. }
  301. const unsigned InitialPad = 2;
  302. for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
  303. const std::string &Option = OptionHelp[i].first;
  304. int Pad = OptionFieldWidth - int(Option.size());
  305. OS.indent(InitialPad) << Option;
  306. // Break on long option names.
  307. if (Pad < 0) {
  308. OS << "\n";
  309. Pad = OptionFieldWidth + InitialPad;
  310. }
  311. OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
  312. }
  313. }
  314. static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
  315. unsigned GroupID = Opts.getOptionGroupID(Id);
  316. // If not in a group, return the default help group.
  317. if (!GroupID)
  318. return "OPTIONS";
  319. // Abuse the help text of the option groups to store the "help group"
  320. // name.
  321. //
  322. // FIXME: Split out option groups.
  323. if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
  324. return GroupHelp;
  325. // Otherwise keep looking.
  326. return getOptionHelpGroup(Opts, GroupID);
  327. }
  328. void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
  329. const char *VersionInfo, bool ShowHidden) const {
  330. PrintHelp(OS, Name, Title, VersionInfo, /*Include*/ 0, /*Exclude*/
  331. (ShowHidden ? 0 : HelpHidden));
  332. }
  333. void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
  334. const char *VersionInfo, unsigned FlagsToInclude,
  335. unsigned FlagsToExclude) const {
  336. OS << "OVERVIEW: " << Title << "\n";
  337. OS << '\n';
  338. OS << "Version: " << VersionInfo << "\n";
  339. OS << '\n';
  340. OS << "USAGE: " << Name << " [options] <inputs>\n";
  341. OS << '\n';
  342. // Render help text into a map of group-name to a list of (option, help)
  343. // pairs.
  344. typedef std::map<std::string,
  345. std::vector<std::pair<std::string, const char*> > > helpmap_ty;
  346. helpmap_ty GroupedOptionHelp;
  347. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  348. unsigned Id = i + 1;
  349. // FIXME: Split out option groups.
  350. if (getOptionKind(Id) == Option::GroupClass)
  351. continue;
  352. unsigned Flags = getInfo(Id).Flags;
  353. if (FlagsToInclude && !(Flags & FlagsToInclude))
  354. continue;
  355. if (Flags & FlagsToExclude)
  356. continue;
  357. if (const char *Text = getOptionHelpText(Id)) {
  358. const char *HelpGroup = getOptionHelpGroup(*this, Id);
  359. const std::string &OptName = getOptionHelpName(*this, Id);
  360. GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
  361. }
  362. }
  363. for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
  364. ie = GroupedOptionHelp.end(); it != ie; ++it) {
  365. if (it != GroupedOptionHelp .begin())
  366. OS << "\n";
  367. PrintHelpOptionList(OS, it->first, it->second);
  368. }
  369. OS.flush();
  370. }