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 
69*fe11483bSZachary Turner     Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
70b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
71a5a97ebeSJim Ingham       Error error;
723bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
73a5a97ebeSJim Ingham 
74b9c1b51eSKate Stone       switch (short_option) {
75a5a97ebeSJim Ingham       case 'c':
76*fe11483bSZachary Turner         error = m_count.SetValueFromString(option_arg, eVarSetOperationAssign);
77a5a97ebeSJim Ingham         break;
78a5a97ebeSJim Ingham       case 's':
79*fe11483bSZachary Turner         if (option_arg == "end") {
807594f14fSEnrico Granata           m_start_idx.SetCurrentValue(UINT64_MAX);
817594f14fSEnrico Granata           m_start_idx.SetOptionWasSet();
82b9c1b51eSKate Stone         } else
83*fe11483bSZachary Turner           error = m_start_idx.SetValueFromString(option_arg,
84b9c1b51eSKate Stone                                                  eVarSetOperationAssign);
857594f14fSEnrico Granata         break;
867594f14fSEnrico Granata       case 'e':
87*fe11483bSZachary Turner         error =
88*fe11483bSZachary Turner             m_stop_idx.SetValueFromString(option_arg, eVarSetOperationAssign);
897594f14fSEnrico Granata         break;
9063123b64SEnrico Granata       case 'C':
9163123b64SEnrico Granata         m_clear.SetCurrentValue(true);
9263123b64SEnrico Granata         m_clear.SetOptionWasSet();
93a5a97ebeSJim Ingham         break;
94a5a97ebeSJim Ingham       default:
95b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
96b9c1b51eSKate Stone                                        short_option);
97a5a97ebeSJim Ingham         break;
98a5a97ebeSJim Ingham       }
99a5a97ebeSJim Ingham 
100a5a97ebeSJim Ingham       return error;
101a5a97ebeSJim Ingham     }
102a5a97ebeSJim Ingham 
103b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1047594f14fSEnrico Granata       m_start_idx.Clear();
1057594f14fSEnrico Granata       m_stop_idx.Clear();
1067594f14fSEnrico Granata       m_count.Clear();
10763123b64SEnrico Granata       m_clear.Clear();
108a5a97ebeSJim Ingham     }
109a5a97ebeSJim Ingham 
1101f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
11170602439SZachary Turner       return llvm::makeArrayRef(g_history_options);
1121f0f5b5bSZachary Turner     }
113a5a97ebeSJim Ingham 
114a5a97ebeSJim Ingham     // Instance variables to hold the values for command options.
115a5a97ebeSJim Ingham 
1167594f14fSEnrico Granata     OptionValueUInt64 m_start_idx;
1177594f14fSEnrico Granata     OptionValueUInt64 m_stop_idx;
1187594f14fSEnrico Granata     OptionValueUInt64 m_count;
11963123b64SEnrico Granata     OptionValueBoolean m_clear;
120a5a97ebeSJim Ingham   };
121a5a97ebeSJim Ingham 
122b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
123b9c1b51eSKate Stone     if (m_options.m_clear.GetCurrentValue() &&
124b9c1b51eSKate Stone         m_options.m_clear.OptionWasSet()) {
1257594f14fSEnrico Granata       m_interpreter.GetCommandHistory().Clear();
1267594f14fSEnrico Granata       result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult);
127b9c1b51eSKate Stone     } else {
128b9c1b51eSKate Stone       if (m_options.m_start_idx.OptionWasSet() &&
129b9c1b51eSKate Stone           m_options.m_stop_idx.OptionWasSet() &&
130b9c1b51eSKate Stone           m_options.m_count.OptionWasSet()) {
131b9c1b51eSKate Stone         result.AppendError("--count, --start-index and --end-index cannot be "
132b9c1b51eSKate Stone                            "all specified in the same invocation");
1337594f14fSEnrico Granata         result.SetStatus(lldb::eReturnStatusFailed);
134b9c1b51eSKate Stone       } else {
135b9c1b51eSKate Stone         std::pair<bool, uint64_t> start_idx(
136b9c1b51eSKate Stone             m_options.m_start_idx.OptionWasSet(),
137b9c1b51eSKate Stone             m_options.m_start_idx.GetCurrentValue());
138b9c1b51eSKate Stone         std::pair<bool, uint64_t> stop_idx(
139b9c1b51eSKate Stone             m_options.m_stop_idx.OptionWasSet(),
140b9c1b51eSKate Stone             m_options.m_stop_idx.GetCurrentValue());
141b9c1b51eSKate Stone         std::pair<bool, uint64_t> count(m_options.m_count.OptionWasSet(),
142b9c1b51eSKate Stone                                         m_options.m_count.GetCurrentValue());
143a5a97ebeSJim Ingham 
1447594f14fSEnrico Granata         const CommandHistory &history(m_interpreter.GetCommandHistory());
1457594f14fSEnrico Granata 
146b9c1b51eSKate Stone         if (start_idx.first && start_idx.second == UINT64_MAX) {
147b9c1b51eSKate Stone           if (count.first) {
1487594f14fSEnrico Granata             start_idx.second = history.GetSize() - count.second;
1497594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
150b9c1b51eSKate Stone           } else if (stop_idx.first) {
1517594f14fSEnrico Granata             start_idx.second = stop_idx.second;
1527594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
153b9c1b51eSKate Stone           } else {
1547594f14fSEnrico Granata             start_idx.second = 0;
1557594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
1567594f14fSEnrico Granata           }
157b9c1b51eSKate Stone         } else {
158b9c1b51eSKate Stone           if (!start_idx.first && !stop_idx.first && !count.first) {
1597594f14fSEnrico Granata             start_idx.second = 0;
1607594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
161b9c1b51eSKate Stone           } else if (start_idx.first) {
162b9c1b51eSKate Stone             if (count.first) {
1637594f14fSEnrico Granata               stop_idx.second = start_idx.second + count.second - 1;
164b9c1b51eSKate Stone             } else if (!stop_idx.first) {
1657594f14fSEnrico Granata               stop_idx.second = history.GetSize() - 1;
1667594f14fSEnrico Granata             }
167b9c1b51eSKate Stone           } else if (stop_idx.first) {
168b9c1b51eSKate Stone             if (count.first) {
1697594f14fSEnrico Granata               if (stop_idx.second >= count.second)
1707594f14fSEnrico Granata                 start_idx.second = stop_idx.second - count.second + 1;
1717594f14fSEnrico Granata               else
1727594f14fSEnrico Granata                 start_idx.second = 0;
1737594f14fSEnrico Granata             }
174b9c1b51eSKate Stone           } else /* if (count.first) */
1757594f14fSEnrico Granata           {
1767594f14fSEnrico Granata             start_idx.second = 0;
1777594f14fSEnrico Granata             stop_idx.second = count.second - 1;
1787594f14fSEnrico Granata           }
1797594f14fSEnrico Granata         }
180b9c1b51eSKate Stone         history.Dump(result.GetOutputStream(), start_idx.second,
181b9c1b51eSKate Stone                      stop_idx.second);
1827594f14fSEnrico Granata       }
1837594f14fSEnrico Granata     }
184a5a97ebeSJim Ingham     return result.Succeeded();
185a5a97ebeSJim Ingham   }
1865a988416SJim Ingham 
1875a988416SJim Ingham   CommandOptions m_options;
188a5a97ebeSJim Ingham };
189a5a97ebeSJim Ingham 
190a5a97ebeSJim Ingham //-------------------------------------------------------------------------
191a5a97ebeSJim Ingham // CommandObjectCommandsSource
192a5a97ebeSJim Ingham //-------------------------------------------------------------------------
193a5a97ebeSJim Ingham 
1941f0f5b5bSZachary Turner static OptionDefinition g_source_options[] = {
1951f0f5b5bSZachary Turner     // clang-format off
1961f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "stop-on-error",    'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true, stop executing commands on error." },
1971f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "stop-on-continue", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true, stop executing commands on continue." },
1981f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "silent-run",       's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true don't echo commands while executing." },
1991f0f5b5bSZachary Turner     // clang-format on
2001f0f5b5bSZachary Turner };
2011f0f5b5bSZachary Turner 
202b9c1b51eSKate Stone class CommandObjectCommandsSource : public CommandObjectParsed {
2035a988416SJim Ingham public:
2047428a18cSKate Stone   CommandObjectCommandsSource(CommandInterpreter &interpreter)
205b9c1b51eSKate Stone       : CommandObjectParsed(
206b9c1b51eSKate Stone             interpreter, "command source",
207b9c1b51eSKate Stone             "Read and execute LLDB commands from the file <filename>.",
2086e3d8e7fSEugene Zelenko             nullptr),
209b9c1b51eSKate Stone         m_options() {
2105a988416SJim Ingham     CommandArgumentEntry arg;
2115a988416SJim Ingham     CommandArgumentData file_arg;
2125a988416SJim Ingham 
2135a988416SJim Ingham     // Define the first (and only) variant of this arg.
2145a988416SJim Ingham     file_arg.arg_type = eArgTypeFilename;
2155a988416SJim Ingham     file_arg.arg_repetition = eArgRepeatPlain;
2165a988416SJim Ingham 
217b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
218b9c1b51eSKate Stone     // argument entry.
2195a988416SJim Ingham     arg.push_back(file_arg);
2205a988416SJim Ingham 
2215a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
2225a988416SJim Ingham     m_arguments.push_back(arg);
2235a988416SJim Ingham   }
2245a988416SJim Ingham 
2256e3d8e7fSEugene Zelenko   ~CommandObjectCommandsSource() override = default;
2265a988416SJim Ingham 
227b9c1b51eSKate Stone   const char *GetRepeatCommand(Args &current_command_args,
228b9c1b51eSKate Stone                                uint32_t index) override {
2295a988416SJim Ingham     return "";
2305a988416SJim Ingham   }
2315a988416SJim Ingham 
232b9c1b51eSKate Stone   int HandleArgumentCompletion(Args &input, int &cursor_index,
2335a988416SJim Ingham                                int &cursor_char_position,
2345a988416SJim Ingham                                OptionElementVector &opt_element_vector,
235b9c1b51eSKate Stone                                int match_start_point, int max_return_elements,
2365a988416SJim Ingham                                bool &word_complete,
237b9c1b51eSKate Stone                                StringList &matches) override {
2385a988416SJim Ingham     std::string completion_str(input.GetArgumentAtIndex(cursor_index));
2395a988416SJim Ingham     completion_str.erase(cursor_char_position);
2405a988416SJim Ingham 
241b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
242b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
243b9c1b51eSKate Stone         completion_str.c_str(), match_start_point, max_return_elements, nullptr,
244b9c1b51eSKate Stone         word_complete, matches);
2455a988416SJim Ingham     return matches.GetSize();
2465a988416SJim Ingham   }
2475a988416SJim Ingham 
248b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
2495a988416SJim Ingham 
2505a988416SJim Ingham protected:
251b9c1b51eSKate Stone   class CommandOptions : public Options {
252e16c50a1SJim Ingham   public:
253b9c1b51eSKate Stone     CommandOptions()
254b9c1b51eSKate Stone         : Options(), m_stop_on_error(true), m_silent_run(false),
255b9c1b51eSKate Stone           m_stop_on_continue(true) {}
256e16c50a1SJim Ingham 
2576e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
258e16c50a1SJim Ingham 
259*fe11483bSZachary Turner     Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
260b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
261e16c50a1SJim Ingham       Error error;
2623bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
263e16c50a1SJim Ingham 
264b9c1b51eSKate Stone       switch (short_option) {
265e16c50a1SJim Ingham       case 'e':
266*fe11483bSZachary Turner         error = m_stop_on_error.SetValueFromString(option_arg);
267e16c50a1SJim Ingham         break;
268340b0309SGreg Clayton 
269e16c50a1SJim Ingham       case 'c':
270*fe11483bSZachary Turner         error = m_stop_on_continue.SetValueFromString(option_arg);
271e16c50a1SJim Ingham         break;
272340b0309SGreg Clayton 
27360986174SMichael Sartain       case 's':
274*fe11483bSZachary Turner         error = m_silent_run.SetValueFromString(option_arg);
27560986174SMichael Sartain         break;
276340b0309SGreg Clayton 
277e16c50a1SJim Ingham       default:
278b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
279b9c1b51eSKate Stone                                        short_option);
280e16c50a1SJim Ingham         break;
281e16c50a1SJim Ingham       }
282e16c50a1SJim Ingham 
283e16c50a1SJim Ingham       return error;
284e16c50a1SJim Ingham     }
285e16c50a1SJim Ingham 
286b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
287012d4fcaSEnrico Granata       m_stop_on_error.Clear();
288340b0309SGreg Clayton       m_silent_run.Clear();
289340b0309SGreg Clayton       m_stop_on_continue.Clear();
290e16c50a1SJim Ingham     }
291e16c50a1SJim Ingham 
2921f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
29370602439SZachary Turner       return llvm::makeArrayRef(g_source_options);
2941f0f5b5bSZachary Turner     }
295e16c50a1SJim Ingham 
296e16c50a1SJim Ingham     // Instance variables to hold the values for command options.
297e16c50a1SJim Ingham 
298012d4fcaSEnrico Granata     OptionValueBoolean m_stop_on_error;
299340b0309SGreg Clayton     OptionValueBoolean m_silent_run;
300340b0309SGreg Clayton     OptionValueBoolean m_stop_on_continue;
301e16c50a1SJim Ingham   };
302e16c50a1SJim Ingham 
303b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
30411eb9c64SZachary Turner     if (command.GetArgumentCount() == 1) {
30511eb9c64SZachary Turner       llvm::StringRef filename = command.GetArgumentAtIndex(0);
306ebc09c36SJim Ingham 
3071ee3853fSJohnny Chen       FileSpec cmd_file(filename, true);
3086e3d8e7fSEugene Zelenko       ExecutionContext *exe_ctx = nullptr; // Just use the default context.
309ebc09c36SJim Ingham 
310340b0309SGreg Clayton       // If any options were set, then use them
311340b0309SGreg Clayton       if (m_options.m_stop_on_error.OptionWasSet() ||
312340b0309SGreg Clayton           m_options.m_silent_run.OptionWasSet() ||
313b9c1b51eSKate Stone           m_options.m_stop_on_continue.OptionWasSet()) {
314340b0309SGreg Clayton         // Use user set settings
31526c7bf93SJim Ingham         CommandInterpreterRunOptions options;
316b9c1b51eSKate Stone         options.SetStopOnContinue(
317b9c1b51eSKate Stone             m_options.m_stop_on_continue.GetCurrentValue());
31826c7bf93SJim Ingham         options.SetStopOnError(m_options.m_stop_on_error.GetCurrentValue());
3197d8555c4SJim Ingham         options.SetEchoCommands(!m_options.m_silent_run.GetCurrentValue());
3207d8555c4SJim Ingham         options.SetPrintResults(!m_options.m_silent_run.GetCurrentValue());
32126c7bf93SJim Ingham 
322b9c1b51eSKate Stone         m_interpreter.HandleCommandsFromFile(cmd_file, exe_ctx, options,
323e16c50a1SJim Ingham                                              result);
324b9c1b51eSKate Stone       } else {
325b9c1b51eSKate Stone         // No options were set, inherit any settings from nested "command
326b9c1b51eSKate Stone         // source" commands,
327340b0309SGreg Clayton         // or set to sane default settings...
32826c7bf93SJim Ingham         CommandInterpreterRunOptions options;
329b9c1b51eSKate Stone         m_interpreter.HandleCommandsFromFile(cmd_file, exe_ctx, options,
330340b0309SGreg Clayton                                              result);
331340b0309SGreg Clayton       }
332b9c1b51eSKate Stone     } else {
333b9c1b51eSKate Stone       result.AppendErrorWithFormat(
334b9c1b51eSKate Stone           "'%s' takes exactly one executable filename argument.\n",
335a449698cSZachary Turner           GetCommandName().str().c_str());
336ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
337ebc09c36SJim Ingham     }
338ebc09c36SJim Ingham     return result.Succeeded();
339ebc09c36SJim Ingham   }
3406e3d8e7fSEugene Zelenko 
3415a988416SJim Ingham   CommandOptions m_options;
342ebc09c36SJim Ingham };
343ebc09c36SJim Ingham 
344ebc09c36SJim Ingham #pragma mark CommandObjectCommandsAlias
345ebc09c36SJim Ingham //-------------------------------------------------------------------------
346ebc09c36SJim Ingham // CommandObjectCommandsAlias
347ebc09c36SJim Ingham //-------------------------------------------------------------------------
348ebc09c36SJim Ingham 
3491f0f5b5bSZachary Turner static OptionDefinition g_alias_options[] = {
3501f0f5b5bSZachary Turner     // clang-format off
3511f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "help",      'h', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeHelpText, "Help text for this command" },
3521f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "long-help", 'H', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeHelpText, "Long help text for this command" },
3531f0f5b5bSZachary Turner     // clang-format on
3541f0f5b5bSZachary Turner };
3551f0f5b5bSZachary Turner 
356b9c1b51eSKate Stone static const char *g_python_command_instructions =
357b9c1b51eSKate Stone     "Enter your Python command(s). Type 'DONE' to end.\n"
358be93a35aSEnrico Granata     "You must define a Python function with this signature:\n"
35944d93782SGreg Clayton     "def my_command_impl(debugger, args, result, internal_dict):\n";
360be93a35aSEnrico Granata 
361b9c1b51eSKate Stone class CommandObjectCommandsAlias : public CommandObjectRaw {
36245d0e238SEnrico Granata protected:
363b9c1b51eSKate Stone   class CommandOptions : public OptionGroup {
364ebc09c36SJim Ingham   public:
365b9c1b51eSKate Stone     CommandOptions() : OptionGroup(), m_help(), m_long_help() {}
36645d0e238SEnrico Granata 
36745d0e238SEnrico Granata     ~CommandOptions() override = default;
36845d0e238SEnrico Granata 
3691f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
37070602439SZachary Turner       return llvm::makeArrayRef(g_alias_options);
3711f0f5b5bSZachary Turner     }
37245d0e238SEnrico Granata 
3738cef4b0bSZachary Turner     Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
374b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
37545d0e238SEnrico Granata       Error error;
37645d0e238SEnrico Granata 
3771f0f5b5bSZachary Turner       const int short_option = GetDefinitions()[option_idx].short_option;
3788cef4b0bSZachary Turner       std::string option_str(option_value);
37945d0e238SEnrico Granata 
380b9c1b51eSKate Stone       switch (short_option) {
38145d0e238SEnrico Granata       case 'h':
3828cef4b0bSZachary Turner         m_help.SetCurrentValue(option_str);
38345d0e238SEnrico Granata         m_help.SetOptionWasSet();
38445d0e238SEnrico Granata         break;
38545d0e238SEnrico Granata 
38645d0e238SEnrico Granata       case 'H':
3878cef4b0bSZachary Turner         m_long_help.SetCurrentValue(option_str);
38845d0e238SEnrico Granata         m_long_help.SetOptionWasSet();
38945d0e238SEnrico Granata         break;
39045d0e238SEnrico Granata 
39145d0e238SEnrico Granata       default:
392b9c1b51eSKate Stone         error.SetErrorStringWithFormat("invalid short option character '%c'",
393b9c1b51eSKate Stone                                        short_option);
39445d0e238SEnrico Granata         break;
39545d0e238SEnrico Granata       }
39645d0e238SEnrico Granata 
39745d0e238SEnrico Granata       return error;
39845d0e238SEnrico Granata     }
39945d0e238SEnrico Granata 
400b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
40145d0e238SEnrico Granata       m_help.Clear();
40245d0e238SEnrico Granata       m_long_help.Clear();
40345d0e238SEnrico Granata     }
40445d0e238SEnrico Granata 
40545d0e238SEnrico Granata     OptionValueString m_help;
40645d0e238SEnrico Granata     OptionValueString m_long_help;
40745d0e238SEnrico Granata   };
40845d0e238SEnrico Granata 
40945d0e238SEnrico Granata   OptionGroupOptions m_option_group;
41045d0e238SEnrico Granata   CommandOptions m_command_options;
41145d0e238SEnrico Granata 
41245d0e238SEnrico Granata public:
413b9c1b51eSKate Stone   Options *GetOptions() override { return &m_option_group; }
41445d0e238SEnrico Granata 
4157428a18cSKate Stone   CommandObjectCommandsAlias(CommandInterpreter &interpreter)
416b9c1b51eSKate Stone       : CommandObjectRaw(
417b9c1b51eSKate Stone             interpreter, "command alias",
418a449698cSZachary Turner             "Define a custom command in terms of an existing command."),
419b9c1b51eSKate Stone         m_option_group(), m_command_options() {
42045d0e238SEnrico Granata     m_option_group.Append(&m_command_options);
42145d0e238SEnrico Granata     m_option_group.Finalize();
42245d0e238SEnrico Granata 
423ebc09c36SJim Ingham     SetHelpLong(
424ea671fbdSKate Stone         "'alias' allows the user to create a short-cut or abbreviation for long \
425ea671fbdSKate Stone commands, multi-word commands, and commands that take particular options.  \
426b9c1b51eSKate Stone Below are some simple examples of how one might use the 'alias' command:"
427b9c1b51eSKate Stone         R"(
428ea671fbdSKate Stone 
429ea671fbdSKate Stone (lldb) command alias sc script
430ea671fbdSKate Stone 
431ea671fbdSKate Stone     Creates the abbreviation 'sc' for the 'script' command.
432ea671fbdSKate Stone 
433ea671fbdSKate Stone (lldb) command alias bp breakpoint
434ea671fbdSKate Stone 
435b9c1b51eSKate Stone )"
436b9c1b51eSKate Stone         "    Creates the abbreviation 'bp' for the 'breakpoint' command.  Since \
437ea671fbdSKate Stone breakpoint commands are two-word commands, the user would still need to \
438b9c1b51eSKate Stone enter the second word after 'bp', e.g. 'bp enable' or 'bp delete'."
439b9c1b51eSKate Stone         R"(
440ea671fbdSKate Stone 
441ea671fbdSKate Stone (lldb) command alias bpl breakpoint list
442ea671fbdSKate Stone 
443ea671fbdSKate Stone     Creates the abbreviation 'bpl' for the two-word command 'breakpoint list'.
444ea671fbdSKate Stone 
445b9c1b51eSKate Stone )"
446b9c1b51eSKate Stone         "An alias can include some options for the command, with the values either \
447ea671fbdSKate Stone filled in at the time the alias is created, or specified as positional \
448ea671fbdSKate Stone arguments, to be filled in when the alias is invoked.  The following example \
449b9c1b51eSKate Stone shows how to create aliases with options:"
450b9c1b51eSKate Stone         R"(
451ea671fbdSKate Stone 
452ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
453ea671fbdSKate Stone 
454b9c1b51eSKate Stone )"
455b9c1b51eSKate Stone         "    Creates the abbreviation 'bfl' (for break-file-line), with the -f and -l \
456ea671fbdSKate Stone options already part of the alias.  So if the user wants to set a breakpoint \
457ea671fbdSKate Stone by file and line without explicitly having to use the -f and -l options, the \
458ea671fbdSKate Stone user can now use 'bfl' instead.  The '%1' and '%2' are positional placeholders \
459ea671fbdSKate Stone for the actual arguments that will be passed when the alias command is used.  \
460ea671fbdSKate Stone The number in the placeholder refers to the position/order the actual value \
461ea671fbdSKate Stone occupies when the alias is used.  All the occurrences of '%1' in the alias \
462ea671fbdSKate Stone will be replaced with the first argument, all the occurrences of '%2' in the \
463ea671fbdSKate Stone alias will be replaced with the second argument, and so on.  This also allows \
464ea671fbdSKate Stone actual arguments to be used multiple times within an alias (see 'process \
465b9c1b51eSKate Stone launch' example below)."
466b9c1b51eSKate Stone         R"(
467ea671fbdSKate Stone 
468b9c1b51eSKate Stone )"
469b9c1b51eSKate Stone         "Note: the positional arguments must substitute as whole words in the resultant \
470ea671fbdSKate Stone command, so you can't at present do something like this to append the file extension \
471b9c1b51eSKate Stone \".cpp\":"
472b9c1b51eSKate Stone         R"(
473ea671fbdSKate Stone 
474ea671fbdSKate Stone (lldb) command alias bcppfl breakpoint set -f %1.cpp -l %2
475ea671fbdSKate Stone 
476b9c1b51eSKate Stone )"
477b9c1b51eSKate Stone         "For more complex aliasing, use the \"command regex\" command instead.  In the \
478ea671fbdSKate Stone 'bfl' case above, the actual file value will be filled in with the first argument \
479ea671fbdSKate Stone following 'bfl' and the actual line number value will be filled in with the second \
480b9c1b51eSKate Stone argument.  The user would use this alias as follows:"
481b9c1b51eSKate Stone         R"(
482ea671fbdSKate Stone 
483ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
484ea671fbdSKate Stone (lldb) bfl my-file.c 137
485ea671fbdSKate Stone 
486ea671fbdSKate Stone This would be the same as if the user had entered 'breakpoint set -f my-file.c -l 137'.
487ea671fbdSKate Stone 
488ea671fbdSKate Stone Another example:
489ea671fbdSKate Stone 
490ea671fbdSKate Stone (lldb) command alias pltty process launch -s -o %1 -e %1
491ea671fbdSKate Stone (lldb) pltty /dev/tty0
492ea671fbdSKate Stone 
493ea671fbdSKate Stone     Interpreted as 'process launch -s -o /dev/tty0 -e /dev/tty0'
494ea671fbdSKate Stone 
495b9c1b51eSKate Stone )"
496b9c1b51eSKate Stone         "If the user always wanted to pass the same value to a particular option, the \
497ea671fbdSKate Stone alias could be defined with that value directly in the alias as a constant, \
498b9c1b51eSKate Stone rather than using a positional placeholder:"
499b9c1b51eSKate Stone         R"(
500ea671fbdSKate Stone 
501ea671fbdSKate Stone (lldb) command alias bl3 breakpoint set -f %1 -l 3
502ea671fbdSKate Stone 
503b9c1b51eSKate Stone     Always sets a breakpoint on line 3 of whatever file is indicated.)");
504ebc09c36SJim Ingham 
505405fe67fSCaroline Tice     CommandArgumentEntry arg1;
506405fe67fSCaroline Tice     CommandArgumentEntry arg2;
507405fe67fSCaroline Tice     CommandArgumentEntry arg3;
508405fe67fSCaroline Tice     CommandArgumentData alias_arg;
509405fe67fSCaroline Tice     CommandArgumentData cmd_arg;
510405fe67fSCaroline Tice     CommandArgumentData options_arg;
511405fe67fSCaroline Tice 
512405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
513405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
514405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
515405fe67fSCaroline Tice 
516b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
517b9c1b51eSKate Stone     // argument entry.
518405fe67fSCaroline Tice     arg1.push_back(alias_arg);
519405fe67fSCaroline Tice 
520405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
521405fe67fSCaroline Tice     cmd_arg.arg_type = eArgTypeCommandName;
522405fe67fSCaroline Tice     cmd_arg.arg_repetition = eArgRepeatPlain;
523405fe67fSCaroline Tice 
524b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
525b9c1b51eSKate Stone     // argument entry.
526405fe67fSCaroline Tice     arg2.push_back(cmd_arg);
527405fe67fSCaroline Tice 
528405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
529405fe67fSCaroline Tice     options_arg.arg_type = eArgTypeAliasOptions;
530405fe67fSCaroline Tice     options_arg.arg_repetition = eArgRepeatOptional;
531405fe67fSCaroline Tice 
532b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
533b9c1b51eSKate Stone     // argument entry.
534405fe67fSCaroline Tice     arg3.push_back(options_arg);
535405fe67fSCaroline Tice 
536405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
537405fe67fSCaroline Tice     m_arguments.push_back(arg1);
538405fe67fSCaroline Tice     m_arguments.push_back(arg2);
539405fe67fSCaroline Tice     m_arguments.push_back(arg3);
540ebc09c36SJim Ingham   }
541ebc09c36SJim Ingham 
5426e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAlias() override = default;
543ebc09c36SJim Ingham 
5445a988416SJim Ingham protected:
545b9c1b51eSKate Stone   bool DoExecute(const char *raw_command_line,
546b9c1b51eSKate Stone                  CommandReturnObject &result) override {
547b9c1b51eSKate Stone     if (!raw_command_line || !raw_command_line[0]) {
548d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
54945d0e238SEnrico Granata       return false;
55045d0e238SEnrico Granata     }
55145d0e238SEnrico Granata 
552e1cfbc79STodd Fiala     ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext();
553e1cfbc79STodd Fiala     m_option_group.NotifyOptionParsingStarting(&exe_ctx);
55445d0e238SEnrico Granata 
55545d0e238SEnrico Granata     const char *remainder = nullptr;
55645d0e238SEnrico Granata 
557b9c1b51eSKate Stone     if (raw_command_line[0] == '-') {
55845d0e238SEnrico Granata       // We have some options and these options MUST end with --.
55945d0e238SEnrico Granata       const char *end_options = nullptr;
56045d0e238SEnrico Granata       const char *s = raw_command_line;
561b9c1b51eSKate Stone       while (s && s[0]) {
56245d0e238SEnrico Granata         end_options = ::strstr(s, "--");
563b9c1b51eSKate Stone         if (end_options) {
56445d0e238SEnrico Granata           end_options += 2; // Get past the "--"
565b9c1b51eSKate Stone           if (::isspace(end_options[0])) {
56645d0e238SEnrico Granata             remainder = end_options;
56745d0e238SEnrico Granata             while (::isspace(*remainder))
56845d0e238SEnrico Granata               ++remainder;
56945d0e238SEnrico Granata             break;
57045d0e238SEnrico Granata           }
57145d0e238SEnrico Granata         }
57245d0e238SEnrico Granata         s = end_options;
57345d0e238SEnrico Granata       }
57445d0e238SEnrico Granata 
575b9c1b51eSKate Stone       if (end_options) {
576b9c1b51eSKate Stone         Args args(
577b9c1b51eSKate Stone             llvm::StringRef(raw_command_line, end_options - raw_command_line));
57845d0e238SEnrico Granata         if (!ParseOptions(args, result))
57945d0e238SEnrico Granata           return false;
58045d0e238SEnrico Granata 
581e1cfbc79STodd Fiala         Error error(m_option_group.NotifyOptionParsingFinished(&exe_ctx));
582b9c1b51eSKate Stone         if (error.Fail()) {
58345d0e238SEnrico Granata           result.AppendError(error.AsCString());
58445d0e238SEnrico Granata           result.SetStatus(eReturnStatusFailed);
58545d0e238SEnrico Granata           return false;
58645d0e238SEnrico Granata         }
58745d0e238SEnrico Granata       }
58845d0e238SEnrico Granata     }
58945d0e238SEnrico Granata     if (nullptr == remainder)
59045d0e238SEnrico Granata       remainder = raw_command_line;
59145d0e238SEnrico Granata 
592a01bccdbSZachary Turner     llvm::StringRef raw_command_string(remainder);
593a01bccdbSZachary Turner     Args args(raw_command_string);
594844d2303SCaroline Tice 
59511eb9c64SZachary Turner     if (args.GetArgumentCount() < 2) {
596d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
597844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
598844d2303SCaroline Tice       return false;
599844d2303SCaroline Tice     }
600844d2303SCaroline Tice 
601844d2303SCaroline Tice     // Get the alias command.
602844d2303SCaroline Tice 
60311eb9c64SZachary Turner     // TODO: Convert this function to use StringRef.  Requires converting
60411eb9c64SZachary Turner     // GetCommandObjectForCommand.
605844d2303SCaroline Tice     const std::string alias_command = args.GetArgumentAtIndex(0);
606b9c1b51eSKate Stone     if (alias_command.size() > 1 && alias_command[0] == '-') {
607d72e412fSEnrico Granata       result.AppendError("aliases starting with a dash are not supported");
608b9c1b51eSKate Stone       if (alias_command == "--help" || alias_command == "--long-help") {
609b9c1b51eSKate Stone         result.AppendWarning("if trying to pass options to 'command alias' add "
610b9c1b51eSKate Stone                              "a -- at the end of the options");
611d72e412fSEnrico Granata       }
612d72e412fSEnrico Granata       result.SetStatus(eReturnStatusFailed);
613d72e412fSEnrico Granata       return false;
614d72e412fSEnrico Granata     }
615844d2303SCaroline Tice 
616b9c1b51eSKate Stone     // Strip the new alias name off 'raw_command_string'  (leave it on args,
617b9c1b51eSKate Stone     // which gets passed to 'Execute', which
618844d2303SCaroline Tice     // does the stripping itself.
619844d2303SCaroline Tice     size_t pos = raw_command_string.find(alias_command);
620b9c1b51eSKate Stone     if (pos == 0) {
621844d2303SCaroline Tice       raw_command_string = raw_command_string.substr(alias_command.size());
622844d2303SCaroline Tice       pos = raw_command_string.find_first_not_of(' ');
623844d2303SCaroline Tice       if ((pos != std::string::npos) && (pos > 0))
624844d2303SCaroline Tice         raw_command_string = raw_command_string.substr(pos);
625b9c1b51eSKate Stone     } else {
626844d2303SCaroline Tice       result.AppendError("Error parsing command string.  No alias created.");
627844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
628844d2303SCaroline Tice       return false;
629844d2303SCaroline Tice     }
630844d2303SCaroline Tice 
631844d2303SCaroline Tice     // Verify that the command is alias-able.
632771ef6d4SMalcolm Parsons     if (m_interpreter.CommandExists(alias_command)) {
633b9c1b51eSKate Stone       result.AppendErrorWithFormat(
634b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
635844d2303SCaroline Tice           alias_command.c_str());
636844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
637844d2303SCaroline Tice       return false;
638844d2303SCaroline Tice     }
639844d2303SCaroline Tice 
640b9c1b51eSKate Stone     // Get CommandObject that is being aliased. The command name is read from
641a01bccdbSZachary Turner     // the front of raw_command_string. raw_command_string is returned with the
642a01bccdbSZachary Turner     // name of the command object stripped off the front.
643a01bccdbSZachary Turner     llvm::StringRef original_raw_command_string = raw_command_string;
644b9c1b51eSKate Stone     CommandObject *cmd_obj =
645b9c1b51eSKate Stone         m_interpreter.GetCommandObjectForCommand(raw_command_string);
646844d2303SCaroline Tice 
647b9c1b51eSKate Stone     if (!cmd_obj) {
648b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid command given to 'command alias'. "
649b9c1b51eSKate Stone                                    "'%s' does not begin with a valid command."
650b9c1b51eSKate Stone                                    "  No alias created.",
651a01bccdbSZachary Turner                                    original_raw_command_string.str().c_str());
652844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
653844d2303SCaroline Tice       return false;
654b9c1b51eSKate Stone     } else if (!cmd_obj->WantsRawCommandString()) {
655b9c1b51eSKate Stone       // Note that args was initialized with the original command, and has not
656b9c1b51eSKate Stone       // been updated to this point.
657b9c1b51eSKate Stone       // Therefore can we pass it to the version of Execute that does not
658b9c1b51eSKate Stone       // need/expect raw input in the alias.
6595a988416SJim Ingham       return HandleAliasingNormalCommand(args, result);
660b9c1b51eSKate Stone     } else {
661b9c1b51eSKate Stone       return HandleAliasingRawCommand(alias_command, raw_command_string,
662b9c1b51eSKate Stone                                       *cmd_obj, result);
6635a988416SJim Ingham     }
6645a988416SJim Ingham     return result.Succeeded();
6655a988416SJim Ingham   }
6665a988416SJim Ingham 
667a01bccdbSZachary Turner   bool HandleAliasingRawCommand(llvm::StringRef alias_command,
668a01bccdbSZachary Turner                                 llvm::StringRef raw_command_string,
669b9c1b51eSKate Stone                                 CommandObject &cmd_obj,
670b9c1b51eSKate Stone                                 CommandReturnObject &result) {
671844d2303SCaroline Tice     // Verify & handle any options/arguments passed to the alias command
672844d2303SCaroline Tice 
673b9c1b51eSKate Stone     OptionArgVectorSP option_arg_vector_sp =
674b9c1b51eSKate Stone         OptionArgVectorSP(new OptionArgVector);
675844d2303SCaroline Tice 
676b9c1b51eSKate Stone     if (CommandObjectSP cmd_obj_sp =
677b9c1b51eSKate Stone             m_interpreter.GetCommandSPExact(cmd_obj.GetCommandName(), false)) {
678a01bccdbSZachary Turner       if (m_interpreter.AliasExists(alias_command) ||
679a01bccdbSZachary Turner           m_interpreter.UserCommandExists(alias_command)) {
680b9c1b51eSKate Stone         result.AppendWarningWithFormat(
681b9c1b51eSKate Stone             "Overwriting existing definition for '%s'.\n",
682a01bccdbSZachary Turner             alias_command.str().c_str());
683844d2303SCaroline Tice       }
684b9c1b51eSKate Stone       if (CommandAlias *alias = m_interpreter.AddAlias(
685a01bccdbSZachary Turner               alias_command, cmd_obj_sp, raw_command_string)) {
68645d0e238SEnrico Granata         if (m_command_options.m_help.OptionWasSet())
68745d0e238SEnrico Granata           alias->SetHelp(m_command_options.m_help.GetCurrentValue());
68845d0e238SEnrico Granata         if (m_command_options.m_long_help.OptionWasSet())
68945d0e238SEnrico Granata           alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
690844d2303SCaroline Tice         result.SetStatus(eReturnStatusSuccessFinishNoResult);
691b9c1b51eSKate Stone       } else {
692472362e6SCaroline Tice         result.AppendError("Unable to create requested alias.\n");
693472362e6SCaroline Tice         result.SetStatus(eReturnStatusFailed);
694472362e6SCaroline Tice       }
695212130acSEnrico Granata 
696b9c1b51eSKate Stone     } else {
697212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
698212130acSEnrico Granata       result.SetStatus(eReturnStatusFailed);
699212130acSEnrico Granata     }
700212130acSEnrico Granata 
701844d2303SCaroline Tice     return result.Succeeded();
702844d2303SCaroline Tice   }
703ebc09c36SJim Ingham 
704b9c1b51eSKate Stone   bool HandleAliasingNormalCommand(Args &args, CommandReturnObject &result) {
705867b185dSCaroline Tice     size_t argc = args.GetArgumentCount();
706ebc09c36SJim Ingham 
707b9c1b51eSKate Stone     if (argc < 2) {
708d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
709ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
710ebc09c36SJim Ingham       return false;
711ebc09c36SJim Ingham     }
712ebc09c36SJim Ingham 
71311eb9c64SZachary Turner     // TODO: Convert these to StringRefs.  Should convert other dependent
71411eb9c64SZachary Turner     // functions (CommandExists, UserCommandExists, AliasExists, AddAlias,
71511eb9c64SZachary Turner     // etc at the same time.
716ebc09c36SJim Ingham     const std::string alias_command = args.GetArgumentAtIndex(0);
717ebc09c36SJim Ingham     const std::string actual_command = args.GetArgumentAtIndex(1);
718ebc09c36SJim Ingham 
719ebc09c36SJim Ingham     args.Shift(); // Shift the alias command word off the argument vector.
720ebc09c36SJim Ingham     args.Shift(); // Shift the old command word off the argument vector.
721ebc09c36SJim Ingham 
722b9c1b51eSKate Stone     // Verify that the command is alias'able, and get the appropriate command
723b9c1b51eSKate Stone     // object.
724ebc09c36SJim Ingham 
725771ef6d4SMalcolm Parsons     if (m_interpreter.CommandExists(alias_command)) {
726b9c1b51eSKate Stone       result.AppendErrorWithFormat(
727b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
728ebc09c36SJim Ingham           alias_command.c_str());
729ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
730b9c1b51eSKate Stone     } else {
731b9c1b51eSKate Stone       CommandObjectSP command_obj_sp(
732a449698cSZachary Turner           m_interpreter.GetCommandSPExact(actual_command, true));
733ebc09c36SJim Ingham       CommandObjectSP subcommand_obj_sp;
734ebc09c36SJim Ingham       bool use_subcommand = false;
735b9c1b51eSKate Stone       if (command_obj_sp) {
736ebc09c36SJim Ingham         CommandObject *cmd_obj = command_obj_sp.get();
7376e3d8e7fSEugene Zelenko         CommandObject *sub_cmd_obj = nullptr;
738b9c1b51eSKate Stone         OptionArgVectorSP option_arg_vector_sp =
739b9c1b51eSKate Stone             OptionArgVectorSP(new OptionArgVector);
740ebc09c36SJim Ingham 
74111eb9c64SZachary Turner         while (cmd_obj->IsMultiwordObject() && !args.empty()) {
742b9c1b51eSKate Stone           if (argc >= 3) {
743a449698cSZachary Turner             const std::string sub_command = args.GetArgumentAtIndex(0);
74411eb9c64SZachary Turner             assert(!sub_command.empty());
74511eb9c64SZachary Turner             subcommand_obj_sp = cmd_obj->GetSubcommandSP(sub_command.data());
746b9c1b51eSKate Stone             if (subcommand_obj_sp) {
747ebc09c36SJim Ingham               sub_cmd_obj = subcommand_obj_sp.get();
748ebc09c36SJim Ingham               use_subcommand = true;
749b9c1b51eSKate Stone               args.Shift(); // Shift the sub_command word off the argument
750b9c1b51eSKate Stone                             // vector.
751844d2303SCaroline Tice               cmd_obj = sub_cmd_obj;
752b9c1b51eSKate Stone             } else {
753b9c1b51eSKate Stone               result.AppendErrorWithFormat(
754b9c1b51eSKate Stone                   "'%s' is not a valid sub-command of '%s'.  "
755f415eeb4SCaroline Tice                   "Unable to create alias.\n",
756a449698cSZachary Turner                   sub_command.c_str(), actual_command.c_str());
757ebc09c36SJim Ingham               result.SetStatus(eReturnStatusFailed);
758ebc09c36SJim Ingham               return false;
759ebc09c36SJim Ingham             }
760ebc09c36SJim Ingham           }
761ebc09c36SJim Ingham         }
762ebc09c36SJim Ingham 
763ebc09c36SJim Ingham         // Verify & handle any options/arguments passed to the alias command
764ebc09c36SJim Ingham 
765212130acSEnrico Granata         std::string args_string;
766212130acSEnrico Granata 
76711eb9c64SZachary Turner         if (!args.empty()) {
768b9c1b51eSKate Stone           CommandObjectSP tmp_sp =
769b9c1b51eSKate Stone               m_interpreter.GetCommandSPExact(cmd_obj->GetCommandName(), false);
770ebc09c36SJim Ingham           if (use_subcommand)
771b9c1b51eSKate Stone             tmp_sp = m_interpreter.GetCommandSPExact(
772b9c1b51eSKate Stone                 sub_cmd_obj->GetCommandName(), false);
773ca90c47eSCaroline Tice 
774ca90c47eSCaroline Tice           args.GetCommandString(args_string);
775867b185dSCaroline Tice         }
776ebc09c36SJim Ingham 
777771ef6d4SMalcolm Parsons         if (m_interpreter.AliasExists(alias_command) ||
778771ef6d4SMalcolm Parsons             m_interpreter.UserCommandExists(alias_command)) {
779b9c1b51eSKate Stone           result.AppendWarningWithFormat(
780b9c1b51eSKate Stone               "Overwriting existing definition for '%s'.\n",
781ebc09c36SJim Ingham               alias_command.c_str());
782ebc09c36SJim Ingham         }
783ebc09c36SJim Ingham 
784b9c1b51eSKate Stone         if (CommandAlias *alias = m_interpreter.AddAlias(
785771ef6d4SMalcolm Parsons                 alias_command,
786212130acSEnrico Granata                 use_subcommand ? subcommand_obj_sp : command_obj_sp,
787771ef6d4SMalcolm Parsons                 args_string)) {
78845d0e238SEnrico Granata           if (m_command_options.m_help.OptionWasSet())
78945d0e238SEnrico Granata             alias->SetHelp(m_command_options.m_help.GetCurrentValue());
79045d0e238SEnrico Granata           if (m_command_options.m_long_help.OptionWasSet())
79145d0e238SEnrico Granata             alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
792ebc09c36SJim Ingham           result.SetStatus(eReturnStatusSuccessFinishNoResult);
793b9c1b51eSKate Stone         } else {
794212130acSEnrico Granata           result.AppendError("Unable to create requested alias.\n");
795212130acSEnrico Granata           result.SetStatus(eReturnStatusFailed);
796212130acSEnrico Granata           return false;
797212130acSEnrico Granata         }
798b9c1b51eSKate Stone       } else {
799b9c1b51eSKate Stone         result.AppendErrorWithFormat("'%s' is not an existing command.\n",
800b9c1b51eSKate Stone                                      actual_command.c_str());
801ebc09c36SJim Ingham         result.SetStatus(eReturnStatusFailed);
802e7941795SCaroline Tice         return false;
803ebc09c36SJim Ingham       }
804ebc09c36SJim Ingham     }
805ebc09c36SJim Ingham 
806ebc09c36SJim Ingham     return result.Succeeded();
807ebc09c36SJim Ingham   }
808ebc09c36SJim Ingham };
809ebc09c36SJim Ingham 
810ebc09c36SJim Ingham #pragma mark CommandObjectCommandsUnalias
811ebc09c36SJim Ingham //-------------------------------------------------------------------------
812ebc09c36SJim Ingham // CommandObjectCommandsUnalias
813ebc09c36SJim Ingham //-------------------------------------------------------------------------
814ebc09c36SJim Ingham 
815b9c1b51eSKate Stone class CommandObjectCommandsUnalias : public CommandObjectParsed {
816ebc09c36SJim Ingham public:
8177428a18cSKate Stone   CommandObjectCommandsUnalias(CommandInterpreter &interpreter)
818b9c1b51eSKate Stone       : CommandObjectParsed(
819b9c1b51eSKate Stone             interpreter, "command unalias",
820b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command alias'.",
821b9c1b51eSKate Stone             nullptr) {
822405fe67fSCaroline Tice     CommandArgumentEntry arg;
823405fe67fSCaroline Tice     CommandArgumentData alias_arg;
824405fe67fSCaroline Tice 
825405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
826405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
827405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
828405fe67fSCaroline Tice 
829b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
830b9c1b51eSKate Stone     // argument entry.
831405fe67fSCaroline Tice     arg.push_back(alias_arg);
832405fe67fSCaroline Tice 
833405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
834405fe67fSCaroline Tice     m_arguments.push_back(arg);
835ebc09c36SJim Ingham   }
836ebc09c36SJim Ingham 
8376e3d8e7fSEugene Zelenko   ~CommandObjectCommandsUnalias() override = default;
838ebc09c36SJim Ingham 
8395a988416SJim Ingham protected:
840b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
841ebc09c36SJim Ingham     CommandObject::CommandMap::iterator pos;
842ebc09c36SJim Ingham     CommandObject *cmd_obj;
843ebc09c36SJim Ingham 
84411eb9c64SZachary Turner     if (args.empty()) {
84511eb9c64SZachary Turner       result.AppendError("must call 'unalias' with a valid alias");
84611eb9c64SZachary Turner       result.SetStatus(eReturnStatusFailed);
84711eb9c64SZachary Turner       return false;
84811eb9c64SZachary Turner     }
84911eb9c64SZachary Turner 
85011eb9c64SZachary Turner     // TODO: Convert this function to return a StringRef.  Should also convert
85111eb9c64SZachary Turner     // dependent functions GetCommandObject, CommandExists, RemoveAlias,
85211eb9c64SZachary Turner     // AliasExists, etc.
853ebc09c36SJim Ingham     const char *command_name = args.GetArgumentAtIndex(0);
854a7015092SGreg Clayton     cmd_obj = m_interpreter.GetCommandObject(command_name);
855b9c1b51eSKate Stone     if (cmd_obj) {
856b9c1b51eSKate Stone       if (m_interpreter.CommandExists(command_name)) {
857b9c1b51eSKate Stone         if (cmd_obj->IsRemovable()) {
858b9c1b51eSKate Stone           result.AppendErrorWithFormat(
859b9c1b51eSKate Stone               "'%s' is not an alias, it is a debugger command which can be "
860b9c1b51eSKate Stone               "removed using the 'command delete' command.\n",
861b547278cSGreg Clayton               command_name);
862b9c1b51eSKate Stone         } else {
863b9c1b51eSKate Stone           result.AppendErrorWithFormat(
864b9c1b51eSKate Stone               "'%s' is a permanent debugger command and cannot be removed.\n",
865ebc09c36SJim Ingham               command_name);
866b547278cSGreg Clayton         }
867ebc09c36SJim Ingham         result.SetStatus(eReturnStatusFailed);
868b9c1b51eSKate Stone       } else {
869b9c1b51eSKate Stone         if (!m_interpreter.RemoveAlias(command_name)) {
870a7015092SGreg Clayton           if (m_interpreter.AliasExists(command_name))
871b9c1b51eSKate Stone             result.AppendErrorWithFormat(
872b9c1b51eSKate Stone                 "Error occurred while attempting to unalias '%s'.\n",
873ebc09c36SJim Ingham                 command_name);
874ebc09c36SJim Ingham           else
875b9c1b51eSKate Stone             result.AppendErrorWithFormat("'%s' is not an existing alias.\n",
876b9c1b51eSKate Stone                                          command_name);
877ebc09c36SJim Ingham           result.SetStatus(eReturnStatusFailed);
878b9c1b51eSKate Stone         } else
879ebc09c36SJim Ingham           result.SetStatus(eReturnStatusSuccessFinishNoResult);
880ebc09c36SJim Ingham       }
881b9c1b51eSKate Stone     } else {
882b9c1b51eSKate Stone       result.AppendErrorWithFormat(
883b9c1b51eSKate Stone           "'%s' is not a known command.\nTry 'help' to see a "
884ebc09c36SJim Ingham           "current list of commands.\n",
885ebc09c36SJim Ingham           command_name);
886ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
887ebc09c36SJim Ingham     }
888ebc09c36SJim Ingham 
889ebc09c36SJim Ingham     return result.Succeeded();
890ebc09c36SJim Ingham   }
891ebc09c36SJim Ingham };
892ebc09c36SJim Ingham 
893b547278cSGreg Clayton #pragma mark CommandObjectCommandsDelete
894b547278cSGreg Clayton //-------------------------------------------------------------------------
895b547278cSGreg Clayton // CommandObjectCommandsDelete
896b547278cSGreg Clayton //-------------------------------------------------------------------------
897b547278cSGreg Clayton 
898b9c1b51eSKate Stone class CommandObjectCommandsDelete : public CommandObjectParsed {
899b547278cSGreg Clayton public:
9007428a18cSKate Stone   CommandObjectCommandsDelete(CommandInterpreter &interpreter)
901b9c1b51eSKate Stone       : CommandObjectParsed(
902b9c1b51eSKate Stone             interpreter, "command delete",
903b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command regex'.",
904b9c1b51eSKate Stone             nullptr) {
905b547278cSGreg Clayton     CommandArgumentEntry arg;
906b547278cSGreg Clayton     CommandArgumentData alias_arg;
907b547278cSGreg Clayton 
908b547278cSGreg Clayton     // Define the first (and only) variant of this arg.
909b547278cSGreg Clayton     alias_arg.arg_type = eArgTypeCommandName;
910b547278cSGreg Clayton     alias_arg.arg_repetition = eArgRepeatPlain;
911b547278cSGreg Clayton 
912b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
913b9c1b51eSKate Stone     // argument entry.
914b547278cSGreg Clayton     arg.push_back(alias_arg);
915b547278cSGreg Clayton 
916b547278cSGreg Clayton     // Push the data for the first argument into the m_arguments vector.
917b547278cSGreg Clayton     m_arguments.push_back(arg);
918b547278cSGreg Clayton   }
919b547278cSGreg Clayton 
9206e3d8e7fSEugene Zelenko   ~CommandObjectCommandsDelete() override = default;
921b547278cSGreg Clayton 
922b547278cSGreg Clayton protected:
923b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
924b547278cSGreg Clayton     CommandObject::CommandMap::iterator pos;
925b547278cSGreg Clayton 
92611eb9c64SZachary Turner     if (args.empty()) {
92711eb9c64SZachary Turner       result.AppendErrorWithFormat("must call '%s' with one or more valid user "
92811eb9c64SZachary Turner                                    "defined regular expression command names",
929a449698cSZachary Turner                                    GetCommandName().str().c_str());
93011eb9c64SZachary Turner       result.SetStatus(eReturnStatusFailed);
93111eb9c64SZachary Turner     }
93211eb9c64SZachary Turner 
93311eb9c64SZachary Turner     // TODO: Convert this to accept a stringRef.
934b547278cSGreg Clayton     const char *command_name = args.GetArgumentAtIndex(0);
935b9c1b51eSKate Stone     if (m_interpreter.CommandExists(command_name)) {
936b9c1b51eSKate Stone       if (m_interpreter.RemoveCommand(command_name)) {
937b547278cSGreg Clayton         result.SetStatus(eReturnStatusSuccessFinishNoResult);
938b9c1b51eSKate Stone       } else {
939b9c1b51eSKate Stone         result.AppendErrorWithFormat(
940b9c1b51eSKate Stone             "'%s' is a permanent debugger command and cannot be removed.\n",
941b547278cSGreg Clayton             command_name);
942b547278cSGreg Clayton         result.SetStatus(eReturnStatusFailed);
943b547278cSGreg Clayton       }
944b9c1b51eSKate Stone     } else {
94546d4aa21SEnrico Granata       StreamString error_msg_stream;
94646d4aa21SEnrico Granata       const bool generate_apropos = true;
94746d4aa21SEnrico Granata       const bool generate_type_lookup = false;
948b9c1b51eSKate Stone       CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage(
949b9c1b51eSKate Stone           &error_msg_stream, command_name, nullptr, nullptr, generate_apropos,
95046d4aa21SEnrico Granata           generate_type_lookup);
95146d4aa21SEnrico Granata       result.AppendErrorWithFormat("%s", error_msg_stream.GetData());
952b547278cSGreg Clayton       result.SetStatus(eReturnStatusFailed);
953b547278cSGreg Clayton     }
954b547278cSGreg Clayton 
955b547278cSGreg Clayton     return result.Succeeded();
956b547278cSGreg Clayton   }
957b547278cSGreg Clayton };
958b547278cSGreg Clayton 
959de164aaaSGreg Clayton //-------------------------------------------------------------------------
960de164aaaSGreg Clayton // CommandObjectCommandsAddRegex
961de164aaaSGreg Clayton //-------------------------------------------------------------------------
9621f0f5b5bSZachary Turner 
9631f0f5b5bSZachary Turner static OptionDefinition g_regex_options[] = {
9641f0f5b5bSZachary Turner     // clang-format off
9651f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "help"  , 'h', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone, "The help text to display for this command." },
9661f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "syntax", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone, "A syntax string showing the typical usage syntax." },
9671f0f5b5bSZachary Turner     // clang-format on
9681f0f5b5bSZachary Turner };
9691f0f5b5bSZachary Turner 
9705a988416SJim Ingham #pragma mark CommandObjectCommandsAddRegex
971de164aaaSGreg Clayton 
972b9c1b51eSKate Stone class CommandObjectCommandsAddRegex : public CommandObjectParsed,
973b9c1b51eSKate Stone                                       public IOHandlerDelegateMultiline {
974de164aaaSGreg Clayton public:
9757428a18cSKate Stone   CommandObjectCommandsAddRegex(CommandInterpreter &interpreter)
976b9c1b51eSKate Stone       : CommandObjectParsed(
977b9c1b51eSKate Stone             interpreter, "command regex", "Define a custom command in terms of "
978b9c1b51eSKate Stone                                           "existing commands by matching "
979b9c1b51eSKate Stone                                           "regular expressions.",
9800e5e5a79SGreg Clayton             "command regex <cmd-name> [s/<regex>/<subst>/ ...]"),
981b9c1b51eSKate Stone         IOHandlerDelegateMultiline("",
982b9c1b51eSKate Stone                                    IOHandlerDelegate::Completion::LLDBCommand),
983b9c1b51eSKate Stone         m_options() {
984b9c1b51eSKate Stone     SetHelpLong(
985b9c1b51eSKate Stone         R"(
986b9c1b51eSKate Stone )"
987b9c1b51eSKate Stone         "This command allows the user to create powerful regular expression commands \
988ea671fbdSKate Stone with substitutions. The regular expressions and substitutions are specified \
989b9c1b51eSKate Stone using the regular expression substitution format of:"
990b9c1b51eSKate Stone         R"(
991ea671fbdSKate Stone 
992ea671fbdSKate Stone     s/<regex>/<subst>/
993ea671fbdSKate Stone 
994b9c1b51eSKate Stone )"
995b9c1b51eSKate Stone         "<regex> is a regular expression that can use parenthesis to capture regular \
996ea671fbdSKate Stone expression input and substitute the captured matches in the output using %1 \
997b9c1b51eSKate Stone for the first match, %2 for the second, and so on."
998b9c1b51eSKate Stone         R"(
999ea671fbdSKate Stone 
1000b9c1b51eSKate Stone )"
1001b9c1b51eSKate Stone         "The regular expressions can all be specified on the command line if more than \
1002ea671fbdSKate Stone one argument is provided. If just the command name is provided on the command \
1003ea671fbdSKate Stone line, then the regular expressions and substitutions can be entered on separate \
1004b9c1b51eSKate Stone lines, followed by an empty line to terminate the command definition."
1005b9c1b51eSKate Stone         R"(
1006ea671fbdSKate Stone 
1007ea671fbdSKate Stone EXAMPLES
1008ea671fbdSKate Stone 
1009b9c1b51eSKate Stone )"
1010b9c1b51eSKate Stone         "The following example will define a regular expression command named 'f' that \
1011ea671fbdSKate Stone will call 'finish' if there are no arguments, or 'frame select <frame-idx>' if \
1012b9c1b51eSKate Stone a number follows 'f':"
1013b9c1b51eSKate Stone         R"(
1014ea671fbdSKate Stone 
1015b9c1b51eSKate Stone     (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')");
1016de164aaaSGreg Clayton   }
1017de164aaaSGreg Clayton 
10186e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAddRegex() override = default;
1019de164aaaSGreg Clayton 
10205a988416SJim Ingham protected:
1021b9c1b51eSKate Stone   void IOHandlerActivated(IOHandler &io_handler) override {
102244d93782SGreg Clayton     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
1023b9c1b51eSKate Stone     if (output_sp) {
1024b9c1b51eSKate Stone       output_sp->PutCString("Enter one of more sed substitution commands in "
1025b9c1b51eSKate Stone                             "the form: 's/<regex>/<subst>/'.\nTerminate the "
1026b9c1b51eSKate Stone                             "substitution list with an empty line.\n");
102744d93782SGreg Clayton       output_sp->Flush();
102844d93782SGreg Clayton     }
102944d93782SGreg Clayton   }
103044d93782SGreg Clayton 
1031b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
1032b9c1b51eSKate Stone                               std::string &data) override {
103344d93782SGreg Clayton     io_handler.SetIsDone(true);
1034b9c1b51eSKate Stone     if (m_regex_cmd_ap) {
103544d93782SGreg Clayton       StringList lines;
1036b9c1b51eSKate Stone       if (lines.SplitIntoLines(data)) {
103744d93782SGreg Clayton         const size_t num_lines = lines.GetSize();
103844d93782SGreg Clayton         bool check_only = false;
1039b9c1b51eSKate Stone         for (size_t i = 0; i < num_lines; ++i) {
104044d93782SGreg Clayton           llvm::StringRef bytes_strref(lines[i]);
104144d93782SGreg Clayton           Error error = AppendRegexSubstitution(bytes_strref, check_only);
1042b9c1b51eSKate Stone           if (error.Fail()) {
1043b9c1b51eSKate Stone             if (!m_interpreter.GetDebugger()
1044b9c1b51eSKate Stone                      .GetCommandInterpreter()
1045b9c1b51eSKate Stone                      .GetBatchCommandMode()) {
1046b9c1b51eSKate Stone               StreamSP out_stream =
1047b9c1b51eSKate Stone                   m_interpreter.GetDebugger().GetAsyncOutputStream();
104844d93782SGreg Clayton               out_stream->Printf("error: %s\n", error.AsCString());
104944d93782SGreg Clayton             }
105044d93782SGreg Clayton           }
105144d93782SGreg Clayton         }
105244d93782SGreg Clayton       }
1053b9c1b51eSKate Stone       if (m_regex_cmd_ap->HasRegexEntries()) {
105444d93782SGreg Clayton         CommandObjectSP cmd_sp(m_regex_cmd_ap.release());
105544d93782SGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
105644d93782SGreg Clayton       }
105744d93782SGreg Clayton     }
105844d93782SGreg Clayton   }
105944d93782SGreg Clayton 
1060b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
10615a988416SJim Ingham     const size_t argc = command.GetArgumentCount();
1062b9c1b51eSKate Stone     if (argc == 0) {
1063b9c1b51eSKate Stone       result.AppendError("usage: 'command regex <command-name> "
1064b9c1b51eSKate Stone                          "[s/<regex1>/<subst1>/ s/<regex2>/<subst2>/ ...]'\n");
10650e5e5a79SGreg Clayton       result.SetStatus(eReturnStatusFailed);
106611eb9c64SZachary Turner       return false;
106711eb9c64SZachary Turner     }
106811eb9c64SZachary Turner 
10690e5e5a79SGreg Clayton     Error error;
10705a988416SJim Ingham     const char *name = command.GetArgumentAtIndex(0);
107111eb9c64SZachary Turner     m_regex_cmd_ap.reset(
107211eb9c64SZachary Turner         new CommandObjectRegexCommand(m_interpreter, name, m_options.GetHelp(),
107311eb9c64SZachary Turner                                       m_options.GetSyntax(), 10, 0, true));
10740e5e5a79SGreg Clayton 
1075b9c1b51eSKate Stone     if (argc == 1) {
107644d93782SGreg Clayton       Debugger &debugger = m_interpreter.GetDebugger();
1077e30f11d9SKate Stone       bool color_prompt = debugger.GetUseColor();
107844d93782SGreg Clayton       const bool multiple_lines = true; // Get multiple lines
1079b9c1b51eSKate Stone       IOHandlerSP io_handler_sp(new IOHandlerEditline(
1080b9c1b51eSKate Stone           debugger, IOHandler::Type::Other,
108173d80faaSGreg Clayton           "lldb-regex",          // Name of input reader for history
1082514d8cd8SZachary Turner           llvm::StringRef("> "), // Prompt
1083514d8cd8SZachary Turner           llvm::StringRef(),     // Continuation prompt
1084b9c1b51eSKate Stone           multiple_lines, color_prompt,
1085f6913cd7SGreg Clayton           0, // Don't show line numbers
108644d93782SGreg Clayton           *this));
108744d93782SGreg Clayton 
1088b9c1b51eSKate Stone       if (io_handler_sp) {
108944d93782SGreg Clayton         debugger.PushIOHandler(io_handler_sp);
1090de164aaaSGreg Clayton         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1091de164aaaSGreg Clayton       }
1092b9c1b51eSKate Stone     } else {
109397d2c401SZachary Turner       for (auto &entry : command.entries().drop_front()) {
109444d93782SGreg Clayton         bool check_only = false;
109597d2c401SZachary Turner         error = AppendRegexSubstitution(entry.ref, check_only);
10960e5e5a79SGreg Clayton         if (error.Fail())
10970e5e5a79SGreg Clayton           break;
10980e5e5a79SGreg Clayton       }
10990e5e5a79SGreg Clayton 
1100b9c1b51eSKate Stone       if (error.Success()) {
11010e5e5a79SGreg Clayton         AddRegexCommandToInterpreter();
11020e5e5a79SGreg Clayton       }
11030e5e5a79SGreg Clayton     }
1104b9c1b51eSKate Stone     if (error.Fail()) {
11050e5e5a79SGreg Clayton       result.AppendError(error.AsCString());
1106de164aaaSGreg Clayton       result.SetStatus(eReturnStatusFailed);
1107de164aaaSGreg Clayton     }
11080e5e5a79SGreg Clayton 
1109de164aaaSGreg Clayton     return result.Succeeded();
1110de164aaaSGreg Clayton   }
1111de164aaaSGreg Clayton 
1112b9c1b51eSKate Stone   Error AppendRegexSubstitution(const llvm::StringRef &regex_sed,
1113b9c1b51eSKate Stone                                 bool check_only) {
11140e5e5a79SGreg Clayton     Error error;
11150e5e5a79SGreg Clayton 
1116b9c1b51eSKate Stone     if (!m_regex_cmd_ap) {
1117b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1118b9c1b51eSKate Stone           "invalid regular expression command object for: '%.*s'",
1119b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11200e5e5a79SGreg Clayton       return error;
1121de164aaaSGreg Clayton     }
11220e5e5a79SGreg Clayton 
11230e5e5a79SGreg Clayton     size_t regex_sed_size = regex_sed.size();
11240e5e5a79SGreg Clayton 
1125b9c1b51eSKate Stone     if (regex_sed_size <= 1) {
1126b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1127b9c1b51eSKate Stone           "regular expression substitution string is too short: '%.*s'",
1128b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11290e5e5a79SGreg Clayton       return error;
11300e5e5a79SGreg Clayton     }
11310e5e5a79SGreg Clayton 
1132b9c1b51eSKate Stone     if (regex_sed[0] != 's') {
1133b9c1b51eSKate Stone       error.SetErrorStringWithFormat("regular expression substitution string "
1134b9c1b51eSKate Stone                                      "doesn't start with 's': '%.*s'",
1135b9c1b51eSKate Stone                                      (int)regex_sed.size(), regex_sed.data());
11360e5e5a79SGreg Clayton       return error;
11370e5e5a79SGreg Clayton     }
11380e5e5a79SGreg Clayton     const size_t first_separator_char_pos = 1;
11390e5e5a79SGreg Clayton     // use the char that follows 's' as the regex separator character
11400e5e5a79SGreg Clayton     // so we can have "s/<regex>/<subst>/" or "s|<regex>|<subst>|"
11410e5e5a79SGreg Clayton     const char separator_char = regex_sed[first_separator_char_pos];
1142b9c1b51eSKate Stone     const size_t second_separator_char_pos =
1143b9c1b51eSKate Stone         regex_sed.find(separator_char, first_separator_char_pos + 1);
11440e5e5a79SGreg Clayton 
1145b9c1b51eSKate Stone     if (second_separator_char_pos == std::string::npos) {
1146b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1147b9c1b51eSKate Stone           "missing second '%c' separator char after '%.*s' in '%.*s'",
11480e5e5a79SGreg Clayton           separator_char,
11490e5e5a79SGreg Clayton           (int)(regex_sed.size() - first_separator_char_pos - 1),
1150ea508635SGreg Clayton           regex_sed.data() + (first_separator_char_pos + 1),
1151b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11520e5e5a79SGreg Clayton       return error;
11530e5e5a79SGreg Clayton     }
11540e5e5a79SGreg Clayton 
1155b9c1b51eSKate Stone     const size_t third_separator_char_pos =
1156b9c1b51eSKate Stone         regex_sed.find(separator_char, second_separator_char_pos + 1);
11570e5e5a79SGreg Clayton 
1158b9c1b51eSKate Stone     if (third_separator_char_pos == std::string::npos) {
1159b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1160b9c1b51eSKate Stone           "missing third '%c' separator char after '%.*s' in '%.*s'",
11610e5e5a79SGreg Clayton           separator_char,
11620e5e5a79SGreg Clayton           (int)(regex_sed.size() - second_separator_char_pos - 1),
1163ea508635SGreg Clayton           regex_sed.data() + (second_separator_char_pos + 1),
1164b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11650e5e5a79SGreg Clayton       return error;
11660e5e5a79SGreg Clayton     }
11670e5e5a79SGreg Clayton 
1168b9c1b51eSKate Stone     if (third_separator_char_pos != regex_sed_size - 1) {
11690e5e5a79SGreg Clayton       // Make sure that everything that follows the last regex
11700e5e5a79SGreg Clayton       // separator char
1171b9c1b51eSKate Stone       if (regex_sed.find_first_not_of("\t\n\v\f\r ",
1172b9c1b51eSKate Stone                                       third_separator_char_pos + 1) !=
1173b9c1b51eSKate Stone           std::string::npos) {
1174b9c1b51eSKate Stone         error.SetErrorStringWithFormat(
1175b9c1b51eSKate Stone             "extra data found after the '%.*s' regular expression substitution "
1176b9c1b51eSKate Stone             "string: '%.*s'",
1177b9c1b51eSKate Stone             (int)third_separator_char_pos + 1, regex_sed.data(),
11780e5e5a79SGreg Clayton             (int)(regex_sed.size() - third_separator_char_pos - 1),
11790e5e5a79SGreg Clayton             regex_sed.data() + (third_separator_char_pos + 1));
11800e5e5a79SGreg Clayton         return error;
11810e5e5a79SGreg Clayton       }
1182b9c1b51eSKate Stone     } else if (first_separator_char_pos + 1 == second_separator_char_pos) {
1183b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1184b9c1b51eSKate Stone           "<regex> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
1185b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
11860e5e5a79SGreg Clayton           regex_sed.data());
11870e5e5a79SGreg Clayton       return error;
1188b9c1b51eSKate Stone     } else if (second_separator_char_pos + 1 == third_separator_char_pos) {
1189b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1190b9c1b51eSKate Stone           "<subst> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
1191b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
11920e5e5a79SGreg Clayton           regex_sed.data());
11930e5e5a79SGreg Clayton       return error;
11940e5e5a79SGreg Clayton     }
119544d93782SGreg Clayton 
1196b9c1b51eSKate Stone     if (!check_only) {
1197b9c1b51eSKate Stone       std::string regex(regex_sed.substr(first_separator_char_pos + 1,
1198b9c1b51eSKate Stone                                          second_separator_char_pos -
1199b9c1b51eSKate Stone                                              first_separator_char_pos - 1));
1200b9c1b51eSKate Stone       std::string subst(regex_sed.substr(second_separator_char_pos + 1,
1201b9c1b51eSKate Stone                                          third_separator_char_pos -
1202b9c1b51eSKate Stone                                              second_separator_char_pos - 1));
1203b9c1b51eSKate Stone       m_regex_cmd_ap->AddRegexCommand(regex.c_str(), subst.c_str());
120444d93782SGreg Clayton     }
12050e5e5a79SGreg Clayton     return error;
1206de164aaaSGreg Clayton   }
1207de164aaaSGreg Clayton 
1208b9c1b51eSKate Stone   void AddRegexCommandToInterpreter() {
1209b9c1b51eSKate Stone     if (m_regex_cmd_ap) {
1210b9c1b51eSKate Stone       if (m_regex_cmd_ap->HasRegexEntries()) {
1211de164aaaSGreg Clayton         CommandObjectSP cmd_sp(m_regex_cmd_ap.release());
1212de164aaaSGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
1213de164aaaSGreg Clayton       }
1214de164aaaSGreg Clayton     }
1215de164aaaSGreg Clayton   }
1216de164aaaSGreg Clayton 
1217de164aaaSGreg Clayton private:
12187b0992d9SGreg Clayton   std::unique_ptr<CommandObjectRegexCommand> m_regex_cmd_ap;
1219de164aaaSGreg Clayton 
1220b9c1b51eSKate Stone   class CommandOptions : public Options {
1221de164aaaSGreg Clayton   public:
1222b9c1b51eSKate Stone     CommandOptions() : Options() {}
1223de164aaaSGreg Clayton 
12246e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1225de164aaaSGreg Clayton 
1226*fe11483bSZachary Turner     Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1227b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
1228de164aaaSGreg Clayton       Error error;
12293bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1230de164aaaSGreg Clayton 
1231b9c1b51eSKate Stone       switch (short_option) {
1232de164aaaSGreg Clayton       case 'h':
1233de164aaaSGreg Clayton         m_help.assign(option_arg);
1234de164aaaSGreg Clayton         break;
1235de164aaaSGreg Clayton       case 's':
1236de164aaaSGreg Clayton         m_syntax.assign(option_arg);
1237de164aaaSGreg Clayton         break;
1238de164aaaSGreg Clayton       default:
1239b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1240b9c1b51eSKate Stone                                        short_option);
1241de164aaaSGreg Clayton         break;
1242de164aaaSGreg Clayton       }
1243de164aaaSGreg Clayton 
1244de164aaaSGreg Clayton       return error;
1245de164aaaSGreg Clayton     }
1246de164aaaSGreg Clayton 
1247b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1248de164aaaSGreg Clayton       m_help.clear();
1249de164aaaSGreg Clayton       m_syntax.clear();
1250de164aaaSGreg Clayton     }
1251de164aaaSGreg Clayton 
12521f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
125370602439SZachary Turner       return llvm::makeArrayRef(g_regex_options);
12541f0f5b5bSZachary Turner     }
1255de164aaaSGreg Clayton 
125611eb9c64SZachary Turner     // TODO: Convert these functions to return StringRefs.
1257b9c1b51eSKate Stone     const char *GetHelp() {
12586e3d8e7fSEugene Zelenko       return (m_help.empty() ? nullptr : m_help.c_str());
1259de164aaaSGreg Clayton     }
12606e3d8e7fSEugene Zelenko 
1261b9c1b51eSKate Stone     const char *GetSyntax() {
12626e3d8e7fSEugene Zelenko       return (m_syntax.empty() ? nullptr : m_syntax.c_str());
1263de164aaaSGreg Clayton     }
12646e3d8e7fSEugene Zelenko 
1265de164aaaSGreg Clayton   protected:
12666e3d8e7fSEugene Zelenko     // Instance variables to hold the values for command options.
12676e3d8e7fSEugene Zelenko 
1268de164aaaSGreg Clayton     std::string m_help;
1269de164aaaSGreg Clayton     std::string m_syntax;
1270de164aaaSGreg Clayton   };
1271de164aaaSGreg Clayton 
1272b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
1273de164aaaSGreg Clayton 
12745a988416SJim Ingham   CommandOptions m_options;
1275de164aaaSGreg Clayton };
1276de164aaaSGreg Clayton 
1277b9c1b51eSKate Stone class CommandObjectPythonFunction : public CommandObjectRaw {
1278223383edSEnrico Granata public:
1279b9c1b51eSKate Stone   CommandObjectPythonFunction(CommandInterpreter &interpreter, std::string name,
1280b9c1b51eSKate Stone                               std::string funct, std::string help,
1281b9c1b51eSKate Stone                               ScriptedCommandSynchronicity synch)
1282a449698cSZachary Turner       : CommandObjectRaw(interpreter, name),
1283b9c1b51eSKate Stone         m_function_name(funct), m_synchro(synch), m_fetched_help_long(false) {
1284735152e3SEnrico Granata     if (!help.empty())
1285735152e3SEnrico Granata       SetHelp(help.c_str());
1286b9c1b51eSKate Stone     else {
1287735152e3SEnrico Granata       StreamString stream;
1288735152e3SEnrico Granata       stream.Printf("For more information run 'help %s'", name.c_str());
1289735152e3SEnrico Granata       SetHelp(stream.GetData());
1290735152e3SEnrico Granata     }
1291223383edSEnrico Granata   }
1292223383edSEnrico Granata 
12936e3d8e7fSEugene Zelenko   ~CommandObjectPythonFunction() override = default;
1294223383edSEnrico Granata 
1295b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
12965a988416SJim Ingham 
1297b9c1b51eSKate Stone   const std::string &GetFunctionName() { return m_function_name; }
12985a988416SJim Ingham 
1299b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
13005a988416SJim Ingham 
1301b9c1b51eSKate Stone   const char *GetHelpLong() override {
1302b9c1b51eSKate Stone     if (!m_fetched_help_long) {
1303fac939e9SEnrico Granata       ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1304b9c1b51eSKate Stone       if (scripter) {
1305fac939e9SEnrico Granata         std::string docstring;
1306b9c1b51eSKate Stone         m_fetched_help_long = scripter->GetDocumentationForItem(
1307b9c1b51eSKate Stone             m_function_name.c_str(), docstring);
1308fac939e9SEnrico Granata         if (!docstring.empty())
1309bfb75e9bSEnrico Granata           SetHelpLong(docstring.c_str());
1310fac939e9SEnrico Granata       }
1311fac939e9SEnrico Granata     }
1312fac939e9SEnrico Granata     return CommandObjectRaw::GetHelpLong();
1313fac939e9SEnrico Granata   }
1314fac939e9SEnrico Granata 
13155a988416SJim Ingham protected:
1316b9c1b51eSKate Stone   bool DoExecute(const char *raw_command_line,
1317b9c1b51eSKate Stone                  CommandReturnObject &result) override {
1318223383edSEnrico Granata     ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1319223383edSEnrico Granata 
1320223383edSEnrico Granata     Error error;
1321223383edSEnrico Granata 
132270f11f88SJim Ingham     result.SetStatus(eReturnStatusInvalid);
132370f11f88SJim Ingham 
1324b9c1b51eSKate Stone     if (!scripter ||
1325b9c1b51eSKate Stone         !scripter->RunScriptBasedCommand(m_function_name.c_str(),
1326b9c1b51eSKate Stone                                          raw_command_line, m_synchro, result,
1327b9c1b51eSKate Stone                                          error, m_exe_ctx)) {
1328223383edSEnrico Granata       result.AppendError(error.AsCString());
1329223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1330b9c1b51eSKate Stone     } else {
133170f11f88SJim Ingham       // Don't change the status if the command already set it...
1332b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1333b9c1b51eSKate Stone         if (result.GetOutputData() == nullptr ||
1334b9c1b51eSKate Stone             result.GetOutputData()[0] == '\0')
1335223383edSEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
133670f11f88SJim Ingham         else
133770f11f88SJim Ingham           result.SetStatus(eReturnStatusSuccessFinishResult);
133870f11f88SJim Ingham       }
133970f11f88SJim Ingham     }
1340223383edSEnrico Granata 
1341223383edSEnrico Granata     return result.Succeeded();
1342223383edSEnrico Granata   }
1343223383edSEnrico Granata 
13446e3d8e7fSEugene Zelenko private:
13456e3d8e7fSEugene Zelenko   std::string m_function_name;
13466e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
13476e3d8e7fSEugene Zelenko   bool m_fetched_help_long;
1348223383edSEnrico Granata };
1349223383edSEnrico Granata 
1350b9c1b51eSKate Stone class CommandObjectScriptingObject : public CommandObjectRaw {
13519fe00e52SEnrico Granata public:
13529fe00e52SEnrico Granata   CommandObjectScriptingObject(CommandInterpreter &interpreter,
13539fe00e52SEnrico Granata                                std::string name,
13540641ca1aSZachary Turner                                StructuredData::GenericSP cmd_obj_sp,
1355b9c1b51eSKate Stone                                ScriptedCommandSynchronicity synch)
1356a449698cSZachary Turner       : CommandObjectRaw(interpreter, name),
1357b9c1b51eSKate Stone         m_cmd_obj_sp(cmd_obj_sp), m_synchro(synch), m_fetched_help_short(false),
1358b9c1b51eSKate Stone         m_fetched_help_long(false) {
13599fe00e52SEnrico Granata     StreamString stream;
13609fe00e52SEnrico Granata     stream.Printf("For more information run 'help %s'", name.c_str());
13619fe00e52SEnrico Granata     SetHelp(stream.GetData());
1362e87764f2SEnrico Granata     if (ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter())
1363e87764f2SEnrico Granata       GetFlags().Set(scripter->GetFlagsForCommandObject(cmd_obj_sp));
13649fe00e52SEnrico Granata   }
13659fe00e52SEnrico Granata 
13666e3d8e7fSEugene Zelenko   ~CommandObjectScriptingObject() override = default;
13679fe00e52SEnrico Granata 
1368b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
13699fe00e52SEnrico Granata 
1370b9c1b51eSKate Stone   StructuredData::GenericSP GetImplementingObject() { return m_cmd_obj_sp; }
13719fe00e52SEnrico Granata 
1372b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
13739fe00e52SEnrico Granata 
1374b9c1b51eSKate Stone   const char *GetHelp() override {
1375b9c1b51eSKate Stone     if (!m_fetched_help_short) {
13766f79bb2dSEnrico Granata       ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1377b9c1b51eSKate Stone       if (scripter) {
13786f79bb2dSEnrico Granata         std::string docstring;
1379b9c1b51eSKate Stone         m_fetched_help_short =
1380b9c1b51eSKate Stone             scripter->GetShortHelpForCommandObject(m_cmd_obj_sp, docstring);
13816f79bb2dSEnrico Granata         if (!docstring.empty())
1382bfb75e9bSEnrico Granata           SetHelp(docstring.c_str());
13836f79bb2dSEnrico Granata       }
13846f79bb2dSEnrico Granata     }
13856f79bb2dSEnrico Granata     return CommandObjectRaw::GetHelp();
13866f79bb2dSEnrico Granata   }
13876f79bb2dSEnrico Granata 
1388b9c1b51eSKate Stone   const char *GetHelpLong() override {
1389b9c1b51eSKate Stone     if (!m_fetched_help_long) {
13906f79bb2dSEnrico Granata       ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1391b9c1b51eSKate Stone       if (scripter) {
13926f79bb2dSEnrico Granata         std::string docstring;
1393b9c1b51eSKate Stone         m_fetched_help_long =
1394b9c1b51eSKate Stone             scripter->GetLongHelpForCommandObject(m_cmd_obj_sp, docstring);
13956f79bb2dSEnrico Granata         if (!docstring.empty())
1396bfb75e9bSEnrico Granata           SetHelpLong(docstring.c_str());
13976f79bb2dSEnrico Granata       }
13986f79bb2dSEnrico Granata     }
13999fe00e52SEnrico Granata     return CommandObjectRaw::GetHelpLong();
14009fe00e52SEnrico Granata   }
14019fe00e52SEnrico Granata 
14029fe00e52SEnrico Granata protected:
1403b9c1b51eSKate Stone   bool DoExecute(const char *raw_command_line,
1404b9c1b51eSKate Stone                  CommandReturnObject &result) override {
14059fe00e52SEnrico Granata     ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
14069fe00e52SEnrico Granata 
14079fe00e52SEnrico Granata     Error error;
14089fe00e52SEnrico Granata 
14099fe00e52SEnrico Granata     result.SetStatus(eReturnStatusInvalid);
14109fe00e52SEnrico Granata 
1411b9c1b51eSKate Stone     if (!scripter ||
1412b9c1b51eSKate Stone         !scripter->RunScriptBasedCommand(m_cmd_obj_sp, raw_command_line,
1413b9c1b51eSKate Stone                                          m_synchro, result, error, m_exe_ctx)) {
14149fe00e52SEnrico Granata       result.AppendError(error.AsCString());
14159fe00e52SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1416b9c1b51eSKate Stone     } else {
14179fe00e52SEnrico Granata       // Don't change the status if the command already set it...
1418b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1419b9c1b51eSKate Stone         if (result.GetOutputData() == nullptr ||
1420b9c1b51eSKate Stone             result.GetOutputData()[0] == '\0')
14219fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
14229fe00e52SEnrico Granata         else
14239fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishResult);
14249fe00e52SEnrico Granata       }
14259fe00e52SEnrico Granata     }
14269fe00e52SEnrico Granata 
14279fe00e52SEnrico Granata     return result.Succeeded();
14289fe00e52SEnrico Granata   }
14299fe00e52SEnrico Granata 
14306e3d8e7fSEugene Zelenko private:
14316e3d8e7fSEugene Zelenko   StructuredData::GenericSP m_cmd_obj_sp;
14326e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
14336e3d8e7fSEugene Zelenko   bool m_fetched_help_short : 1;
14346e3d8e7fSEugene Zelenko   bool m_fetched_help_long : 1;
14359fe00e52SEnrico Granata };
14369fe00e52SEnrico Granata 
1437a9dbf432SEnrico Granata //-------------------------------------------------------------------------
1438a9dbf432SEnrico Granata // CommandObjectCommandsScriptImport
1439a9dbf432SEnrico Granata //-------------------------------------------------------------------------
1440a9dbf432SEnrico Granata 
14411f0f5b5bSZachary Turner OptionDefinition g_script_import_options[] = {
14421f0f5b5bSZachary Turner     // clang-format off
14431f0f5b5bSZachary 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." },
14441f0f5b5bSZachary Turner     // clang-format on
14451f0f5b5bSZachary Turner };
14461f0f5b5bSZachary Turner 
1447b9c1b51eSKate Stone class CommandObjectCommandsScriptImport : public CommandObjectParsed {
14485a988416SJim Ingham public:
1449b9c1b51eSKate Stone   CommandObjectCommandsScriptImport(CommandInterpreter &interpreter)
1450b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script import",
1451b9c1b51eSKate Stone                             "Import a scripting module in LLDB.", nullptr),
1452b9c1b51eSKate Stone         m_options() {
14535a988416SJim Ingham     CommandArgumentEntry arg1;
14545a988416SJim Ingham     CommandArgumentData cmd_arg;
14555a988416SJim Ingham 
14565a988416SJim Ingham     // Define the first (and only) variant of this arg.
14575a988416SJim Ingham     cmd_arg.arg_type = eArgTypeFilename;
14583b00e35bSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlus;
14595a988416SJim Ingham 
1460b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1461b9c1b51eSKate Stone     // argument entry.
14625a988416SJim Ingham     arg1.push_back(cmd_arg);
14635a988416SJim Ingham 
14645a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
14655a988416SJim Ingham     m_arguments.push_back(arg1);
14665a988416SJim Ingham   }
14675a988416SJim Ingham 
14686e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptImport() override = default;
14695a988416SJim Ingham 
1470b9c1b51eSKate Stone   int HandleArgumentCompletion(Args &input, int &cursor_index,
14715a988416SJim Ingham                                int &cursor_char_position,
14725a988416SJim Ingham                                OptionElementVector &opt_element_vector,
1473b9c1b51eSKate Stone                                int match_start_point, int max_return_elements,
14745a988416SJim Ingham                                bool &word_complete,
1475b9c1b51eSKate Stone                                StringList &matches) override {
14765a988416SJim Ingham     std::string completion_str(input.GetArgumentAtIndex(cursor_index));
14775a988416SJim Ingham     completion_str.erase(cursor_char_position);
14785a988416SJim Ingham 
1479b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
1480b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
1481b9c1b51eSKate Stone         completion_str.c_str(), match_start_point, max_return_elements, nullptr,
1482b9c1b51eSKate Stone         word_complete, matches);
14835a988416SJim Ingham     return matches.GetSize();
14845a988416SJim Ingham   }
14855a988416SJim Ingham 
1486b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
14875a988416SJim Ingham 
14885a988416SJim Ingham protected:
1489b9c1b51eSKate Stone   class CommandOptions : public Options {
14900a305db7SEnrico Granata   public:
1491b9c1b51eSKate Stone     CommandOptions() : Options() {}
14920a305db7SEnrico Granata 
14936e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
14940a305db7SEnrico Granata 
1495*fe11483bSZachary Turner     Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1496b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
14970a305db7SEnrico Granata       Error error;
14983bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
14990a305db7SEnrico Granata 
1500b9c1b51eSKate Stone       switch (short_option) {
15010a305db7SEnrico Granata       case 'r':
15020a305db7SEnrico Granata         m_allow_reload = true;
15030a305db7SEnrico Granata         break;
15040a305db7SEnrico Granata       default:
1505b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1506b9c1b51eSKate Stone                                        short_option);
15070a305db7SEnrico Granata         break;
15080a305db7SEnrico Granata       }
15090a305db7SEnrico Granata 
15100a305db7SEnrico Granata       return error;
15110a305db7SEnrico Granata     }
15120a305db7SEnrico Granata 
1513b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1514e0c70f1bSEnrico Granata       m_allow_reload = true;
15150a305db7SEnrico Granata     }
15160a305db7SEnrico Granata 
15171f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
151870602439SZachary Turner       return llvm::makeArrayRef(g_script_import_options);
15191f0f5b5bSZachary Turner     }
15200a305db7SEnrico Granata 
15210a305db7SEnrico Granata     // Instance variables to hold the values for command options.
15220a305db7SEnrico Granata 
15230a305db7SEnrico Granata     bool m_allow_reload;
15240a305db7SEnrico Granata   };
15250a305db7SEnrico Granata 
1526b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1527b9c1b51eSKate Stone     if (m_interpreter.GetDebugger().GetScriptLanguage() !=
1528b9c1b51eSKate Stone         lldb::eScriptLanguagePython) {
1529b9c1b51eSKate Stone       result.AppendError("only scripting language supported for module "
1530b9c1b51eSKate Stone                          "importing is currently Python");
1531a9dbf432SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1532a9dbf432SEnrico Granata       return false;
1533a9dbf432SEnrico Granata     }
1534a9dbf432SEnrico Granata 
153511eb9c64SZachary Turner     if (command.empty()) {
15363b00e35bSEnrico Granata       result.AppendError("command script import needs one or more arguments");
1537a9dbf432SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1538a9dbf432SEnrico Granata       return false;
1539a9dbf432SEnrico Granata     }
1540a9dbf432SEnrico Granata 
154111eb9c64SZachary Turner     for (auto &entry : command.entries()) {
1542a9dbf432SEnrico Granata       Error error;
1543a9dbf432SEnrico Granata 
1544c9d645d3SGreg Clayton       const bool init_session = true;
1545b9c1b51eSKate Stone       // FIXME: this is necessary because CommandObject::CheckRequirements()
154611eb9c64SZachary Turner       // assumes that commands won't ever be recursively invoked, but it's
154711eb9c64SZachary Turner       // actually possible to craft a Python script that does other "command
154811eb9c64SZachary Turner       // script imports" in __lldb_init_module the real fix is to have recursive
154911eb9c64SZachary Turner       // commands possible with a CommandInvocation object separate from the
155011eb9c64SZachary Turner       // CommandObject itself, so that recursive command invocations won't stomp
155111eb9c64SZachary Turner       // on each other (wrt to execution contents, options, and more)
1552078551c7SEnrico Granata       m_exe_ctx.Clear();
1553b9c1b51eSKate Stone       if (m_interpreter.GetScriptInterpreter()->LoadScriptingModule(
155411eb9c64SZachary Turner               entry.c_str(), m_options.m_allow_reload, init_session, error)) {
1555a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1556b9c1b51eSKate Stone       } else {
1557b9c1b51eSKate Stone         result.AppendErrorWithFormat("module importing failed: %s",
1558b9c1b51eSKate Stone                                      error.AsCString());
1559a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusFailed);
1560a9dbf432SEnrico Granata       }
15613b00e35bSEnrico Granata     }
1562a9dbf432SEnrico Granata 
1563a9dbf432SEnrico Granata     return result.Succeeded();
1564a9dbf432SEnrico Granata   }
15650a305db7SEnrico Granata 
15665a988416SJim Ingham   CommandOptions m_options;
1567a9dbf432SEnrico Granata };
1568223383edSEnrico Granata 
1569223383edSEnrico Granata //-------------------------------------------------------------------------
1570223383edSEnrico Granata // CommandObjectCommandsScriptAdd
1571223383edSEnrico Granata //-------------------------------------------------------------------------
1572223383edSEnrico Granata 
15731f0f5b5bSZachary Turner static OptionEnumValueElement g_script_synchro_type[] = {
15741f0f5b5bSZachary Turner     {eScriptedCommandSynchronicitySynchronous, "synchronous",
15751f0f5b5bSZachary Turner      "Run synchronous"},
15761f0f5b5bSZachary Turner     {eScriptedCommandSynchronicityAsynchronous, "asynchronous",
15771f0f5b5bSZachary Turner      "Run asynchronous"},
15781f0f5b5bSZachary Turner     {eScriptedCommandSynchronicityCurrentValue, "current",
15791f0f5b5bSZachary Turner      "Do not alter current setting"},
15801f0f5b5bSZachary Turner     {0, nullptr, nullptr}};
15811f0f5b5bSZachary Turner 
15821f0f5b5bSZachary Turner static OptionDefinition g_script_add_options[] = {
15831f0f5b5bSZachary Turner     // clang-format off
15841f0f5b5bSZachary 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." },
15851f0f5b5bSZachary 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." },
15861f0f5b5bSZachary Turner   { LLDB_OPT_SET_1,   false, "help"  ,        'h', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeHelpText,                     "The help text to display for this command." },
15871f0f5b5bSZachary 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." },
15881f0f5b5bSZachary Turner     // clang-format on
15891f0f5b5bSZachary Turner };
15901f0f5b5bSZachary Turner 
1591b9c1b51eSKate Stone class CommandObjectCommandsScriptAdd : public CommandObjectParsed,
1592b9c1b51eSKate Stone                                        public IOHandlerDelegateMultiline {
15935a988416SJim Ingham public:
1594b9c1b51eSKate Stone   CommandObjectCommandsScriptAdd(CommandInterpreter &interpreter)
1595b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script add",
15965a988416SJim Ingham                             "Add a scripted function as an LLDB command.",
15976e3d8e7fSEugene Zelenko                             nullptr),
1598b9c1b51eSKate Stone         IOHandlerDelegateMultiline("DONE"), m_options() {
15995a988416SJim Ingham     CommandArgumentEntry arg1;
16005a988416SJim Ingham     CommandArgumentData cmd_arg;
16015a988416SJim Ingham 
16025a988416SJim Ingham     // Define the first (and only) variant of this arg.
16035a988416SJim Ingham     cmd_arg.arg_type = eArgTypeCommandName;
16045a988416SJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlain;
16055a988416SJim Ingham 
1606b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1607b9c1b51eSKate Stone     // argument entry.
16085a988416SJim Ingham     arg1.push_back(cmd_arg);
16095a988416SJim Ingham 
16105a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
16115a988416SJim Ingham     m_arguments.push_back(arg1);
16125a988416SJim Ingham   }
16135a988416SJim Ingham 
16146e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptAdd() override = default;
16155a988416SJim Ingham 
1616b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
16175a988416SJim Ingham 
16185a988416SJim Ingham protected:
1619b9c1b51eSKate Stone   class CommandOptions : public Options {
1620223383edSEnrico Granata   public:
1621b9c1b51eSKate Stone     CommandOptions()
1622b9c1b51eSKate Stone         : Options(), m_class_name(), m_funct_name(), m_short_help(),
1623b9c1b51eSKate Stone           m_synchronicity(eScriptedCommandSynchronicitySynchronous) {}
1624223383edSEnrico Granata 
16256e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1626223383edSEnrico Granata 
1627*fe11483bSZachary Turner     Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1628b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
1629223383edSEnrico Granata       Error error;
16303bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1631223383edSEnrico Granata 
1632b9c1b51eSKate Stone       switch (short_option) {
1633223383edSEnrico Granata       case 'f':
1634*fe11483bSZachary Turner         if (!option_arg.empty())
1635*fe11483bSZachary Turner           m_funct_name = option_arg;
1636735152e3SEnrico Granata         break;
16379fe00e52SEnrico Granata       case 'c':
1638*fe11483bSZachary Turner         if (!option_arg.empty())
1639*fe11483bSZachary Turner           m_class_name = option_arg;
16409fe00e52SEnrico Granata         break;
1641735152e3SEnrico Granata       case 'h':
1642*fe11483bSZachary Turner         if (!option_arg.empty())
1643*fe11483bSZachary Turner           m_short_help = option_arg;
1644223383edSEnrico Granata         break;
16450a305db7SEnrico Granata       case 's':
1646b9c1b51eSKate Stone         m_synchronicity =
1647b9c1b51eSKate Stone             (ScriptedCommandSynchronicity)Args::StringToOptionEnum(
1648*fe11483bSZachary Turner                 option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
16490a305db7SEnrico Granata         if (!error.Success())
1650b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
1651*fe11483bSZachary Turner               "unrecognized value for synchronicity '%s'",
1652*fe11483bSZachary Turner               option_arg.str().c_str());
16530a305db7SEnrico Granata         break;
1654223383edSEnrico Granata       default:
1655b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1656b9c1b51eSKate Stone                                        short_option);
1657223383edSEnrico Granata         break;
1658223383edSEnrico Granata       }
1659223383edSEnrico Granata 
1660223383edSEnrico Granata       return error;
1661223383edSEnrico Granata     }
1662223383edSEnrico Granata 
1663b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
16649fe00e52SEnrico Granata       m_class_name.clear();
1665735152e3SEnrico Granata       m_funct_name.clear();
1666735152e3SEnrico Granata       m_short_help.clear();
166744d93782SGreg Clayton       m_synchronicity = eScriptedCommandSynchronicitySynchronous;
1668223383edSEnrico Granata     }
1669223383edSEnrico Granata 
16701f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
167170602439SZachary Turner       return llvm::makeArrayRef(g_script_add_options);
16721f0f5b5bSZachary Turner     }
1673223383edSEnrico Granata 
1674223383edSEnrico Granata     // Instance variables to hold the values for command options.
1675223383edSEnrico Granata 
16769fe00e52SEnrico Granata     std::string m_class_name;
1677223383edSEnrico Granata     std::string m_funct_name;
1678735152e3SEnrico Granata     std::string m_short_help;
167944d93782SGreg Clayton     ScriptedCommandSynchronicity m_synchronicity;
1680223383edSEnrico Granata   };
1681223383edSEnrico Granata 
1682b9c1b51eSKate Stone   void IOHandlerActivated(IOHandler &io_handler) override {
168344d93782SGreg Clayton     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
1684b9c1b51eSKate Stone     if (output_sp) {
168544d93782SGreg Clayton       output_sp->PutCString(g_python_command_instructions);
168644d93782SGreg Clayton       output_sp->Flush();
1687223383edSEnrico Granata     }
1688223383edSEnrico Granata   }
1689223383edSEnrico Granata 
1690b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
1691b9c1b51eSKate Stone                               std::string &data) override {
169244d93782SGreg Clayton     StreamFileSP error_sp = io_handler.GetErrorStreamFile();
169344d93782SGreg Clayton 
169444d93782SGreg Clayton     ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter();
1695b9c1b51eSKate Stone     if (interpreter) {
169644d93782SGreg Clayton 
169744d93782SGreg Clayton       StringList lines;
169844d93782SGreg Clayton       lines.SplitIntoLines(data);
1699b9c1b51eSKate Stone       if (lines.GetSize() > 0) {
1700a73b7df7SEnrico Granata         std::string funct_name_str;
1701b9c1b51eSKate Stone         if (interpreter->GenerateScriptAliasFunction(lines, funct_name_str)) {
1702b9c1b51eSKate Stone           if (funct_name_str.empty()) {
1703b9c1b51eSKate Stone             error_sp->Printf("error: unable to obtain a function name, didn't "
1704b9c1b51eSKate Stone                              "add python command.\n");
170544d93782SGreg Clayton             error_sp->Flush();
1706b9c1b51eSKate Stone           } else {
1707223383edSEnrico Granata             // everything should be fine now, let's add this alias
1708223383edSEnrico Granata 
1709b9c1b51eSKate Stone             CommandObjectSP command_obj_sp(new CommandObjectPythonFunction(
1710771ef6d4SMalcolm Parsons                 m_interpreter, m_cmd_name, funct_name_str, m_short_help,
171144d93782SGreg Clayton                 m_synchronicity));
1712223383edSEnrico Granata 
1713b9c1b51eSKate Stone             if (!m_interpreter.AddUserCommand(m_cmd_name, command_obj_sp,
1714b9c1b51eSKate Stone                                               true)) {
1715b9c1b51eSKate Stone               error_sp->Printf("error: unable to add selected command, didn't "
1716b9c1b51eSKate Stone                                "add python command.\n");
171744d93782SGreg Clayton               error_sp->Flush();
1718223383edSEnrico Granata             }
1719223383edSEnrico Granata           }
1720b9c1b51eSKate Stone         } else {
1721b9c1b51eSKate Stone           error_sp->Printf(
1722b9c1b51eSKate Stone               "error: unable to create function, didn't add python command.\n");
172344d93782SGreg Clayton           error_sp->Flush();
172444d93782SGreg Clayton         }
1725b9c1b51eSKate Stone       } else {
172644d93782SGreg Clayton         error_sp->Printf("error: empty function, didn't add python command.\n");
172744d93782SGreg Clayton         error_sp->Flush();
172844d93782SGreg Clayton       }
1729b9c1b51eSKate Stone     } else {
1730b9c1b51eSKate Stone       error_sp->Printf(
1731b9c1b51eSKate Stone           "error: script interpreter missing, didn't add python command.\n");
173244d93782SGreg Clayton       error_sp->Flush();
173344d93782SGreg Clayton     }
173444d93782SGreg Clayton 
173544d93782SGreg Clayton     io_handler.SetIsDone(true);
173644d93782SGreg Clayton   }
1737223383edSEnrico Granata 
17385a988416SJim Ingham protected:
1739b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1740b9c1b51eSKate Stone     if (m_interpreter.GetDebugger().GetScriptLanguage() !=
1741b9c1b51eSKate Stone         lldb::eScriptLanguagePython) {
1742b9c1b51eSKate Stone       result.AppendError("only scripting language supported for scripted "
1743b9c1b51eSKate Stone                          "commands is currently Python");
174499f0b8f9SEnrico Granata       result.SetStatus(eReturnStatusFailed);
174599f0b8f9SEnrico Granata       return false;
174699f0b8f9SEnrico Granata     }
174799f0b8f9SEnrico Granata 
174811eb9c64SZachary Turner     if (command.GetArgumentCount() != 1) {
1749223383edSEnrico Granata       result.AppendError("'command script add' requires one argument");
1750223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1751223383edSEnrico Granata       return false;
1752223383edSEnrico Granata     }
1753223383edSEnrico Granata 
1754735152e3SEnrico Granata     // Store the options in case we get multi-line input
175544d93782SGreg Clayton     m_cmd_name = command.GetArgumentAtIndex(0);
1756735152e3SEnrico Granata     m_short_help.assign(m_options.m_short_help);
175744d93782SGreg Clayton     m_synchronicity = m_options.m_synchronicity;
1758223383edSEnrico Granata 
1759b9c1b51eSKate Stone     if (m_options.m_class_name.empty()) {
1760b9c1b51eSKate Stone       if (m_options.m_funct_name.empty()) {
1761b9c1b51eSKate Stone         m_interpreter.GetPythonCommandsFromIOHandler(
1762b9c1b51eSKate Stone             "     ",  // Prompt
176344d93782SGreg Clayton             *this,    // IOHandlerDelegate
176444d93782SGreg Clayton             true,     // Run IOHandler in async mode
1765b9c1b51eSKate Stone             nullptr); // Baton for the "io_handler" that will be passed back
1766b9c1b51eSKate Stone                       // into our IOHandlerDelegate functions
1767b9c1b51eSKate Stone       } else {
1768b9c1b51eSKate Stone         CommandObjectSP new_cmd(new CommandObjectPythonFunction(
1769b9c1b51eSKate Stone             m_interpreter, m_cmd_name, m_options.m_funct_name,
1770b9c1b51eSKate Stone             m_options.m_short_help, m_synchronicity));
1771b9c1b51eSKate Stone         if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) {
1772223383edSEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
1773b9c1b51eSKate Stone         } else {
1774223383edSEnrico Granata           result.AppendError("cannot add command");
1775223383edSEnrico Granata           result.SetStatus(eReturnStatusFailed);
1776223383edSEnrico Granata         }
1777223383edSEnrico Granata       }
1778b9c1b51eSKate Stone     } else {
1779b9c1b51eSKate Stone       ScriptInterpreter *interpreter =
1780b9c1b51eSKate Stone           GetCommandInterpreter().GetScriptInterpreter();
1781b9c1b51eSKate Stone       if (!interpreter) {
17829fe00e52SEnrico Granata         result.AppendError("cannot find ScriptInterpreter");
17839fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17849fe00e52SEnrico Granata         return false;
17859fe00e52SEnrico Granata       }
17869fe00e52SEnrico Granata 
1787b9c1b51eSKate Stone       auto cmd_obj_sp = interpreter->CreateScriptCommandObject(
1788b9c1b51eSKate Stone           m_options.m_class_name.c_str());
1789b9c1b51eSKate Stone       if (!cmd_obj_sp) {
17909fe00e52SEnrico Granata         result.AppendError("cannot create helper object");
17919fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17929fe00e52SEnrico Granata         return false;
17939fe00e52SEnrico Granata       }
17949fe00e52SEnrico Granata 
1795b9c1b51eSKate Stone       CommandObjectSP new_cmd(new CommandObjectScriptingObject(
1796b9c1b51eSKate Stone           m_interpreter, m_cmd_name, cmd_obj_sp, m_synchronicity));
1797b9c1b51eSKate Stone       if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) {
17989fe00e52SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1799b9c1b51eSKate Stone       } else {
18009fe00e52SEnrico Granata         result.AppendError("cannot add command");
18019fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
18029fe00e52SEnrico Granata       }
18039fe00e52SEnrico Granata     }
1804223383edSEnrico Granata 
1805223383edSEnrico Granata     return result.Succeeded();
1806223383edSEnrico Granata   }
18075a988416SJim Ingham 
18085a988416SJim Ingham   CommandOptions m_options;
180944d93782SGreg Clayton   std::string m_cmd_name;
1810735152e3SEnrico Granata   std::string m_short_help;
181144d93782SGreg Clayton   ScriptedCommandSynchronicity m_synchronicity;
1812223383edSEnrico Granata };
1813223383edSEnrico Granata 
1814223383edSEnrico Granata //-------------------------------------------------------------------------
1815223383edSEnrico Granata // CommandObjectCommandsScriptList
1816223383edSEnrico Granata //-------------------------------------------------------------------------
1817223383edSEnrico Granata 
1818b9c1b51eSKate Stone class CommandObjectCommandsScriptList : public CommandObjectParsed {
1819223383edSEnrico Granata public:
1820b9c1b51eSKate Stone   CommandObjectCommandsScriptList(CommandInterpreter &interpreter)
1821b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script list",
1822b9c1b51eSKate Stone                             "List defined scripted commands.", nullptr) {}
1823223383edSEnrico Granata 
18246e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptList() override = default;
1825223383edSEnrico Granata 
1826b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1827b9c1b51eSKate Stone     m_interpreter.GetHelp(result, CommandInterpreter::eCommandTypesUserDef);
1828223383edSEnrico Granata 
1829223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1830223383edSEnrico Granata 
1831223383edSEnrico Granata     return true;
1832223383edSEnrico Granata   }
1833223383edSEnrico Granata };
1834223383edSEnrico Granata 
1835223383edSEnrico Granata //-------------------------------------------------------------------------
1836223383edSEnrico Granata // CommandObjectCommandsScriptClear
1837223383edSEnrico Granata //-------------------------------------------------------------------------
1838223383edSEnrico Granata 
1839b9c1b51eSKate Stone class CommandObjectCommandsScriptClear : public CommandObjectParsed {
1840223383edSEnrico Granata public:
1841b9c1b51eSKate Stone   CommandObjectCommandsScriptClear(CommandInterpreter &interpreter)
1842b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script clear",
1843b9c1b51eSKate Stone                             "Delete all scripted commands.", nullptr) {}
1844223383edSEnrico Granata 
18456e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptClear() override = default;
1846223383edSEnrico Granata 
18475a988416SJim Ingham protected:
1848b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1849223383edSEnrico Granata     m_interpreter.RemoveAllUser();
1850223383edSEnrico Granata 
1851223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1852223383edSEnrico Granata 
1853223383edSEnrico Granata     return true;
1854223383edSEnrico Granata   }
1855223383edSEnrico Granata };
1856223383edSEnrico Granata 
1857223383edSEnrico Granata //-------------------------------------------------------------------------
1858223383edSEnrico Granata // CommandObjectCommandsScriptDelete
1859223383edSEnrico Granata //-------------------------------------------------------------------------
1860223383edSEnrico Granata 
1861b9c1b51eSKate Stone class CommandObjectCommandsScriptDelete : public CommandObjectParsed {
1862223383edSEnrico Granata public:
1863b9c1b51eSKate Stone   CommandObjectCommandsScriptDelete(CommandInterpreter &interpreter)
1864b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script delete",
1865b9c1b51eSKate Stone                             "Delete a scripted command.", nullptr) {
1866223383edSEnrico Granata     CommandArgumentEntry arg1;
1867223383edSEnrico Granata     CommandArgumentData cmd_arg;
1868223383edSEnrico Granata 
1869223383edSEnrico Granata     // Define the first (and only) variant of this arg.
1870223383edSEnrico Granata     cmd_arg.arg_type = eArgTypeCommandName;
1871223383edSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlain;
1872223383edSEnrico Granata 
1873b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1874b9c1b51eSKate Stone     // argument entry.
1875223383edSEnrico Granata     arg1.push_back(cmd_arg);
1876223383edSEnrico Granata 
1877223383edSEnrico Granata     // Push the data for the first argument into the m_arguments vector.
1878223383edSEnrico Granata     m_arguments.push_back(arg1);
1879223383edSEnrico Granata   }
1880223383edSEnrico Granata 
18816e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptDelete() override = default;
1882223383edSEnrico Granata 
18835a988416SJim Ingham protected:
1884b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1885223383edSEnrico Granata 
188611eb9c64SZachary Turner     if (command.GetArgumentCount() != 1) {
1887223383edSEnrico Granata       result.AppendError("'command script delete' requires one argument");
1888223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1889223383edSEnrico Granata       return false;
1890223383edSEnrico Granata     }
1891223383edSEnrico Granata 
18925a988416SJim Ingham     const char *cmd_name = command.GetArgumentAtIndex(0);
1893223383edSEnrico Granata 
1894b9c1b51eSKate Stone     if (cmd_name && *cmd_name && m_interpreter.HasUserCommands() &&
1895b9c1b51eSKate Stone         m_interpreter.UserCommandExists(cmd_name)) {
1896223383edSEnrico Granata       m_interpreter.RemoveUser(cmd_name);
1897223383edSEnrico Granata       result.SetStatus(eReturnStatusSuccessFinishResult);
1898b9c1b51eSKate Stone     } else {
1899223383edSEnrico Granata       result.AppendErrorWithFormat("command %s not found", cmd_name);
1900223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1901223383edSEnrico Granata     }
1902223383edSEnrico Granata 
1903223383edSEnrico Granata     return result.Succeeded();
1904223383edSEnrico Granata   }
1905223383edSEnrico Granata };
1906223383edSEnrico Granata 
1907223383edSEnrico Granata #pragma mark CommandObjectMultiwordCommandsScript
1908223383edSEnrico Granata 
1909223383edSEnrico Granata //-------------------------------------------------------------------------
1910223383edSEnrico Granata // CommandObjectMultiwordCommandsScript
1911223383edSEnrico Granata //-------------------------------------------------------------------------
1912223383edSEnrico Granata 
1913b9c1b51eSKate Stone class CommandObjectMultiwordCommandsScript : public CommandObjectMultiword {
1914223383edSEnrico Granata public:
19157428a18cSKate Stone   CommandObjectMultiwordCommandsScript(CommandInterpreter &interpreter)
1916b9c1b51eSKate Stone       : CommandObjectMultiword(
1917b9c1b51eSKate Stone             interpreter, "command script", "Commands for managing custom "
1918b9c1b51eSKate Stone                                            "commands implemented by "
1919b9c1b51eSKate Stone                                            "interpreter scripts.",
1920b9c1b51eSKate Stone             "command script <subcommand> [<subcommand-options>]") {
1921b9c1b51eSKate Stone     LoadSubCommand("add", CommandObjectSP(
1922b9c1b51eSKate Stone                               new CommandObjectCommandsScriptAdd(interpreter)));
1923b9c1b51eSKate Stone     LoadSubCommand(
1924b9c1b51eSKate Stone         "delete",
1925b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptDelete(interpreter)));
1926b9c1b51eSKate Stone     LoadSubCommand(
1927b9c1b51eSKate Stone         "clear",
1928b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptClear(interpreter)));
1929b9c1b51eSKate Stone     LoadSubCommand("list", CommandObjectSP(new CommandObjectCommandsScriptList(
1930b9c1b51eSKate Stone                                interpreter)));
1931b9c1b51eSKate Stone     LoadSubCommand(
1932b9c1b51eSKate Stone         "import",
1933b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptImport(interpreter)));
1934223383edSEnrico Granata   }
1935223383edSEnrico Granata 
19366e3d8e7fSEugene Zelenko   ~CommandObjectMultiwordCommandsScript() override = default;
1937223383edSEnrico Granata };
1938223383edSEnrico Granata 
1939ebc09c36SJim Ingham #pragma mark CommandObjectMultiwordCommands
1940ebc09c36SJim Ingham 
1941ebc09c36SJim Ingham //-------------------------------------------------------------------------
1942ebc09c36SJim Ingham // CommandObjectMultiwordCommands
1943ebc09c36SJim Ingham //-------------------------------------------------------------------------
1944ebc09c36SJim Ingham 
1945b9c1b51eSKate Stone CommandObjectMultiwordCommands::CommandObjectMultiwordCommands(
1946b9c1b51eSKate Stone     CommandInterpreter &interpreter)
1947b9c1b51eSKate Stone     : CommandObjectMultiword(interpreter, "command",
1948b9c1b51eSKate Stone                              "Commands for managing custom LLDB commands.",
1949b9c1b51eSKate Stone                              "command <subcommand> [<subcommand-options>]") {
1950b9c1b51eSKate Stone   LoadSubCommand("source",
1951b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsSource(interpreter)));
1952b9c1b51eSKate Stone   LoadSubCommand("alias",
1953b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsAlias(interpreter)));
1954b9c1b51eSKate Stone   LoadSubCommand("unalias", CommandObjectSP(
1955b9c1b51eSKate Stone                                 new CommandObjectCommandsUnalias(interpreter)));
1956b9c1b51eSKate Stone   LoadSubCommand("delete",
1957b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsDelete(interpreter)));
1958b9c1b51eSKate Stone   LoadSubCommand(
1959b9c1b51eSKate Stone       "regex", CommandObjectSP(new CommandObjectCommandsAddRegex(interpreter)));
1960b9c1b51eSKate Stone   LoadSubCommand("history", CommandObjectSP(
1961b9c1b51eSKate Stone                                 new CommandObjectCommandsHistory(interpreter)));
1962b9c1b51eSKate Stone   LoadSubCommand(
1963b9c1b51eSKate Stone       "script",
1964b9c1b51eSKate Stone       CommandObjectSP(new CommandObjectMultiwordCommandsScript(interpreter)));
1965ebc09c36SJim Ingham }
1966ebc09c36SJim Ingham 
19676e3d8e7fSEugene Zelenko CommandObjectMultiwordCommands::~CommandObjectMultiwordCommands() = default;
1968