1ebc09c36SJim Ingham //===-- CommandObjectSource.cpp ---------------------------------*- C++ -*-===//
2ebc09c36SJim Ingham //
3ebc09c36SJim Ingham //                     The LLVM Compiler Infrastructure
4ebc09c36SJim Ingham //
5ebc09c36SJim Ingham // This file is distributed under the University of Illinois Open Source
6ebc09c36SJim Ingham // License. See LICENSE.TXT for details.
7ebc09c36SJim Ingham //
8ebc09c36SJim Ingham //===----------------------------------------------------------------------===//
9ebc09c36SJim Ingham 
10ebc09c36SJim Ingham // C Includes
11ebc09c36SJim Ingham // C++ Includes
12ebc09c36SJim Ingham // Other libraries and framework includes
130e5e5a79SGreg Clayton #include "llvm/ADT/StringRef.h"
140e5e5a79SGreg Clayton 
15ebc09c36SJim Ingham // Project includes
166e3d8e7fSEugene Zelenko #include "CommandObjectCommands.h"
1746d4aa21SEnrico Granata #include "CommandObjectHelp.h"
18ebc09c36SJim Ingham #include "lldb/Core/Debugger.h"
1944d93782SGreg Clayton #include "lldb/Core/IOHandler.h"
20be93a35aSEnrico Granata #include "lldb/Core/StringList.h"
21de164aaaSGreg Clayton #include "lldb/Interpreter/Args.h"
227594f14fSEnrico Granata #include "lldb/Interpreter/CommandHistory.h"
23ebc09c36SJim Ingham #include "lldb/Interpreter/CommandInterpreter.h"
24de164aaaSGreg Clayton #include "lldb/Interpreter/CommandObjectRegexCommand.h"
25ebc09c36SJim Ingham #include "lldb/Interpreter/CommandReturnObject.h"
26012d4fcaSEnrico Granata #include "lldb/Interpreter/OptionValueBoolean.h"
2745d0e238SEnrico Granata #include "lldb/Interpreter/OptionValueString.h"
287594f14fSEnrico Granata #include "lldb/Interpreter/OptionValueUInt64.h"
29ebc09c36SJim Ingham #include "lldb/Interpreter/Options.h"
3099f0b8f9SEnrico Granata #include "lldb/Interpreter/ScriptInterpreter.h"
31ebc09c36SJim Ingham 
32ebc09c36SJim Ingham using namespace lldb;
33ebc09c36SJim Ingham using namespace lldb_private;
34ebc09c36SJim Ingham 
35ebc09c36SJim Ingham //-------------------------------------------------------------------------
36ebc09c36SJim Ingham // CommandObjectCommandsSource
37ebc09c36SJim Ingham //-------------------------------------------------------------------------
38ebc09c36SJim Ingham 
391f0f5b5bSZachary Turner static OptionDefinition g_history_options[] = {
401f0f5b5bSZachary Turner     // clang-format off
411f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "count",       'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "How many history commands to print." },
421f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "start-index", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Index at which to start printing history commands (or end to mean tail mode)." },
431f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "end-index",   'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Index at which to stop printing history commands." },
441f0f5b5bSZachary Turner   { LLDB_OPT_SET_2, false, "clear",       'C', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeBoolean,         "Clears the current command history." },
451f0f5b5bSZachary Turner     // clang-format on
461f0f5b5bSZachary Turner };
471f0f5b5bSZachary Turner 
48b9c1b51eSKate Stone class CommandObjectCommandsHistory : public CommandObjectParsed {
495a988416SJim Ingham public:
50b9c1b51eSKate Stone   CommandObjectCommandsHistory(CommandInterpreter &interpreter)
51b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command history",
525a988416SJim Ingham                             "Dump the history of commands in this session.",
536e3d8e7fSEugene Zelenko                             nullptr),
54b9c1b51eSKate Stone         m_options() {}
555a988416SJim Ingham 
566e3d8e7fSEugene Zelenko   ~CommandObjectCommandsHistory() override = default;
575a988416SJim Ingham 
58b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
595a988416SJim Ingham 
605a988416SJim Ingham protected:
61b9c1b51eSKate Stone   class CommandOptions : public Options {
62a5a97ebeSJim Ingham   public:
63b9c1b51eSKate Stone     CommandOptions()
64b9c1b51eSKate Stone         : Options(), m_start_idx(0), m_stop_idx(0), m_count(0), m_clear(false) {
65a5a97ebeSJim Ingham     }
66a5a97ebeSJim Ingham 
676e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
68a5a97ebeSJim Ingham 
69b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
70b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
71a5a97ebeSJim Ingham       Error error;
723bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
738cef4b0bSZachary Turner       llvm::StringRef option_strref =
748cef4b0bSZachary Turner           llvm::StringRef::withNullAsEmpty(option_arg);
75a5a97ebeSJim Ingham 
76b9c1b51eSKate Stone       switch (short_option) {
77a5a97ebeSJim Ingham       case 'c':
788cef4b0bSZachary Turner         error =
798cef4b0bSZachary Turner             m_count.SetValueFromString(option_strref, eVarSetOperationAssign);
80a5a97ebeSJim Ingham         break;
81a5a97ebeSJim Ingham       case 's':
82b9c1b51eSKate Stone         if (option_arg && strcmp("end", option_arg) == 0) {
837594f14fSEnrico Granata           m_start_idx.SetCurrentValue(UINT64_MAX);
847594f14fSEnrico Granata           m_start_idx.SetOptionWasSet();
85b9c1b51eSKate Stone         } else
868cef4b0bSZachary Turner           error = m_start_idx.SetValueFromString(option_strref,
87b9c1b51eSKate Stone                                                  eVarSetOperationAssign);
887594f14fSEnrico Granata         break;
897594f14fSEnrico Granata       case 'e':
908cef4b0bSZachary Turner         error = m_stop_idx.SetValueFromString(option_strref,
918cef4b0bSZachary Turner                                               eVarSetOperationAssign);
927594f14fSEnrico Granata         break;
9363123b64SEnrico Granata       case 'C':
9463123b64SEnrico Granata         m_clear.SetCurrentValue(true);
9563123b64SEnrico Granata         m_clear.SetOptionWasSet();
96a5a97ebeSJim Ingham         break;
97a5a97ebeSJim Ingham       default:
98b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
99b9c1b51eSKate Stone                                        short_option);
100a5a97ebeSJim Ingham         break;
101a5a97ebeSJim Ingham       }
102a5a97ebeSJim Ingham 
103a5a97ebeSJim Ingham       return error;
104a5a97ebeSJim Ingham     }
105a5a97ebeSJim Ingham 
106b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1077594f14fSEnrico Granata       m_start_idx.Clear();
1087594f14fSEnrico Granata       m_stop_idx.Clear();
1097594f14fSEnrico Granata       m_count.Clear();
11063123b64SEnrico Granata       m_clear.Clear();
111a5a97ebeSJim Ingham     }
112a5a97ebeSJim Ingham 
1131f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
11470602439SZachary Turner       return llvm::makeArrayRef(g_history_options);
1151f0f5b5bSZachary Turner     }
116a5a97ebeSJim Ingham 
117a5a97ebeSJim Ingham     // Instance variables to hold the values for command options.
118a5a97ebeSJim Ingham 
1197594f14fSEnrico Granata     OptionValueUInt64 m_start_idx;
1207594f14fSEnrico Granata     OptionValueUInt64 m_stop_idx;
1217594f14fSEnrico Granata     OptionValueUInt64 m_count;
12263123b64SEnrico Granata     OptionValueBoolean m_clear;
123a5a97ebeSJim Ingham   };
124a5a97ebeSJim Ingham 
125b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
126b9c1b51eSKate Stone     if (m_options.m_clear.GetCurrentValue() &&
127b9c1b51eSKate Stone         m_options.m_clear.OptionWasSet()) {
1287594f14fSEnrico Granata       m_interpreter.GetCommandHistory().Clear();
1297594f14fSEnrico Granata       result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult);
130b9c1b51eSKate Stone     } else {
131b9c1b51eSKate Stone       if (m_options.m_start_idx.OptionWasSet() &&
132b9c1b51eSKate Stone           m_options.m_stop_idx.OptionWasSet() &&
133b9c1b51eSKate Stone           m_options.m_count.OptionWasSet()) {
134b9c1b51eSKate Stone         result.AppendError("--count, --start-index and --end-index cannot be "
135b9c1b51eSKate Stone                            "all specified in the same invocation");
1367594f14fSEnrico Granata         result.SetStatus(lldb::eReturnStatusFailed);
137b9c1b51eSKate Stone       } else {
138b9c1b51eSKate Stone         std::pair<bool, uint64_t> start_idx(
139b9c1b51eSKate Stone             m_options.m_start_idx.OptionWasSet(),
140b9c1b51eSKate Stone             m_options.m_start_idx.GetCurrentValue());
141b9c1b51eSKate Stone         std::pair<bool, uint64_t> stop_idx(
142b9c1b51eSKate Stone             m_options.m_stop_idx.OptionWasSet(),
143b9c1b51eSKate Stone             m_options.m_stop_idx.GetCurrentValue());
144b9c1b51eSKate Stone         std::pair<bool, uint64_t> count(m_options.m_count.OptionWasSet(),
145b9c1b51eSKate Stone                                         m_options.m_count.GetCurrentValue());
146a5a97ebeSJim Ingham 
1477594f14fSEnrico Granata         const CommandHistory &history(m_interpreter.GetCommandHistory());
1487594f14fSEnrico Granata 
149b9c1b51eSKate Stone         if (start_idx.first && start_idx.second == UINT64_MAX) {
150b9c1b51eSKate Stone           if (count.first) {
1517594f14fSEnrico Granata             start_idx.second = history.GetSize() - count.second;
1527594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
153b9c1b51eSKate Stone           } else if (stop_idx.first) {
1547594f14fSEnrico Granata             start_idx.second = stop_idx.second;
1557594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
156b9c1b51eSKate Stone           } else {
1577594f14fSEnrico Granata             start_idx.second = 0;
1587594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
1597594f14fSEnrico Granata           }
160b9c1b51eSKate Stone         } else {
161b9c1b51eSKate Stone           if (!start_idx.first && !stop_idx.first && !count.first) {
1627594f14fSEnrico Granata             start_idx.second = 0;
1637594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
164b9c1b51eSKate Stone           } else if (start_idx.first) {
165b9c1b51eSKate Stone             if (count.first) {
1667594f14fSEnrico Granata               stop_idx.second = start_idx.second + count.second - 1;
167b9c1b51eSKate Stone             } else if (!stop_idx.first) {
1687594f14fSEnrico Granata               stop_idx.second = history.GetSize() - 1;
1697594f14fSEnrico Granata             }
170b9c1b51eSKate Stone           } else if (stop_idx.first) {
171b9c1b51eSKate Stone             if (count.first) {
1727594f14fSEnrico Granata               if (stop_idx.second >= count.second)
1737594f14fSEnrico Granata                 start_idx.second = stop_idx.second - count.second + 1;
1747594f14fSEnrico Granata               else
1757594f14fSEnrico Granata                 start_idx.second = 0;
1767594f14fSEnrico Granata             }
177b9c1b51eSKate Stone           } else /* if (count.first) */
1787594f14fSEnrico Granata           {
1797594f14fSEnrico Granata             start_idx.second = 0;
1807594f14fSEnrico Granata             stop_idx.second = count.second - 1;
1817594f14fSEnrico Granata           }
1827594f14fSEnrico Granata         }
183b9c1b51eSKate Stone         history.Dump(result.GetOutputStream(), start_idx.second,
184b9c1b51eSKate Stone                      stop_idx.second);
1857594f14fSEnrico Granata       }
1867594f14fSEnrico Granata     }
187a5a97ebeSJim Ingham     return result.Succeeded();
188a5a97ebeSJim Ingham   }
1895a988416SJim Ingham 
1905a988416SJim Ingham   CommandOptions m_options;
191a5a97ebeSJim Ingham };
192a5a97ebeSJim Ingham 
193a5a97ebeSJim Ingham //-------------------------------------------------------------------------
194a5a97ebeSJim Ingham // CommandObjectCommandsSource
195a5a97ebeSJim Ingham //-------------------------------------------------------------------------
196a5a97ebeSJim Ingham 
1971f0f5b5bSZachary Turner static OptionDefinition g_source_options[] = {
1981f0f5b5bSZachary Turner     // clang-format off
1991f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "stop-on-error",    'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true, stop executing commands on error." },
2001f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "stop-on-continue", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true, stop executing commands on continue." },
2011f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "silent-run",       's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true don't echo commands while executing." },
2021f0f5b5bSZachary Turner     // clang-format on
2031f0f5b5bSZachary Turner };
2041f0f5b5bSZachary Turner 
205b9c1b51eSKate Stone class CommandObjectCommandsSource : public CommandObjectParsed {
2065a988416SJim Ingham public:
2077428a18cSKate Stone   CommandObjectCommandsSource(CommandInterpreter &interpreter)
208b9c1b51eSKate Stone       : CommandObjectParsed(
209b9c1b51eSKate Stone             interpreter, "command source",
210b9c1b51eSKate Stone             "Read and execute LLDB commands from the file <filename>.",
2116e3d8e7fSEugene Zelenko             nullptr),
212b9c1b51eSKate Stone         m_options() {
2135a988416SJim Ingham     CommandArgumentEntry arg;
2145a988416SJim Ingham     CommandArgumentData file_arg;
2155a988416SJim Ingham 
2165a988416SJim Ingham     // Define the first (and only) variant of this arg.
2175a988416SJim Ingham     file_arg.arg_type = eArgTypeFilename;
2185a988416SJim Ingham     file_arg.arg_repetition = eArgRepeatPlain;
2195a988416SJim Ingham 
220b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
221b9c1b51eSKate Stone     // argument entry.
2225a988416SJim Ingham     arg.push_back(file_arg);
2235a988416SJim Ingham 
2245a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
2255a988416SJim Ingham     m_arguments.push_back(arg);
2265a988416SJim Ingham   }
2275a988416SJim Ingham 
2286e3d8e7fSEugene Zelenko   ~CommandObjectCommandsSource() override = default;
2295a988416SJim Ingham 
230b9c1b51eSKate Stone   const char *GetRepeatCommand(Args &current_command_args,
231b9c1b51eSKate Stone                                uint32_t index) override {
2325a988416SJim Ingham     return "";
2335a988416SJim Ingham   }
2345a988416SJim Ingham 
235b9c1b51eSKate Stone   int HandleArgumentCompletion(Args &input, int &cursor_index,
2365a988416SJim Ingham                                int &cursor_char_position,
2375a988416SJim Ingham                                OptionElementVector &opt_element_vector,
238b9c1b51eSKate Stone                                int match_start_point, int max_return_elements,
2395a988416SJim Ingham                                bool &word_complete,
240b9c1b51eSKate Stone                                StringList &matches) override {
2415a988416SJim Ingham     std::string completion_str(input.GetArgumentAtIndex(cursor_index));
2425a988416SJim Ingham     completion_str.erase(cursor_char_position);
2435a988416SJim Ingham 
244b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
245b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
246b9c1b51eSKate Stone         completion_str.c_str(), match_start_point, max_return_elements, nullptr,
247b9c1b51eSKate Stone         word_complete, matches);
2485a988416SJim Ingham     return matches.GetSize();
2495a988416SJim Ingham   }
2505a988416SJim Ingham 
251b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
2525a988416SJim Ingham 
2535a988416SJim Ingham protected:
254b9c1b51eSKate Stone   class CommandOptions : public Options {
255e16c50a1SJim Ingham   public:
256b9c1b51eSKate Stone     CommandOptions()
257b9c1b51eSKate Stone         : Options(), m_stop_on_error(true), m_silent_run(false),
258b9c1b51eSKate Stone           m_stop_on_continue(true) {}
259e16c50a1SJim Ingham 
2606e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
261e16c50a1SJim Ingham 
262b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
263b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
264e16c50a1SJim Ingham       Error error;
2653bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
2668cef4b0bSZachary Turner       llvm::StringRef option_strref =
2678cef4b0bSZachary Turner           llvm::StringRef::withNullAsEmpty(option_arg);
268e16c50a1SJim Ingham 
269b9c1b51eSKate Stone       switch (short_option) {
270e16c50a1SJim Ingham       case 'e':
2718cef4b0bSZachary Turner         error = m_stop_on_error.SetValueFromString(option_strref);
272e16c50a1SJim Ingham         break;
273340b0309SGreg Clayton 
274e16c50a1SJim Ingham       case 'c':
2758cef4b0bSZachary Turner         error = m_stop_on_continue.SetValueFromString(option_strref);
276e16c50a1SJim Ingham         break;
277340b0309SGreg Clayton 
27860986174SMichael Sartain       case 's':
2798cef4b0bSZachary Turner         error = m_silent_run.SetValueFromString(option_strref);
28060986174SMichael Sartain         break;
281340b0309SGreg Clayton 
282e16c50a1SJim Ingham       default:
283b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
284b9c1b51eSKate Stone                                        short_option);
285e16c50a1SJim Ingham         break;
286e16c50a1SJim Ingham       }
287e16c50a1SJim Ingham 
288e16c50a1SJim Ingham       return error;
289e16c50a1SJim Ingham     }
290e16c50a1SJim Ingham 
291b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
292012d4fcaSEnrico Granata       m_stop_on_error.Clear();
293340b0309SGreg Clayton       m_silent_run.Clear();
294340b0309SGreg Clayton       m_stop_on_continue.Clear();
295e16c50a1SJim Ingham     }
296e16c50a1SJim Ingham 
2971f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
29870602439SZachary Turner       return llvm::makeArrayRef(g_source_options);
2991f0f5b5bSZachary Turner     }
300e16c50a1SJim Ingham 
301e16c50a1SJim Ingham     // Instance variables to hold the values for command options.
302e16c50a1SJim Ingham 
303012d4fcaSEnrico Granata     OptionValueBoolean m_stop_on_error;
304340b0309SGreg Clayton     OptionValueBoolean m_silent_run;
305340b0309SGreg Clayton     OptionValueBoolean m_stop_on_continue;
306e16c50a1SJim Ingham   };
307e16c50a1SJim Ingham 
308b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
30911eb9c64SZachary Turner     if (command.GetArgumentCount() == 1) {
31011eb9c64SZachary Turner       llvm::StringRef filename = command.GetArgumentAtIndex(0);
311ebc09c36SJim Ingham 
3121ee3853fSJohnny Chen       FileSpec cmd_file(filename, true);
3136e3d8e7fSEugene Zelenko       ExecutionContext *exe_ctx = nullptr; // Just use the default context.
314ebc09c36SJim Ingham 
315340b0309SGreg Clayton       // If any options were set, then use them
316340b0309SGreg Clayton       if (m_options.m_stop_on_error.OptionWasSet() ||
317340b0309SGreg Clayton           m_options.m_silent_run.OptionWasSet() ||
318b9c1b51eSKate Stone           m_options.m_stop_on_continue.OptionWasSet()) {
319340b0309SGreg Clayton         // Use user set settings
32026c7bf93SJim Ingham         CommandInterpreterRunOptions options;
321b9c1b51eSKate Stone         options.SetStopOnContinue(
322b9c1b51eSKate Stone             m_options.m_stop_on_continue.GetCurrentValue());
32326c7bf93SJim Ingham         options.SetStopOnError(m_options.m_stop_on_error.GetCurrentValue());
3247d8555c4SJim Ingham         options.SetEchoCommands(!m_options.m_silent_run.GetCurrentValue());
3257d8555c4SJim Ingham         options.SetPrintResults(!m_options.m_silent_run.GetCurrentValue());
32626c7bf93SJim Ingham 
327b9c1b51eSKate Stone         m_interpreter.HandleCommandsFromFile(cmd_file, exe_ctx, options,
328e16c50a1SJim Ingham                                              result);
329b9c1b51eSKate Stone       } else {
330b9c1b51eSKate Stone         // No options were set, inherit any settings from nested "command
331b9c1b51eSKate Stone         // source" commands,
332340b0309SGreg Clayton         // or set to sane default settings...
33326c7bf93SJim Ingham         CommandInterpreterRunOptions options;
334b9c1b51eSKate Stone         m_interpreter.HandleCommandsFromFile(cmd_file, exe_ctx, options,
335340b0309SGreg Clayton                                              result);
336340b0309SGreg Clayton       }
337b9c1b51eSKate Stone     } else {
338b9c1b51eSKate Stone       result.AppendErrorWithFormat(
339b9c1b51eSKate Stone           "'%s' takes exactly one executable filename argument.\n",
340a449698cSZachary Turner           GetCommandName().str().c_str());
341ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
342ebc09c36SJim Ingham     }
343ebc09c36SJim Ingham     return result.Succeeded();
344ebc09c36SJim Ingham   }
3456e3d8e7fSEugene Zelenko 
3465a988416SJim Ingham   CommandOptions m_options;
347ebc09c36SJim Ingham };
348ebc09c36SJim Ingham 
349ebc09c36SJim Ingham #pragma mark CommandObjectCommandsAlias
350ebc09c36SJim Ingham //-------------------------------------------------------------------------
351ebc09c36SJim Ingham // CommandObjectCommandsAlias
352ebc09c36SJim Ingham //-------------------------------------------------------------------------
353ebc09c36SJim Ingham 
3541f0f5b5bSZachary Turner static OptionDefinition g_alias_options[] = {
3551f0f5b5bSZachary Turner     // clang-format off
3561f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "help",      'h', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeHelpText, "Help text for this command" },
3571f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "long-help", 'H', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeHelpText, "Long help text for this command" },
3581f0f5b5bSZachary Turner     // clang-format on
3591f0f5b5bSZachary Turner };
3601f0f5b5bSZachary Turner 
361b9c1b51eSKate Stone static const char *g_python_command_instructions =
362b9c1b51eSKate Stone     "Enter your Python command(s). Type 'DONE' to end.\n"
363be93a35aSEnrico Granata     "You must define a Python function with this signature:\n"
36444d93782SGreg Clayton     "def my_command_impl(debugger, args, result, internal_dict):\n";
365be93a35aSEnrico Granata 
366b9c1b51eSKate Stone class CommandObjectCommandsAlias : public CommandObjectRaw {
36745d0e238SEnrico Granata protected:
368b9c1b51eSKate Stone   class CommandOptions : public OptionGroup {
369ebc09c36SJim Ingham   public:
370b9c1b51eSKate Stone     CommandOptions() : OptionGroup(), m_help(), m_long_help() {}
37145d0e238SEnrico Granata 
37245d0e238SEnrico Granata     ~CommandOptions() override = default;
37345d0e238SEnrico Granata 
3741f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
37570602439SZachary Turner       return llvm::makeArrayRef(g_alias_options);
3761f0f5b5bSZachary Turner     }
37745d0e238SEnrico Granata 
3788cef4b0bSZachary Turner     Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
379b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
38045d0e238SEnrico Granata       Error error;
38145d0e238SEnrico Granata 
3821f0f5b5bSZachary Turner       const int short_option = GetDefinitions()[option_idx].short_option;
3838cef4b0bSZachary Turner       std::string option_str(option_value);
38445d0e238SEnrico Granata 
385b9c1b51eSKate Stone       switch (short_option) {
38645d0e238SEnrico Granata       case 'h':
3878cef4b0bSZachary Turner         m_help.SetCurrentValue(option_str);
38845d0e238SEnrico Granata         m_help.SetOptionWasSet();
38945d0e238SEnrico Granata         break;
39045d0e238SEnrico Granata 
39145d0e238SEnrico Granata       case 'H':
3928cef4b0bSZachary Turner         m_long_help.SetCurrentValue(option_str);
39345d0e238SEnrico Granata         m_long_help.SetOptionWasSet();
39445d0e238SEnrico Granata         break;
39545d0e238SEnrico Granata 
39645d0e238SEnrico Granata       default:
397b9c1b51eSKate Stone         error.SetErrorStringWithFormat("invalid short option character '%c'",
398b9c1b51eSKate Stone                                        short_option);
39945d0e238SEnrico Granata         break;
40045d0e238SEnrico Granata       }
40145d0e238SEnrico Granata 
40245d0e238SEnrico Granata       return error;
40345d0e238SEnrico Granata     }
4048cef4b0bSZachary Turner     Error SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete;
40545d0e238SEnrico Granata 
406b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
40745d0e238SEnrico Granata       m_help.Clear();
40845d0e238SEnrico Granata       m_long_help.Clear();
40945d0e238SEnrico Granata     }
41045d0e238SEnrico Granata 
41145d0e238SEnrico Granata     OptionValueString m_help;
41245d0e238SEnrico Granata     OptionValueString m_long_help;
41345d0e238SEnrico Granata   };
41445d0e238SEnrico Granata 
41545d0e238SEnrico Granata   OptionGroupOptions m_option_group;
41645d0e238SEnrico Granata   CommandOptions m_command_options;
41745d0e238SEnrico Granata 
41845d0e238SEnrico Granata public:
419b9c1b51eSKate Stone   Options *GetOptions() override { return &m_option_group; }
42045d0e238SEnrico Granata 
4217428a18cSKate Stone   CommandObjectCommandsAlias(CommandInterpreter &interpreter)
422b9c1b51eSKate Stone       : CommandObjectRaw(
423b9c1b51eSKate Stone             interpreter, "command alias",
424a449698cSZachary Turner             "Define a custom command in terms of an existing command."),
425b9c1b51eSKate Stone         m_option_group(), m_command_options() {
42645d0e238SEnrico Granata     m_option_group.Append(&m_command_options);
42745d0e238SEnrico Granata     m_option_group.Finalize();
42845d0e238SEnrico Granata 
429ebc09c36SJim Ingham     SetHelpLong(
430ea671fbdSKate Stone         "'alias' allows the user to create a short-cut or abbreviation for long \
431ea671fbdSKate Stone commands, multi-word commands, and commands that take particular options.  \
432b9c1b51eSKate Stone Below are some simple examples of how one might use the 'alias' command:"
433b9c1b51eSKate Stone         R"(
434ea671fbdSKate Stone 
435ea671fbdSKate Stone (lldb) command alias sc script
436ea671fbdSKate Stone 
437ea671fbdSKate Stone     Creates the abbreviation 'sc' for the 'script' command.
438ea671fbdSKate Stone 
439ea671fbdSKate Stone (lldb) command alias bp breakpoint
440ea671fbdSKate Stone 
441b9c1b51eSKate Stone )"
442b9c1b51eSKate Stone         "    Creates the abbreviation 'bp' for the 'breakpoint' command.  Since \
443ea671fbdSKate Stone breakpoint commands are two-word commands, the user would still need to \
444b9c1b51eSKate Stone enter the second word after 'bp', e.g. 'bp enable' or 'bp delete'."
445b9c1b51eSKate Stone         R"(
446ea671fbdSKate Stone 
447ea671fbdSKate Stone (lldb) command alias bpl breakpoint list
448ea671fbdSKate Stone 
449ea671fbdSKate Stone     Creates the abbreviation 'bpl' for the two-word command 'breakpoint list'.
450ea671fbdSKate Stone 
451b9c1b51eSKate Stone )"
452b9c1b51eSKate Stone         "An alias can include some options for the command, with the values either \
453ea671fbdSKate Stone filled in at the time the alias is created, or specified as positional \
454ea671fbdSKate Stone arguments, to be filled in when the alias is invoked.  The following example \
455b9c1b51eSKate Stone shows how to create aliases with options:"
456b9c1b51eSKate Stone         R"(
457ea671fbdSKate Stone 
458ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
459ea671fbdSKate Stone 
460b9c1b51eSKate Stone )"
461b9c1b51eSKate Stone         "    Creates the abbreviation 'bfl' (for break-file-line), with the -f and -l \
462ea671fbdSKate Stone options already part of the alias.  So if the user wants to set a breakpoint \
463ea671fbdSKate Stone by file and line without explicitly having to use the -f and -l options, the \
464ea671fbdSKate Stone user can now use 'bfl' instead.  The '%1' and '%2' are positional placeholders \
465ea671fbdSKate Stone for the actual arguments that will be passed when the alias command is used.  \
466ea671fbdSKate Stone The number in the placeholder refers to the position/order the actual value \
467ea671fbdSKate Stone occupies when the alias is used.  All the occurrences of '%1' in the alias \
468ea671fbdSKate Stone will be replaced with the first argument, all the occurrences of '%2' in the \
469ea671fbdSKate Stone alias will be replaced with the second argument, and so on.  This also allows \
470ea671fbdSKate Stone actual arguments to be used multiple times within an alias (see 'process \
471b9c1b51eSKate Stone launch' example below)."
472b9c1b51eSKate Stone         R"(
473ea671fbdSKate Stone 
474b9c1b51eSKate Stone )"
475b9c1b51eSKate Stone         "Note: the positional arguments must substitute as whole words in the resultant \
476ea671fbdSKate Stone command, so you can't at present do something like this to append the file extension \
477b9c1b51eSKate Stone \".cpp\":"
478b9c1b51eSKate Stone         R"(
479ea671fbdSKate Stone 
480ea671fbdSKate Stone (lldb) command alias bcppfl breakpoint set -f %1.cpp -l %2
481ea671fbdSKate Stone 
482b9c1b51eSKate Stone )"
483b9c1b51eSKate Stone         "For more complex aliasing, use the \"command regex\" command instead.  In the \
484ea671fbdSKate Stone 'bfl' case above, the actual file value will be filled in with the first argument \
485ea671fbdSKate Stone following 'bfl' and the actual line number value will be filled in with the second \
486b9c1b51eSKate Stone argument.  The user would use this alias as follows:"
487b9c1b51eSKate Stone         R"(
488ea671fbdSKate Stone 
489ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
490ea671fbdSKate Stone (lldb) bfl my-file.c 137
491ea671fbdSKate Stone 
492ea671fbdSKate Stone This would be the same as if the user had entered 'breakpoint set -f my-file.c -l 137'.
493ea671fbdSKate Stone 
494ea671fbdSKate Stone Another example:
495ea671fbdSKate Stone 
496ea671fbdSKate Stone (lldb) command alias pltty process launch -s -o %1 -e %1
497ea671fbdSKate Stone (lldb) pltty /dev/tty0
498ea671fbdSKate Stone 
499ea671fbdSKate Stone     Interpreted as 'process launch -s -o /dev/tty0 -e /dev/tty0'
500ea671fbdSKate Stone 
501b9c1b51eSKate Stone )"
502b9c1b51eSKate Stone         "If the user always wanted to pass the same value to a particular option, the \
503ea671fbdSKate Stone alias could be defined with that value directly in the alias as a constant, \
504b9c1b51eSKate Stone rather than using a positional placeholder:"
505b9c1b51eSKate Stone         R"(
506ea671fbdSKate Stone 
507ea671fbdSKate Stone (lldb) command alias bl3 breakpoint set -f %1 -l 3
508ea671fbdSKate Stone 
509b9c1b51eSKate Stone     Always sets a breakpoint on line 3 of whatever file is indicated.)");
510ebc09c36SJim Ingham 
511405fe67fSCaroline Tice     CommandArgumentEntry arg1;
512405fe67fSCaroline Tice     CommandArgumentEntry arg2;
513405fe67fSCaroline Tice     CommandArgumentEntry arg3;
514405fe67fSCaroline Tice     CommandArgumentData alias_arg;
515405fe67fSCaroline Tice     CommandArgumentData cmd_arg;
516405fe67fSCaroline Tice     CommandArgumentData options_arg;
517405fe67fSCaroline Tice 
518405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
519405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
520405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
521405fe67fSCaroline Tice 
522b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
523b9c1b51eSKate Stone     // argument entry.
524405fe67fSCaroline Tice     arg1.push_back(alias_arg);
525405fe67fSCaroline Tice 
526405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
527405fe67fSCaroline Tice     cmd_arg.arg_type = eArgTypeCommandName;
528405fe67fSCaroline Tice     cmd_arg.arg_repetition = eArgRepeatPlain;
529405fe67fSCaroline Tice 
530b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
531b9c1b51eSKate Stone     // argument entry.
532405fe67fSCaroline Tice     arg2.push_back(cmd_arg);
533405fe67fSCaroline Tice 
534405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
535405fe67fSCaroline Tice     options_arg.arg_type = eArgTypeAliasOptions;
536405fe67fSCaroline Tice     options_arg.arg_repetition = eArgRepeatOptional;
537405fe67fSCaroline Tice 
538b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
539b9c1b51eSKate Stone     // argument entry.
540405fe67fSCaroline Tice     arg3.push_back(options_arg);
541405fe67fSCaroline Tice 
542405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
543405fe67fSCaroline Tice     m_arguments.push_back(arg1);
544405fe67fSCaroline Tice     m_arguments.push_back(arg2);
545405fe67fSCaroline Tice     m_arguments.push_back(arg3);
546ebc09c36SJim Ingham   }
547ebc09c36SJim Ingham 
5486e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAlias() override = default;
549ebc09c36SJim Ingham 
5505a988416SJim Ingham protected:
551b9c1b51eSKate Stone   bool DoExecute(const char *raw_command_line,
552b9c1b51eSKate Stone                  CommandReturnObject &result) override {
553b9c1b51eSKate Stone     if (!raw_command_line || !raw_command_line[0]) {
554d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
55545d0e238SEnrico Granata       return false;
55645d0e238SEnrico Granata     }
55745d0e238SEnrico Granata 
558e1cfbc79STodd Fiala     ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext();
559e1cfbc79STodd Fiala     m_option_group.NotifyOptionParsingStarting(&exe_ctx);
56045d0e238SEnrico Granata 
56145d0e238SEnrico Granata     const char *remainder = nullptr;
56245d0e238SEnrico Granata 
563b9c1b51eSKate Stone     if (raw_command_line[0] == '-') {
56445d0e238SEnrico Granata       // We have some options and these options MUST end with --.
56545d0e238SEnrico Granata       const char *end_options = nullptr;
56645d0e238SEnrico Granata       const char *s = raw_command_line;
567b9c1b51eSKate Stone       while (s && s[0]) {
56845d0e238SEnrico Granata         end_options = ::strstr(s, "--");
569b9c1b51eSKate Stone         if (end_options) {
57045d0e238SEnrico Granata           end_options += 2; // Get past the "--"
571b9c1b51eSKate Stone           if (::isspace(end_options[0])) {
57245d0e238SEnrico Granata             remainder = end_options;
57345d0e238SEnrico Granata             while (::isspace(*remainder))
57445d0e238SEnrico Granata               ++remainder;
57545d0e238SEnrico Granata             break;
57645d0e238SEnrico Granata           }
57745d0e238SEnrico Granata         }
57845d0e238SEnrico Granata         s = end_options;
57945d0e238SEnrico Granata       }
58045d0e238SEnrico Granata 
581b9c1b51eSKate Stone       if (end_options) {
582b9c1b51eSKate Stone         Args args(
583b9c1b51eSKate Stone             llvm::StringRef(raw_command_line, end_options - raw_command_line));
58445d0e238SEnrico Granata         if (!ParseOptions(args, result))
58545d0e238SEnrico Granata           return false;
58645d0e238SEnrico Granata 
587e1cfbc79STodd Fiala         Error error(m_option_group.NotifyOptionParsingFinished(&exe_ctx));
588b9c1b51eSKate Stone         if (error.Fail()) {
58945d0e238SEnrico Granata           result.AppendError(error.AsCString());
59045d0e238SEnrico Granata           result.SetStatus(eReturnStatusFailed);
59145d0e238SEnrico Granata           return false;
59245d0e238SEnrico Granata         }
59345d0e238SEnrico Granata       }
59445d0e238SEnrico Granata     }
59545d0e238SEnrico Granata     if (nullptr == remainder)
59645d0e238SEnrico Granata       remainder = raw_command_line;
59745d0e238SEnrico Granata 
598*a01bccdbSZachary Turner     llvm::StringRef raw_command_string(remainder);
599*a01bccdbSZachary Turner     Args args(raw_command_string);
600844d2303SCaroline Tice 
60111eb9c64SZachary Turner     if (args.GetArgumentCount() < 2) {
602d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
603844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
604844d2303SCaroline Tice       return false;
605844d2303SCaroline Tice     }
606844d2303SCaroline Tice 
607844d2303SCaroline Tice     // Get the alias command.
608844d2303SCaroline Tice 
60911eb9c64SZachary Turner     // TODO: Convert this function to use StringRef.  Requires converting
61011eb9c64SZachary Turner     // GetCommandObjectForCommand.
611844d2303SCaroline Tice     const std::string alias_command = args.GetArgumentAtIndex(0);
612b9c1b51eSKate Stone     if (alias_command.size() > 1 && alias_command[0] == '-') {
613d72e412fSEnrico Granata       result.AppendError("aliases starting with a dash are not supported");
614b9c1b51eSKate Stone       if (alias_command == "--help" || alias_command == "--long-help") {
615b9c1b51eSKate Stone         result.AppendWarning("if trying to pass options to 'command alias' add "
616b9c1b51eSKate Stone                              "a -- at the end of the options");
617d72e412fSEnrico Granata       }
618d72e412fSEnrico Granata       result.SetStatus(eReturnStatusFailed);
619d72e412fSEnrico Granata       return false;
620d72e412fSEnrico Granata     }
621844d2303SCaroline Tice 
622b9c1b51eSKate Stone     // Strip the new alias name off 'raw_command_string'  (leave it on args,
623b9c1b51eSKate Stone     // which gets passed to 'Execute', which
624844d2303SCaroline Tice     // does the stripping itself.
625844d2303SCaroline Tice     size_t pos = raw_command_string.find(alias_command);
626b9c1b51eSKate Stone     if (pos == 0) {
627844d2303SCaroline Tice       raw_command_string = raw_command_string.substr(alias_command.size());
628844d2303SCaroline Tice       pos = raw_command_string.find_first_not_of(' ');
629844d2303SCaroline Tice       if ((pos != std::string::npos) && (pos > 0))
630844d2303SCaroline Tice         raw_command_string = raw_command_string.substr(pos);
631b9c1b51eSKate Stone     } else {
632844d2303SCaroline Tice       result.AppendError("Error parsing command string.  No alias created.");
633844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
634844d2303SCaroline Tice       return false;
635844d2303SCaroline Tice     }
636844d2303SCaroline Tice 
637844d2303SCaroline Tice     // Verify that the command is alias-able.
638b9c1b51eSKate Stone     if (m_interpreter.CommandExists(alias_command.c_str())) {
639b9c1b51eSKate Stone       result.AppendErrorWithFormat(
640b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
641844d2303SCaroline Tice           alias_command.c_str());
642844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
643844d2303SCaroline Tice       return false;
644844d2303SCaroline Tice     }
645844d2303SCaroline Tice 
646b9c1b51eSKate Stone     // Get CommandObject that is being aliased. The command name is read from
647*a01bccdbSZachary Turner     // the front of raw_command_string. raw_command_string is returned with the
648*a01bccdbSZachary Turner     // name of the command object stripped off the front.
649*a01bccdbSZachary Turner     llvm::StringRef original_raw_command_string = raw_command_string;
650b9c1b51eSKate Stone     CommandObject *cmd_obj =
651b9c1b51eSKate Stone         m_interpreter.GetCommandObjectForCommand(raw_command_string);
652844d2303SCaroline Tice 
653b9c1b51eSKate Stone     if (!cmd_obj) {
654b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid command given to 'command alias'. "
655b9c1b51eSKate Stone                                    "'%s' does not begin with a valid command."
656b9c1b51eSKate Stone                                    "  No alias created.",
657*a01bccdbSZachary Turner                                    original_raw_command_string.str().c_str());
658844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
659844d2303SCaroline Tice       return false;
660b9c1b51eSKate Stone     } else if (!cmd_obj->WantsRawCommandString()) {
661b9c1b51eSKate Stone       // Note that args was initialized with the original command, and has not
662b9c1b51eSKate Stone       // been updated to this point.
663b9c1b51eSKate Stone       // Therefore can we pass it to the version of Execute that does not
664b9c1b51eSKate Stone       // need/expect raw input in the alias.
6655a988416SJim Ingham       return HandleAliasingNormalCommand(args, result);
666b9c1b51eSKate Stone     } else {
667b9c1b51eSKate Stone       return HandleAliasingRawCommand(alias_command, raw_command_string,
668b9c1b51eSKate Stone                                       *cmd_obj, result);
6695a988416SJim Ingham     }
6705a988416SJim Ingham     return result.Succeeded();
6715a988416SJim Ingham   }
6725a988416SJim Ingham 
673*a01bccdbSZachary Turner   bool HandleAliasingRawCommand(llvm::StringRef alias_command,
674*a01bccdbSZachary Turner                                 llvm::StringRef raw_command_string,
675b9c1b51eSKate Stone                                 CommandObject &cmd_obj,
676b9c1b51eSKate Stone                                 CommandReturnObject &result) {
677844d2303SCaroline Tice     // Verify & handle any options/arguments passed to the alias command
678844d2303SCaroline Tice 
679b9c1b51eSKate Stone     OptionArgVectorSP option_arg_vector_sp =
680b9c1b51eSKate Stone         OptionArgVectorSP(new OptionArgVector);
681844d2303SCaroline Tice 
682b9c1b51eSKate Stone     if (CommandObjectSP cmd_obj_sp =
683b9c1b51eSKate Stone             m_interpreter.GetCommandSPExact(cmd_obj.GetCommandName(), false)) {
684*a01bccdbSZachary Turner       if (m_interpreter.AliasExists(alias_command) ||
685*a01bccdbSZachary Turner           m_interpreter.UserCommandExists(alias_command)) {
686b9c1b51eSKate Stone         result.AppendWarningWithFormat(
687b9c1b51eSKate Stone             "Overwriting existing definition for '%s'.\n",
688*a01bccdbSZachary Turner             alias_command.str().c_str());
689844d2303SCaroline Tice       }
690b9c1b51eSKate Stone       if (CommandAlias *alias = m_interpreter.AddAlias(
691*a01bccdbSZachary Turner               alias_command, cmd_obj_sp, raw_command_string)) {
69245d0e238SEnrico Granata         if (m_command_options.m_help.OptionWasSet())
69345d0e238SEnrico Granata           alias->SetHelp(m_command_options.m_help.GetCurrentValue());
69445d0e238SEnrico Granata         if (m_command_options.m_long_help.OptionWasSet())
69545d0e238SEnrico Granata           alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
696844d2303SCaroline Tice         result.SetStatus(eReturnStatusSuccessFinishNoResult);
697b9c1b51eSKate Stone       } else {
698472362e6SCaroline Tice         result.AppendError("Unable to create requested alias.\n");
699472362e6SCaroline Tice         result.SetStatus(eReturnStatusFailed);
700472362e6SCaroline Tice       }
701212130acSEnrico Granata 
702b9c1b51eSKate Stone     } else {
703212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
704212130acSEnrico Granata       result.SetStatus(eReturnStatusFailed);
705212130acSEnrico Granata     }
706212130acSEnrico Granata 
707844d2303SCaroline Tice     return result.Succeeded();
708844d2303SCaroline Tice   }
709ebc09c36SJim Ingham 
710b9c1b51eSKate Stone   bool HandleAliasingNormalCommand(Args &args, CommandReturnObject &result) {
711867b185dSCaroline Tice     size_t argc = args.GetArgumentCount();
712ebc09c36SJim Ingham 
713b9c1b51eSKate Stone     if (argc < 2) {
714d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
715ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
716ebc09c36SJim Ingham       return false;
717ebc09c36SJim Ingham     }
718ebc09c36SJim Ingham 
71911eb9c64SZachary Turner     // TODO: Convert these to StringRefs.  Should convert other dependent
72011eb9c64SZachary Turner     // functions (CommandExists, UserCommandExists, AliasExists, AddAlias,
72111eb9c64SZachary Turner     // etc at the same time.
722ebc09c36SJim Ingham     const std::string alias_command = args.GetArgumentAtIndex(0);
723ebc09c36SJim Ingham     const std::string actual_command = args.GetArgumentAtIndex(1);
724ebc09c36SJim Ingham 
725ebc09c36SJim Ingham     args.Shift(); // Shift the alias command word off the argument vector.
726ebc09c36SJim Ingham     args.Shift(); // Shift the old command word off the argument vector.
727ebc09c36SJim Ingham 
728b9c1b51eSKate Stone     // Verify that the command is alias'able, and get the appropriate command
729b9c1b51eSKate Stone     // object.
730ebc09c36SJim Ingham 
731b9c1b51eSKate Stone     if (m_interpreter.CommandExists(alias_command.c_str())) {
732b9c1b51eSKate Stone       result.AppendErrorWithFormat(
733b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
734ebc09c36SJim Ingham           alias_command.c_str());
735ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
736b9c1b51eSKate Stone     } else {
737b9c1b51eSKate Stone       CommandObjectSP command_obj_sp(
738a449698cSZachary Turner           m_interpreter.GetCommandSPExact(actual_command, true));
739ebc09c36SJim Ingham       CommandObjectSP subcommand_obj_sp;
740ebc09c36SJim Ingham       bool use_subcommand = false;
741b9c1b51eSKate Stone       if (command_obj_sp) {
742ebc09c36SJim Ingham         CommandObject *cmd_obj = command_obj_sp.get();
7436e3d8e7fSEugene Zelenko         CommandObject *sub_cmd_obj = nullptr;
744b9c1b51eSKate Stone         OptionArgVectorSP option_arg_vector_sp =
745b9c1b51eSKate Stone             OptionArgVectorSP(new OptionArgVector);
746ebc09c36SJim Ingham 
74711eb9c64SZachary Turner         while (cmd_obj->IsMultiwordObject() && !args.empty()) {
748b9c1b51eSKate Stone           if (argc >= 3) {
749a449698cSZachary Turner             const std::string sub_command = args.GetArgumentAtIndex(0);
75011eb9c64SZachary Turner             assert(!sub_command.empty());
75111eb9c64SZachary Turner             subcommand_obj_sp = cmd_obj->GetSubcommandSP(sub_command.data());
752b9c1b51eSKate Stone             if (subcommand_obj_sp) {
753ebc09c36SJim Ingham               sub_cmd_obj = subcommand_obj_sp.get();
754ebc09c36SJim Ingham               use_subcommand = true;
755b9c1b51eSKate Stone               args.Shift(); // Shift the sub_command word off the argument
756b9c1b51eSKate Stone                             // vector.
757844d2303SCaroline Tice               cmd_obj = sub_cmd_obj;
758b9c1b51eSKate Stone             } else {
759b9c1b51eSKate Stone               result.AppendErrorWithFormat(
760b9c1b51eSKate Stone                   "'%s' is not a valid sub-command of '%s'.  "
761f415eeb4SCaroline Tice                   "Unable to create alias.\n",
762a449698cSZachary Turner                   sub_command.c_str(), actual_command.c_str());
763ebc09c36SJim Ingham               result.SetStatus(eReturnStatusFailed);
764ebc09c36SJim Ingham               return false;
765ebc09c36SJim Ingham             }
766ebc09c36SJim Ingham           }
767ebc09c36SJim Ingham         }
768ebc09c36SJim Ingham 
769ebc09c36SJim Ingham         // Verify & handle any options/arguments passed to the alias command
770ebc09c36SJim Ingham 
771212130acSEnrico Granata         std::string args_string;
772212130acSEnrico Granata 
77311eb9c64SZachary Turner         if (!args.empty()) {
774b9c1b51eSKate Stone           CommandObjectSP tmp_sp =
775b9c1b51eSKate Stone               m_interpreter.GetCommandSPExact(cmd_obj->GetCommandName(), false);
776ebc09c36SJim Ingham           if (use_subcommand)
777b9c1b51eSKate Stone             tmp_sp = m_interpreter.GetCommandSPExact(
778b9c1b51eSKate Stone                 sub_cmd_obj->GetCommandName(), false);
779ca90c47eSCaroline Tice 
780ca90c47eSCaroline Tice           args.GetCommandString(args_string);
781867b185dSCaroline Tice         }
782ebc09c36SJim Ingham 
783b9c1b51eSKate Stone         if (m_interpreter.AliasExists(alias_command.c_str()) ||
784b9c1b51eSKate Stone             m_interpreter.UserCommandExists(alias_command.c_str())) {
785b9c1b51eSKate Stone           result.AppendWarningWithFormat(
786b9c1b51eSKate Stone               "Overwriting existing definition for '%s'.\n",
787ebc09c36SJim Ingham               alias_command.c_str());
788ebc09c36SJim Ingham         }
789ebc09c36SJim Ingham 
790b9c1b51eSKate Stone         if (CommandAlias *alias = m_interpreter.AddAlias(
791b9c1b51eSKate Stone                 alias_command.c_str(),
792212130acSEnrico Granata                 use_subcommand ? subcommand_obj_sp : command_obj_sp,
793b9c1b51eSKate Stone                 args_string.c_str())) {
79445d0e238SEnrico Granata           if (m_command_options.m_help.OptionWasSet())
79545d0e238SEnrico Granata             alias->SetHelp(m_command_options.m_help.GetCurrentValue());
79645d0e238SEnrico Granata           if (m_command_options.m_long_help.OptionWasSet())
79745d0e238SEnrico Granata             alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
798ebc09c36SJim Ingham           result.SetStatus(eReturnStatusSuccessFinishNoResult);
799b9c1b51eSKate Stone         } else {
800212130acSEnrico Granata           result.AppendError("Unable to create requested alias.\n");
801212130acSEnrico Granata           result.SetStatus(eReturnStatusFailed);
802212130acSEnrico Granata           return false;
803212130acSEnrico Granata         }
804b9c1b51eSKate Stone       } else {
805b9c1b51eSKate Stone         result.AppendErrorWithFormat("'%s' is not an existing command.\n",
806b9c1b51eSKate Stone                                      actual_command.c_str());
807ebc09c36SJim Ingham         result.SetStatus(eReturnStatusFailed);
808e7941795SCaroline Tice         return false;
809ebc09c36SJim Ingham       }
810ebc09c36SJim Ingham     }
811ebc09c36SJim Ingham 
812ebc09c36SJim Ingham     return result.Succeeded();
813ebc09c36SJim Ingham   }
814ebc09c36SJim Ingham };
815ebc09c36SJim Ingham 
816ebc09c36SJim Ingham #pragma mark CommandObjectCommandsUnalias
817ebc09c36SJim Ingham //-------------------------------------------------------------------------
818ebc09c36SJim Ingham // CommandObjectCommandsUnalias
819ebc09c36SJim Ingham //-------------------------------------------------------------------------
820ebc09c36SJim Ingham 
821b9c1b51eSKate Stone class CommandObjectCommandsUnalias : public CommandObjectParsed {
822ebc09c36SJim Ingham public:
8237428a18cSKate Stone   CommandObjectCommandsUnalias(CommandInterpreter &interpreter)
824b9c1b51eSKate Stone       : CommandObjectParsed(
825b9c1b51eSKate Stone             interpreter, "command unalias",
826b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command alias'.",
827b9c1b51eSKate Stone             nullptr) {
828405fe67fSCaroline Tice     CommandArgumentEntry arg;
829405fe67fSCaroline Tice     CommandArgumentData alias_arg;
830405fe67fSCaroline Tice 
831405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
832405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
833405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
834405fe67fSCaroline Tice 
835b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
836b9c1b51eSKate Stone     // argument entry.
837405fe67fSCaroline Tice     arg.push_back(alias_arg);
838405fe67fSCaroline Tice 
839405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
840405fe67fSCaroline Tice     m_arguments.push_back(arg);
841ebc09c36SJim Ingham   }
842ebc09c36SJim Ingham 
8436e3d8e7fSEugene Zelenko   ~CommandObjectCommandsUnalias() override = default;
844ebc09c36SJim Ingham 
8455a988416SJim Ingham protected:
846b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
847ebc09c36SJim Ingham     CommandObject::CommandMap::iterator pos;
848ebc09c36SJim Ingham     CommandObject *cmd_obj;
849ebc09c36SJim Ingham 
85011eb9c64SZachary Turner     if (args.empty()) {
85111eb9c64SZachary Turner       result.AppendError("must call 'unalias' with a valid alias");
85211eb9c64SZachary Turner       result.SetStatus(eReturnStatusFailed);
85311eb9c64SZachary Turner       return false;
85411eb9c64SZachary Turner     }
85511eb9c64SZachary Turner 
85611eb9c64SZachary Turner     // TODO: Convert this function to return a StringRef.  Should also convert
85711eb9c64SZachary Turner     // dependent functions GetCommandObject, CommandExists, RemoveAlias,
85811eb9c64SZachary Turner     // AliasExists, etc.
859ebc09c36SJim Ingham     const char *command_name = args.GetArgumentAtIndex(0);
860a7015092SGreg Clayton     cmd_obj = m_interpreter.GetCommandObject(command_name);
861b9c1b51eSKate Stone     if (cmd_obj) {
862b9c1b51eSKate Stone       if (m_interpreter.CommandExists(command_name)) {
863b9c1b51eSKate Stone         if (cmd_obj->IsRemovable()) {
864b9c1b51eSKate Stone           result.AppendErrorWithFormat(
865b9c1b51eSKate Stone               "'%s' is not an alias, it is a debugger command which can be "
866b9c1b51eSKate Stone               "removed using the 'command delete' command.\n",
867b547278cSGreg Clayton               command_name);
868b9c1b51eSKate Stone         } else {
869b9c1b51eSKate Stone           result.AppendErrorWithFormat(
870b9c1b51eSKate Stone               "'%s' is a permanent debugger command and cannot be removed.\n",
871ebc09c36SJim Ingham               command_name);
872b547278cSGreg Clayton         }
873ebc09c36SJim Ingham         result.SetStatus(eReturnStatusFailed);
874b9c1b51eSKate Stone       } else {
875b9c1b51eSKate Stone         if (!m_interpreter.RemoveAlias(command_name)) {
876a7015092SGreg Clayton           if (m_interpreter.AliasExists(command_name))
877b9c1b51eSKate Stone             result.AppendErrorWithFormat(
878b9c1b51eSKate Stone                 "Error occurred while attempting to unalias '%s'.\n",
879ebc09c36SJim Ingham                 command_name);
880ebc09c36SJim Ingham           else
881b9c1b51eSKate Stone             result.AppendErrorWithFormat("'%s' is not an existing alias.\n",
882b9c1b51eSKate Stone                                          command_name);
883ebc09c36SJim Ingham           result.SetStatus(eReturnStatusFailed);
884b9c1b51eSKate Stone         } else
885ebc09c36SJim Ingham           result.SetStatus(eReturnStatusSuccessFinishNoResult);
886ebc09c36SJim Ingham       }
887b9c1b51eSKate Stone     } else {
888b9c1b51eSKate Stone       result.AppendErrorWithFormat(
889b9c1b51eSKate Stone           "'%s' is not a known command.\nTry 'help' to see a "
890ebc09c36SJim Ingham           "current list of commands.\n",
891ebc09c36SJim Ingham           command_name);
892ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
893ebc09c36SJim Ingham     }
894ebc09c36SJim Ingham 
895ebc09c36SJim Ingham     return result.Succeeded();
896ebc09c36SJim Ingham   }
897ebc09c36SJim Ingham };
898ebc09c36SJim Ingham 
899b547278cSGreg Clayton #pragma mark CommandObjectCommandsDelete
900b547278cSGreg Clayton //-------------------------------------------------------------------------
901b547278cSGreg Clayton // CommandObjectCommandsDelete
902b547278cSGreg Clayton //-------------------------------------------------------------------------
903b547278cSGreg Clayton 
904b9c1b51eSKate Stone class CommandObjectCommandsDelete : public CommandObjectParsed {
905b547278cSGreg Clayton public:
9067428a18cSKate Stone   CommandObjectCommandsDelete(CommandInterpreter &interpreter)
907b9c1b51eSKate Stone       : CommandObjectParsed(
908b9c1b51eSKate Stone             interpreter, "command delete",
909b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command regex'.",
910b9c1b51eSKate Stone             nullptr) {
911b547278cSGreg Clayton     CommandArgumentEntry arg;
912b547278cSGreg Clayton     CommandArgumentData alias_arg;
913b547278cSGreg Clayton 
914b547278cSGreg Clayton     // Define the first (and only) variant of this arg.
915b547278cSGreg Clayton     alias_arg.arg_type = eArgTypeCommandName;
916b547278cSGreg Clayton     alias_arg.arg_repetition = eArgRepeatPlain;
917b547278cSGreg Clayton 
918b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
919b9c1b51eSKate Stone     // argument entry.
920b547278cSGreg Clayton     arg.push_back(alias_arg);
921b547278cSGreg Clayton 
922b547278cSGreg Clayton     // Push the data for the first argument into the m_arguments vector.
923b547278cSGreg Clayton     m_arguments.push_back(arg);
924b547278cSGreg Clayton   }
925b547278cSGreg Clayton 
9266e3d8e7fSEugene Zelenko   ~CommandObjectCommandsDelete() override = default;
927b547278cSGreg Clayton 
928b547278cSGreg Clayton protected:
929b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
930b547278cSGreg Clayton     CommandObject::CommandMap::iterator pos;
931b547278cSGreg Clayton 
93211eb9c64SZachary Turner     if (args.empty()) {
93311eb9c64SZachary Turner       result.AppendErrorWithFormat("must call '%s' with one or more valid user "
93411eb9c64SZachary Turner                                    "defined regular expression command names",
935a449698cSZachary Turner                                    GetCommandName().str().c_str());
93611eb9c64SZachary Turner       result.SetStatus(eReturnStatusFailed);
93711eb9c64SZachary Turner     }
93811eb9c64SZachary Turner 
93911eb9c64SZachary Turner     // TODO: Convert this to accept a stringRef.
940b547278cSGreg Clayton     const char *command_name = args.GetArgumentAtIndex(0);
941b9c1b51eSKate Stone     if (m_interpreter.CommandExists(command_name)) {
942b9c1b51eSKate Stone       if (m_interpreter.RemoveCommand(command_name)) {
943b547278cSGreg Clayton         result.SetStatus(eReturnStatusSuccessFinishNoResult);
944b9c1b51eSKate Stone       } else {
945b9c1b51eSKate Stone         result.AppendErrorWithFormat(
946b9c1b51eSKate Stone             "'%s' is a permanent debugger command and cannot be removed.\n",
947b547278cSGreg Clayton             command_name);
948b547278cSGreg Clayton         result.SetStatus(eReturnStatusFailed);
949b547278cSGreg Clayton       }
950b9c1b51eSKate Stone     } else {
95146d4aa21SEnrico Granata       StreamString error_msg_stream;
95246d4aa21SEnrico Granata       const bool generate_apropos = true;
95346d4aa21SEnrico Granata       const bool generate_type_lookup = false;
954b9c1b51eSKate Stone       CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage(
955b9c1b51eSKate Stone           &error_msg_stream, command_name, nullptr, nullptr, generate_apropos,
95646d4aa21SEnrico Granata           generate_type_lookup);
95746d4aa21SEnrico Granata       result.AppendErrorWithFormat("%s", error_msg_stream.GetData());
958b547278cSGreg Clayton       result.SetStatus(eReturnStatusFailed);
959b547278cSGreg Clayton     }
960b547278cSGreg Clayton 
961b547278cSGreg Clayton     return result.Succeeded();
962b547278cSGreg Clayton   }
963b547278cSGreg Clayton };
964b547278cSGreg Clayton 
965de164aaaSGreg Clayton //-------------------------------------------------------------------------
966de164aaaSGreg Clayton // CommandObjectCommandsAddRegex
967de164aaaSGreg Clayton //-------------------------------------------------------------------------
9681f0f5b5bSZachary Turner 
9691f0f5b5bSZachary Turner static OptionDefinition g_regex_options[] = {
9701f0f5b5bSZachary Turner     // clang-format off
9711f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "help"  , 'h', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone, "The help text to display for this command." },
9721f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "syntax", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone, "A syntax string showing the typical usage syntax." },
9731f0f5b5bSZachary Turner     // clang-format on
9741f0f5b5bSZachary Turner };
9751f0f5b5bSZachary Turner 
9765a988416SJim Ingham #pragma mark CommandObjectCommandsAddRegex
977de164aaaSGreg Clayton 
978b9c1b51eSKate Stone class CommandObjectCommandsAddRegex : public CommandObjectParsed,
979b9c1b51eSKate Stone                                       public IOHandlerDelegateMultiline {
980de164aaaSGreg Clayton public:
9817428a18cSKate Stone   CommandObjectCommandsAddRegex(CommandInterpreter &interpreter)
982b9c1b51eSKate Stone       : CommandObjectParsed(
983b9c1b51eSKate Stone             interpreter, "command regex", "Define a custom command in terms of "
984b9c1b51eSKate Stone                                           "existing commands by matching "
985b9c1b51eSKate Stone                                           "regular expressions.",
9860e5e5a79SGreg Clayton             "command regex <cmd-name> [s/<regex>/<subst>/ ...]"),
987b9c1b51eSKate Stone         IOHandlerDelegateMultiline("",
988b9c1b51eSKate Stone                                    IOHandlerDelegate::Completion::LLDBCommand),
989b9c1b51eSKate Stone         m_options() {
990b9c1b51eSKate Stone     SetHelpLong(
991b9c1b51eSKate Stone         R"(
992b9c1b51eSKate Stone )"
993b9c1b51eSKate Stone         "This command allows the user to create powerful regular expression commands \
994ea671fbdSKate Stone with substitutions. The regular expressions and substitutions are specified \
995b9c1b51eSKate Stone using the regular expression substitution format of:"
996b9c1b51eSKate Stone         R"(
997ea671fbdSKate Stone 
998ea671fbdSKate Stone     s/<regex>/<subst>/
999ea671fbdSKate Stone 
1000b9c1b51eSKate Stone )"
1001b9c1b51eSKate Stone         "<regex> is a regular expression that can use parenthesis to capture regular \
1002ea671fbdSKate Stone expression input and substitute the captured matches in the output using %1 \
1003b9c1b51eSKate Stone for the first match, %2 for the second, and so on."
1004b9c1b51eSKate Stone         R"(
1005ea671fbdSKate Stone 
1006b9c1b51eSKate Stone )"
1007b9c1b51eSKate Stone         "The regular expressions can all be specified on the command line if more than \
1008ea671fbdSKate Stone one argument is provided. If just the command name is provided on the command \
1009ea671fbdSKate Stone line, then the regular expressions and substitutions can be entered on separate \
1010b9c1b51eSKate Stone lines, followed by an empty line to terminate the command definition."
1011b9c1b51eSKate Stone         R"(
1012ea671fbdSKate Stone 
1013ea671fbdSKate Stone EXAMPLES
1014ea671fbdSKate Stone 
1015b9c1b51eSKate Stone )"
1016b9c1b51eSKate Stone         "The following example will define a regular expression command named 'f' that \
1017ea671fbdSKate Stone will call 'finish' if there are no arguments, or 'frame select <frame-idx>' if \
1018b9c1b51eSKate Stone a number follows 'f':"
1019b9c1b51eSKate Stone         R"(
1020ea671fbdSKate Stone 
1021b9c1b51eSKate Stone     (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')");
1022de164aaaSGreg Clayton   }
1023de164aaaSGreg Clayton 
10246e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAddRegex() override = default;
1025de164aaaSGreg Clayton 
10265a988416SJim Ingham protected:
1027b9c1b51eSKate Stone   void IOHandlerActivated(IOHandler &io_handler) override {
102844d93782SGreg Clayton     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
1029b9c1b51eSKate Stone     if (output_sp) {
1030b9c1b51eSKate Stone       output_sp->PutCString("Enter one of more sed substitution commands in "
1031b9c1b51eSKate Stone                             "the form: 's/<regex>/<subst>/'.\nTerminate the "
1032b9c1b51eSKate Stone                             "substitution list with an empty line.\n");
103344d93782SGreg Clayton       output_sp->Flush();
103444d93782SGreg Clayton     }
103544d93782SGreg Clayton   }
103644d93782SGreg Clayton 
1037b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
1038b9c1b51eSKate Stone                               std::string &data) override {
103944d93782SGreg Clayton     io_handler.SetIsDone(true);
1040b9c1b51eSKate Stone     if (m_regex_cmd_ap) {
104144d93782SGreg Clayton       StringList lines;
1042b9c1b51eSKate Stone       if (lines.SplitIntoLines(data)) {
104344d93782SGreg Clayton         const size_t num_lines = lines.GetSize();
104444d93782SGreg Clayton         bool check_only = false;
1045b9c1b51eSKate Stone         for (size_t i = 0; i < num_lines; ++i) {
104644d93782SGreg Clayton           llvm::StringRef bytes_strref(lines[i]);
104744d93782SGreg Clayton           Error error = AppendRegexSubstitution(bytes_strref, check_only);
1048b9c1b51eSKate Stone           if (error.Fail()) {
1049b9c1b51eSKate Stone             if (!m_interpreter.GetDebugger()
1050b9c1b51eSKate Stone                      .GetCommandInterpreter()
1051b9c1b51eSKate Stone                      .GetBatchCommandMode()) {
1052b9c1b51eSKate Stone               StreamSP out_stream =
1053b9c1b51eSKate Stone                   m_interpreter.GetDebugger().GetAsyncOutputStream();
105444d93782SGreg Clayton               out_stream->Printf("error: %s\n", error.AsCString());
105544d93782SGreg Clayton             }
105644d93782SGreg Clayton           }
105744d93782SGreg Clayton         }
105844d93782SGreg Clayton       }
1059b9c1b51eSKate Stone       if (m_regex_cmd_ap->HasRegexEntries()) {
106044d93782SGreg Clayton         CommandObjectSP cmd_sp(m_regex_cmd_ap.release());
106144d93782SGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
106244d93782SGreg Clayton       }
106344d93782SGreg Clayton     }
106444d93782SGreg Clayton   }
106544d93782SGreg Clayton 
1066b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
10675a988416SJim Ingham     const size_t argc = command.GetArgumentCount();
1068b9c1b51eSKate Stone     if (argc == 0) {
1069b9c1b51eSKate Stone       result.AppendError("usage: 'command regex <command-name> "
1070b9c1b51eSKate Stone                          "[s/<regex1>/<subst1>/ s/<regex2>/<subst2>/ ...]'\n");
10710e5e5a79SGreg Clayton       result.SetStatus(eReturnStatusFailed);
107211eb9c64SZachary Turner       return false;
107311eb9c64SZachary Turner     }
107411eb9c64SZachary Turner 
10750e5e5a79SGreg Clayton     Error error;
10765a988416SJim Ingham     const char *name = command.GetArgumentAtIndex(0);
107711eb9c64SZachary Turner     m_regex_cmd_ap.reset(
107811eb9c64SZachary Turner         new CommandObjectRegexCommand(m_interpreter, name, m_options.GetHelp(),
107911eb9c64SZachary Turner                                       m_options.GetSyntax(), 10, 0, true));
10800e5e5a79SGreg Clayton 
1081b9c1b51eSKate Stone     if (argc == 1) {
108244d93782SGreg Clayton       Debugger &debugger = m_interpreter.GetDebugger();
1083e30f11d9SKate Stone       bool color_prompt = debugger.GetUseColor();
108444d93782SGreg Clayton       const bool multiple_lines = true; // Get multiple lines
1085b9c1b51eSKate Stone       IOHandlerSP io_handler_sp(new IOHandlerEditline(
1086b9c1b51eSKate Stone           debugger, IOHandler::Type::Other,
108773d80faaSGreg Clayton           "lldb-regex",          // Name of input reader for history
1088514d8cd8SZachary Turner           llvm::StringRef("> "), // Prompt
1089514d8cd8SZachary Turner           llvm::StringRef(),     // Continuation prompt
1090b9c1b51eSKate Stone           multiple_lines, color_prompt,
1091f6913cd7SGreg Clayton           0, // Don't show line numbers
109244d93782SGreg Clayton           *this));
109344d93782SGreg Clayton 
1094b9c1b51eSKate Stone       if (io_handler_sp) {
109544d93782SGreg Clayton         debugger.PushIOHandler(io_handler_sp);
1096de164aaaSGreg Clayton         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1097de164aaaSGreg Clayton       }
1098b9c1b51eSKate Stone     } else {
1099b9c1b51eSKate Stone       for (size_t arg_idx = 1; arg_idx < argc; ++arg_idx) {
11005a988416SJim Ingham         llvm::StringRef arg_strref(command.GetArgumentAtIndex(arg_idx));
110144d93782SGreg Clayton         bool check_only = false;
110244d93782SGreg Clayton         error = AppendRegexSubstitution(arg_strref, check_only);
11030e5e5a79SGreg Clayton         if (error.Fail())
11040e5e5a79SGreg Clayton           break;
11050e5e5a79SGreg Clayton       }
11060e5e5a79SGreg Clayton 
1107b9c1b51eSKate Stone       if (error.Success()) {
11080e5e5a79SGreg Clayton         AddRegexCommandToInterpreter();
11090e5e5a79SGreg Clayton       }
11100e5e5a79SGreg Clayton     }
1111b9c1b51eSKate Stone     if (error.Fail()) {
11120e5e5a79SGreg Clayton       result.AppendError(error.AsCString());
1113de164aaaSGreg Clayton       result.SetStatus(eReturnStatusFailed);
1114de164aaaSGreg Clayton     }
11150e5e5a79SGreg Clayton 
1116de164aaaSGreg Clayton     return result.Succeeded();
1117de164aaaSGreg Clayton   }
1118de164aaaSGreg Clayton 
1119b9c1b51eSKate Stone   Error AppendRegexSubstitution(const llvm::StringRef &regex_sed,
1120b9c1b51eSKate Stone                                 bool check_only) {
11210e5e5a79SGreg Clayton     Error error;
11220e5e5a79SGreg Clayton 
1123b9c1b51eSKate Stone     if (!m_regex_cmd_ap) {
1124b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1125b9c1b51eSKate Stone           "invalid regular expression command object for: '%.*s'",
1126b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11270e5e5a79SGreg Clayton       return error;
1128de164aaaSGreg Clayton     }
11290e5e5a79SGreg Clayton 
11300e5e5a79SGreg Clayton     size_t regex_sed_size = regex_sed.size();
11310e5e5a79SGreg Clayton 
1132b9c1b51eSKate Stone     if (regex_sed_size <= 1) {
1133b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1134b9c1b51eSKate Stone           "regular expression substitution string is too short: '%.*s'",
1135b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11360e5e5a79SGreg Clayton       return error;
11370e5e5a79SGreg Clayton     }
11380e5e5a79SGreg Clayton 
1139b9c1b51eSKate Stone     if (regex_sed[0] != 's') {
1140b9c1b51eSKate Stone       error.SetErrorStringWithFormat("regular expression substitution string "
1141b9c1b51eSKate Stone                                      "doesn't start with 's': '%.*s'",
1142b9c1b51eSKate Stone                                      (int)regex_sed.size(), regex_sed.data());
11430e5e5a79SGreg Clayton       return error;
11440e5e5a79SGreg Clayton     }
11450e5e5a79SGreg Clayton     const size_t first_separator_char_pos = 1;
11460e5e5a79SGreg Clayton     // use the char that follows 's' as the regex separator character
11470e5e5a79SGreg Clayton     // so we can have "s/<regex>/<subst>/" or "s|<regex>|<subst>|"
11480e5e5a79SGreg Clayton     const char separator_char = regex_sed[first_separator_char_pos];
1149b9c1b51eSKate Stone     const size_t second_separator_char_pos =
1150b9c1b51eSKate Stone         regex_sed.find(separator_char, first_separator_char_pos + 1);
11510e5e5a79SGreg Clayton 
1152b9c1b51eSKate Stone     if (second_separator_char_pos == std::string::npos) {
1153b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1154b9c1b51eSKate Stone           "missing second '%c' separator char after '%.*s' in '%.*s'",
11550e5e5a79SGreg Clayton           separator_char,
11560e5e5a79SGreg Clayton           (int)(regex_sed.size() - first_separator_char_pos - 1),
1157ea508635SGreg Clayton           regex_sed.data() + (first_separator_char_pos + 1),
1158b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11590e5e5a79SGreg Clayton       return error;
11600e5e5a79SGreg Clayton     }
11610e5e5a79SGreg Clayton 
1162b9c1b51eSKate Stone     const size_t third_separator_char_pos =
1163b9c1b51eSKate Stone         regex_sed.find(separator_char, second_separator_char_pos + 1);
11640e5e5a79SGreg Clayton 
1165b9c1b51eSKate Stone     if (third_separator_char_pos == std::string::npos) {
1166b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1167b9c1b51eSKate Stone           "missing third '%c' separator char after '%.*s' in '%.*s'",
11680e5e5a79SGreg Clayton           separator_char,
11690e5e5a79SGreg Clayton           (int)(regex_sed.size() - second_separator_char_pos - 1),
1170ea508635SGreg Clayton           regex_sed.data() + (second_separator_char_pos + 1),
1171b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11720e5e5a79SGreg Clayton       return error;
11730e5e5a79SGreg Clayton     }
11740e5e5a79SGreg Clayton 
1175b9c1b51eSKate Stone     if (third_separator_char_pos != regex_sed_size - 1) {
11760e5e5a79SGreg Clayton       // Make sure that everything that follows the last regex
11770e5e5a79SGreg Clayton       // separator char
1178b9c1b51eSKate Stone       if (regex_sed.find_first_not_of("\t\n\v\f\r ",
1179b9c1b51eSKate Stone                                       third_separator_char_pos + 1) !=
1180b9c1b51eSKate Stone           std::string::npos) {
1181b9c1b51eSKate Stone         error.SetErrorStringWithFormat(
1182b9c1b51eSKate Stone             "extra data found after the '%.*s' regular expression substitution "
1183b9c1b51eSKate Stone             "string: '%.*s'",
1184b9c1b51eSKate Stone             (int)third_separator_char_pos + 1, regex_sed.data(),
11850e5e5a79SGreg Clayton             (int)(regex_sed.size() - third_separator_char_pos - 1),
11860e5e5a79SGreg Clayton             regex_sed.data() + (third_separator_char_pos + 1));
11870e5e5a79SGreg Clayton         return error;
11880e5e5a79SGreg Clayton       }
1189b9c1b51eSKate Stone     } else if (first_separator_char_pos + 1 == second_separator_char_pos) {
1190b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1191b9c1b51eSKate Stone           "<regex> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
1192b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
11930e5e5a79SGreg Clayton           regex_sed.data());
11940e5e5a79SGreg Clayton       return error;
1195b9c1b51eSKate Stone     } else if (second_separator_char_pos + 1 == third_separator_char_pos) {
1196b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1197b9c1b51eSKate Stone           "<subst> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
1198b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
11990e5e5a79SGreg Clayton           regex_sed.data());
12000e5e5a79SGreg Clayton       return error;
12010e5e5a79SGreg Clayton     }
120244d93782SGreg Clayton 
1203b9c1b51eSKate Stone     if (!check_only) {
1204b9c1b51eSKate Stone       std::string regex(regex_sed.substr(first_separator_char_pos + 1,
1205b9c1b51eSKate Stone                                          second_separator_char_pos -
1206b9c1b51eSKate Stone                                              first_separator_char_pos - 1));
1207b9c1b51eSKate Stone       std::string subst(regex_sed.substr(second_separator_char_pos + 1,
1208b9c1b51eSKate Stone                                          third_separator_char_pos -
1209b9c1b51eSKate Stone                                              second_separator_char_pos - 1));
1210b9c1b51eSKate Stone       m_regex_cmd_ap->AddRegexCommand(regex.c_str(), subst.c_str());
121144d93782SGreg Clayton     }
12120e5e5a79SGreg Clayton     return error;
1213de164aaaSGreg Clayton   }
1214de164aaaSGreg Clayton 
1215b9c1b51eSKate Stone   void AddRegexCommandToInterpreter() {
1216b9c1b51eSKate Stone     if (m_regex_cmd_ap) {
1217b9c1b51eSKate Stone       if (m_regex_cmd_ap->HasRegexEntries()) {
1218de164aaaSGreg Clayton         CommandObjectSP cmd_sp(m_regex_cmd_ap.release());
1219de164aaaSGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
1220de164aaaSGreg Clayton       }
1221de164aaaSGreg Clayton     }
1222de164aaaSGreg Clayton   }
1223de164aaaSGreg Clayton 
1224de164aaaSGreg Clayton private:
12257b0992d9SGreg Clayton   std::unique_ptr<CommandObjectRegexCommand> m_regex_cmd_ap;
1226de164aaaSGreg Clayton 
1227b9c1b51eSKate Stone   class CommandOptions : public Options {
1228de164aaaSGreg Clayton   public:
1229b9c1b51eSKate Stone     CommandOptions() : Options() {}
1230de164aaaSGreg Clayton 
12316e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1232de164aaaSGreg Clayton 
1233b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
1234b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
1235de164aaaSGreg Clayton       Error error;
12363bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1237de164aaaSGreg Clayton 
1238b9c1b51eSKate Stone       switch (short_option) {
1239de164aaaSGreg Clayton       case 'h':
1240de164aaaSGreg Clayton         m_help.assign(option_arg);
1241de164aaaSGreg Clayton         break;
1242de164aaaSGreg Clayton       case 's':
1243de164aaaSGreg Clayton         m_syntax.assign(option_arg);
1244de164aaaSGreg Clayton         break;
1245de164aaaSGreg Clayton       default:
1246b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1247b9c1b51eSKate Stone                                        short_option);
1248de164aaaSGreg Clayton         break;
1249de164aaaSGreg Clayton       }
1250de164aaaSGreg Clayton 
1251de164aaaSGreg Clayton       return error;
1252de164aaaSGreg Clayton     }
1253de164aaaSGreg Clayton 
1254b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1255de164aaaSGreg Clayton       m_help.clear();
1256de164aaaSGreg Clayton       m_syntax.clear();
1257de164aaaSGreg Clayton     }
1258de164aaaSGreg Clayton 
12591f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
126070602439SZachary Turner       return llvm::makeArrayRef(g_regex_options);
12611f0f5b5bSZachary Turner     }
1262de164aaaSGreg Clayton 
126311eb9c64SZachary Turner     // TODO: Convert these functions to return StringRefs.
1264b9c1b51eSKate Stone     const char *GetHelp() {
12656e3d8e7fSEugene Zelenko       return (m_help.empty() ? nullptr : m_help.c_str());
1266de164aaaSGreg Clayton     }
12676e3d8e7fSEugene Zelenko 
1268b9c1b51eSKate Stone     const char *GetSyntax() {
12696e3d8e7fSEugene Zelenko       return (m_syntax.empty() ? nullptr : m_syntax.c_str());
1270de164aaaSGreg Clayton     }
12716e3d8e7fSEugene Zelenko 
1272de164aaaSGreg Clayton   protected:
12736e3d8e7fSEugene Zelenko     // Instance variables to hold the values for command options.
12746e3d8e7fSEugene Zelenko 
1275de164aaaSGreg Clayton     std::string m_help;
1276de164aaaSGreg Clayton     std::string m_syntax;
1277de164aaaSGreg Clayton   };
1278de164aaaSGreg Clayton 
1279b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
1280de164aaaSGreg Clayton 
12815a988416SJim Ingham   CommandOptions m_options;
1282de164aaaSGreg Clayton };
1283de164aaaSGreg Clayton 
1284b9c1b51eSKate Stone class CommandObjectPythonFunction : public CommandObjectRaw {
1285223383edSEnrico Granata public:
1286b9c1b51eSKate Stone   CommandObjectPythonFunction(CommandInterpreter &interpreter, std::string name,
1287b9c1b51eSKate Stone                               std::string funct, std::string help,
1288b9c1b51eSKate Stone                               ScriptedCommandSynchronicity synch)
1289a449698cSZachary Turner       : CommandObjectRaw(interpreter, name),
1290b9c1b51eSKate Stone         m_function_name(funct), m_synchro(synch), m_fetched_help_long(false) {
1291735152e3SEnrico Granata     if (!help.empty())
1292735152e3SEnrico Granata       SetHelp(help.c_str());
1293b9c1b51eSKate Stone     else {
1294735152e3SEnrico Granata       StreamString stream;
1295735152e3SEnrico Granata       stream.Printf("For more information run 'help %s'", name.c_str());
1296735152e3SEnrico Granata       SetHelp(stream.GetData());
1297735152e3SEnrico Granata     }
1298223383edSEnrico Granata   }
1299223383edSEnrico Granata 
13006e3d8e7fSEugene Zelenko   ~CommandObjectPythonFunction() override = default;
1301223383edSEnrico Granata 
1302b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
13035a988416SJim Ingham 
1304b9c1b51eSKate Stone   const std::string &GetFunctionName() { return m_function_name; }
13055a988416SJim Ingham 
1306b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
13075a988416SJim Ingham 
1308b9c1b51eSKate Stone   const char *GetHelpLong() override {
1309b9c1b51eSKate Stone     if (!m_fetched_help_long) {
1310fac939e9SEnrico Granata       ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1311b9c1b51eSKate Stone       if (scripter) {
1312fac939e9SEnrico Granata         std::string docstring;
1313b9c1b51eSKate Stone         m_fetched_help_long = scripter->GetDocumentationForItem(
1314b9c1b51eSKate Stone             m_function_name.c_str(), docstring);
1315fac939e9SEnrico Granata         if (!docstring.empty())
1316bfb75e9bSEnrico Granata           SetHelpLong(docstring.c_str());
1317fac939e9SEnrico Granata       }
1318fac939e9SEnrico Granata     }
1319fac939e9SEnrico Granata     return CommandObjectRaw::GetHelpLong();
1320fac939e9SEnrico Granata   }
1321fac939e9SEnrico Granata 
13225a988416SJim Ingham protected:
1323b9c1b51eSKate Stone   bool DoExecute(const char *raw_command_line,
1324b9c1b51eSKate Stone                  CommandReturnObject &result) override {
1325223383edSEnrico Granata     ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1326223383edSEnrico Granata 
1327223383edSEnrico Granata     Error error;
1328223383edSEnrico Granata 
132970f11f88SJim Ingham     result.SetStatus(eReturnStatusInvalid);
133070f11f88SJim Ingham 
1331b9c1b51eSKate Stone     if (!scripter ||
1332b9c1b51eSKate Stone         !scripter->RunScriptBasedCommand(m_function_name.c_str(),
1333b9c1b51eSKate Stone                                          raw_command_line, m_synchro, result,
1334b9c1b51eSKate Stone                                          error, m_exe_ctx)) {
1335223383edSEnrico Granata       result.AppendError(error.AsCString());
1336223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1337b9c1b51eSKate Stone     } else {
133870f11f88SJim Ingham       // Don't change the status if the command already set it...
1339b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1340b9c1b51eSKate Stone         if (result.GetOutputData() == nullptr ||
1341b9c1b51eSKate Stone             result.GetOutputData()[0] == '\0')
1342223383edSEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
134370f11f88SJim Ingham         else
134470f11f88SJim Ingham           result.SetStatus(eReturnStatusSuccessFinishResult);
134570f11f88SJim Ingham       }
134670f11f88SJim Ingham     }
1347223383edSEnrico Granata 
1348223383edSEnrico Granata     return result.Succeeded();
1349223383edSEnrico Granata   }
1350223383edSEnrico Granata 
13516e3d8e7fSEugene Zelenko private:
13526e3d8e7fSEugene Zelenko   std::string m_function_name;
13536e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
13546e3d8e7fSEugene Zelenko   bool m_fetched_help_long;
1355223383edSEnrico Granata };
1356223383edSEnrico Granata 
1357b9c1b51eSKate Stone class CommandObjectScriptingObject : public CommandObjectRaw {
13589fe00e52SEnrico Granata public:
13599fe00e52SEnrico Granata   CommandObjectScriptingObject(CommandInterpreter &interpreter,
13609fe00e52SEnrico Granata                                std::string name,
13610641ca1aSZachary Turner                                StructuredData::GenericSP cmd_obj_sp,
1362b9c1b51eSKate Stone                                ScriptedCommandSynchronicity synch)
1363a449698cSZachary Turner       : CommandObjectRaw(interpreter, name),
1364b9c1b51eSKate Stone         m_cmd_obj_sp(cmd_obj_sp), m_synchro(synch), m_fetched_help_short(false),
1365b9c1b51eSKate Stone         m_fetched_help_long(false) {
13669fe00e52SEnrico Granata     StreamString stream;
13679fe00e52SEnrico Granata     stream.Printf("For more information run 'help %s'", name.c_str());
13689fe00e52SEnrico Granata     SetHelp(stream.GetData());
1369e87764f2SEnrico Granata     if (ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter())
1370e87764f2SEnrico Granata       GetFlags().Set(scripter->GetFlagsForCommandObject(cmd_obj_sp));
13719fe00e52SEnrico Granata   }
13729fe00e52SEnrico Granata 
13736e3d8e7fSEugene Zelenko   ~CommandObjectScriptingObject() override = default;
13749fe00e52SEnrico Granata 
1375b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
13769fe00e52SEnrico Granata 
1377b9c1b51eSKate Stone   StructuredData::GenericSP GetImplementingObject() { return m_cmd_obj_sp; }
13789fe00e52SEnrico Granata 
1379b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
13809fe00e52SEnrico Granata 
1381b9c1b51eSKate Stone   const char *GetHelp() override {
1382b9c1b51eSKate Stone     if (!m_fetched_help_short) {
13836f79bb2dSEnrico Granata       ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1384b9c1b51eSKate Stone       if (scripter) {
13856f79bb2dSEnrico Granata         std::string docstring;
1386b9c1b51eSKate Stone         m_fetched_help_short =
1387b9c1b51eSKate Stone             scripter->GetShortHelpForCommandObject(m_cmd_obj_sp, docstring);
13886f79bb2dSEnrico Granata         if (!docstring.empty())
1389bfb75e9bSEnrico Granata           SetHelp(docstring.c_str());
13906f79bb2dSEnrico Granata       }
13916f79bb2dSEnrico Granata     }
13926f79bb2dSEnrico Granata     return CommandObjectRaw::GetHelp();
13936f79bb2dSEnrico Granata   }
13946f79bb2dSEnrico Granata 
1395b9c1b51eSKate Stone   const char *GetHelpLong() override {
1396b9c1b51eSKate Stone     if (!m_fetched_help_long) {
13976f79bb2dSEnrico Granata       ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1398b9c1b51eSKate Stone       if (scripter) {
13996f79bb2dSEnrico Granata         std::string docstring;
1400b9c1b51eSKate Stone         m_fetched_help_long =
1401b9c1b51eSKate Stone             scripter->GetLongHelpForCommandObject(m_cmd_obj_sp, docstring);
14026f79bb2dSEnrico Granata         if (!docstring.empty())
1403bfb75e9bSEnrico Granata           SetHelpLong(docstring.c_str());
14046f79bb2dSEnrico Granata       }
14056f79bb2dSEnrico Granata     }
14069fe00e52SEnrico Granata     return CommandObjectRaw::GetHelpLong();
14079fe00e52SEnrico Granata   }
14089fe00e52SEnrico Granata 
14099fe00e52SEnrico Granata protected:
1410b9c1b51eSKate Stone   bool DoExecute(const char *raw_command_line,
1411b9c1b51eSKate Stone                  CommandReturnObject &result) override {
14129fe00e52SEnrico Granata     ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
14139fe00e52SEnrico Granata 
14149fe00e52SEnrico Granata     Error error;
14159fe00e52SEnrico Granata 
14169fe00e52SEnrico Granata     result.SetStatus(eReturnStatusInvalid);
14179fe00e52SEnrico Granata 
1418b9c1b51eSKate Stone     if (!scripter ||
1419b9c1b51eSKate Stone         !scripter->RunScriptBasedCommand(m_cmd_obj_sp, raw_command_line,
1420b9c1b51eSKate Stone                                          m_synchro, result, error, m_exe_ctx)) {
14219fe00e52SEnrico Granata       result.AppendError(error.AsCString());
14229fe00e52SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1423b9c1b51eSKate Stone     } else {
14249fe00e52SEnrico Granata       // Don't change the status if the command already set it...
1425b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1426b9c1b51eSKate Stone         if (result.GetOutputData() == nullptr ||
1427b9c1b51eSKate Stone             result.GetOutputData()[0] == '\0')
14289fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
14299fe00e52SEnrico Granata         else
14309fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishResult);
14319fe00e52SEnrico Granata       }
14329fe00e52SEnrico Granata     }
14339fe00e52SEnrico Granata 
14349fe00e52SEnrico Granata     return result.Succeeded();
14359fe00e52SEnrico Granata   }
14369fe00e52SEnrico Granata 
14376e3d8e7fSEugene Zelenko private:
14386e3d8e7fSEugene Zelenko   StructuredData::GenericSP m_cmd_obj_sp;
14396e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
14406e3d8e7fSEugene Zelenko   bool m_fetched_help_short : 1;
14416e3d8e7fSEugene Zelenko   bool m_fetched_help_long : 1;
14429fe00e52SEnrico Granata };
14439fe00e52SEnrico Granata 
1444a9dbf432SEnrico Granata //-------------------------------------------------------------------------
1445a9dbf432SEnrico Granata // CommandObjectCommandsScriptImport
1446a9dbf432SEnrico Granata //-------------------------------------------------------------------------
1447a9dbf432SEnrico Granata 
14481f0f5b5bSZachary Turner OptionDefinition g_script_import_options[] = {
14491f0f5b5bSZachary Turner     // clang-format off
14501f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "allow-reload", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow the script to be loaded even if it was already loaded before. This argument exists for backwards compatibility, but reloading is always allowed, whether you specify it or not." },
14511f0f5b5bSZachary Turner     // clang-format on
14521f0f5b5bSZachary Turner };
14531f0f5b5bSZachary Turner 
1454b9c1b51eSKate Stone class CommandObjectCommandsScriptImport : public CommandObjectParsed {
14555a988416SJim Ingham public:
1456b9c1b51eSKate Stone   CommandObjectCommandsScriptImport(CommandInterpreter &interpreter)
1457b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script import",
1458b9c1b51eSKate Stone                             "Import a scripting module in LLDB.", nullptr),
1459b9c1b51eSKate Stone         m_options() {
14605a988416SJim Ingham     CommandArgumentEntry arg1;
14615a988416SJim Ingham     CommandArgumentData cmd_arg;
14625a988416SJim Ingham 
14635a988416SJim Ingham     // Define the first (and only) variant of this arg.
14645a988416SJim Ingham     cmd_arg.arg_type = eArgTypeFilename;
14653b00e35bSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlus;
14665a988416SJim Ingham 
1467b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1468b9c1b51eSKate Stone     // argument entry.
14695a988416SJim Ingham     arg1.push_back(cmd_arg);
14705a988416SJim Ingham 
14715a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
14725a988416SJim Ingham     m_arguments.push_back(arg1);
14735a988416SJim Ingham   }
14745a988416SJim Ingham 
14756e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptImport() override = default;
14765a988416SJim Ingham 
1477b9c1b51eSKate Stone   int HandleArgumentCompletion(Args &input, int &cursor_index,
14785a988416SJim Ingham                                int &cursor_char_position,
14795a988416SJim Ingham                                OptionElementVector &opt_element_vector,
1480b9c1b51eSKate Stone                                int match_start_point, int max_return_elements,
14815a988416SJim Ingham                                bool &word_complete,
1482b9c1b51eSKate Stone                                StringList &matches) override {
14835a988416SJim Ingham     std::string completion_str(input.GetArgumentAtIndex(cursor_index));
14845a988416SJim Ingham     completion_str.erase(cursor_char_position);
14855a988416SJim Ingham 
1486b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
1487b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
1488b9c1b51eSKate Stone         completion_str.c_str(), match_start_point, max_return_elements, nullptr,
1489b9c1b51eSKate Stone         word_complete, matches);
14905a988416SJim Ingham     return matches.GetSize();
14915a988416SJim Ingham   }
14925a988416SJim Ingham 
1493b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
14945a988416SJim Ingham 
14955a988416SJim Ingham protected:
1496b9c1b51eSKate Stone   class CommandOptions : public Options {
14970a305db7SEnrico Granata   public:
1498b9c1b51eSKate Stone     CommandOptions() : Options() {}
14990a305db7SEnrico Granata 
15006e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
15010a305db7SEnrico Granata 
1502b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
1503b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
15040a305db7SEnrico Granata       Error error;
15053bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
15060a305db7SEnrico Granata 
1507b9c1b51eSKate Stone       switch (short_option) {
15080a305db7SEnrico Granata       case 'r':
15090a305db7SEnrico Granata         m_allow_reload = true;
15100a305db7SEnrico Granata         break;
15110a305db7SEnrico Granata       default:
1512b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1513b9c1b51eSKate Stone                                        short_option);
15140a305db7SEnrico Granata         break;
15150a305db7SEnrico Granata       }
15160a305db7SEnrico Granata 
15170a305db7SEnrico Granata       return error;
15180a305db7SEnrico Granata     }
15190a305db7SEnrico Granata 
1520b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1521e0c70f1bSEnrico Granata       m_allow_reload = true;
15220a305db7SEnrico Granata     }
15230a305db7SEnrico Granata 
15241f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
152570602439SZachary Turner       return llvm::makeArrayRef(g_script_import_options);
15261f0f5b5bSZachary Turner     }
15270a305db7SEnrico Granata 
15280a305db7SEnrico Granata     // Instance variables to hold the values for command options.
15290a305db7SEnrico Granata 
15300a305db7SEnrico Granata     bool m_allow_reload;
15310a305db7SEnrico Granata   };
15320a305db7SEnrico Granata 
1533b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1534b9c1b51eSKate Stone     if (m_interpreter.GetDebugger().GetScriptLanguage() !=
1535b9c1b51eSKate Stone         lldb::eScriptLanguagePython) {
1536b9c1b51eSKate Stone       result.AppendError("only scripting language supported for module "
1537b9c1b51eSKate Stone                          "importing is currently Python");
1538a9dbf432SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1539a9dbf432SEnrico Granata       return false;
1540a9dbf432SEnrico Granata     }
1541a9dbf432SEnrico Granata 
154211eb9c64SZachary Turner     if (command.empty()) {
15433b00e35bSEnrico Granata       result.AppendError("command script import needs one or more arguments");
1544a9dbf432SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1545a9dbf432SEnrico Granata       return false;
1546a9dbf432SEnrico Granata     }
1547a9dbf432SEnrico Granata 
154811eb9c64SZachary Turner     for (auto &entry : command.entries()) {
1549a9dbf432SEnrico Granata       Error error;
1550a9dbf432SEnrico Granata 
1551c9d645d3SGreg Clayton       const bool init_session = true;
1552b9c1b51eSKate Stone       // FIXME: this is necessary because CommandObject::CheckRequirements()
155311eb9c64SZachary Turner       // assumes that commands won't ever be recursively invoked, but it's
155411eb9c64SZachary Turner       // actually possible to craft a Python script that does other "command
155511eb9c64SZachary Turner       // script imports" in __lldb_init_module the real fix is to have recursive
155611eb9c64SZachary Turner       // commands possible with a CommandInvocation object separate from the
155711eb9c64SZachary Turner       // CommandObject itself, so that recursive command invocations won't stomp
155811eb9c64SZachary Turner       // on each other (wrt to execution contents, options, and more)
1559078551c7SEnrico Granata       m_exe_ctx.Clear();
1560b9c1b51eSKate Stone       if (m_interpreter.GetScriptInterpreter()->LoadScriptingModule(
156111eb9c64SZachary Turner               entry.c_str(), m_options.m_allow_reload, init_session, error)) {
1562a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1563b9c1b51eSKate Stone       } else {
1564b9c1b51eSKate Stone         result.AppendErrorWithFormat("module importing failed: %s",
1565b9c1b51eSKate Stone                                      error.AsCString());
1566a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusFailed);
1567a9dbf432SEnrico Granata       }
15683b00e35bSEnrico Granata     }
1569a9dbf432SEnrico Granata 
1570a9dbf432SEnrico Granata     return result.Succeeded();
1571a9dbf432SEnrico Granata   }
15720a305db7SEnrico Granata 
15735a988416SJim Ingham   CommandOptions m_options;
1574a9dbf432SEnrico Granata };
1575223383edSEnrico Granata 
1576223383edSEnrico Granata //-------------------------------------------------------------------------
1577223383edSEnrico Granata // CommandObjectCommandsScriptAdd
1578223383edSEnrico Granata //-------------------------------------------------------------------------
1579223383edSEnrico Granata 
15801f0f5b5bSZachary Turner static OptionEnumValueElement g_script_synchro_type[] = {
15811f0f5b5bSZachary Turner     {eScriptedCommandSynchronicitySynchronous, "synchronous",
15821f0f5b5bSZachary Turner      "Run synchronous"},
15831f0f5b5bSZachary Turner     {eScriptedCommandSynchronicityAsynchronous, "asynchronous",
15841f0f5b5bSZachary Turner      "Run asynchronous"},
15851f0f5b5bSZachary Turner     {eScriptedCommandSynchronicityCurrentValue, "current",
15861f0f5b5bSZachary Turner      "Do not alter current setting"},
15871f0f5b5bSZachary Turner     {0, nullptr, nullptr}};
15881f0f5b5bSZachary Turner 
15891f0f5b5bSZachary Turner static OptionDefinition g_script_add_options[] = {
15901f0f5b5bSZachary Turner     // clang-format off
15911f0f5b5bSZachary Turner   { LLDB_OPT_SET_1,   false, "function",      'f', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypePythonFunction,               "Name of the Python function to bind to this command name." },
15921f0f5b5bSZachary Turner   { LLDB_OPT_SET_2,   false, "class",         'c', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypePythonClass,                  "Name of the Python class to bind to this command name." },
15931f0f5b5bSZachary Turner   { LLDB_OPT_SET_1,   false, "help"  ,        'h', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeHelpText,                     "The help text to display for this command." },
15941f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "synchronicity", 's', OptionParser::eRequiredArgument, nullptr, g_script_synchro_type, 0, eArgTypeScriptedCommandSynchronicity, "Set the synchronicity of this command's executions with regard to LLDB event system." },
15951f0f5b5bSZachary Turner     // clang-format on
15961f0f5b5bSZachary Turner };
15971f0f5b5bSZachary Turner 
1598b9c1b51eSKate Stone class CommandObjectCommandsScriptAdd : public CommandObjectParsed,
1599b9c1b51eSKate Stone                                        public IOHandlerDelegateMultiline {
16005a988416SJim Ingham public:
1601b9c1b51eSKate Stone   CommandObjectCommandsScriptAdd(CommandInterpreter &interpreter)
1602b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script add",
16035a988416SJim Ingham                             "Add a scripted function as an LLDB command.",
16046e3d8e7fSEugene Zelenko                             nullptr),
1605b9c1b51eSKate Stone         IOHandlerDelegateMultiline("DONE"), m_options() {
16065a988416SJim Ingham     CommandArgumentEntry arg1;
16075a988416SJim Ingham     CommandArgumentData cmd_arg;
16085a988416SJim Ingham 
16095a988416SJim Ingham     // Define the first (and only) variant of this arg.
16105a988416SJim Ingham     cmd_arg.arg_type = eArgTypeCommandName;
16115a988416SJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlain;
16125a988416SJim Ingham 
1613b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1614b9c1b51eSKate Stone     // argument entry.
16155a988416SJim Ingham     arg1.push_back(cmd_arg);
16165a988416SJim Ingham 
16175a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
16185a988416SJim Ingham     m_arguments.push_back(arg1);
16195a988416SJim Ingham   }
16205a988416SJim Ingham 
16216e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptAdd() override = default;
16225a988416SJim Ingham 
1623b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
16245a988416SJim Ingham 
16255a988416SJim Ingham protected:
1626b9c1b51eSKate Stone   class CommandOptions : public Options {
1627223383edSEnrico Granata   public:
1628b9c1b51eSKate Stone     CommandOptions()
1629b9c1b51eSKate Stone         : Options(), m_class_name(), m_funct_name(), m_short_help(),
1630b9c1b51eSKate Stone           m_synchronicity(eScriptedCommandSynchronicitySynchronous) {}
1631223383edSEnrico Granata 
16326e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1633223383edSEnrico Granata 
1634b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
1635b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
1636223383edSEnrico Granata       Error error;
16373bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1638223383edSEnrico Granata 
1639b9c1b51eSKate Stone       switch (short_option) {
1640223383edSEnrico Granata       case 'f':
1641735152e3SEnrico Granata         if (option_arg)
1642735152e3SEnrico Granata           m_funct_name.assign(option_arg);
1643735152e3SEnrico Granata         break;
16449fe00e52SEnrico Granata       case 'c':
16459fe00e52SEnrico Granata         if (option_arg)
16469fe00e52SEnrico Granata           m_class_name.assign(option_arg);
16479fe00e52SEnrico Granata         break;
1648735152e3SEnrico Granata       case 'h':
1649735152e3SEnrico Granata         if (option_arg)
1650735152e3SEnrico Granata           m_short_help.assign(option_arg);
1651223383edSEnrico Granata         break;
16520a305db7SEnrico Granata       case 's':
1653b9c1b51eSKate Stone         m_synchronicity =
1654b9c1b51eSKate Stone             (ScriptedCommandSynchronicity)Args::StringToOptionEnum(
16558cef4b0bSZachary Turner                 llvm::StringRef::withNullAsEmpty(option_arg),
16568cef4b0bSZachary Turner                 GetDefinitions()[option_idx].enum_values, 0, error);
16570a305db7SEnrico Granata         if (!error.Success())
1658b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
1659b9c1b51eSKate Stone               "unrecognized value for synchronicity '%s'", option_arg);
16600a305db7SEnrico Granata         break;
1661223383edSEnrico Granata       default:
1662b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1663b9c1b51eSKate Stone                                        short_option);
1664223383edSEnrico Granata         break;
1665223383edSEnrico Granata       }
1666223383edSEnrico Granata 
1667223383edSEnrico Granata       return error;
1668223383edSEnrico Granata     }
1669223383edSEnrico Granata 
1670b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
16719fe00e52SEnrico Granata       m_class_name.clear();
1672735152e3SEnrico Granata       m_funct_name.clear();
1673735152e3SEnrico Granata       m_short_help.clear();
167444d93782SGreg Clayton       m_synchronicity = eScriptedCommandSynchronicitySynchronous;
1675223383edSEnrico Granata     }
1676223383edSEnrico Granata 
16771f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
167870602439SZachary Turner       return llvm::makeArrayRef(g_script_add_options);
16791f0f5b5bSZachary Turner     }
1680223383edSEnrico Granata 
1681223383edSEnrico Granata     // Instance variables to hold the values for command options.
1682223383edSEnrico Granata 
16839fe00e52SEnrico Granata     std::string m_class_name;
1684223383edSEnrico Granata     std::string m_funct_name;
1685735152e3SEnrico Granata     std::string m_short_help;
168644d93782SGreg Clayton     ScriptedCommandSynchronicity m_synchronicity;
1687223383edSEnrico Granata   };
1688223383edSEnrico Granata 
1689b9c1b51eSKate Stone   void IOHandlerActivated(IOHandler &io_handler) override {
169044d93782SGreg Clayton     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
1691b9c1b51eSKate Stone     if (output_sp) {
169244d93782SGreg Clayton       output_sp->PutCString(g_python_command_instructions);
169344d93782SGreg Clayton       output_sp->Flush();
1694223383edSEnrico Granata     }
1695223383edSEnrico Granata   }
1696223383edSEnrico Granata 
1697b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
1698b9c1b51eSKate Stone                               std::string &data) override {
169944d93782SGreg Clayton     StreamFileSP error_sp = io_handler.GetErrorStreamFile();
170044d93782SGreg Clayton 
170144d93782SGreg Clayton     ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter();
1702b9c1b51eSKate Stone     if (interpreter) {
170344d93782SGreg Clayton 
170444d93782SGreg Clayton       StringList lines;
170544d93782SGreg Clayton       lines.SplitIntoLines(data);
1706b9c1b51eSKate Stone       if (lines.GetSize() > 0) {
1707a73b7df7SEnrico Granata         std::string funct_name_str;
1708b9c1b51eSKate Stone         if (interpreter->GenerateScriptAliasFunction(lines, funct_name_str)) {
1709b9c1b51eSKate Stone           if (funct_name_str.empty()) {
1710b9c1b51eSKate Stone             error_sp->Printf("error: unable to obtain a function name, didn't "
1711b9c1b51eSKate Stone                              "add python command.\n");
171244d93782SGreg Clayton             error_sp->Flush();
1713b9c1b51eSKate Stone           } else {
1714223383edSEnrico Granata             // everything should be fine now, let's add this alias
1715223383edSEnrico Granata 
1716b9c1b51eSKate Stone             CommandObjectSP command_obj_sp(new CommandObjectPythonFunction(
1717b9c1b51eSKate Stone                 m_interpreter, m_cmd_name, funct_name_str.c_str(), m_short_help,
171844d93782SGreg Clayton                 m_synchronicity));
1719223383edSEnrico Granata 
1720b9c1b51eSKate Stone             if (!m_interpreter.AddUserCommand(m_cmd_name, command_obj_sp,
1721b9c1b51eSKate Stone                                               true)) {
1722b9c1b51eSKate Stone               error_sp->Printf("error: unable to add selected command, didn't "
1723b9c1b51eSKate Stone                                "add python command.\n");
172444d93782SGreg Clayton               error_sp->Flush();
1725223383edSEnrico Granata             }
1726223383edSEnrico Granata           }
1727b9c1b51eSKate Stone         } else {
1728b9c1b51eSKate Stone           error_sp->Printf(
1729b9c1b51eSKate Stone               "error: unable to create function, didn't add python command.\n");
173044d93782SGreg Clayton           error_sp->Flush();
173144d93782SGreg Clayton         }
1732b9c1b51eSKate Stone       } else {
173344d93782SGreg Clayton         error_sp->Printf("error: empty function, didn't add python command.\n");
173444d93782SGreg Clayton         error_sp->Flush();
173544d93782SGreg Clayton       }
1736b9c1b51eSKate Stone     } else {
1737b9c1b51eSKate Stone       error_sp->Printf(
1738b9c1b51eSKate Stone           "error: script interpreter missing, didn't add python command.\n");
173944d93782SGreg Clayton       error_sp->Flush();
174044d93782SGreg Clayton     }
174144d93782SGreg Clayton 
174244d93782SGreg Clayton     io_handler.SetIsDone(true);
174344d93782SGreg Clayton   }
1744223383edSEnrico Granata 
17455a988416SJim Ingham protected:
1746b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1747b9c1b51eSKate Stone     if (m_interpreter.GetDebugger().GetScriptLanguage() !=
1748b9c1b51eSKate Stone         lldb::eScriptLanguagePython) {
1749b9c1b51eSKate Stone       result.AppendError("only scripting language supported for scripted "
1750b9c1b51eSKate Stone                          "commands is currently Python");
175199f0b8f9SEnrico Granata       result.SetStatus(eReturnStatusFailed);
175299f0b8f9SEnrico Granata       return false;
175399f0b8f9SEnrico Granata     }
175499f0b8f9SEnrico Granata 
175511eb9c64SZachary Turner     if (command.GetArgumentCount() != 1) {
1756223383edSEnrico Granata       result.AppendError("'command script add' requires one argument");
1757223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1758223383edSEnrico Granata       return false;
1759223383edSEnrico Granata     }
1760223383edSEnrico Granata 
1761735152e3SEnrico Granata     // Store the options in case we get multi-line input
176244d93782SGreg Clayton     m_cmd_name = command.GetArgumentAtIndex(0);
1763735152e3SEnrico Granata     m_short_help.assign(m_options.m_short_help);
176444d93782SGreg Clayton     m_synchronicity = m_options.m_synchronicity;
1765223383edSEnrico Granata 
1766b9c1b51eSKate Stone     if (m_options.m_class_name.empty()) {
1767b9c1b51eSKate Stone       if (m_options.m_funct_name.empty()) {
1768b9c1b51eSKate Stone         m_interpreter.GetPythonCommandsFromIOHandler(
1769b9c1b51eSKate Stone             "     ",  // Prompt
177044d93782SGreg Clayton             *this,    // IOHandlerDelegate
177144d93782SGreg Clayton             true,     // Run IOHandler in async mode
1772b9c1b51eSKate Stone             nullptr); // Baton for the "io_handler" that will be passed back
1773b9c1b51eSKate Stone                       // into our IOHandlerDelegate functions
1774b9c1b51eSKate Stone       } else {
1775b9c1b51eSKate Stone         CommandObjectSP new_cmd(new CommandObjectPythonFunction(
1776b9c1b51eSKate Stone             m_interpreter, m_cmd_name, m_options.m_funct_name,
1777b9c1b51eSKate Stone             m_options.m_short_help, m_synchronicity));
1778b9c1b51eSKate Stone         if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) {
1779223383edSEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
1780b9c1b51eSKate Stone         } else {
1781223383edSEnrico Granata           result.AppendError("cannot add command");
1782223383edSEnrico Granata           result.SetStatus(eReturnStatusFailed);
1783223383edSEnrico Granata         }
1784223383edSEnrico Granata       }
1785b9c1b51eSKate Stone     } else {
1786b9c1b51eSKate Stone       ScriptInterpreter *interpreter =
1787b9c1b51eSKate Stone           GetCommandInterpreter().GetScriptInterpreter();
1788b9c1b51eSKate Stone       if (!interpreter) {
17899fe00e52SEnrico Granata         result.AppendError("cannot find ScriptInterpreter");
17909fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17919fe00e52SEnrico Granata         return false;
17929fe00e52SEnrico Granata       }
17939fe00e52SEnrico Granata 
1794b9c1b51eSKate Stone       auto cmd_obj_sp = interpreter->CreateScriptCommandObject(
1795b9c1b51eSKate Stone           m_options.m_class_name.c_str());
1796b9c1b51eSKate Stone       if (!cmd_obj_sp) {
17979fe00e52SEnrico Granata         result.AppendError("cannot create helper object");
17989fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17999fe00e52SEnrico Granata         return false;
18009fe00e52SEnrico Granata       }
18019fe00e52SEnrico Granata 
1802b9c1b51eSKate Stone       CommandObjectSP new_cmd(new CommandObjectScriptingObject(
1803b9c1b51eSKate Stone           m_interpreter, m_cmd_name, cmd_obj_sp, m_synchronicity));
1804b9c1b51eSKate Stone       if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) {
18059fe00e52SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1806b9c1b51eSKate Stone       } else {
18079fe00e52SEnrico Granata         result.AppendError("cannot add command");
18089fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
18099fe00e52SEnrico Granata       }
18109fe00e52SEnrico Granata     }
1811223383edSEnrico Granata 
1812223383edSEnrico Granata     return result.Succeeded();
1813223383edSEnrico Granata   }
18145a988416SJim Ingham 
18155a988416SJim Ingham   CommandOptions m_options;
181644d93782SGreg Clayton   std::string m_cmd_name;
1817735152e3SEnrico Granata   std::string m_short_help;
181844d93782SGreg Clayton   ScriptedCommandSynchronicity m_synchronicity;
1819223383edSEnrico Granata };
1820223383edSEnrico Granata 
1821223383edSEnrico Granata //-------------------------------------------------------------------------
1822223383edSEnrico Granata // CommandObjectCommandsScriptList
1823223383edSEnrico Granata //-------------------------------------------------------------------------
1824223383edSEnrico Granata 
1825b9c1b51eSKate Stone class CommandObjectCommandsScriptList : public CommandObjectParsed {
1826223383edSEnrico Granata public:
1827b9c1b51eSKate Stone   CommandObjectCommandsScriptList(CommandInterpreter &interpreter)
1828b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script list",
1829b9c1b51eSKate Stone                             "List defined scripted commands.", nullptr) {}
1830223383edSEnrico Granata 
18316e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptList() override = default;
1832223383edSEnrico Granata 
1833b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1834b9c1b51eSKate Stone     m_interpreter.GetHelp(result, CommandInterpreter::eCommandTypesUserDef);
1835223383edSEnrico Granata 
1836223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1837223383edSEnrico Granata 
1838223383edSEnrico Granata     return true;
1839223383edSEnrico Granata   }
1840223383edSEnrico Granata };
1841223383edSEnrico Granata 
1842223383edSEnrico Granata //-------------------------------------------------------------------------
1843223383edSEnrico Granata // CommandObjectCommandsScriptClear
1844223383edSEnrico Granata //-------------------------------------------------------------------------
1845223383edSEnrico Granata 
1846b9c1b51eSKate Stone class CommandObjectCommandsScriptClear : public CommandObjectParsed {
1847223383edSEnrico Granata public:
1848b9c1b51eSKate Stone   CommandObjectCommandsScriptClear(CommandInterpreter &interpreter)
1849b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script clear",
1850b9c1b51eSKate Stone                             "Delete all scripted commands.", nullptr) {}
1851223383edSEnrico Granata 
18526e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptClear() override = default;
1853223383edSEnrico Granata 
18545a988416SJim Ingham protected:
1855b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1856223383edSEnrico Granata     m_interpreter.RemoveAllUser();
1857223383edSEnrico Granata 
1858223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1859223383edSEnrico Granata 
1860223383edSEnrico Granata     return true;
1861223383edSEnrico Granata   }
1862223383edSEnrico Granata };
1863223383edSEnrico Granata 
1864223383edSEnrico Granata //-------------------------------------------------------------------------
1865223383edSEnrico Granata // CommandObjectCommandsScriptDelete
1866223383edSEnrico Granata //-------------------------------------------------------------------------
1867223383edSEnrico Granata 
1868b9c1b51eSKate Stone class CommandObjectCommandsScriptDelete : public CommandObjectParsed {
1869223383edSEnrico Granata public:
1870b9c1b51eSKate Stone   CommandObjectCommandsScriptDelete(CommandInterpreter &interpreter)
1871b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script delete",
1872b9c1b51eSKate Stone                             "Delete a scripted command.", nullptr) {
1873223383edSEnrico Granata     CommandArgumentEntry arg1;
1874223383edSEnrico Granata     CommandArgumentData cmd_arg;
1875223383edSEnrico Granata 
1876223383edSEnrico Granata     // Define the first (and only) variant of this arg.
1877223383edSEnrico Granata     cmd_arg.arg_type = eArgTypeCommandName;
1878223383edSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlain;
1879223383edSEnrico Granata 
1880b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1881b9c1b51eSKate Stone     // argument entry.
1882223383edSEnrico Granata     arg1.push_back(cmd_arg);
1883223383edSEnrico Granata 
1884223383edSEnrico Granata     // Push the data for the first argument into the m_arguments vector.
1885223383edSEnrico Granata     m_arguments.push_back(arg1);
1886223383edSEnrico Granata   }
1887223383edSEnrico Granata 
18886e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptDelete() override = default;
1889223383edSEnrico Granata 
18905a988416SJim Ingham protected:
1891b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1892223383edSEnrico Granata 
189311eb9c64SZachary Turner     if (command.GetArgumentCount() != 1) {
1894223383edSEnrico Granata       result.AppendError("'command script delete' requires one argument");
1895223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1896223383edSEnrico Granata       return false;
1897223383edSEnrico Granata     }
1898223383edSEnrico Granata 
18995a988416SJim Ingham     const char *cmd_name = command.GetArgumentAtIndex(0);
1900223383edSEnrico Granata 
1901b9c1b51eSKate Stone     if (cmd_name && *cmd_name && m_interpreter.HasUserCommands() &&
1902b9c1b51eSKate Stone         m_interpreter.UserCommandExists(cmd_name)) {
1903223383edSEnrico Granata       m_interpreter.RemoveUser(cmd_name);
1904223383edSEnrico Granata       result.SetStatus(eReturnStatusSuccessFinishResult);
1905b9c1b51eSKate Stone     } else {
1906223383edSEnrico Granata       result.AppendErrorWithFormat("command %s not found", cmd_name);
1907223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1908223383edSEnrico Granata     }
1909223383edSEnrico Granata 
1910223383edSEnrico Granata     return result.Succeeded();
1911223383edSEnrico Granata   }
1912223383edSEnrico Granata };
1913223383edSEnrico Granata 
1914223383edSEnrico Granata #pragma mark CommandObjectMultiwordCommandsScript
1915223383edSEnrico Granata 
1916223383edSEnrico Granata //-------------------------------------------------------------------------
1917223383edSEnrico Granata // CommandObjectMultiwordCommandsScript
1918223383edSEnrico Granata //-------------------------------------------------------------------------
1919223383edSEnrico Granata 
1920b9c1b51eSKate Stone class CommandObjectMultiwordCommandsScript : public CommandObjectMultiword {
1921223383edSEnrico Granata public:
19227428a18cSKate Stone   CommandObjectMultiwordCommandsScript(CommandInterpreter &interpreter)
1923b9c1b51eSKate Stone       : CommandObjectMultiword(
1924b9c1b51eSKate Stone             interpreter, "command script", "Commands for managing custom "
1925b9c1b51eSKate Stone                                            "commands implemented by "
1926b9c1b51eSKate Stone                                            "interpreter scripts.",
1927b9c1b51eSKate Stone             "command script <subcommand> [<subcommand-options>]") {
1928b9c1b51eSKate Stone     LoadSubCommand("add", CommandObjectSP(
1929b9c1b51eSKate Stone                               new CommandObjectCommandsScriptAdd(interpreter)));
1930b9c1b51eSKate Stone     LoadSubCommand(
1931b9c1b51eSKate Stone         "delete",
1932b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptDelete(interpreter)));
1933b9c1b51eSKate Stone     LoadSubCommand(
1934b9c1b51eSKate Stone         "clear",
1935b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptClear(interpreter)));
1936b9c1b51eSKate Stone     LoadSubCommand("list", CommandObjectSP(new CommandObjectCommandsScriptList(
1937b9c1b51eSKate Stone                                interpreter)));
1938b9c1b51eSKate Stone     LoadSubCommand(
1939b9c1b51eSKate Stone         "import",
1940b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptImport(interpreter)));
1941223383edSEnrico Granata   }
1942223383edSEnrico Granata 
19436e3d8e7fSEugene Zelenko   ~CommandObjectMultiwordCommandsScript() override = default;
1944223383edSEnrico Granata };
1945223383edSEnrico Granata 
1946ebc09c36SJim Ingham #pragma mark CommandObjectMultiwordCommands
1947ebc09c36SJim Ingham 
1948ebc09c36SJim Ingham //-------------------------------------------------------------------------
1949ebc09c36SJim Ingham // CommandObjectMultiwordCommands
1950ebc09c36SJim Ingham //-------------------------------------------------------------------------
1951ebc09c36SJim Ingham 
1952b9c1b51eSKate Stone CommandObjectMultiwordCommands::CommandObjectMultiwordCommands(
1953b9c1b51eSKate Stone     CommandInterpreter &interpreter)
1954b9c1b51eSKate Stone     : CommandObjectMultiword(interpreter, "command",
1955b9c1b51eSKate Stone                              "Commands for managing custom LLDB commands.",
1956b9c1b51eSKate Stone                              "command <subcommand> [<subcommand-options>]") {
1957b9c1b51eSKate Stone   LoadSubCommand("source",
1958b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsSource(interpreter)));
1959b9c1b51eSKate Stone   LoadSubCommand("alias",
1960b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsAlias(interpreter)));
1961b9c1b51eSKate Stone   LoadSubCommand("unalias", CommandObjectSP(
1962b9c1b51eSKate Stone                                 new CommandObjectCommandsUnalias(interpreter)));
1963b9c1b51eSKate Stone   LoadSubCommand("delete",
1964b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsDelete(interpreter)));
1965b9c1b51eSKate Stone   LoadSubCommand(
1966b9c1b51eSKate Stone       "regex", CommandObjectSP(new CommandObjectCommandsAddRegex(interpreter)));
1967b9c1b51eSKate Stone   LoadSubCommand("history", CommandObjectSP(
1968b9c1b51eSKate Stone                                 new CommandObjectCommandsHistory(interpreter)));
1969b9c1b51eSKate Stone   LoadSubCommand(
1970b9c1b51eSKate Stone       "script",
1971b9c1b51eSKate Stone       CommandObjectSP(new CommandObjectMultiwordCommandsScript(interpreter)));
1972ebc09c36SJim Ingham }
1973ebc09c36SJim Ingham 
19746e3d8e7fSEugene Zelenko CommandObjectMultiwordCommands::~CommandObjectMultiwordCommands() = default;
1975