Options.h revision 263363
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
15// C++ Includes
16#include <set>
17#include <vector>
18
19// Other libraries and framework includes
20// Project includes
21#include "lldb/lldb-private.h"
22#include "lldb/lldb-defines.h"
23#include "lldb/Interpreter/Args.h"
24
25namespace lldb_private {
26
27  static inline bool
28  isprint8 (int ch)
29  {
30      if (ch & 0xffffff00u)
31          return false;
32      return isprint(ch);
33  }
34
35
36//----------------------------------------------------------------------
37/// @class Options Options.h "lldb/Interpreter/Options.h"
38/// @brief A command line option parsing protocol class.
39///
40/// Options is designed to be subclassed to contain all needed
41/// options for a given command. The options can be parsed by calling:
42/// \code
43///     Error Args::ParseOptions (Options &);
44/// \endcode
45///
46/// The options are specified using the format defined for the libc
47/// options parsing function getopt_long_only:
48/// \code
49///     #include <getopt.h>
50///     int getopt_long_only(int argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex);
51/// \endcode
52///
53/// Example code:
54/// \code
55///     #include <getopt.h>
56///     #include <string>
57///
58///     class CommandOptions : public Options
59///     {
60///     public:
61///         virtual struct option *
62///         GetLongOptions() {
63///             return g_options;
64///         }
65///
66///         virtual Error
67///         SetOptionValue (uint32_t option_idx, int option_val, const char *option_arg)
68///         {
69///             Error error;
70///             switch (option_val)
71///             {
72///             case 'g': debug = true; break;
73///             case 'v': verbose = true; break;
74///             case 'l': log_file = option_arg; break;
75///             case 'f': log_flags = strtoull(option_arg, NULL, 0); break;
76///             default:
77///                 error.SetErrorStringWithFormat("unrecognized short option %c", option_val);
78///                 break;
79///             }
80///
81///             return error;
82///         }
83///
84///         CommandOptions (CommandInterpreter &interpreter) : debug (true), verbose (false), log_file (), log_flags (0)
85///         {}
86///
87///         bool debug;
88///         bool verbose;
89///         std::string log_file;
90///         uint32_t log_flags;
91///
92///         static struct option g_options[];
93///
94///     };
95///
96///     struct option CommandOptions::g_options[] =
97///     {
98///         { "debug",              no_argument,        NULL,   'g' },
99///         { "log-file",           required_argument,  NULL,   'l' },
100///         { "log-flags",          required_argument,  NULL,   'f' },
101///         { "verbose",            no_argument,        NULL,   'v' },
102///         { NULL,                 0,                  NULL,   0   }
103///     };
104///
105///     int main (int argc, const char **argv, const char **envp)
106///     {
107///         CommandOptions options;
108///         Args main_command;
109///         main_command.SetArguments(argc, argv, false);
110///         main_command.ParseOptions(options);
111///
112///         if (options.verbose)
113///         {
114///             std::cout << "verbose is on" << std::endl;
115///         }
116///     }
117/// \endcode
118//----------------------------------------------------------------------
119class Options
120{
121public:
122
123    Options (CommandInterpreter &interpreter);
124
125    virtual
126    ~Options ();
127
128    void
129    BuildGetoptTable ();
130
131    void
132    BuildValidOptionSets ();
133
134    uint32_t
135    NumCommandOptions ();
136
137    //------------------------------------------------------------------
138    /// Get the option definitions to use when parsing Args options.
139    ///
140    /// @see Args::ParseOptions (Options&)
141    /// @see man getopt_long_only
142    //------------------------------------------------------------------
143    Option *
144    GetLongOptions ();
145
146    // This gets passed the short option as an integer...
147    void
148    OptionSeen (int short_option);
149
150    bool
151    VerifyOptions (CommandReturnObject &result);
152
153    // Verify that the options given are in the options table and can
154    // be used together, but there may be some required options that are
155    // missing (used to verify options that get folded into command aliases).
156
157    bool
158    VerifyPartialOptions (CommandReturnObject &result);
159
160    void
161    OutputFormattedUsageText (Stream &strm,
162                              const char *text,
163                              uint32_t output_max_columns);
164
165    void
166    GenerateOptionUsage (Stream &strm,
167                         CommandObject *cmd);
168
169    bool
170    SupportsLongOption (const char *long_option);
171
172    // The following two pure virtual functions must be defined by every
173    // class that inherits from this class.
174
175    virtual const OptionDefinition*
176    GetDefinitions () { return NULL; }
177
178    // Call this prior to parsing any options. This call will call the
179    // subclass OptionParsingStarting() and will avoid the need for all
180    // OptionParsingStarting() function instances from having to call the
181    // Option::OptionParsingStarting() like they did before. This was error
182    // prone and subclasses shouldn't have to do it.
183    void
184    NotifyOptionParsingStarting ();
185
186    Error
187    NotifyOptionParsingFinished ();
188
189    //------------------------------------------------------------------
190    /// Set the value of an option.
191    ///
192    /// @param[in] option_idx
193    ///     The index into the "struct option" array that was returned
194    ///     by Options::GetLongOptions().
195    ///
196    /// @param[in] option_arg
197    ///     The argument value for the option that the user entered, or
198    ///     NULL if there is no argument for the current option.
199    ///
200    ///
201    /// @see Args::ParseOptions (Options&)
202    /// @see man getopt_long_only
203    //------------------------------------------------------------------
204    virtual Error
205    SetOptionValue (uint32_t option_idx, const char *option_arg) = 0;
206
207    //------------------------------------------------------------------
208    /// Handles the generic bits of figuring out whether we are in an
209    /// option, and if so completing it.
210    ///
211    /// @param[in] input
212    ///    The command line parsed into words
213    ///
214    /// @param[in] cursor_index
215    ///     The index in \ainput of the word in which the cursor lies.
216    ///
217    /// @param[in] char_pos
218    ///     The character position of the cursor in its argument word.
219    ///
220    /// @param[in] match_start_point
221    /// @param[in] match_return_elements
222    ///     See CommandObject::HandleCompletions for a description of
223    ///     how these work.
224    ///
225    /// @param[in] interpreter
226    ///     The interpreter that's doing the completing.
227    ///
228    /// @param[out] word_complete
229    ///     \btrue if this is a complete option value (a space will be
230    ///     inserted after the completion.) \b false otherwise.
231    ///
232    /// @param[out] matches
233    ///     The array of matches returned.
234    ///
235    /// FIXME: This is the wrong return value, since we also need to
236    /// make a distinction between total number of matches, and the
237    /// window the user wants returned.
238    ///
239    /// @return
240    ///     \btrue if we were in an option, \bfalse otherwise.
241    //------------------------------------------------------------------
242    bool
243    HandleOptionCompletion (Args &input,
244                            OptionElementVector &option_map,
245                            int cursor_index,
246                            int char_pos,
247                            int match_start_point,
248                            int max_return_elements,
249                            bool &word_complete,
250                            lldb_private::StringList &matches);
251
252    //------------------------------------------------------------------
253    /// Handles the generic bits of figuring out whether we are in an
254    /// option, and if so completing it.
255    ///
256    /// @param[in] interpreter
257    ///    The command interpreter doing the completion.
258    ///
259    /// @param[in] input
260    ///    The command line parsed into words
261    ///
262    /// @param[in] cursor_index
263    ///     The index in \ainput of the word in which the cursor lies.
264    ///
265    /// @param[in] char_pos
266    ///     The character position of the cursor in its argument word.
267    ///
268    /// @param[in] opt_element_vector
269    ///     The results of the options parse of \a input.
270    ///
271    /// @param[in] opt_element_index
272    ///     The position in \a opt_element_vector of the word in \a
273    ///     input containing the cursor.
274    ///
275    /// @param[in] match_start_point
276    /// @param[in] match_return_elements
277    ///     See CommandObject::HandleCompletions for a description of
278    ///     how these work.
279    ///
280    /// @param[out] word_complete
281    ///     \btrue if this is a complete option value (a space will
282    ///     be inserted after the completion.) \bfalse otherwise.
283    ///
284    /// @param[out] matches
285    ///     The array of matches returned.
286    ///
287    /// FIXME: This is the wrong return value, since we also need to
288    /// make a distinction between total number of matches, and the
289    /// window the user wants returned.
290    ///
291    /// @return
292    ///     \btrue if we were in an option, \bfalse otherwise.
293    //------------------------------------------------------------------
294    virtual bool
295    HandleOptionArgumentCompletion (Args &input,
296                                    int cursor_index,
297                                    int char_pos,
298                                    OptionElementVector &opt_element_vector,
299                                    int opt_element_index,
300                                    int match_start_point,
301                                    int max_return_elements,
302                                    bool &word_complete,
303                                    StringList &matches);
304
305protected:
306    // This is a set of options expressed as indexes into the options table for this Option.
307    typedef std::set<int> OptionSet;
308    typedef std::vector<OptionSet> OptionSetVector;
309
310    CommandInterpreter &m_interpreter;
311    std::vector<Option> m_getopt_table;
312    OptionSet m_seen_options;
313    OptionSetVector m_required_options;
314    OptionSetVector m_optional_options;
315
316    OptionSetVector &GetRequiredOptions ()
317    {
318        BuildValidOptionSets();
319        return m_required_options;
320    }
321
322    OptionSetVector &GetOptionalOptions ()
323    {
324        BuildValidOptionSets();
325        return m_optional_options;
326    }
327
328    bool
329    IsASubset (const OptionSet& set_a, const OptionSet& set_b);
330
331    size_t
332    OptionsSetDiff (const OptionSet &set_a, const OptionSet &set_b, OptionSet &diffs);
333
334    void
335    OptionsSetUnion (const OptionSet &set_a, const OptionSet &set_b, OptionSet &union_set);
336
337    // Subclasses must reset their option values prior to starting a new
338    // option parse. Each subclass must override this function and revert
339    // all option settings to default values.
340    virtual void
341    OptionParsingStarting () = 0;
342
343    virtual Error
344    OptionParsingFinished ()
345    {
346        // If subclasses need to know when the options are done being parsed
347        // they can implement this function to do extra checking
348        Error error;
349        return error;
350    }
351};
352
353    class OptionGroup
354    {
355    public:
356        OptionGroup ()
357        {
358        }
359
360        virtual
361        ~OptionGroup ()
362        {
363        }
364
365        virtual uint32_t
366        GetNumDefinitions () = 0;
367
368        virtual const OptionDefinition*
369        GetDefinitions () = 0;
370
371        virtual Error
372        SetOptionValue (CommandInterpreter &interpreter,
373                        uint32_t option_idx,
374                        const char *option_value) = 0;
375
376        virtual void
377        OptionParsingStarting (CommandInterpreter &interpreter) = 0;
378
379        virtual Error
380        OptionParsingFinished (CommandInterpreter &interpreter)
381        {
382            // If subclasses need to know when the options are done being parsed
383            // they can implement this function to do extra checking
384            Error error;
385            return error;
386        }
387    };
388
389    class OptionGroupOptions : public Options
390    {
391    public:
392
393        OptionGroupOptions (CommandInterpreter &interpreter) :
394            Options (interpreter),
395            m_option_defs (),
396            m_option_infos (),
397            m_did_finalize (false)
398        {
399        }
400
401        virtual
402        ~OptionGroupOptions ()
403        {
404        }
405
406
407        //----------------------------------------------------------------------
408        /// Append options from a OptionGroup class.
409        ///
410        /// Append all options from \a group using the exact same option groups
411        /// that each option is defined with.
412        ///
413        /// @param[in] group
414        ///     A group of options to take option values from and copy their
415        ///     definitions into this class.
416        //----------------------------------------------------------------------
417        void
418        Append (OptionGroup* group);
419
420        //----------------------------------------------------------------------
421        /// Append options from a OptionGroup class.
422        ///
423        /// Append options from \a group that have a usage mask that has any bits
424        /// in "src_mask" set. After the option definition is copied into the
425        /// options definitions in this class, set the usage_mask to "dst_mask".
426        ///
427        /// @param[in] group
428        ///     A group of options to take option values from and copy their
429        ///     definitions into this class.
430        ///
431        /// @param[in] src_mask
432        ///     When copying options from \a group, you might only want some of
433        ///     the options to be appended to this group. This mask allows you
434        ///     to control which options from \a group get added. It also allows
435        ///     you to specify the same options from \a group multiple times
436        ///     for different option sets.
437        ///
438        /// @param[in] dst_mask
439        ///     Set the usage mask for any copied options to \a dst_mask after
440        ///     copying the option definition.
441        //----------------------------------------------------------------------
442        void
443        Append (OptionGroup* group,
444                uint32_t src_mask,
445                uint32_t dst_mask);
446
447        void
448        Finalize ();
449
450        bool
451        DidFinalize ()
452        {
453            return m_did_finalize;
454        }
455
456        virtual Error
457        SetOptionValue (uint32_t option_idx,
458                        const char *option_arg);
459
460        virtual void
461        OptionParsingStarting ();
462
463        virtual Error
464        OptionParsingFinished ();
465
466        const OptionDefinition*
467        GetDefinitions ()
468        {
469            assert (m_did_finalize);
470            return &m_option_defs[0];
471        }
472
473        const OptionGroup*
474        GetGroupWithOption (char short_opt);
475
476        struct OptionInfo
477        {
478            OptionInfo (OptionGroup* g, uint32_t i) :
479                option_group (g),
480                option_index (i)
481            {
482            }
483            OptionGroup* option_group;  // The group that this option came from
484            uint32_t option_index;      // The original option index from the OptionGroup
485        };
486        typedef std::vector<OptionInfo> OptionInfos;
487
488        std::vector<OptionDefinition> m_option_defs;
489        OptionInfos m_option_infos;
490        bool m_did_finalize;
491    };
492
493
494} // namespace lldb_private
495
496#endif  // liblldb_Options_h_
497