CommandInterpreter.h revision e9a5a50885c68f0bbd5f87c610be0aea639a8d9e
1//===-- CommandInterpreter.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_CommandInterpreter_h_
11#define liblldb_CommandInterpreter_h_
12
13// C Includes
14// C++ Includes
15// Other libraries and framework includes
16// Project includes
17#include "lldb/lldb-private.h"
18#include "lldb/Core/Broadcaster.h"
19#include "lldb/Core/Debugger.h"
20#include "lldb/Core/Log.h"
21#include "lldb/Interpreter/CommandObject.h"
22#include "lldb/Interpreter/ScriptInterpreter.h"
23#include "lldb/Core/Event.h"
24#include "lldb/Interpreter/Args.h"
25#include "lldb/Core/StringList.h"
26
27namespace lldb_private {
28
29class CommandInterpreter :
30    public Broadcaster,
31    public Properties
32{
33public:
34    typedef std::map<std::string, OptionArgVectorSP> OptionArgMap;
35
36    enum
37    {
38        eBroadcastBitThreadShouldExit       = (1 << 0),
39        eBroadcastBitResetPrompt            = (1 << 1),
40        eBroadcastBitQuitCommandReceived    = (1 << 2),   // User entered quit
41        eBroadcastBitAsynchronousOutputData = (1 << 3),
42        eBroadcastBitAsynchronousErrorData  = (1 << 4)
43    };
44
45    enum ChildrenTruncatedWarningStatus // tristate boolean to manage children truncation warning
46    {
47        eNoTruncation = 0, // never truncated
48        eUnwarnedTruncation = 1, // truncated but did not notify
49        eWarnedTruncation = 2 // truncated and notified
50    };
51
52    enum CommandTypes
53    {
54        eCommandTypesBuiltin = 0x0001,  // native commands such as "frame"
55        eCommandTypesUserDef = 0x0002,  // scripted commands
56        eCommandTypesAliases = 0x0004,  // aliases such as "po"
57        eCommandTypesAllThem = 0xFFFF   // all commands
58    };
59
60    // These two functions fill out the Broadcaster interface:
61
62    static ConstString &GetStaticBroadcasterClass ();
63
64    virtual ConstString &GetBroadcasterClass() const
65    {
66        return GetStaticBroadcasterClass();
67    }
68
69    void
70    SourceInitFile (bool in_cwd,
71                    CommandReturnObject &result);
72
73    CommandInterpreter (Debugger &debugger,
74                        lldb::ScriptLanguage script_language,
75                        bool synchronous_execution);
76
77    virtual
78    ~CommandInterpreter ();
79
80    bool
81    AddCommand (const char *name,
82                const lldb::CommandObjectSP &cmd_sp,
83                bool can_replace);
84
85    bool
86    AddUserCommand (std::string name,
87                    const lldb::CommandObjectSP &cmd_sp,
88                    bool can_replace);
89
90    lldb::CommandObjectSP
91    GetCommandSPExact (const char *cmd,
92                       bool include_aliases);
93
94    CommandObject *
95    GetCommandObjectExact (const char *cmd_cstr,
96                           bool include_aliases);
97
98    CommandObject *
99    GetCommandObject (const char *cmd,
100                      StringList *matches = NULL);
101
102    bool
103    CommandExists (const char *cmd);
104
105    bool
106    AliasExists (const char *cmd);
107
108    bool
109    UserCommandExists (const char *cmd);
110
111    void
112    AddAlias (const char *alias_name,
113              lldb::CommandObjectSP& command_obj_sp);
114
115    bool
116    RemoveAlias (const char *alias_name);
117
118    bool
119    RemoveUser (const char *alias_name);
120
121    void
122    RemoveAllUser ()
123    {
124        m_user_dict.clear();
125    }
126
127    OptionArgVectorSP
128    GetAliasOptions (const char *alias_name);
129
130
131    bool
132    ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
133                             const char *options_args,
134                             OptionArgVectorSP &option_arg_vector_sp);
135
136    void
137    RemoveAliasOptions (const char *alias_name);
138
139    void
140    AddOrReplaceAliasOptions (const char *alias_name,
141                              OptionArgVectorSP &option_arg_vector_sp);
142
143    CommandObject *
144    BuildAliasResult (const char *alias_name,
145                      std::string &raw_input_string,
146                      std::string &alias_result,
147                      CommandReturnObject &result);
148
149    bool
150    HandleCommand (const char *command_line,
151                   LazyBool add_to_history,
152                   CommandReturnObject &result,
153                   ExecutionContext *override_context = NULL,
154                   bool repeat_on_empty_command = true,
155                   bool no_context_switching = false);
156
157    //------------------------------------------------------------------
158    /// Execute a list of commands in sequence.
159    ///
160    /// @param[in] commands
161    ///    The list of commands to execute.
162    /// @param[in/out] context
163    ///    The execution context in which to run the commands.  Can be NULL in which case the default
164    ///    context will be used.
165    /// @param[in] stop_on_continue
166    ///    If \b true execution will end on the first command that causes the process in the
167    ///    execution context to continue.  If \false, we won't check the execution status.
168    /// @param[in] stop_on_error
169    ///    If \b true execution will end on the first command that causes an error.
170    /// @param[in] echo_commands
171    ///    If \b true echo the command before executing it.  If \false, execute silently.
172    /// @param[in] print_results
173    ///    If \b true print the results of the command after executing it.  If \false, execute silently.
174    /// @param[out] result
175    ///    This is marked as succeeding with no output if all commands execute safely,
176    ///    and failed with some explanation if we aborted executing the commands at some point.
177    //------------------------------------------------------------------
178    void
179    HandleCommands (const StringList &commands,
180                    ExecutionContext *context,
181                    bool stop_on_continue,
182                    bool stop_on_error,
183                    bool echo_commands,
184                    bool print_results,
185                    LazyBool add_to_history,
186                    CommandReturnObject &result);
187
188    //------------------------------------------------------------------
189    /// Execute a list of commands from a file.
190    ///
191    /// @param[in] file
192    ///    The file from which to read in commands.
193    /// @param[in/out] context
194    ///    The execution context in which to run the commands.  Can be NULL in which case the default
195    ///    context will be used.
196    /// @param[in] stop_on_continue
197    ///    If \b true execution will end on the first command that causes the process in the
198    ///    execution context to continue.  If \false, we won't check the execution status.
199    /// @param[in] stop_on_error
200    ///    If \b true execution will end on the first command that causes an error.
201    /// @param[in] echo_commands
202    ///    If \b true echo the command before executing it.  If \false, execute silently.
203    /// @param[in] print_results
204    ///    If \b true print the results of the command after executing it.  If \false, execute silently.
205    /// @param[out] result
206    ///    This is marked as succeeding with no output if all commands execute safely,
207    ///    and failed with some explanation if we aborted executing the commands at some point.
208    //------------------------------------------------------------------
209    void
210    HandleCommandsFromFile (FileSpec &file,
211                            ExecutionContext *context,
212                            bool stop_on_continue,
213                            bool stop_on_error,
214                            bool echo_commands,
215                            bool print_results,
216                            LazyBool add_to_history,
217                            CommandReturnObject &result);
218
219    CommandObject *
220    GetCommandObjectForCommand (std::string &command_line);
221
222    // This handles command line completion.  You are given a pointer to the command string buffer, to the current cursor,
223    // and to the end of the string (in case it is not NULL terminated).
224    // You also passed in an StringList object to fill with the returns.
225    // The first element of the array will be filled with the string that you would need to insert at
226    // the cursor point to complete the cursor point to the longest common matching prefix.
227    // If you want to limit the number of elements returned, set max_return_elements to the number of elements
228    // you want returned.  Otherwise set max_return_elements to -1.
229    // If you want to start some way into the match list, then set match_start_point to the desired start
230    // point.
231    // Returns:
232    // -1 if the completion character should be inserted
233    // -2 if the entire command line should be deleted and replaced with matches.GetStringAtIndex(0)
234    // INT_MAX if the number of matches is > max_return_elements, but it is expensive to compute.
235    // Otherwise, returns the number of matches.
236    //
237    // FIXME: Only max_return_elements == -1 is supported at present.
238
239    int
240    HandleCompletion (const char *current_line,
241                      const char *cursor,
242                      const char *last_char,
243                      int match_start_point,
244                      int max_return_elements,
245                      StringList &matches);
246
247    // This version just returns matches, and doesn't compute the substring.  It is here so the
248    // Help command can call it for the first argument.
249    // word_complete tells whether a the completions are considered a "complete" response (so the
250    // completer should complete the quote & put a space after the word.
251
252    int
253    HandleCompletionMatches (Args &input,
254                             int &cursor_index,
255                             int &cursor_char_position,
256                             int match_start_point,
257                             int max_return_elements,
258                             bool &word_complete,
259                             StringList &matches);
260
261
262    int
263    GetCommandNamesMatchingPartialString (const char *cmd_cstr,
264                                          bool include_aliases,
265                                          StringList &matches);
266
267    void
268    GetHelp (CommandReturnObject &result,
269             uint32_t types = eCommandTypesAllThem);
270
271    void
272    GetAliasHelp (const char *alias_name,
273                  const char *command_name,
274                  StreamString &help_string);
275
276    void
277    OutputFormattedHelpText (Stream &stream,
278                             const char *command_word,
279                             const char *separator,
280                             const char *help_text,
281                             size_t max_word_len);
282
283    // this mimics OutputFormattedHelpText but it does perform a much simpler
284    // formatting, basically ensuring line alignment. This is only good if you have
285    // some complicated layout for your help text and want as little help as reasonable
286    // in properly displaying it. Most of the times, you simply want to type some text
287    // and have it printed in a reasonable way on screen. If so, use OutputFormattedHelpText
288    void
289    OutputHelpText (Stream &stream,
290                    const char *command_word,
291                    const char *separator,
292                    const char *help_text,
293                    uint32_t max_word_len);
294
295    Debugger &
296    GetDebugger ()
297    {
298        return m_debugger;
299    }
300
301    ExecutionContext
302    GetExecutionContext()
303    {
304        return m_exe_ctx_ref.Lock();
305    }
306
307    void
308    UpdateExecutionContext (ExecutionContext *override_context);
309
310    lldb::PlatformSP
311    GetPlatform (bool prefer_target_platform);
312
313    const char *
314    ProcessEmbeddedScriptCommands (const char *arg);
315
316    const char *
317    GetPrompt ();
318
319    void
320    SetPrompt (const char *);
321
322    bool Confirm (const char *message, bool default_answer);
323
324    static size_t
325    GetConfirmationInputReaderCallback (void *baton,
326                                        InputReader &reader,
327                                        lldb::InputReaderAction action,
328                                        const char *bytes,
329                                        size_t bytes_len);
330
331    void
332    LoadCommandDictionary ();
333
334    void
335    Initialize ();
336
337    void
338    SetScriptLanguage (lldb::ScriptLanguage lang);
339
340
341    bool
342    HasCommands ();
343
344    bool
345    HasAliases ();
346
347    bool
348    HasUserCommands ();
349
350    bool
351    HasAliasOptions ();
352
353    void
354    BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
355                           const char *alias_name,
356                           Args &cmd_args,
357                           std::string &raw_input_string,
358                           CommandReturnObject &result);
359
360    int
361    GetOptionArgumentPosition (const char *in_string);
362
363    ScriptInterpreter *
364    GetScriptInterpreter (bool can_create = true);
365
366    void
367    SkipLLDBInitFiles (bool skip_lldbinit_files)
368    {
369        m_skip_lldbinit_files = skip_lldbinit_files;
370    }
371
372    void
373    SkipAppInitFiles (bool skip_app_init_files)
374    {
375        m_skip_app_init_files = m_skip_lldbinit_files;
376    }
377
378    bool
379    GetSynchronous ();
380
381    void
382    DumpHistory (Stream &stream, uint32_t count) const;
383
384    void
385    DumpHistory (Stream &stream, uint32_t start, uint32_t end) const;
386
387    const char *
388    FindHistoryString (const char *input_str) const;
389
390    size_t
391    FindLongestCommandWord (CommandObject::CommandMap &dict);
392
393    void
394    FindCommandsForApropos (const char *word,
395                            StringList &commands_found,
396                            StringList &commands_help);
397
398    bool
399    GetBatchCommandMode () { return m_batch_command_mode; }
400
401    void
402    SetBatchCommandMode (bool value) { m_batch_command_mode = value; }
403
404    void
405    ChildrenTruncated()
406    {
407        if (m_truncation_warning == eNoTruncation)
408            m_truncation_warning = eUnwarnedTruncation;
409    }
410
411    bool
412    TruncationWarningNecessary()
413    {
414        return (m_truncation_warning == eUnwarnedTruncation);
415    }
416
417    void
418    TruncationWarningGiven()
419    {
420        m_truncation_warning = eWarnedTruncation;
421    }
422
423    const char *
424    TruncationWarningText()
425    {
426        return "*** Some of your variables have more members than the debugger will show by default. To show all of them, you can either use the --show-all-children option to %s or raise the limit by changing the target.max-children-count setting.\n";
427    }
428
429    //------------------------------------------------------------------
430    // Properties
431    //------------------------------------------------------------------
432    bool
433    GetExpandRegexAliases () const;
434
435    bool
436    GetPromptOnQuit () const;
437
438protected:
439    friend class Debugger;
440
441    void
442    SetSynchronous (bool value);
443
444    lldb::CommandObjectSP
445    GetCommandSP (const char *cmd, bool include_aliases = true, bool exact = true, StringList *matches = NULL);
446
447private:
448
449    Error
450    PreprocessCommand (std::string &command);
451
452    Debugger &m_debugger;                       // The debugger session that this interpreter is associated with
453    ExecutionContextRef m_exe_ctx_ref;          // The current execution context to use when handling commands
454    bool m_synchronous_execution;
455    bool m_skip_lldbinit_files;
456    bool m_skip_app_init_files;
457    CommandObject::CommandMap m_command_dict;   // Stores basic built-in commands (they cannot be deleted, removed or overwritten).
458    CommandObject::CommandMap m_alias_dict;     // Stores user aliases/abbreviations for commands
459    CommandObject::CommandMap m_user_dict;      // Stores user-defined commands
460    OptionArgMap m_alias_options;               // Stores any options (with or without arguments) that go with any alias.
461    std::vector<std::string> m_command_history;
462    std::string m_repeat_command;               // Stores the command that will be executed for an empty command string.
463    std::auto_ptr<ScriptInterpreter> m_script_interpreter_ap;
464    char m_comment_char;
465    char m_repeat_char;
466    bool m_batch_command_mode;
467    ChildrenTruncatedWarningStatus m_truncation_warning;    // Whether we truncated children and whether the user has been told
468    uint32_t m_command_source_depth;
469
470};
471
472
473} // namespace lldb_private
474
475#endif  // liblldb_CommandInterpreter_h_
476