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