Options.h revision f15996eea072cdaa8a092f22d3a1212b3d95f0ec
1//===-- Options.h -----------------------------------------------*- C++ -*-===//
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
10#ifndef liblldb_Options_h_
11#define liblldb_Options_h_
12
13// C Includes
14#include <getopt.h>
15
16// C++ Includes
17#include <set>
18#include <vector>
19
20// Other libraries and framework includes
21// Project includes
22#include "lldb/lldb-private.h"
23#include "lldb/lldb-defines.h"
24#include "lldb/Interpreter/Args.h"
25
26namespace lldb_private {
27
28//----------------------------------------------------------------------
29/// @class Options Options.h "lldb/Interpreter/Options.h"
30/// @brief A command line option parsing protocol class.
31///
32/// Options is designed to be subclassed to contain all needed
33/// options for a given command. The options can be parsed by calling:
34/// \code
35///     Error Args::ParseOptions (Options &);
36/// \endcode
37///
38/// The options are specified using the format defined for the libc
39/// options parsing function getopt_long:
40/// \code
41///     #include <getopt.h>
42///     int getopt_long(int argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex);
43/// \endcode
44///
45/// Example code:
46/// \code
47///     #include <getopt.h>
48///     #include <string>
49///
50///     class CommandOptions : public Options
51///     {
52///     public:
53///         virtual struct option *
54///         GetLongOptions() {
55///             return g_options;
56///         }
57///
58///         virtual Error
59///         SetOptionValue (int option_idx, int option_val, const char *option_arg)
60///         {
61///             Error error;
62///             switch (option_val)
63///             {
64///             case 'g': debug = true; break;
65///             case 'v': verbose = true; break;
66///             case 'l': log_file = option_arg; break;
67///             case 'f': log_flags = strtoull(option_arg, NULL, 0); break;
68///             default:
69///                 error.SetErrorStringWithFormat("unrecognized short option %c", option_val);
70///                 break;
71///             }
72///
73///             return error;
74///         }
75///
76///         CommandOptions (CommandInterpreter &interpreter) : debug (true), verbose (false), log_file (), log_flags (0)
77///         {}
78///
79///         bool debug;
80///         bool verbose;
81///         std::string log_file;
82///         uint32_t log_flags;
83///
84///         static struct option g_options[];
85///
86///     };
87///
88///     struct option CommandOptions::g_options[] =
89///     {
90///         { "debug",              no_argument,        NULL,   'g' },
91///         { "log-file",           required_argument,  NULL,   'l' },
92///         { "log-flags",          required_argument,  NULL,   'f' },
93///         { "verbose",            no_argument,        NULL,   'v' },
94///         { NULL,                 0,                  NULL,   0   }
95///     };
96///
97///     int main (int argc, const char **argv, const char **envp)
98///     {
99///         CommandOptions options;
100///         Args main_command;
101///         main_command.SetArguments(argc, argv, false);
102///         main_command.ParseOptions(options);
103///
104///         if (options.verbose)
105///         {
106///             std::cout << "verbose is on" << std::endl;
107///         }
108///     }
109/// \endcode
110//----------------------------------------------------------------------
111class Options
112{
113public:
114
115    Options (CommandInterpreter &interpreter);
116
117    virtual
118    ~Options ();
119
120    void
121    BuildGetoptTable ();
122
123    void
124    BuildValidOptionSets ();
125
126    uint32_t
127    NumCommandOptions ();
128
129    //------------------------------------------------------------------
130    /// Get the option definitions to use when parsing Args options.
131    ///
132    /// @see Args::ParseOptions (Options&)
133    /// @see man getopt_long
134    //------------------------------------------------------------------
135    struct option *
136    GetLongOptions ();
137
138    // This gets passed the short option as an integer...
139    void
140    OptionSeen (int short_option);
141
142    bool
143    VerifyOptions (CommandReturnObject &result);
144
145    // Verify that the options given are in the options table and can be used together, but there may be
146    // some required options that are missing (used to verify options that get folded into command aliases).
147
148    bool
149    VerifyPartialOptions (CommandReturnObject &result);
150
151//    void
152//    BuildAliasOptions (OptionArgVector *option_arg_vector, Args args);
153
154    void
155    OutputFormattedUsageText (Stream &strm,
156                              const char *text,
157                              uint32_t output_max_columns);
158
159    void
160    GenerateOptionUsage (Stream &strm,
161                         CommandObject *cmd);
162
163    // The following two pure virtual functions must be defined by every class that inherits from
164    // this class.
165
166    virtual const OptionDefinition*
167    GetDefinitions () { return NULL; }
168
169    // Call this prior to parsing any options. This call will call the
170    // subclass ResetOptionValues() and will avoid the need for all
171    // ResetOptionValues() function instances from having to call the
172    // Option::ResetOptionValues() like they did before. This was error
173    // prone and subclasses shouldn't have to do it.
174    void
175    Reset ();
176
177    //------------------------------------------------------------------
178    /// Set the value of an option.
179    ///
180    /// @param[in] option_idx
181    ///     The index into the "struct option" array that was returned
182    ///     by Options::GetLongOptions().
183    ///
184    /// @param[in] option_arg
185    ///     The argument value for the option that the user entered, or
186    ///     NULL if there is no argument for the current option.
187    ///
188    ///
189    /// @see Args::ParseOptions (Options&)
190    /// @see man getopt_long
191    //------------------------------------------------------------------
192    virtual Error
193    SetOptionValue (int option_idx, const char *option_arg) = 0;
194
195    //------------------------------------------------------------------
196    ///  Handles the generic bits of figuring out whether we are in an option, and if so completing
197    /// it.
198    ///
199    /// @param[in] input
200    ///    The command line parsed into words
201    ///
202    /// @param[in] cursor_index
203    ///     The index in \ainput of the word in which the cursor lies.
204    ///
205    /// @param[in] char_pos
206    ///     The character position of the cursor in its argument word.
207    ///
208    /// @param[in] match_start_point
209    /// @param[in] match_return_elements
210    ///     See CommandObject::HandleCompletions for a description of how these work.
211    ///
212    /// @param[in] interpreter
213    ///     The interpreter that's doing the completing.
214    ///
215    /// @param[out] word_complete
216    ///     \btrue if this is a complete option value (a space will be inserted after the
217    ///     completion.)  \bfalse otherwise.
218    ///
219    /// @param[out] matches
220    ///     The array of matches returned.
221    ///
222    /// FIXME: This is the wrong return value, since we also need to make a distinction between
223    /// total number of matches, and the window the user wants returned.
224    ///
225    /// @return
226    ///     \btrue if we were in an option, \bfalse otherwise.
227    //------------------------------------------------------------------
228    bool
229    HandleOptionCompletion (Args &input,
230                            OptionElementVector &option_map,
231                            int cursor_index,
232                            int char_pos,
233                            int match_start_point,
234                            int max_return_elements,
235                            bool &word_complete,
236                            lldb_private::StringList &matches);
237
238    //------------------------------------------------------------------
239    ///  Handles the generic bits of figuring out whether we are in an option, and if so completing
240    /// it.
241    ///
242    /// @param[in] interpreter
243    ///    The command interpreter doing the completion.
244    ///
245    /// @param[in] input
246    ///    The command line parsed into words
247    ///
248    /// @param[in] cursor_index
249    ///     The index in \ainput of the word in which the cursor lies.
250    ///
251    /// @param[in] char_pos
252    ///     The character position of the cursor in its argument word.
253    ///
254    /// @param[in] opt_element_vector
255    ///     The results of the options parse of \a input.
256    ///
257    /// @param[in] opt_element_index
258    ///     The position in \a opt_element_vector of the word in \a input containing the cursor.
259    ///
260    /// @param[in] match_start_point
261    /// @param[in] match_return_elements
262    ///     See CommandObject::HandleCompletions for a description of how these work.
263    ///
264    /// @param[out] word_complete
265    ///     \btrue if this is a complete option value (a space will be inserted after the
266    ///     completion.)  \bfalse otherwise.
267    ///
268    /// @param[out] matches
269    ///     The array of matches returned.
270    ///
271    /// FIXME: This is the wrong return value, since we also need to make a distinction between
272    /// total number of matches, and the window the user wants returned.
273    ///
274    /// @return
275    ///     \btrue if we were in an option, \bfalse otherwise.
276    //------------------------------------------------------------------
277    virtual bool
278    HandleOptionArgumentCompletion (Args &input,
279                                    int cursor_index,
280                                    int char_pos,
281                                    OptionElementVector &opt_element_vector,
282                                    int opt_element_index,
283                                    int match_start_point,
284                                    int max_return_elements,
285                                    bool &word_complete,
286                                    StringList &matches);
287
288protected:
289    // This is a set of options expressed as indexes into the options table for this Option.
290    typedef std::set<char> OptionSet;
291    typedef std::vector<OptionSet> OptionSetVector;
292
293    CommandInterpreter &m_interpreter;
294    std::vector<struct option> m_getopt_table;
295    OptionSet m_seen_options;
296    OptionSetVector m_required_options;
297    OptionSetVector m_optional_options;
298
299    OptionSetVector &GetRequiredOptions ()
300    {
301        BuildValidOptionSets();
302        return m_required_options;
303    }
304
305    OptionSetVector &GetOptionalOptions ()
306    {
307        BuildValidOptionSets();
308        return m_optional_options;
309    }
310
311    bool
312    IsASubset (const OptionSet& set_a, const OptionSet& set_b);
313
314    size_t
315    OptionsSetDiff (const OptionSet &set_a, const OptionSet &set_b, OptionSet &diffs);
316
317    void
318    OptionsSetUnion (const OptionSet &set_a, const OptionSet &set_b, OptionSet &union_set);
319
320    // Subclasses must reset their option values prior to starting a new
321    // option parse. Each subclass must override this function and revert
322    // all option settings to default values.
323    virtual void
324    ResetOptionValues () = 0;
325};
326
327} // namespace lldb_private
328
329#endif  // liblldb_Options_h_
330