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