OptTable.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- OptTable.h - Option Table --------------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_OPTION_OPTTABLE_H
  14. #define LLVM_OPTION_OPTTABLE_H
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/SmallString.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/Option/OptSpecifier.h"
  19. #include "llvm/Support/StringSaver.h"
  20. #include <cassert>
  21. #include <string>
  22. #include <vector>
  23. namespace llvm {
  24. class raw_ostream;
  25. template <typename Fn> class function_ref;
  26. namespace opt {
  27. class Arg;
  28. class ArgList;
  29. class InputArgList;
  30. class Option;
  31. /// Provide access to the Option info table.
  32. ///
  33. /// The OptTable class provides a layer of indirection which allows Option
  34. /// instance to be created lazily. In the common case, only a few options will
  35. /// be needed at runtime; the OptTable class maintains enough information to
  36. /// parse command lines without instantiating Options, while letting other
  37. /// parts of the driver still use Option instances where convenient.
  38. class OptTable {
  39. public:
  40. /// Entry for a single option instance in the option data table.
  41. struct Info {
  42. /// A null terminated array of prefix strings to apply to name while
  43. /// matching.
  44. ArrayRef<StringLiteral> Prefixes;
  45. StringRef Name;
  46. const char *HelpText;
  47. const char *MetaVar;
  48. unsigned ID;
  49. unsigned char Kind;
  50. unsigned char Param;
  51. unsigned int Flags;
  52. unsigned short GroupID;
  53. unsigned short AliasID;
  54. const char *AliasArgs;
  55. const char *Values;
  56. };
  57. private:
  58. /// The option information table.
  59. ArrayRef<Info> OptionInfos;
  60. bool IgnoreCase;
  61. bool GroupedShortOptions = false;
  62. const char *EnvVar = nullptr;
  63. unsigned InputOptionID = 0;
  64. unsigned UnknownOptionID = 0;
  65. protected:
  66. /// The index of the first option which can be parsed (i.e., is not a
  67. /// special option like 'input' or 'unknown', and is not an option group).
  68. unsigned FirstSearchableIndex = 0;
  69. /// The union of the first element of all option prefixes.
  70. SmallString<8> PrefixChars;
  71. /// The union of all option prefixes. If an argument does not begin with
  72. /// one of these, it is an input.
  73. virtual ArrayRef<StringLiteral> getPrefixesUnion() const = 0;
  74. private:
  75. const Info &getInfo(OptSpecifier Opt) const {
  76. unsigned id = Opt.getID();
  77. assert(id > 0 && id - 1 < getNumOptions() && "Invalid Option ID.");
  78. return OptionInfos[id - 1];
  79. }
  80. std::unique_ptr<Arg> parseOneArgGrouped(InputArgList &Args,
  81. unsigned &Index) const;
  82. protected:
  83. /// Initialize OptTable using Tablegen'ed OptionInfos. Child class must
  84. /// manually call \c buildPrefixChars once they are fully constructed.
  85. OptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase = false);
  86. /// Build (or rebuild) the PrefixChars member.
  87. void buildPrefixChars();
  88. public:
  89. virtual ~OptTable();
  90. /// Return the total number of option classes.
  91. unsigned getNumOptions() const { return OptionInfos.size(); }
  92. /// Get the given Opt's Option instance, lazily creating it
  93. /// if necessary.
  94. ///
  95. /// \return The option, or null for the INVALID option id.
  96. const Option getOption(OptSpecifier Opt) const;
  97. /// Lookup the name of the given option.
  98. StringRef getOptionName(OptSpecifier id) const { return getInfo(id).Name; }
  99. /// Get the kind of the given option.
  100. unsigned getOptionKind(OptSpecifier id) const {
  101. return getInfo(id).Kind;
  102. }
  103. /// Get the group id for the given option.
  104. unsigned getOptionGroupID(OptSpecifier id) const {
  105. return getInfo(id).GroupID;
  106. }
  107. /// Get the help text to use to describe this option.
  108. const char *getOptionHelpText(OptSpecifier id) const {
  109. return getInfo(id).HelpText;
  110. }
  111. /// Get the meta-variable name to use when describing
  112. /// this options values in the help text.
  113. const char *getOptionMetaVar(OptSpecifier id) const {
  114. return getInfo(id).MetaVar;
  115. }
  116. /// Specify the environment variable where initial options should be read.
  117. void setInitialOptionsFromEnvironment(const char *E) { EnvVar = E; }
  118. /// Support grouped short options. e.g. -ab represents -a -b.
  119. void setGroupedShortOptions(bool Value) { GroupedShortOptions = Value; }
  120. /// Find possible value for given flags. This is used for shell
  121. /// autocompletion.
  122. ///
  123. /// \param [in] Option - Key flag like "-stdlib=" when "-stdlib=l"
  124. /// was passed to clang.
  125. ///
  126. /// \param [in] Arg - Value which we want to autocomplete like "l"
  127. /// when "-stdlib=l" was passed to clang.
  128. ///
  129. /// \return The vector of possible values.
  130. std::vector<std::string> suggestValueCompletions(StringRef Option,
  131. StringRef Arg) const;
  132. /// Find flags from OptTable which starts with Cur.
  133. ///
  134. /// \param [in] Cur - String prefix that all returned flags need
  135. // to start with.
  136. ///
  137. /// \return The vector of flags which start with Cur.
  138. std::vector<std::string> findByPrefix(StringRef Cur,
  139. unsigned int DisableFlags) const;
  140. /// Find the OptTable option that most closely matches the given string.
  141. ///
  142. /// \param [in] Option - A string, such as "-stdlibs=l", that represents user
  143. /// input of an option that may not exist in the OptTable. Note that the
  144. /// string includes prefix dashes "-" as well as values "=l".
  145. /// \param [out] NearestString - The nearest option string found in the
  146. /// OptTable.
  147. /// \param [in] FlagsToInclude - Only find options with any of these flags.
  148. /// Zero is the default, which includes all flags.
  149. /// \param [in] FlagsToExclude - Don't find options with this flag. Zero
  150. /// is the default, and means exclude nothing.
  151. /// \param [in] MinimumLength - Don't find options shorter than this length.
  152. /// For example, a minimum length of 3 prevents "-x" from being considered
  153. /// near to "-S".
  154. /// \param [in] MaximumDistance - Don't find options whose distance is greater
  155. /// than this value.
  156. ///
  157. /// \return The edit distance of the nearest string found.
  158. unsigned findNearest(StringRef Option, std::string &NearestString,
  159. unsigned FlagsToInclude = 0, unsigned FlagsToExclude = 0,
  160. unsigned MinimumLength = 4,
  161. unsigned MaximumDistance = UINT_MAX) const;
  162. bool findExact(StringRef Option, std::string &ExactString,
  163. unsigned FlagsToInclude = 0,
  164. unsigned FlagsToExclude = 0) const {
  165. return findNearest(Option, ExactString, FlagsToInclude, FlagsToExclude, 4,
  166. 0) == 0;
  167. }
  168. /// Parse a single argument; returning the new argument and
  169. /// updating Index.
  170. ///
  171. /// \param [in,out] Index - The current parsing position in the argument
  172. /// string list; on return this will be the index of the next argument
  173. /// string to parse.
  174. /// \param [in] FlagsToInclude - Only parse options with any of these flags.
  175. /// Zero is the default which includes all flags.
  176. /// \param [in] FlagsToExclude - Don't parse options with this flag. Zero
  177. /// is the default and means exclude nothing.
  178. ///
  179. /// \return The parsed argument, or 0 if the argument is missing values
  180. /// (in which case Index still points at the conceptual next argument string
  181. /// to parse).
  182. std::unique_ptr<Arg> ParseOneArg(const ArgList &Args, unsigned &Index,
  183. unsigned FlagsToInclude = 0,
  184. unsigned FlagsToExclude = 0) const;
  185. /// Parse an list of arguments into an InputArgList.
  186. ///
  187. /// The resulting InputArgList will reference the strings in [\p ArgBegin,
  188. /// \p ArgEnd), and their lifetime should extend past that of the returned
  189. /// InputArgList.
  190. ///
  191. /// The only error that can occur in this routine is if an argument is
  192. /// missing values; in this case \p MissingArgCount will be non-zero.
  193. ///
  194. /// \param MissingArgIndex - On error, the index of the option which could
  195. /// not be parsed.
  196. /// \param MissingArgCount - On error, the number of missing options.
  197. /// \param FlagsToInclude - Only parse options with any of these flags.
  198. /// Zero is the default which includes all flags.
  199. /// \param FlagsToExclude - Don't parse options with this flag. Zero
  200. /// is the default and means exclude nothing.
  201. /// \return An InputArgList; on error this will contain all the options
  202. /// which could be parsed.
  203. InputArgList ParseArgs(ArrayRef<const char *> Args, unsigned &MissingArgIndex,
  204. unsigned &MissingArgCount, unsigned FlagsToInclude = 0,
  205. unsigned FlagsToExclude = 0) const;
  206. /// A convenience helper which handles optional initial options populated from
  207. /// an environment variable, expands response files recursively and parses
  208. /// options.
  209. ///
  210. /// \param ErrorFn - Called on a formatted error message for missing arguments
  211. /// or unknown options.
  212. /// \return An InputArgList; on error this will contain all the options which
  213. /// could be parsed.
  214. InputArgList parseArgs(int Argc, char *const *Argv, OptSpecifier Unknown,
  215. StringSaver &Saver,
  216. function_ref<void(StringRef)> ErrorFn) const;
  217. /// Render the help text for an option table.
  218. ///
  219. /// \param OS - The stream to write the help text to.
  220. /// \param Usage - USAGE: Usage
  221. /// \param Title - OVERVIEW: Title
  222. /// \param FlagsToInclude - If non-zero, only include options with any
  223. /// of these flags set.
  224. /// \param FlagsToExclude - Exclude options with any of these flags set.
  225. /// \param ShowAllAliases - If true, display all options including aliases
  226. /// that don't have help texts. By default, we display
  227. /// only options that are not hidden and have help
  228. /// texts.
  229. void printHelp(raw_ostream &OS, const char *Usage, const char *Title,
  230. unsigned FlagsToInclude, unsigned FlagsToExclude,
  231. bool ShowAllAliases) const;
  232. void printHelp(raw_ostream &OS, const char *Usage, const char *Title,
  233. bool ShowHidden = false, bool ShowAllAliases = false) const;
  234. };
  235. /// Specialization of OptTable
  236. class GenericOptTable : public OptTable {
  237. SmallVector<StringLiteral> PrefixesUnionBuffer;
  238. protected:
  239. GenericOptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase = false);
  240. ArrayRef<StringLiteral> getPrefixesUnion() const final {
  241. return PrefixesUnionBuffer;
  242. }
  243. };
  244. class PrecomputedOptTable : public OptTable {
  245. ArrayRef<StringLiteral> PrefixesUnion;
  246. protected:
  247. PrecomputedOptTable(ArrayRef<Info> OptionInfos,
  248. ArrayRef<StringLiteral> PrefixesTable,
  249. bool IgnoreCase = false)
  250. : OptTable(OptionInfos, IgnoreCase), PrefixesUnion(PrefixesTable) {
  251. buildPrefixChars();
  252. }
  253. ArrayRef<StringLiteral> getPrefixesUnion() const final {
  254. return PrefixesUnion;
  255. }
  256. };
  257. } // end namespace opt
  258. } // end namespace llvm
  259. #endif // LLVM_OPTION_OPTTABLE_H
  260. #ifdef __GNUC__
  261. #pragma GCC diagnostic pop
  262. #endif