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