OptTable.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. // HLSL Change - begin
  167. Option OptTable::findOption(const char *normalizedName, unsigned FlagsToInclude, unsigned FlagsToExclude) const {
  168. const Info *Start = OptionInfos + FirstSearchableIndex;
  169. const Info *End = OptionInfos + getNumOptions();
  170. StringRef Str(normalizedName);
  171. for (; Start != End; ++Start) {
  172. // Scan for first option which is a proper prefix.
  173. for (; Start != End; ++Start)
  174. if (Str.startswith(Start->Name))
  175. break;
  176. if (Start == End)
  177. break;
  178. Option Opt(Start, this);
  179. if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
  180. continue;
  181. if (Opt.hasFlag(FlagsToExclude))
  182. continue;
  183. return Opt;
  184. }
  185. return Option(nullptr, this);
  186. }
  187. // HLSL Change - end
  188. Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
  189. unsigned FlagsToInclude,
  190. unsigned FlagsToExclude) const {
  191. unsigned Prev = Index;
  192. const char *Str = Args.getArgString(Index);
  193. // Anything that doesn't start with PrefixesUnion is an input, as is '-'
  194. // itself.
  195. if (isInput(PrefixesUnion, Str))
  196. 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);
  200. // Search for the first next option which could be a prefix.
  201. Start = std::lower_bound(Start, End, Name.data());
  202. // Options are stored in sorted order, with '\0' at the end of the
  203. // alphabet. Since the only options which can accept a string must
  204. // prefix it, we iteratively search for the next option which could
  205. // be a prefix.
  206. //
  207. // FIXME: This is searching much more than necessary, but I am
  208. // blanking on the simplest way to make it fast. We can solve this
  209. // problem when we move to TableGen.
  210. for (; Start != End; ++Start) {
  211. unsigned ArgSize = 0;
  212. // Scan for first option which is a proper prefix.
  213. for (; Start != End; ++Start)
  214. if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
  215. break;
  216. if (Start == End)
  217. break;
  218. Option Opt(Start, this);
  219. if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
  220. continue;
  221. if (Opt.hasFlag(FlagsToExclude))
  222. continue;
  223. // See if this option matches.
  224. if (Arg *A = Opt.accept(Args, Index, ArgSize))
  225. return A;
  226. // Otherwise, see if this argument was missing values.
  227. if (Prev != Index)
  228. return nullptr;
  229. }
  230. // If we failed to find an option and this arg started with /, then it's
  231. // probably an input path.
  232. if (Str[0] == '/')
  233. return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
  234. return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
  235. }
  236. InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr,
  237. unsigned &MissingArgIndex,
  238. unsigned &MissingArgCount,
  239. unsigned FlagsToInclude,
  240. unsigned FlagsToExclude) const {
  241. InputArgList Args(ArgArr.begin(), ArgArr.end());
  242. // FIXME: Handle '@' args (or at least error on them).
  243. MissingArgIndex = MissingArgCount = 0;
  244. unsigned Index = 0, End = ArgArr.size();
  245. while (Index < End) {
  246. // Ingore nullptrs, they are response file's EOL markers
  247. if (Args.getArgString(Index) == nullptr) {
  248. ++Index;
  249. continue;
  250. }
  251. // Ignore empty arguments (other things may still take them as arguments).
  252. StringRef Str = Args.getArgString(Index);
  253. if (Str == "") {
  254. ++Index;
  255. continue;
  256. }
  257. unsigned Prev = Index;
  258. Arg *A = ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
  259. assert(Index > Prev && "Parser failed to consume argument.");
  260. // Check for missing argument error.
  261. if (!A) {
  262. assert(Index >= End && "Unexpected parser error.");
  263. assert(Index - Prev - 1 && "No missing arguments!");
  264. MissingArgIndex = Prev;
  265. MissingArgCount = Index - Prev - 1;
  266. break;
  267. }
  268. Args.append(A);
  269. }
  270. return Args;
  271. }
  272. static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
  273. const Option O = Opts.getOption(Id);
  274. 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.");
  279. case Option::MultiArgClass:
  280. if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
  281. // For MultiArgs, metavar is full list of all argument names.
  282. Name += ' ';
  283. Name += MetaVarName;
  284. }
  285. else {
  286. // For MultiArgs<N>, if metavar not supplied, print <value> N times.
  287. for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
  288. Name += " <value>";
  289. }
  290. }
  291. break;
  292. case Option::FlagClass:
  293. break;
  294. case Option::SeparateClass: case Option::JoinedOrSeparateClass:
  295. case Option::RemainingArgsClass:
  296. Name += ' ';
  297. // FALLTHROUGH
  298. case Option::JoinedClass: case Option::CommaJoinedClass:
  299. case Option::JoinedAndSeparateClass:
  300. if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
  301. Name += MetaVarName;
  302. else
  303. Name += "<value>";
  304. break;
  305. }
  306. return Name;
  307. }
  308. static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
  309. std::vector<std::pair<std::string,
  310. const char*> > &OptionHelp) {
  311. OS << Title << ":\n";
  312. // Find the maximum option length.
  313. unsigned OptionFieldWidth = 0;
  314. for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
  315. // Skip titles.
  316. if (!OptionHelp[i].second)
  317. continue;
  318. // Limit the amount of padding we are willing to give up for alignment.
  319. unsigned Length = OptionHelp[i].first.size();
  320. if (Length <= 23)
  321. OptionFieldWidth = std::max(OptionFieldWidth, Length);
  322. }
  323. const unsigned InitialPad = 2;
  324. for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
  325. const std::string &Option = OptionHelp[i].first;
  326. int Pad = OptionFieldWidth - int(Option.size());
  327. OS.indent(InitialPad) << Option;
  328. // Break on long option names.
  329. if (Pad < 0) {
  330. OS << "\n";
  331. Pad = OptionFieldWidth + InitialPad;
  332. }
  333. OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
  334. }
  335. }
  336. static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
  337. unsigned GroupID = Opts.getOptionGroupID(Id);
  338. // If not in a group, return the default help group.
  339. if (!GroupID)
  340. return "OPTIONS";
  341. // Abuse the help text of the option groups to store the "help group"
  342. // name.
  343. //
  344. // FIXME: Split out option groups.
  345. if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
  346. return GroupHelp;
  347. // Otherwise keep looking.
  348. return getOptionHelpGroup(Opts, GroupID);
  349. }
  350. void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
  351. const char *VersionInfo, bool ShowHidden) const {
  352. PrintHelp(OS, Name, Title, VersionInfo, /*Include*/ 0, /*Exclude*/
  353. (ShowHidden ? 0 : HelpHidden));
  354. }
  355. void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
  356. const char *VersionInfo, unsigned FlagsToInclude,
  357. unsigned FlagsToExclude) const {
  358. OS << "OVERVIEW: " << Title << "\n";
  359. OS << '\n';
  360. OS << "Version: " << VersionInfo << "\n";
  361. OS << '\n';
  362. OS << "USAGE: " << Name << " [options] <inputs>\n";
  363. OS << '\n';
  364. // Render help text into a map of group-name to a list of (option, help)
  365. // pairs.
  366. typedef std::map<std::string,
  367. std::vector<std::pair<std::string, const char*> > > helpmap_ty;
  368. helpmap_ty GroupedOptionHelp;
  369. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  370. unsigned Id = i + 1;
  371. // FIXME: Split out option groups.
  372. if (getOptionKind(Id) == Option::GroupClass)
  373. continue;
  374. unsigned Flags = getInfo(Id).Flags;
  375. if (FlagsToInclude && !(Flags & FlagsToInclude))
  376. continue;
  377. if (Flags & FlagsToExclude)
  378. continue;
  379. if (const char *Text = getOptionHelpText(Id)) {
  380. const char *HelpGroup = getOptionHelpGroup(*this, Id);
  381. const std::string &OptName = getOptionHelpName(*this, Id);
  382. GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
  383. }
  384. }
  385. for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
  386. ie = GroupedOptionHelp.end(); it != ie; ++it) {
  387. if (it != GroupedOptionHelp .begin())
  388. OS << "\n";
  389. PrintHelpOptionList(OS, it->first, it->second);
  390. }
  391. OS.flush();
  392. }