]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/include/lldb/Interpreter/CommandObject.h
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / include / lldb / Interpreter / CommandObject.h
1 //===-- CommandObject.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_CommandObject_h_
11 #define liblldb_CommandObject_h_
12
13 #include <map>
14 #include <string>
15 #include <vector>
16
17 #include "lldb/Utility/Flags.h"
18
19 #include "lldb/Interpreter/CommandCompletions.h"
20 #include "lldb/Interpreter/Options.h"
21 #include "lldb/Target/ExecutionContext.h"
22 #include "lldb/Utility/Args.h"
23 #include "lldb/Utility/CompletionRequest.h"
24 #include "lldb/Utility/StringList.h"
25 #include "lldb/lldb-private.h"
26
27 namespace lldb_private {
28
29 // This function really deals with CommandObjectLists, but we didn't make a
30 // CommandObjectList class, so I'm sticking it here.  But we really should have
31 // such a class.  Anyway, it looks up the commands in the map that match the
32 // partial string cmd_str, inserts the matches into matches, and returns the
33 // number added.
34
35 template <typename ValueType>
36 int AddNamesMatchingPartialString(
37     const std::map<std::string, ValueType> &in_map, llvm::StringRef cmd_str,
38     StringList &matches, StringList *descriptions = nullptr) {
39   int number_added = 0;
40
41   const bool add_all = cmd_str.empty();
42
43   for (auto iter = in_map.begin(), end = in_map.end(); iter != end; iter++) {
44     if (add_all || (iter->first.find(cmd_str, 0) == 0)) {
45       ++number_added;
46       matches.AppendString(iter->first.c_str());
47       if (descriptions)
48         descriptions->AppendString(iter->second->GetHelp());
49     }
50   }
51
52   return number_added;
53 }
54
55 template <typename ValueType>
56 size_t FindLongestCommandWord(std::map<std::string, ValueType> &dict) {
57   auto end = dict.end();
58   size_t max_len = 0;
59
60   for (auto pos = dict.begin(); pos != end; ++pos) {
61     size_t len = pos->first.size();
62     if (max_len < len)
63       max_len = len;
64   }
65   return max_len;
66 }
67
68 class CommandObject {
69 public:
70   typedef llvm::StringRef(ArgumentHelpCallbackFunction)();
71
72   struct ArgumentHelpCallback {
73     ArgumentHelpCallbackFunction *help_callback;
74     bool self_formatting;
75
76     llvm::StringRef operator()() const { return (*help_callback)(); }
77
78     explicit operator bool() const { return (help_callback != nullptr); }
79   };
80
81   struct ArgumentTableEntry // Entries in the main argument information table
82   {
83     lldb::CommandArgumentType arg_type;
84     const char *arg_name;
85     CommandCompletions::CommonCompletionTypes completion_type;
86     ArgumentHelpCallback help_function;
87     const char *help_text;
88   };
89
90   struct CommandArgumentData // Used to build individual command argument lists
91   {
92     lldb::CommandArgumentType arg_type;
93     ArgumentRepetitionType arg_repetition;
94     uint32_t arg_opt_set_association; // This arg might be associated only with
95                                       // some particular option set(s).
96     CommandArgumentData()
97         : arg_type(lldb::eArgTypeNone), arg_repetition(eArgRepeatPlain),
98           arg_opt_set_association(LLDB_OPT_SET_ALL) // By default, the arg
99                                                     // associates to all option
100                                                     // sets.
101     {}
102   };
103
104   typedef std::vector<CommandArgumentData>
105       CommandArgumentEntry; // Used to build individual command argument lists
106
107   static ArgumentTableEntry g_arguments_data
108       [lldb::eArgTypeLastArg]; // Main argument information table
109
110   typedef std::map<std::string, lldb::CommandObjectSP> CommandMap;
111
112   CommandObject(CommandInterpreter &interpreter, llvm::StringRef name,
113     llvm::StringRef help = "", llvm::StringRef syntax = "",
114                 uint32_t flags = 0);
115
116   virtual ~CommandObject();
117
118   static const char *
119   GetArgumentTypeAsCString(const lldb::CommandArgumentType arg_type);
120
121   static const char *
122   GetArgumentDescriptionAsCString(const lldb::CommandArgumentType arg_type);
123
124   CommandInterpreter &GetCommandInterpreter() { return m_interpreter; }
125
126   virtual llvm::StringRef GetHelp();
127
128   virtual llvm::StringRef GetHelpLong();
129
130   virtual llvm::StringRef GetSyntax();
131
132   llvm::StringRef GetCommandName() const;
133
134   virtual void SetHelp(llvm::StringRef str);
135
136   virtual void SetHelpLong(llvm::StringRef str);
137
138   void SetSyntax(llvm::StringRef str);
139
140   // override this to return true if you want to enable the user to delete the
141   // Command object from the Command dictionary (aliases have their own
142   // deletion scheme, so they do not need to care about this)
143   virtual bool IsRemovable() const { return false; }
144
145   virtual bool IsMultiwordObject() { return false; }
146
147   virtual CommandObjectMultiword *GetAsMultiwordCommand() { return nullptr; }
148
149   virtual bool IsAlias() { return false; }
150
151   // override this to return true if your command is somehow a "dash-dash" form
152   // of some other command (e.g. po is expr -O --); this is a powerful hint to
153   // the help system that one cannot pass options to this command
154   virtual bool IsDashDashCommand() { return false; }
155
156   virtual lldb::CommandObjectSP GetSubcommandSP(llvm::StringRef sub_cmd,
157                                                 StringList *matches = nullptr) {
158     return lldb::CommandObjectSP();
159   }
160
161   virtual CommandObject *GetSubcommandObject(llvm::StringRef sub_cmd,
162                                              StringList *matches = nullptr) {
163     return nullptr;
164   }
165
166   virtual void AproposAllSubCommands(llvm::StringRef prefix,
167                                      llvm::StringRef search_word,
168                                      StringList &commands_found,
169                                      StringList &commands_help) {}
170
171   void FormatLongHelpText(Stream &output_strm, llvm::StringRef long_help);
172
173   void GenerateHelpText(CommandReturnObject &result);
174
175   virtual void GenerateHelpText(Stream &result);
176
177   // this is needed in order to allow the SBCommand class to transparently try
178   // and load subcommands - it will fail on anything but a multiword command,
179   // but it avoids us doing type checkings and casts
180   virtual bool LoadSubCommand(llvm::StringRef cmd_name,
181                               const lldb::CommandObjectSP &command_obj) {
182     return false;
183   }
184
185   virtual bool WantsRawCommandString() = 0;
186
187   // By default, WantsCompletion = !WantsRawCommandString. Subclasses who want
188   // raw command string but desire, for example, argument completion should
189   // override this method to return true.
190   virtual bool WantsCompletion() { return !WantsRawCommandString(); }
191
192   virtual Options *GetOptions();
193
194   static const ArgumentTableEntry *GetArgumentTable();
195
196   static lldb::CommandArgumentType LookupArgumentName(llvm::StringRef arg_name);
197
198   static const ArgumentTableEntry *
199   FindArgumentDataByType(lldb::CommandArgumentType arg_type);
200
201   int GetNumArgumentEntries();
202
203   CommandArgumentEntry *GetArgumentEntryAtIndex(int idx);
204
205   static void GetArgumentHelp(Stream &str, lldb::CommandArgumentType arg_type,
206                               CommandInterpreter &interpreter);
207
208   static const char *GetArgumentName(lldb::CommandArgumentType arg_type);
209
210   // Generates a nicely formatted command args string for help command output.
211   // By default, all possible args are taken into account, for example, '<expr
212   // | variable-name>'.  This can be refined by passing a second arg specifying
213   // which option set(s) we are interested, which could then, for example,
214   // produce either '<expr>' or '<variable-name>'.
215   void GetFormattedCommandArguments(Stream &str,
216                                     uint32_t opt_set_mask = LLDB_OPT_SET_ALL);
217
218   bool IsPairType(ArgumentRepetitionType arg_repeat_type);
219
220   bool ParseOptions(Args &args, CommandReturnObject &result);
221
222   void SetCommandName(llvm::StringRef name);
223
224   //------------------------------------------------------------------
225   /// This default version handles calling option argument completions and then
226   /// calls HandleArgumentCompletion if the cursor is on an argument, not an
227   /// option. Don't override this method, override HandleArgumentCompletion
228   /// instead unless you have special reasons.
229   ///
230   /// @param[in/out] request
231   ///    The completion request that needs to be answered.
232   ///
233   /// FIXME: This is the wrong return value, since we also need to make a
234   /// distinction between
235   /// total number of matches, and the window the user wants returned.
236   ///
237   /// @return
238   ///     \btrue if we were in an option, \bfalse otherwise.
239   //------------------------------------------------------------------
240   virtual int HandleCompletion(CompletionRequest &request);
241
242   //------------------------------------------------------------------
243   /// The input array contains a parsed version of the line.  The insertion
244   /// point is given by cursor_index (the index in input of the word containing
245   /// the cursor) and cursor_char_position (the position of the cursor in that
246   /// word.)
247   /// We've constructed the map of options and their arguments as well if that
248   /// is helpful for the completion.
249   ///
250   /// @param[in/out] request
251   ///    The completion request that needs to be answered.
252   ///
253   /// FIXME: This is the wrong return value, since we also need to make a
254   /// distinction between
255   /// total number of matches, and the window the user wants returned.
256   ///
257   /// @return
258   ///     The number of completions.
259   //------------------------------------------------------------------
260   virtual int
261   HandleArgumentCompletion(CompletionRequest &request,
262                            OptionElementVector &opt_element_vector) {
263     return 0;
264   }
265
266   bool HelpTextContainsWord(llvm::StringRef search_word,
267                             bool search_short_help = true,
268                             bool search_long_help = true,
269                             bool search_syntax = true,
270                             bool search_options = true);
271
272   //------------------------------------------------------------------
273   /// The flags accessor.
274   ///
275   /// @return
276   ///     A reference to the Flags member variable.
277   //------------------------------------------------------------------
278   Flags &GetFlags() { return m_flags; }
279
280   //------------------------------------------------------------------
281   /// The flags const accessor.
282   ///
283   /// @return
284   ///     A const reference to the Flags member variable.
285   //------------------------------------------------------------------
286   const Flags &GetFlags() const { return m_flags; }
287
288   //------------------------------------------------------------------
289   /// Get the command that appropriate for a "repeat" of the current command.
290   ///
291   /// @param[in] current_command_line
292   ///    The complete current command line.
293   ///
294   /// @return
295   ///     nullptr if there is no special repeat command - it will use the
296   ///     current command line.
297   ///     Otherwise a pointer to the command to be repeated.
298   ///     If the returned string is the empty string, the command won't be
299   ///     repeated.
300   //------------------------------------------------------------------
301   virtual const char *GetRepeatCommand(Args &current_command_args,
302                                        uint32_t index) {
303     return nullptr;
304   }
305
306   bool HasOverrideCallback() const {
307     return m_command_override_callback ||
308            m_deprecated_command_override_callback;
309   }
310
311   void SetOverrideCallback(lldb::CommandOverrideCallback callback,
312                            void *baton) {
313     m_deprecated_command_override_callback = callback;
314     m_command_override_baton = baton;
315   }
316
317   void SetOverrideCallback(lldb::CommandOverrideCallbackWithResult callback,
318                            void *baton) {
319     m_command_override_callback = callback;
320     m_command_override_baton = baton;
321   }
322
323   bool InvokeOverrideCallback(const char **argv, CommandReturnObject &result) {
324     if (m_command_override_callback)
325       return m_command_override_callback(m_command_override_baton, argv,
326                                          result);
327     else if (m_deprecated_command_override_callback)
328       return m_deprecated_command_override_callback(m_command_override_baton,
329                                                     argv);
330     else
331       return false;
332   }
333
334   virtual bool Execute(const char *args_string,
335                        CommandReturnObject &result) = 0;
336
337 protected:
338   bool ParseOptionsAndNotify(Args &args, CommandReturnObject &result,
339                              OptionGroupOptions &group_options,
340                              ExecutionContext &exe_ctx);
341
342   virtual const char *GetInvalidTargetDescription() {
343     return "invalid target, create a target using the 'target create' command";
344   }
345
346   virtual const char *GetInvalidProcessDescription() {
347     return "invalid process";
348   }
349
350   virtual const char *GetInvalidThreadDescription() { return "invalid thread"; }
351
352   virtual const char *GetInvalidFrameDescription() { return "invalid frame"; }
353
354   virtual const char *GetInvalidRegContextDescription() {
355     return "invalid frame, no registers";
356   }
357
358   // This is for use in the command interpreter, when you either want the
359   // selected target, or if no target is present you want to prime the dummy
360   // target with entities that will be copied over to new targets.
361   Target *GetSelectedOrDummyTarget(bool prefer_dummy = false);
362   Target *GetDummyTarget();
363
364   // If a command needs to use the "current" thread, use this call. Command
365   // objects will have an ExecutionContext to use, and that may or may not have
366   // a thread in it.  If it does, you should use that by default, if not, then
367   // use the ExecutionContext's target's selected thread, etc... This call
368   // insulates you from the details of this calculation.
369   Thread *GetDefaultThread();
370
371   //------------------------------------------------------------------
372   /// Check the command to make sure anything required by this
373   /// command is available.
374   ///
375   /// @param[out] result
376   ///     A command result object, if it is not okay to run the command
377   ///     this will be filled in with a suitable error.
378   ///
379   /// @return
380   ///     \b true if it is okay to run this command, \b false otherwise.
381   //------------------------------------------------------------------
382   bool CheckRequirements(CommandReturnObject &result);
383
384   void Cleanup();
385
386   CommandInterpreter &m_interpreter;
387   ExecutionContext m_exe_ctx;
388   std::unique_lock<std::recursive_mutex> m_api_locker;
389   std::string m_cmd_name;
390   std::string m_cmd_help_short;
391   std::string m_cmd_help_long;
392   std::string m_cmd_syntax;
393   Flags m_flags;
394   std::vector<CommandArgumentEntry> m_arguments;
395   lldb::CommandOverrideCallback m_deprecated_command_override_callback;
396   lldb::CommandOverrideCallbackWithResult m_command_override_callback;
397   void *m_command_override_baton;
398
399   // Helper function to populate IDs or ID ranges as the command argument data
400   // to the specified command argument entry.
401   static void AddIDsArgumentData(CommandArgumentEntry &arg,
402                                  lldb::CommandArgumentType ID,
403                                  lldb::CommandArgumentType IDRange);
404 };
405
406 class CommandObjectParsed : public CommandObject {
407 public:
408   CommandObjectParsed(CommandInterpreter &interpreter, const char *name,
409                       const char *help = nullptr, const char *syntax = nullptr,
410                       uint32_t flags = 0)
411       : CommandObject(interpreter, name, help, syntax, flags) {}
412
413   ~CommandObjectParsed() override = default;
414
415   bool Execute(const char *args_string, CommandReturnObject &result) override;
416
417 protected:
418   virtual bool DoExecute(Args &command, CommandReturnObject &result) = 0;
419
420   bool WantsRawCommandString() override { return false; }
421 };
422
423 class CommandObjectRaw : public CommandObject {
424 public:
425   CommandObjectRaw(CommandInterpreter &interpreter, llvm::StringRef name,
426     llvm::StringRef help = "", llvm::StringRef syntax = "",
427                    uint32_t flags = 0)
428       : CommandObject(interpreter, name, help, syntax, flags) {}
429
430   ~CommandObjectRaw() override = default;
431
432   bool Execute(const char *args_string, CommandReturnObject &result) override;
433
434 protected:
435   virtual bool DoExecute(llvm::StringRef command,
436                          CommandReturnObject &result) = 0;
437
438   bool WantsRawCommandString() override { return true; }
439 };
440
441 } // namespace lldb_private
442
443 #endif // liblldb_CommandObject_h_