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/SmallString.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/Option/OptSpecifier.h"
16#include "llvm/Support/StringSaver.h"
17#include <cassert>
18#include <string>
19#include <vector>
20
21namespace llvm {
22
23class raw_ostream;
24template <typename Fn> class function_ref;
25
26namespace opt {
27
28class Arg;
29class ArgList;
30class InputArgList;
31class 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.
40class OptTable {
41public:
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 ArrayRef<StringLiteral> Prefixes;
47 StringRef 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
60private:
61 /// The option information table.
62 ArrayRef<Info> OptionInfos;
63 bool IgnoreCase;
64 bool GroupedShortOptions = false;
65 bool DashDashParsing = false;
66 const char *EnvVar = nullptr;
67
68 unsigned InputOptionID = 0;
69 unsigned UnknownOptionID = 0;
70
71protected:
72 /// The index of the first option which can be parsed (i.e., is not a
73 /// special option like 'input' or 'unknown', and is not an option group).
74 unsigned FirstSearchableIndex = 0;
75
76 /// The union of the first element of all option prefixes.
77 SmallString<8> PrefixChars;
78
79 /// The union of all option prefixes. If an argument does not begin with
80 /// one of these, it is an input.
81 virtual ArrayRef<StringLiteral> getPrefixesUnion() const = 0;
82
83private:
84 const Info &getInfo(OptSpecifier Opt) const {
85 unsigned id = Opt.getID();
86 assert(id > 0 && id - 1 < getNumOptions() && "Invalid Option ID.");
87 return OptionInfos[id - 1];
88 }
89
90 std::unique_ptr<Arg> parseOneArgGrouped(InputArgList &Args,
91 unsigned &Index) const;
92
93protected:
94 /// Initialize OptTable using Tablegen'ed OptionInfos. Child class must
95 /// manually call \c buildPrefixChars once they are fully constructed.
96 OptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase = false);
97
98 /// Build (or rebuild) the PrefixChars member.
99 void buildPrefixChars();
100
101public:
102 virtual ~OptTable();
103
104 /// Return the total number of option classes.
105 unsigned getNumOptions() const { return OptionInfos.size(); }
106
107 /// Get the given Opt's Option instance, lazily creating it
108 /// if necessary.
109 ///
110 /// \return The option, or null for the INVALID option id.
111 const Option getOption(OptSpecifier Opt) const;
112
113 /// Lookup the name of the given option.
114 StringRef getOptionName(OptSpecifier id) const { return getInfo(Opt: id).Name; }
115
116 /// Get the kind of the given option.
117 unsigned getOptionKind(OptSpecifier id) const {
118 return getInfo(Opt: id).Kind;
119 }
120
121 /// Get the group id for the given option.
122 unsigned getOptionGroupID(OptSpecifier id) const {
123 return getInfo(Opt: id).GroupID;
124 }
125
126 /// Get the help text to use to describe this option.
127 const char *getOptionHelpText(OptSpecifier id) const {
128 return getInfo(Opt: id).HelpText;
129 }
130
131 /// Get the meta-variable name to use when describing
132 /// this options values in the help text.
133 const char *getOptionMetaVar(OptSpecifier id) const {
134 return getInfo(Opt: id).MetaVar;
135 }
136
137 /// Specify the environment variable where initial options should be read.
138 void setInitialOptionsFromEnvironment(const char *E) { EnvVar = E; }
139
140 /// Support grouped short options. e.g. -ab represents -a -b.
141 void setGroupedShortOptions(bool Value) { GroupedShortOptions = Value; }
142
143 /// Set whether "--" stops option parsing and treats all subsequent arguments
144 /// as positional. E.g. -- -a -b gives two positional inputs.
145 void setDashDashParsing(bool Value) { DashDashParsing = Value; }
146
147 /// Find possible value for given flags. This is used for shell
148 /// autocompletion.
149 ///
150 /// \param [in] Option - Key flag like "-stdlib=" when "-stdlib=l"
151 /// was passed to clang.
152 ///
153 /// \param [in] Arg - Value which we want to autocomplete like "l"
154 /// when "-stdlib=l" was passed to clang.
155 ///
156 /// \return The vector of possible values.
157 std::vector<std::string> suggestValueCompletions(StringRef Option,
158 StringRef Arg) const;
159
160 /// Find flags from OptTable which starts with Cur.
161 ///
162 /// \param [in] Cur - String prefix that all returned flags need
163 // to start with.
164 ///
165 /// \return The vector of flags which start with Cur.
166 std::vector<std::string> findByPrefix(StringRef Cur,
167 unsigned int DisableFlags) const;
168
169 /// Find the OptTable option that most closely matches the given string.
170 ///
171 /// \param [in] Option - A string, such as "-stdlibs=l", that represents user
172 /// input of an option that may not exist in the OptTable. Note that the
173 /// string includes prefix dashes "-" as well as values "=l".
174 /// \param [out] NearestString - The nearest option string found in the
175 /// OptTable.
176 /// \param [in] FlagsToInclude - Only find options with any of these flags.
177 /// Zero is the default, which includes all flags.
178 /// \param [in] FlagsToExclude - Don't find options with this flag. Zero
179 /// is the default, and means exclude nothing.
180 /// \param [in] MinimumLength - Don't find options shorter than this length.
181 /// For example, a minimum length of 3 prevents "-x" from being considered
182 /// near to "-S".
183 /// \param [in] MaximumDistance - Don't find options whose distance is greater
184 /// than this value.
185 ///
186 /// \return The edit distance of the nearest string found.
187 unsigned findNearest(StringRef Option, std::string &NearestString,
188 unsigned FlagsToInclude = 0, unsigned FlagsToExclude = 0,
189 unsigned MinimumLength = 4,
190 unsigned MaximumDistance = UINT_MAX) const;
191
192 bool findExact(StringRef Option, std::string &ExactString,
193 unsigned FlagsToInclude = 0,
194 unsigned FlagsToExclude = 0) const {
195 return findNearest(Option, NearestString&: ExactString, FlagsToInclude, FlagsToExclude, MinimumLength: 4,
196 MaximumDistance: 0) == 0;
197 }
198
199 /// Parse a single argument; returning the new argument and
200 /// updating Index.
201 ///
202 /// \param [in,out] Index - The current parsing position in the argument
203 /// string list; on return this will be the index of the next argument
204 /// string to parse.
205 /// \param [in] FlagsToInclude - Only parse options with any of these flags.
206 /// Zero is the default which includes all flags.
207 /// \param [in] FlagsToExclude - Don't parse options with this flag. Zero
208 /// is the default and means exclude nothing.
209 ///
210 /// \return The parsed argument, or 0 if the argument is missing values
211 /// (in which case Index still points at the conceptual next argument string
212 /// to parse).
213 std::unique_ptr<Arg> ParseOneArg(const ArgList &Args, unsigned &Index,
214 unsigned FlagsToInclude = 0,
215 unsigned FlagsToExclude = 0) const;
216
217 /// Parse an list of arguments into an InputArgList.
218 ///
219 /// The resulting InputArgList will reference the strings in [\p ArgBegin,
220 /// \p ArgEnd), and their lifetime should extend past that of the returned
221 /// InputArgList.
222 ///
223 /// The only error that can occur in this routine is if an argument is
224 /// missing values; in this case \p MissingArgCount will be non-zero.
225 ///
226 /// \param MissingArgIndex - On error, the index of the option which could
227 /// not be parsed.
228 /// \param MissingArgCount - On error, the number of missing options.
229 /// \param FlagsToInclude - Only parse options with any of these flags.
230 /// Zero is the default which includes all flags.
231 /// \param FlagsToExclude - Don't parse options with this flag. Zero
232 /// is the default and means exclude nothing.
233 /// \return An InputArgList; on error this will contain all the options
234 /// which could be parsed.
235 InputArgList ParseArgs(ArrayRef<const char *> Args, unsigned &MissingArgIndex,
236 unsigned &MissingArgCount, unsigned FlagsToInclude = 0,
237 unsigned FlagsToExclude = 0) const;
238
239 /// A convenience helper which handles optional initial options populated from
240 /// an environment variable, expands response files recursively and parses
241 /// options.
242 ///
243 /// \param ErrorFn - Called on a formatted error message for missing arguments
244 /// or unknown options.
245 /// \return An InputArgList; on error this will contain all the options which
246 /// could be parsed.
247 InputArgList parseArgs(int Argc, char *const *Argv, OptSpecifier Unknown,
248 StringSaver &Saver,
249 function_ref<void(StringRef)> ErrorFn) const;
250
251 /// Render the help text for an option table.
252 ///
253 /// \param OS - The stream to write the help text to.
254 /// \param Usage - USAGE: Usage
255 /// \param Title - OVERVIEW: Title
256 /// \param FlagsToInclude - If non-zero, only include options with any
257 /// of these flags set.
258 /// \param FlagsToExclude - Exclude options with any of these flags set.
259 /// \param ShowAllAliases - If true, display all options including aliases
260 /// that don't have help texts. By default, we display
261 /// only options that are not hidden and have help
262 /// texts.
263 void printHelp(raw_ostream &OS, const char *Usage, const char *Title,
264 unsigned FlagsToInclude, unsigned FlagsToExclude,
265 bool ShowAllAliases) const;
266
267 void printHelp(raw_ostream &OS, const char *Usage, const char *Title,
268 bool ShowHidden = false, bool ShowAllAliases = false) const;
269};
270
271/// Specialization of OptTable
272class GenericOptTable : public OptTable {
273 SmallVector<StringLiteral> PrefixesUnionBuffer;
274
275protected:
276 GenericOptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase = false);
277 ArrayRef<StringLiteral> getPrefixesUnion() const final {
278 return PrefixesUnionBuffer;
279 }
280};
281
282class PrecomputedOptTable : public OptTable {
283 ArrayRef<StringLiteral> PrefixesUnion;
284
285protected:
286 PrecomputedOptTable(ArrayRef<Info> OptionInfos,
287 ArrayRef<StringLiteral> PrefixesTable,
288 bool IgnoreCase = false)
289 : OptTable(OptionInfos, IgnoreCase), PrefixesUnion(PrefixesTable) {
290 buildPrefixChars();
291 }
292 ArrayRef<StringLiteral> getPrefixesUnion() const final {
293 return PrefixesUnion;
294 }
295};
296
297} // end namespace opt
298
299} // end namespace llvm
300
301#endif // LLVM_OPTION_OPTTABLE_H
302

source code of include/llvm-17/llvm/Option/OptTable.h